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.

Wednesday, March 7, 2012

Meta Data Web Service in CRM with Example in 4.0.


Metadata Web Service

This Web Service is the one that provides access to the entire CRM metadata.
A new feature with this version of Microsoft CRM, the metadata can now be used to create, update, or delete entities, as well as create or delete relationships within entities. You can also use it to add, delete, or modify attributes to an existing entity programmatically.
This Web Service can be very useful for ISVs to look up entities on a setup installer to see if the product was already installed or to check whether any conflict exists with the entities of the CRM system on which a customization would be deployed.

The URL for this Web Service reference is
http://<servername>:<portnumber>/MSCrmServices/2007/MetadataService.asmx

For example:
http://crm4:5555/MSCrmServices/2007/MetadataService.asmx

To add a Web Reference for this Web Service, go to Visual Studio 2005 and, using the new console application project you created, right-click the project name in the Solution Explorer and choose Add Web Reference from the menu. Enter the URL of the metadata Web Service, click GO, and then enter CrmSdk.Metadata as the Web Reference Name

Click Add Reference to finally add the Web Service reference to your project.
This Web Service exposes only one method, the Execute method.
Execute Method
This method accepts the following submethods:

CreateAttribute
CreateEntity
CreateManyToMany
CreateOneToMany
DeleteAttribute
DeleteEntity
DeleteOptionValue
DeleteStatusValue
DeleteRelationship
InsertOptionValue
InsertStatusValue
OrderOption
OrderStatus
RetrieveAllEntities
RetrieveAttribute
RetrieveEntity
RetrieveRelationship
RetrieveTimestamp
UpdateAttribute
UpdateEntity
UpdateOptionValue
UpdateStatusValue
UpdateRelationship

Each of these submethods has its own Request and Response classes.
To use the CreateAttribute method, for example, you must create an instance of CreateAttributeRequest, and the Execute method would return an instance of CreateAttributeResponse.
For example, you might use the following code to find out whether the custom entity new_MyNewCustomEntity already exists in a CRM implementation. As with the Main Data Web Service, you will generate a common method to retrieve the Metadata Web Service URL for the organization by using the Discovery Web Service. You will use this method throughout the samples related to the Metadata Web Service.

Example:
namespace MetadataWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(CheckEntity("ORGNAME","account"));
            Console.ReadKey();
        }
        private static bool CheckEntity(string organizationName, string entityName)
        {
            try
            {
                CrmSdk.Metadata.MetadataService myCrm = new CrmSdk.Metadata.MetadataService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.Metadata.CrmAuthenticationToken myToken = new CrmSdk.Metadata.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

                CrmSdk.Metadata.RetrieveEntityRequest myRequest = new CrmSdk.Metadata.RetrieveEntityRequest();
                myRequest.LogicalName = entityName.ToLower();
                CrmSdk.Metadata.RetrieveEntityResponse myResponse;
                myResponse = (CrmSdk.Metadata.RetrieveEntityResponse)myCrm.Execute(myRequest);
                return true;
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString());
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return false;
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "password";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }
    }
}

Above code check that account entity is exist or not.Now Lets see another Example.

private static bool CreateCustomEntity(string organizationName, string entityName)
{
   try
   {

       CrmSdk.Metadata.MetadataService myCrm = new CrmSdk.Metadata.MetadataService();
       myCrm.Url = GetCrmMetadataServiceForOrganization(organizationName);
       CrmSdk.Metadata.CrmAuthenticationToken myToken = new CrmSdk.Metadata.CrmAuthenticationToken();
       myToken.AuthenticationType = 0;
       myToken.OrganizationName = organizationName;
       myCrm.CrmAuthenticationTokenValue = myToken;
       myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

       // Creates new entity
       CrmSdk.Metadata.EntityMetadata myNewEntity = new CrmSdk.Metadata.EntityMetadata();
       myNewEntity.Description = CreateLabel(entityName);
       myNewEntity.DisplayCollectionName = CreateLabel(entityName);
       myNewEntity.DisplayName = CreateLabel(entityName);

       myNewEntity.IsAvailableOffline = new CrmSdk.Metadata.CrmBoolean();
       myNewEntity.IsAvailableOffline.Value = true;
       myNewEntity.DuplicateDetection = new CrmSdk.Metadata.CrmBoolean();
       myNewEntity.DuplicateDetection.Value = true;
       myNewEntity.SchemaName = entityName;
       myNewEntity.LogicalName = entityName;
       myNewEntity.OwnershipType = new CrmSdk.Metadata.CrmOwnershipTypes();
       myNewEntity.OwnershipType.Value = CrmSdk.Metadata.OwnershipTypes.UserOwned;

       // creates primary attribute
       CrmSdk.Metadata.StringAttributeMetadata myPrimaryAttr = new CrmSdk.Metadata.StringAttributeMetadata();
       myPrimaryAttr.DisplayName = CreateLabel("Name");
       myPrimaryAttr.Description = CreateLabel("this is the Name");
       myPrimaryAttr.AttributeType = new CrmSdk.Metadata.CrmAttributeType();
       myPrimaryAttr.AttributeType.Value = CrmSdk.Metadata.AttributeType.String;
       myPrimaryAttr.MaxLength = new CrmSdk.Metadata.CrmNumber();       myPrimaryAttr.MaxLength.Value = 100;
       myPrimaryAttr.SchemaName = "new_Name";
       myPrimaryAttr.Format = new CrmSdk.Metadata.CrmStringFormat();
       myPrimaryAttr.Format.Value = CrmSdk.Metadata.StringFormat.Text;
       myPrimaryAttr.RequiredLevel = new CrmSdk.Metadata.CrmAttributeRequiredLevel();
       myPrimaryAttr.RequiredLevel.Value = CrmSdk.Metadata.AttributeRequiredLevel.Required;
       myPrimaryAttr.DisplayMask = new CrmSdk.Metadata.CrmDisplayMasks();
       myPrimaryAttr.DisplayMask.Value = CrmSdk.Metadata.DisplayMasks.PrimaryName;
       myPrimaryAttr.LogicalName = "new_name";

       // prepare request
       CrmSdk.Metadata.CreateEntityRequest myRequest = new CrmSdk.Metadata.CreateEntityRequest();
       myRequest.Entity = myNewEntity;
       myRequest.HasActivities = true;
       myRequest.HasNotes = true;
       myRequest.PrimaryAttribute = myPrimaryAttr;

       CrmSdk.Metadata.CreateEntityResponse myResponse;
       myResponse = (CrmSdk.Metadata.CreateEntityResponse)myCrm.Execute(myRequest);
       return true;
   }
   catch (System.Web.Services.Protocols.SoapException soapEx)
   {
       Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString());
       return false;
   }
   catch (Exception ex)
   {
       Console.WriteLine("General exception: " + ex.ToString());
       return false;
   }
}

                                        

Note

The code uses a custom method called CreateLabel to simplify the code used to set up the labels; they must be managed in a collection because of the Multilanguage feature. This sample uses only the English language for the strings, but you can easily customize it to use other languages.

private static CrmSdk.Metadata.CrmLabel CreateLabel(string myString)
{
   CrmSdk.Metadata.CrmLabel myLabel = new CrmSdk.Metadata.CrmLabel();
   CrmSdk.Metadata.LocLabel[] myLabels = new CrmSdk.Metadata.LocLabel[1];
   myLabels[0] = new CrmSdk.Metadata.LocLabel();
   myLabels[0].Label = myString;
   myLabels[0].LanguageCode = new CrmSdk.Metadata.CrmNumber();
   myLabels[0].LanguageCode.Value = 1033; // English code
   myLabel.LocLabels = myLabels;
   return myLabel;
}

Now if you want to create a new entity with the name of new_MyNewCustomEntity on the organization with the name Webfortis, you could use the following code:
static void Main(string[] args)
{
        CreateCustomEntity("Webfortis", "new_MyNewCustomEntity");

        Console.ReadKey();
}

Note

Be sure the entity name doesn't already exist in the CRM system, or the Execute method will raise an exception. To be sure, you could use the CheckEntity method you created before and use a code as follows:
static void Main(string[] args)
{
   if (!CheckEntity("Webfortis", "new_MyNewCustomEntity"))
         {
             CreateCustomEntity("Webfortis", "new_MyNewCustomEntity");
         }
    Console.ReadKey();
}

In addition, you must set at least the primary attribute on the request, and this one must be required.

You can also use this Web Service if you want to show all the options from a Picklist attribute on another application.
As another example, imagine that you needed to retrieve all possible values for the Shipping Method property for Accounts. Because the Shipping Method is a Picklist, you would have to query the MetaData to get the values.
This method can be used as follows:
Code View:
private static void GetShippingMethod(string organizationName)
{
    CrmSdk.Metadata.MetadataService myCrm = new CrmSdk.Metadata.MetadataService();
    myCrm.Url = GetCrmMetadataServiceForOrganization(organizationName);
    CrmSdk.Metadata.CrmAuthenticationToken myToken = new CrmSdk.Metadata.CrmAuthenticationToken();
    myToken.AuthenticationType = 0;
    myToken.OrganizationName = organizationName;
    myCrm.CrmAuthenticationTokenValue = myToken;
    myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

    CrmSdk.Metadata.RetrieveAttributeRequest myRequest = new CrmSdk.Metadata.RetrieveAttributeRequest();
    myRequest.EntityLogicalName = CrmSdk.EntityName.account.ToString();
    myRequest.LogicalName = "address1_shippingmethodcode";

    CrmSdk.Metadata.RetrieveAttributeResponse myResponse;
    myResponse = (CrmSdk.Metadata.RetrieveAttributeResponse)
    myCrm.Execute(myRequest);
    foreach (CrmSdk.Metadata.Option myOption in ((CrmSdk.Metadata.PicklistAttributeMetadata)(myResponse.AttributeMetadata)).Options)
    {
        Console.WriteLine(myOption.Label.LocLabels[0].Label);
    }
}

Now if you want to test this method on the organization with the name Webfortis, you could use the following code:
static void Main(string[] args)
{
        GetShippingMethod("Webfortis");
        Console.ReadKey();
}

Tuesday, March 6, 2012

Main Data Web Service in CRM 4.0.


Main Data Service

The other Web Service reference that is necessary for a custom application is the Main Data Web Service:
http://<servername>:<portnumber>/MSCRMServices/2007/CrmServiceWsdl.aspx

For example:
http://crm4:5555/MSCRMServices/2007/CrmServiceWsdl.aspx

To add a Web Reference for this Web Service, Follow same Procedure as Discuss above. Then enter CrmSdk as the Web Reference Name.
Click Add Reference to add the Web Service reference to your project.

This Web Service has the following methods:

Create
Retrieve
RetrieveMultiple
Delete
Execute
Fetch
Update

Create Method

This method is used to create new instances of an existing entity, such as a new Account or Contact.
This method has only one implementation: It returns a Global Unique Identifier (GUID), which is the unique identifier of the new entity record to be created; it accepts one parameter of type BusinessEntity. Because all entities in CRM inherit from the BusinessEntity base class, you can pass any entity class to this input parameter.
This is an example of how to create a new Account record programmatically in Visual Studio 2005 with C#:
Code View:

namespace ConsoleWebService
{
    class MainDataService
    {
        static void Main(string[] args)
        {
            Console.WriteLine("New Account GUID="+CreateAccount("ORGNAME","New Account"));
            Console.ReadKey();
        }

        private static string CreateAccount(string organizationName, string accountName)
        {
            try
            {
            
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;
              
              
                CrmSdk.account newAccount = new CrmSdk.account();
              
                newAccount.name = accountName;
                newAccount.address1_country = "India";
                newAccount.address1_city = "Mumbai";

                CrmSdk.Lookup objLookup=new CrmSdk.Lookup();
                objLookup.type= "account";
                objLookup.Value= new Guid("A8A58DB6-5364-E111-9493-00E04C39161E");
            
                newAccount.parentaccountid = objLookup;
                CrmSdk.Lookup objLookup1 = new CrmSdk.Lookup();
                objLookup1.type = "contact";
                objLookup1.Value = new Guid("1EDE79DD-FC5D-E111-9493-00E04C39161E");

                newAccount.primarycontactid = objLookup1;
                CrmSdk.Picklist pl = new CrmSdk.Picklist();
                pl.name = "address1_addresstypecode";
                pl.Value = 1;
                newAccount.address1_addresstypecode = pl;

            
              
                Guid newAccountId = myCrm.Create(newAccount);
                return newAccountId.ToString();
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + " " + soapEx.ToString());
                return soapEx.Detail.InnerText + "  " + soapEx.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return "General exception: " + ex.ToString();
            }

        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "domainname";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "password";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }

    }
}


 Retrieve Method

This method gets an instance of an entity object. To get more than one instance of an entity, use the RetrieveMultiple method (explained in the next section).
This method returns a class type of BusinessEntity, so it is necessary to cast the returned value to the entity you want to retrieve.
The input parameters are the string of the entity name, the GUID of the instance of the entity, and a set of columns or fields you want to retrieve.
It is important to define the columns you want to retrieve in the last parameter, or you will get null values even though the instance in the CRM system has values.
This is an example of the Retrieve method and Using that I am Retriving the Information of one Account:

Code View:

namespace ConsoleWebService
{
    public class Retrive
    {
        static void Main(string[] args)
        {
            string newAccountId = "A003B5FA-7F67-E111-9493-00E04C39161E";
            Console.WriteLine("Account GUID = " + newAccountId);
            CrmSdk.account acc = new CrmSdk.account();
            acc=RetrieveAccount("ORGNAME", new Guid(newAccountId));
            Console.WriteLine("Name="+acc.name);
            Console.WriteLine("City="+acc.address1_city);
            Console.WriteLine("Country="+acc.address1_country);
        
            Console.ReadKey(); //added for debugging purposes only

        }
      
        private static CrmSdk.account RetrieveAccount(string organizationName, Guid accountId)
        {
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;
                CrmSdk.ColumnSet columns = new CrmSdk.ColumnSet();
                // add more attributes if you want separated by coma below
                columns.Attributes = new string[] { "name", "accountid", "address1_city", "address1_country" };
                Guid myAccountId = accountId;
                CrmSdk.account myAccount =
                (CrmSdk.account)myCrm.Retrieve(CrmSdk.EntityName.account.ToString(),
                                               myAccountId, columns);
                return myAccount;
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                                  + "  " + soapEx.ToString());
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return null;
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12@";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }
    }
}

RetrieveMultiple Method

This method gets one or more than one instance of an entity.
For example, you can use this method to retrieve all the Accounts for an organization, as illustrated here:

namespace ConsoleWebService
{
    class GetAllAccount
    {
        static void Main(string[] args)
        {
            GetAllAccounts("ORGNAME");
            Console.ReadKey(); //added for debugging purposes only
        }
        private static void GetAllAccounts(string organizationName)
        {
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

                // Creates a column set holding the names of the columns to be retreived
                CrmSdk.ColumnSet colsPrincipal = new CrmSdk.ColumnSet();
                // Sets the Column Set's Properties
                colsPrincipal.Attributes = new string[] { "accountid", "name" };

                // Create the Query Expression
                CrmSdk.QueryExpression queryPrincipal = new CrmSdk.QueryExpression();

                // Set the QueryExpression's Properties
                queryPrincipal.EntityName = CrmSdk.EntityName.account.ToString();
                queryPrincipal.ColumnSet = colsPrincipal;

                /// Retrieve the accounts.
                CrmSdk.BusinessEntityCollection myAccounts = myCrm.RetrieveMultiple(
                                                            queryPrincipal);
                Console.WriteLine("\nGetAllAccounts found {0} accounts\n", myAccounts.BusinessEntities.Length);
                foreach (CrmSdk.BusinessEntity myEntity in myAccounts.BusinessEntities)
                {
                    CrmSdk.account myAccount = (CrmSdk.account)myEntity;
                    Console.WriteLine(myAccount.name);
                }
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "password";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }
    }
}

Now Lets Take another Example For example, to retrieve all the Accounts whose names match or start with a selected first letter, use this code:


namespace ConsoleWebService
{
    class MatchAccount
    {
        static void Main(string[] args)
        {
            List<CrmSdk.account> accounts;
            Console.WriteLine("Accounts that starts with the letter N");
            accounts = GetAllAccountsByName("ORGNAME", "N%",
                ConsoleWebService.CrmSdk.ConditionOperator.Like);
            if (accounts == null)
            {
                Console.WriteLine("No accounts found");
            }

            Console.WriteLine("Accounts equal to 'Test Account'");
            accounts = GetAllAccountsByName("ORGNAME", "Test Account",
            ConsoleWebService.CrmSdk.ConditionOperator.Equal);
            if (accounts == null)
            {
                Console.WriteLine("No accounts found");
            }
            Console.ReadKey(); //added for debugging purposes only
        }
        private static List<CrmSdk.account> GetAllAccountsByName(string organizationName,
        string accountName, CrmSdk.ConditionOperator conditionalOperator)
        {
            List<CrmSdk.account> accounts = null;
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

                // Creates a column set holding the names of the columns to be retreived
                CrmSdk.ColumnSet colsPrincipal = new CrmSdk.ColumnSet();
                // Sets the Column Set's Properties
                colsPrincipal.Attributes = new string[] { "accountid", "name" };

                // Create a ConditionExpression
                CrmSdk.ConditionExpression conditionPrincipal =
                                        new CrmSdk.ConditionExpression();

                // Sets the ConditionExpressions Properties so that the condition
                // is true when the ownerid of the account Equals the principalId
                conditionPrincipal.AttributeName = "name";
                conditionPrincipal.Operator = conditionalOperator;
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = accountName;

                // Create the FilterExpression
                CrmSdk.FilterExpression filterPrincipal = new CrmSdk.FilterExpression();

                // Set the FilterExpression's Properties
                filterPrincipal.FilterOperator = CrmSdk.LogicalOperator.And;
                filterPrincipal.Conditions = new CrmSdk.ConditionExpression[] { conditionPrincipal };

                // Create the Query Expression
                CrmSdk.QueryExpression queryPrincipal = new CrmSdk.QueryExpression();

                // Set the QueryExpression's Properties
                queryPrincipal.EntityName = CrmSdk.EntityName.account.ToString();
                queryPrincipal.ColumnSet = colsPrincipal;
                queryPrincipal.Criteria = filterPrincipal;

                /// Retrieve the accounts.
                CrmSdk.BusinessEntityCollection myAccounts = myCrm.RetrieveMultiple(queryPrincipal);
                accounts = new List<ConsoleWebService.CrmSdk.account>();
                Console.WriteLine("\nGetAllAccountsByName found {0} accounts\n", myAccounts.BusinessEntities.Length);
                foreach (CrmSdk.BusinessEntity myEntity in myAccounts.BusinessEntities)
                {
                    CrmSdk.account myAccount = (CrmSdk.account)myEntity;
                    accounts.Add(myAccount);
                    Console.WriteLine(myAccount.name);
                }
                return accounts;
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                                + "  " + soapEx.ToString());
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return null;
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12@";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }

    }
}

Delete Method

This method deletes an existing instance of an entity. This method doesn't return any value and accepts two inputs parameters. The first parameter is a string containing the entity type (you can use the EntityName enumerator here), and the second parameter is the GUID of the instance of the entity you will delete.
This is an example of how to delete a new Account programmatically in Visual Studio 2005 with C#:

Code View:


namespace ConsoleWebService
{
    class Delete
    {
        static void Main(string[] args)
        {
            List<CrmSdk.account> accounts;
            Console.WriteLine("Accounts equal to 'test'");
            accounts = GetAllAccountsByName("ORGNAME", "test",
            ConsoleWebService.CrmSdk.ConditionOperator.Equal);
            if (accounts == null)
            {
                Console.WriteLine("No accounts found");
            }
            else
            {
                foreach (CrmSdk.account myAccount in accounts)
                {

                    Console.WriteLine(
                    DeleteAccount("ORGNAME", myAccount.accountid.Value));
                }
            }
            Console.ReadKey(); //added for debugging purposes only
        }
        private static List<CrmSdk.account> GetAllAccountsByName(string organizationName,
     string accountName, CrmSdk.ConditionOperator conditionalOperator)
        {
            List<CrmSdk.account> accounts = null;
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

                // Creates a column set holding the names of the columns to be retreived
                CrmSdk.ColumnSet colsPrincipal = new CrmSdk.ColumnSet();
                // Sets the Column Set's Properties
                colsPrincipal.Attributes = new string[] { "accountid", "name" };

                // Create a ConditionExpression
                CrmSdk.ConditionExpression conditionPrincipal =
                                        new CrmSdk.ConditionExpression();

                // Sets the ConditionExpressions Properties so that the condition
                // is true when the ownerid of the account Equals the principalId
                conditionPrincipal.AttributeName = "name";
                conditionPrincipal.Operator = conditionalOperator;
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = accountName;

                // Create the FilterExpression
                CrmSdk.FilterExpression filterPrincipal = new CrmSdk.FilterExpression();

                // Set the FilterExpression's Properties
                filterPrincipal.FilterOperator = CrmSdk.LogicalOperator.And;
                filterPrincipal.Conditions = new CrmSdk.ConditionExpression[] { conditionPrincipal };

                // Create the Query Expression
                CrmSdk.QueryExpression queryPrincipal = new CrmSdk.QueryExpression();

                // Set the QueryExpression's Properties
                queryPrincipal.EntityName = CrmSdk.EntityName.account.ToString();
                queryPrincipal.ColumnSet = colsPrincipal;
                queryPrincipal.Criteria = filterPrincipal;

                /// Retrieve the accounts.
                CrmSdk.BusinessEntityCollection myAccounts = myCrm.RetrieveMultiple(queryPrincipal);
                accounts = new List<ConsoleWebService.CrmSdk.account>();
                Console.WriteLine("\nGetAllAccountsByName found {0} accounts\n", myAccounts.BusinessEntities.Length);
                foreach (CrmSdk.BusinessEntity myEntity in myAccounts.BusinessEntities)
                {
                    CrmSdk.account myAccount = (CrmSdk.account)myEntity;
                    accounts.Add(myAccount);
                    Console.WriteLine(myAccount.name);
                }
                return accounts;
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                                + "  " + soapEx.ToString());
                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return null;
            }
        }
      
      
        private static string DeleteAccount(string organizationName, Guid accountToDelete)
        {
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;
                myCrm.Delete(CrmSdk.EntityName.account.ToString(), accountToDelete);
                return "Account successfully deleted";
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                                + "  " + soapEx.ToString());
                return "SOAP exception: " + soapEx.Detail.InnerText
                                + "  " + soapEx.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return "General exception: " + ex.ToString();
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12@";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }

    }

}


Execute Method

This method executes business logic.

It returns a Response object and accepts a parameter as the input of the Request type.
You can use this method as a wildcard for all the other methods. This means that you can create an Account by using this method because the class called CreateRequest derives from Request and can be used as the input parameter; you receive a CreateResponse as the result. The same happens for UpdateRequest, UpdateResponse, RetrieveRequest, and RetrieveResponse.


However, this method is usually used for things you can't do with the other methods. A good example is to use this method, close a CRM Case. Although the Case entity can be updated, you can't update the status by using the Update method. To close a Case, you need to use this method:

Code View:

private static bool CloseCase(string organizationName, Guid caseId)
{
   try
   {
       CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
       myCrm.Url = GetCrmServiceForOrganization(organizationName);
       CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
       myToken.AuthenticationType = 0;
       myToken.OrganizationName = organizationName;
       myCrm.CrmAuthenticationTokenValue = myToken;
       myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

       CrmSdk.incident myIncident = new CrmSdk.incident();
       myIncident.incidentid = new CrmSdk.Key();
       myIncident.incidentid.Value = caseId;

       CrmSdk.incidentresolution myIncidentResolution = new CrmSdk.incidentresolution();
       myIncidentResolution.incidentid = new CrmSdk.Lookup();
       myIncidentResolution.incidentid.type = CrmSdk.EntityName.incident.ToString();
       myIncidentResolution.incidentid.Value = myIncident.incidentid.Value;

       CrmSdk.CloseIncidentRequest closeIncident = new CrmSdk.CloseIncidentRequest();
       closeIncident.IncidentResolution = myIncidentResolution;
       closeIncident.Status = -1;
       myCrm.Execute(closeIncident);
       Console.WriteLine("Case successfully closed ");
       return true;
   }
   catch (System.Web.Services.Protocols.SoapException soapEx)
   {
       Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                         + "  " + soapEx.ToString());
       return false;
   }
   catch (Exception ex)
   {
       Console.WriteLine("General exception: " + ex.ToString());
        return false;
   }
}

                                        
Fetch Method

This method executes a query defined by the FetchXML language.
This method is similar to the RetrieveMultiple method, but it returns a string containing the XML representation of the entities result set.
A few points to remember about the Fetch method:
Fetch does not support a Union join. To view all the tasks for an account by checking all the contacts of a Contact, you need to perform separate Fetch methods—one on the contact tasks and the one on the account contacts—and then merge the results.
The result set of records depends on the user privilege that invokes the Web Service.
Performance is lower than when using Retrieve or RetrieveMultiple methods.
The following code example shows how to use this method to retrieve all contacts with all their properties:

Code View:

private static void GetAllContacts(string organizationName)
{
    try
    {
        CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
        myCrm.Url = GetCrmServiceForOrganization(organizationName);
        CrmSdk.CrmAuthenticationToken myToken = new
CrmSdk.CrmAuthenticationToken();
        myToken.AuthenticationType = 0;
        myToken.OrganizationName = organizationName;
        myCrm.CrmAuthenticationTokenValue = myToken;
        myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

        // Retrieve all Contacts.
        StringBuilder fetchStr = new StringBuilder();
        fetchStr.Append(@"<fetch mapping='logical'>");
        fetchStr.Append(@"<entity name='contact'><all-attributes/>");
        fetchStr.Append(@"</entity></fetch>");

        // Fetch the results.
        String resultXML = myCrm.Fetch(fetchStr.ToString());

        System.Xml.XmlDocument myXMLDoc = new System.Xml.XmlDocument();
        myXMLDoc.LoadXml(resultXML);
        System.Xml.XmlNodeList myNodeList = myXMLDoc.GetElementsByTagName ("fullname");
        Console.WriteLine("\nGetAllContacts found {0} contacts\n", myNodeList.Count);
        foreach (System.Xml.XmlNode myNode in myNodeList)
        {
            Console.WriteLine("Contact fullname = {0}", myNode.InnerText);
        }
    }
    catch (System.Web.Services.Protocols.SoapException soapEx)
    {
        Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                         + "  " + soapEx.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine("General exception: " + ex.ToString());
    }
}



Update Method

This method updates data related to an instance of an entity.
This method has only one implementation and doesn't return a value. In the same way as the Create method, it accepts one parameter of type BusinessEntity. Because all the entities in CRM inherit from the BusinessEntity base class, you can pass any entity class to this input parameter. To use this method, you must set at least the ID property of the entity to be updated. For example, you would set the accountid property if you wanted to update an account.
This is an example of how to update an existing Account programmatically in Visual Studio 2005 with C#:

Code View

namespace ConsoleWebService
{
    class Update
    {
        static void Main(string[] args)
        {
            UpdateAccountName("GTLDEV", new Guid("B4C606E9-9067-E111-9493-00E04C39161E"), "test");
            Console.ReadKey(); //added for debugging purposes only
        }
        private static string UpdateAccountName(string organizationName, Guid accountId, string newName)
        {
            try
            {
                CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
                myCrm.Url = GetCrmServiceForOrganization(organizationName);
                CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
                myToken.AuthenticationType = 0;
                myToken.OrganizationName = organizationName;
                myCrm.CrmAuthenticationTokenValue = myToken;
                myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

                CrmSdk.account myAcoount = new CrmSdk.account();
                myAcoount.accountid = new CrmSdk.Key();
                myAcoount.accountid.Value = accountId;
                myAcoount.name = newName;
                myCrm.Update(myAcoount);
   Console.WriteLine("Account successfully updated");

                return "Account successfully updated ";
            }
            catch (System.Web.Services.Protocols.SoapException soapEx)
            {
                Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText
                               + "  " + soapEx.ToString());
                return "SOAP exception: " + soapEx.Detail.InnerText
                               + "  " + soapEx.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine("General exception: " + ex.ToString());
                return "General exception: " + ex.ToString();
            }
        }
        private static string GetCrmServiceForOrganization(string organizationName)
        {
            string urlResult = "";
            CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();

            //myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
            System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
            System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12@";
            myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();

            CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
            foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
            {
                Console.WriteLine("Organization = " + tDetail.OrganizationName);
                if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
                {
                    return tDetail.CrmServiceUrl;
                }
            }
            return urlResult;

        }

    }
}
Note that only the properties you set are updated. This means that, in the previous example, only the company name property will be changed and the other properties will keep their values. This happens even though they are not set and they have null values when sending them to the Update method.


Note
Remember to always replace ORGNAME with your organization name.

The Meta Data WebService will be Discuss in my Next Post.