Thursday 3 May 2012

Loading WebImages onto the Windows Application

Hi,

Here is the solution for loading webimages onto the windows application.

1) The first thing that we need is to create a HttpWebRequest object from the Image URL.
2) GetResponse will get the resulting response from the request we have made.
3) From GetResponseStream method of HttpWebResponse we can get the Stream of the URL.
4) After getting the Stream objtect, create an Image object from it.
 
        private Image GetImageFromWeb(string strURL)
        {
            Stream streamImage = null;
            try
            {
                //Create a web request to the url containing the image
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(strURL);
                //gets the response from the web request
                HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
                //return the image stream from the URL specified earlier
                streamImage = wRes.GetResponseStream();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }

            if (streamImage != null)
            {
                return Image.FromStream(streamImage);
            }
            else
            {
                return null;
            }
        }

Now you got the image, you can give it to the picturebox and that will display the image.
Lets say, we have pbxImage(PictureBox) is there on the form.
then just the write the below line in your code, that will load the image from the web.
                  string strURL = "<URL of the Image>";
                 pbxImage .Image = GetImageFromWeb(strURL);

Hope this helps

--
Happy Coding
Gopinath

C# to SQL


Connecting  SQL server  from C#
To connect to a SQL server database, you first need to set up a SQL Connection object. You then need something called a connection string to tell C# where the database is.
Specify the connection string
<connectionStrings>
    <add name="OsmEmpConString" connectionString="Data Source=.\sqlexpress;Initial Catalog=EmpolyeeDB; User ID= Sqluser ; Password= 123456789;"
    providerName="System.Data.SqlClient" />
  </connectionStrings>
DataSource = Your database source
Initial Catalog = Database name
User ID = User id of the database
Password = Password to the database
Use that connection in .cs file
string strDbCon = WebConfigurationManager.ConnectionStrings["OsmEmpConString"].ToString();
    SqlConnection _cnEmpDB = new SqlConnection(strDbCon);
       _ cnEmpDB.Open();
_ cnEmpDB is the instance of SqlConnection.
The namespace required for doing this is using System.Data.SqlClient;

C# code

Below are the methods in which you can do all types of operations from C# code.

private SqlConnection _cnEdu;

        // Open Connection
        public void OpenConnection()
        {
            AppSettingsReader objAppReader = new AppSettingsReader();
            string strDbCon = objAppReader.GetValue("DbconEdu", typeof(string)).ToString();
            _cnEdu = new SqlConnection(strDbCon);
            _cnEdu.Open();
        }

        // Close Connection
        public void CloseConnection()
        {
            if (_cnEdu == null)
            {
                return;
            }
            _cnEdu.Close();
            _cnEdu.Dispose();
        }

        // Method to check the Database connection. If the connection is closed, Opens it.
        private void CheckDbConnection()
        {
            if (_cnEdu == null)
            {
                //checks for connection
                OpenConnection();
            }
            else if (_cnEdu.State == ConnectionState.Closed)
            {
                OpenConnection();
            }
        }

        // Method which takes SQL query as parameter and returns a DataTable.
        public DataTable ExecuteDataTable(string strQuery)
        {
            if (strQuery == null && strQuery.Length == 0)//checks for the query
            {
                return null;
            }
            CheckDbConnection();
            DataTable dtReturn = new DataTable();//creates table
            using (SqlDataAdapter daExecute = new SqlDataAdapter(strQuery, _cnEdu))
            {
                daExecute.Fill(dtReturn);
            }
            return dtReturn;
        }

        // Method which takes SQL query as parameter and return true if the record exists in the database.
        public bool RecordExists(string strQuery)
        {
            CheckDbConnection();
            using (SqlCommand cmdEdu = new SqlCommand())
            {
                cmdEdu.Connection = _cnEdu;
                cmdEdu.CommandText = strQuery;
                cmdEdu.CommandType = CommandType.Text;
                Object objColValue = cmdEdu.ExecuteScalar();
                bool blnExists = true;
                if (objColValue == null)
                {
                    blnExists = false;
                }
                return blnExists;
            }
        }

        // Method which takes SQL insert and update query and executes in the database.
        public void ExecQuery(string strQuery)
        {
            CheckDbConnection();
            using (SqlCommand cmdEdu = new SqlCommand())
            {
                cmdEdu.Connection = _cnEdu;
                cmdEdu.CommandText = strQuery;
                cmdEdu.CommandType = CommandType.Text;
                int intColValue = cmdEdu.ExecuteNonQuery();
            }
        }

        // Method which takes a input parameter and executes the specified storedprocedure.
        public void ExecuteStoredProcuedure(string strEmpID)
        {
            CheckDbConnection();
            SqlCommand cmd = new SqlCommand("updateEmployee", _cnEdu);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@pi_emp_id", SqlDbType.VarChar, 20).Value = strEmpID;
            cmd.Parameters.Add("@pi_name",SqlDbType.VarChar, 50).Value = "Name";
            cmd.Parameters.Add("@po_address", SqlDbType.VarChar, 500).Value = "Address of the Employee";
            cmd.Parameters.Add("@po_email", SqlDbType.VarChar, 50).Value = "name@name.com";
            cmd.ExecuteNonQuery();
        }



Tuesday 1 May 2012

How to know the status of the Case? How to know Case Resolved date and Re-Activated date in CRM 2011?


How to know the Status of the Case? How to know Case Resolved date and Re-Activated date in CRM 2011?
First I have a open case and I did resolve it. After some days, due to some reasons I have Re-Opened the same Case. Now the re-opened case status will be Active.
Here comes the question, how can we know that the case is resolved first and later it is re-opened
We can able to get Open, Cancel and Resolved status of the case easily but to know the case is first resolved first and later it is re-opened.
 Here is the solution for it.
When the case is Resolved, CRM 2011 creates a activity(Case Resolution) under Closed Activities entity.
If the Activity status is Completed then the Case is Resolved.
If the Activity status is Cancelled then the Case is Resolved and Re-Opened.
By getting the Closed activity of the case, we can know the case status and even know the when was the case resolved i.e Createdon date of the CaseResolution activity and for Re-Opened date, ModifiedOn date of the CaseResolution activity.

<!--[endif]-->
Resolved Case

Re-Opened Case

<!--[endif]-->



CRM Javascript



Get and Set Values

 Xrm.Page.getAttribute('<schema name of the attribute>').setValue(null);
 var strAttributeValue = Xrm.Page.getAttribute('<schema name of the attribute>').getValue();

Get and Set Disabled Property

 Xrm.Page.ui.controls.get('<schema name of the attribute>').setDisabled(true); 

Get and Set Attribute Disabled Property

-- Set
// below line is used to disable the field.

Xrm.Page.ui.controls.get("<schema name of the attribute>").setDisabled(true);

 // below line is used to enable the disabled field.
 Xrm.Page.ui.controls.get("<schema name of the attribute>").setDisabled(false);

-- Get

var blnStatus = Xrm.Page.ui.controls.get('<schema name of the attribute>').getDisabled()


Setting RequiredLevel

There are required levels
1)Required
2)Recommended

3)None


Xrm.Page.getAttribute("<schema name of the attribute>").setRequiredLevel("required");

Xrm.Page.getAttribute("<schema name of the attribute>").setRequiredLevel("recommended");


Xrm.Page.getAttribute("<schema name of the attribute>").setRequiredLevel("none");


 To set the Focus
 Xrm.Page.getControl("<("<schema name of the attribute>").setFocus(true);

CRM FormTypes

crmForm.FormType = 1 // When creating a record

crmForm.FormType = 2 // When updating a record

crmForm.FormType = 3 // When the form is read-only


crmForm.FormType = 4 // De-activated or Disabled


crmForm.FormType = 5 // Quick Create

crmForm.FormType =  6// Bulk Edit


crmForm.ObjectId // To get the uniqueId associated with the record


crmForm.IsDirty== true // Have any fields on the form are changed


Method to Construct Date in JavaScript
function ConstructDate(Day, Month, Year) {

    var DateConstruct = new Date();

    DateConstruct.setDate(Day)

    // JavaScript Month starts from Index 0, so subtracted 1 form the original value.

    //    The parseInt function decides what base the number is by looking

    // at the number. By convention it assumes that any number beginning

    // with 0x is Hexadecimal, and otherwise any number beginning with

    // 0 is Octal. To force use of base 10 add a second parameter

    // `` parseInt("09",10) ''

    DateConstruct.setMonth(parseInt(Month, 10) - 1)

    DateConstruct.setYear(Year)

    DateConstruct.setHours(0, 0, 0, 0);

    return DateConstruct;

}


Function to format a date to the UTC format.

function DateToUTCFormat(inputDate) {
    var date = inputDate.getDate();
    var month = inputDate.getMonth() + 1;

    var year = inputDate.getYear();

    var hours = inputDate.getHours();

    var minutes = inputDate.getMinutes();

    var ampm = " AM";

    if (hours > 11) {

        ampm = " PM";

        hours = hours - 12;

    }

    if (hours == 0)

    { hours = 12; }

    if (minutes < 10) {

        var time = hours.toString() + ":0" + minutes.toString() + ":00" + ampm;

    }

    else {

        var time = hours.toString() + ":" + minutes.toString() + ":00" + ampm;

    }

    var UTCDate = month.toString() + "/" + date.toString() + "/" + year.toString() + " " + time;

    return UTCDate;

}


Get the Language code of the current user
 var UserLcid = Xrm.Page.context.getUserLcid();

Binding Click events
 crmForm.all.schemaname.onclick = function () {
            crmForm.all.schemaname.FireOnChange();

        }





Now,  it's time to write some generic methods in a single JavaScript and use them wherever we want...

//1. Hide/ Show  form fields.

//objField   -  Name of field to show/hide.
//blnVisible -  True to show the field, False to hide.
function ShowHideField(objField, blnVisible) {
    objField = Xrm.Page.ui.controls.get(objField);
    objField.setVisible(blnVisible);
}

//2. Set the CRM 2011 form field Submit Mode

// objField      - Name of the field to move to
// strSubmitMode - must be one of "always", "never" or "dirty"
function SetFieldSubmitMode(objField, strSubmitMode) {
    objField = Xrm.Page.ui.controls.get(objField);
    objField.setSubmitMode(strSubmitMode);
}

//3.  Re-label the field

//  objField  - Name of field to relabel.
//  strNewFieldLabel -  New Label for the label.
function RelabelField(objField, strNewFieldLabel) {
    objField = Xrm.Page.ui.controls.get(objField);
    objField.setLabel(strNewFieldLabel);
}


//4. Enable /Disable the form field

// objFieldName - name of the field.
// blnDisabled  - True to make field disabled, False to not.
function SetDisabledLevel(objFieldName, blnDisabled) {
    objField = Xrm.Page.ui.controls.get(objFieldName);
    objField.setDisabled(blnDisabled);
}

//5. Show/ Hide the section on the specific tab

// strTabName     - Name of the tab to locate.
// strSectionName - Name of the Section to locate.
// blnVisible     - True to show the tab section, False to hide.
function ShowHideSection(strTabName, strSectionName, blnVisible) {
    objSectionItem = Xrm.Page.ui.tabs.get(strTabName).sections.get(strSectionName);
    objSectionItem.setVisible(blnVisible);
}

//6. Show  / Hide  Tab on the form

//  strTabName  - Name of the tab to locate.
//  blnVisible  - True to show the tab, False to hide.
function ShowHideTab(strTabName, blnVisible) {
    objTabItem = Xrm.Page.ui.tabs.get(strTabName);
    objTabItem.setVisible(blnVisible);
}

//7. Set the Requirement level of the form field

// objFieldName  - name of the field.
// strRequirementLevel - none, required or recommended
function SetRequirementLevel(objFieldName, SstrRequirementLevel) {
    objField = Xrm.Page.data.entity.attributes.get(objFieldName);
    objField.setRequiredLevel(strRequirementLevel);
}

//8. Collapse the Tab

// tabName  -Tab name to be collapsed
function CollapseTab(tabName) {
    var control = Xrm.Page.ui.tabs.get(tabName);
    control.setDisplayState("collapsed");
}


//9. Expand the Tab

// tabName -  Tab name to be expanded
function ExpandTab(tabName) {
    var control = Xrm.Page.ui.tabs.get(tabName);
    control.setDisplayState("expanded");
}

//10. Get the user Details

//Note : you need to include json.js file in order to run the script below.

function GetUserDetails(Scolumns) {
    var context = Xrm.Page.context;
    userID = context.getUserId();
    serverUrl = context.getServerUrl();
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    startTime = new Date();
    var retrieveReq = new XMLHttpRequest();
    retrieveReq.open("GET", ODataPath + "/SystemUserSet(guid'" + userID + "')?$select=" + Scolumns, false);
    retrieveReq.setRequestHeader("Accept", "application/json");
    retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    retrieveReq.onreadystatechange = function() { RetrieveUserRequestCallBack(this); };
    retrieveReq.send();
}

function RetrieveUserRequestCallBack(responseReq) {
    if (responseReq.readyState == 4 /* complete */) {
        if (responseReq.status == 200) {
            try {
                //Success
                var retrievedUser = JSON.parse(responseReq.responseText).d;
                return retrievedUser;
            }
            catch (e) {
                alert("RetrieveUserRequestCallBack:", e.Message);
            }
        }
        else {
            //Failure
            alert("RetrieveUserRequestCallBack function failure END");
            return null;
        }
    }
}