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.

1 comment:

  1. I love ur simple codes.. I refer to ur website wen i hav to begin wid a particular technology.. bt the bookish definitions dont suit ur simple website.. u cud actually explain all the definitions in a layman terms so tat its easy fr freshers lik me to learn theory as well frm ur site.. Awsome site!!! thank you so much. Beyondweb Technologies is one of the top leading mobile app development companies in Bangalore, offering the best customised android and iOS app development services in Bangalore. Visit our official website https://www.beyondweb.ind.in/ for more info.

    ReplyDelete