Friday, June 29, 2012

Javascript in CRM 2011


JavaScript events are related to forms and the controls inside the forms only. Each form has two events OnLoad and OnSave events, which can accept JavaScript (shown in Figure). Each field also has the OnChange event, which can accept JavaScript.

Form Event(Entity Event)


Field Event in Form

                                        
Now lets see details about these three Events

OnLoad
The OnLoad event occurs every time the window of an entity(Form) is open, either when you edit an existing record or when you create a new one.

OnSave
The OnSave event occurs every time the Save icon or the Save and Close button is pressed.

OnChange
The OnChange event is fired every time the value of the field is changed and after it loses the focus.


Now Lets see the the Javascript Example in CRM

In CRM you can add the event like onkeypress, onkeyup, or onkeydown events

Suppose that you have a custom entity called House to which you have added the following custom fields: width, height, and area. You want to have the area automatically calculated from the width and height without forcing the user to move the focus from one control to the other to see the changes. You could add the following piece of code in the OnLoad event to attach a field control to the standard onkeyup event:

To see this sample working, follow these steps:

 1.  Go to Settings, Customizations, Customize Entities.

 2.  Click New to create a new entity.

 3.  Enter House in the Display Name field and Houses in the Plural Name field.

 4.  Click Save  and Close

 5.Now click on House Entity and click on Main Form.

 6.Add Three Field and Height,width and Area and  put into the Form with Floating Point Number as a Type.
7.Create a .Js File and add the Following code.
  
  function doCalc ()
  {
crmForm.all.new_area.value = crmForm.all.new_height.value *
crmForm.all.new_width.value;
   }

8.Now go to settings->customization->Customize the System -> from left menu select the Web Resources->New->write Name(calcarea)->under Type select Script(Jscript) and Upload a File and Save it.



9.Now go to House Entity and open Main Form and select the Form Properties and Add Form Libraries First.and you will find new_calcarea Library and add it.
  
8.Then below it Select Form Control and select OnLoad Event.Now Add it.specify Name doCalc.
9.Then Select Height Control and Select OnChange Event and Add the Javascript name(doCalc) for it.
10.do the same Step for Width Control
11.Click Ok and publish entity and open the House Entity.First it will show 0 in Area Field and Type width and Height it will calculate the area.

Now open the Entity and just type width and Height.It will automatically calculate the Area.

Final Output


Wednesday, June 20, 2012

Assign Owner to Account in CRM 2011


Introduction:

  Here I am Posting how to assign/Change a Owner to any account.

Here The First step will find the account to which the owner to set.after finding it pass the Guid of the new owner to the AssignRequest.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Collections;
using System.ServiceModel.Description;
using System.ServiceModel;

    public class Setowner
    {
        private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;


        static public void Main(string[] args)
        {
            Setowner p = new Setowner();
            p.Settingowner();
            Console.WriteLine("Owner set");
            Console.ReadKey();
        }

        private void Settingowner()
        {
            try
            {
                string file = "SetOwner.txt";
                GetCRMService();
              
                //Find the account to which the owner has to set
                var query = from a in orgContext.CreateQuery("account")
                            where (String)a["name"] == "manish"
                            select a["accountid"];
                foreach (var accid in query)
                {

                    try
                    {
                        AssignRequest assign = new AssignRequest
                        {

                            //systemuser; i.e., User to whome you are assigning the entity to
                            //Current record which you are assigning to the user
                            Assignee = new EntityReference("systemuser", GetOwnerId("Dinesh Desai")),
                            Target = new EntityReference("account", new Guid(accid.ToString()))

                        };

                        // Execute the Request
                        _service.Execute(assign);
                        File.AppendAllLines(file, new string[] { "Assigned" });

                    }
                    catch (FaultException ex)
                    {
                        File.AppendAllLines("Error.txt", new string[] { "manish" + ":" + (ex.InnerException == null ? ex.Message : ex.InnerException.Message) });
                    }
                }
            }

            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    
       // This Method will Find the Guid of the Owner
        private Guid GetOwnerId(string owner)
        {
            Guid OwnerId = Guid.Empty;

            var query = from a in orgContext.CreateQuery("systemuser")
                        where (String)a["fullname"] == owner.Trim()
                        select a["systemuserid"];

            foreach (var id in query)
            {
                OwnerId = new Guid(id.ToString());
            }

            return OwnerId;
        }

       //For connection to CRM
        private static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

            


          
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Kartik");
            
              
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri,credential, null);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }
}


GetCRMService()-This Method is For Setting up with CRM.That includes credential+CRM Url etc.
Settingowner():-This Method will be For setting the Owner to any account
GetOwnerId():-This Method is For Finding the Guid Of the new owner for account.

Same way you can set the Owner for any Entity You have to just set the Target in Settingowner() Method.
Here I take "account" in Target.Because we are setting the owner in account if you want to set it in contact then you just need to specify "contact" in place of  "account".


Download the Sample Code from Here
 Download

Insert Account Record in Account Entity in MS CRM 2011


Introduction:

      Here I am going to show how to insert account into CRM 2011.
      First you have to Add the appropriate Reference Dll for CRM.Add Reference microsoft.crm.sdk.proxy,microsoft.xrm.sdk,System.Servicemodel,System.EnterpriceService,System.Web.Services etc

       Here I am insering the account in CRM.I am insering the name,parent account and Email Address to CRM.As we know that Parent account is the Lookup value and to set the Look up value we need top find the Id of it and then need to insert it.so to set the Parent Account I need to Find the accountid of Account and then have to set.so I have Created on Method here that will Find the account id of the parent account.Here i am just inserting three value name,parent account and Email Address.but you can insert more if you want just need to set it.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Collections;
using System.ServiceModel.Description;
using System.ServiceModel;

 private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;


        static public void Main(string[] args)
        {
            SampleTest p = new SampleTest();
            p.InsertAccount();
            Console.WriteLine("Inserted");
            Console.ReadKey();
        }

        private void InsertAccount()
        {
            try
            {
                string file = "insertlead.txt";
                GetCRMService();
                Entity entity = new Entity("account");
                entity["name"] = "Manish";
                entity["parentaccountid"] = new EntityReference("account", GetParentaccountid("dinesh"));//GetParentaccountid("Kartik"));
                entity["emailaddress1"] = "manish@gmail.com";
                _service.Create(entity);
                File.AppendAllLines(file, new string[] { entity["name"].ToString() });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }

        private Guid GetParentaccountid(string accountname)
        {
            Guid accountid = Guid.Empty;
            var querry = (from a in orgContext.CreateQuery("account") where (string)a["name"] == accountname select a["accountid"]).SingleOrDefault();
            accountid = new Guid(querry.ToString());
            //foreach (var k in querry)
            //{
            //    accountid = new Guid(querry.ToString());
            //}
            return accountid;
        }

        private static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

            
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Kartik");
          
            
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }
}

Download the Sample Code from Here
 Download

Friday, June 15, 2012

Getting an Error while using Online CRM 2011 Value cannot be null.Parameter name: DeviceCredentials


Introduction:

                    I am using CRM 2011 online and facing the Problem of  Value cannot be null.Parameter name: DeviceCredentials.i used the Following code.

ClientCredentials credential = new ClientCredentials();
credential.Windows.ClientCredential = new NetworkCredential("liveid@hotmail.com", "password", "Kartik");
_serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);
_serviceProxy.EnableProxyTypes();
_service = (IOrganizationService)_serviceProxy;
orgContext = new OrganizationServiceContext(_serviceProxy);

If you facing the above problem then use the following code for that.

  var deviceIDcreds = new ClientCredentials();
  deviceIDcreds.UserName.UserName = "11pqlm4ldg5nqps9b4ivlngbfv";
  deviceIDcreds.UserName.Password = "J-n60IBG7h;Ga`b5##SsDQhP";

  var liveIDCreds = new ClientCredentials();
  liveIDCreds.UserName.UserName = "liveid@hotmail.com";
  liveIDCreds.UserName.Password = "password";

 _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, liveIDCreds, deviceIDcreds);
_serviceProxy.EnableProxyTypes();
_service = (IOrganizationService)_serviceProxy;
orgContext = new OrganizationServiceContext(_serviceProxy);

Hope this will help you.