Click here to Skip to main content
15,896,063 members
Articles / Programming Languages / C#

Dynamics CRM 4.0 Web Service SDK Example

Rate me:
Please Sign up or sign in to vote.
4.41/5 (9 votes)
11 Nov 2009CPOL4 min read 77.7K   2K   27  
Using Dynamics CRM Web Service to Query & Create User Calendar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrmDiscoveryTester.CrmSdk.Discovery;
using CrmDiscoveryTester.CrmSdk;
/*
 * The purpose of the application is to practice connect - authenticate - query - create entity records operations on a given CRM 
 * Server using CRM 4.0 standard web services programming model.
 * This is a step by step C# Console application that demonestrates :-
 * [1] Establishing a connection with a CRM Server instance.
 * [2] Obtain an instance of the CRM Discovery Web Service authenticating via Active Directory.
 * [3] Locate A target organization, obtain a security token and read the Url for the CRM Web Service.
 * [4] Use CRM Web Service to Execute a Query to Obtain roles assigned to a given user.
 * [5] When that User has a Role of Sales Rep. Then ..
 * [6] Use CRM Web Service to Create a user related work Days and Hours Calendar that is read from an internal Data Structure.
 * Note:-
 * Later on a CRM Workflow custom activity shall execute a system job to call this console application and pass a user login 
 * parameter for automatic creation of a user working Days/hours Calendar triggered when a User role of Sales Rep. is given for the user.
 * */

namespace CrmDiscoveryTester
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Error: Required Parameters [1] Crm Server Login Name [2] Password");
                return 1;
            }
            // Create and configure the CrmDiscoveryService Web service proxy.
                CrmDiscoveryService discoveryService = new CrmDiscoveryService();
                discoveryService.UseDefaultCredentials = true;
                discoveryService.Url = "http://10.0.0.117:5555/MSCRMServices/2007/AD/CrmDiscoveryService.asmx";
            // Retrieve the list of organizations that the logged on user belongs to.
                RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
                orgRequest.UserId = args[0];
                orgRequest.Password = args[1];
                RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);
            // Locate the target organization in the list and Decalre the Security Token to Access CrmService.
                CrmService service = new CrmService();
                CrmAuthenticationToken token = new CrmAuthenticationToken();                
                foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails) // It is only One organization in our case ..
                 {
                    Console.WriteLine("*Organization : " + orgDetail.OrganizationName);
                    token.OrganizationName = orgDetail.OrganizationName; 
                    Console.WriteLine("*Organization Url : " + orgDetail.CrmServiceUrl.Replace("moss", "10.0.0.117"));
                    service.Url = orgDetail.CrmServiceUrl.Replace("moss", "10.0.0.117");
                }
            
            /* Locate Roles Assigned to a given  User .. */

                token.AuthenticationType = 0; // AD authentication Type;
                service.CrmAuthenticationTokenValue = token;
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                // Create, populate a QueryExpression.
                QueryExpression qe = new QueryExpression();
                ConditionExpression ce = new ConditionExpression();
                qe.EntityName = "systemuser";
                ColumnSet cols = new ColumnSet();
                cols.Attributes = new string[] { "systemuserid", "lastname" };
                qe.ColumnSet = cols;

            // The condition is to find the user ID.
                ce.AttributeName = "domainname";
                ce.Operator = ConditionOperator.Equal;
                ce.Values = new object[] { "LITWAREINC\\AymanI" }; /* Hardcoded User Login name should be passed as a parameter*/
                qe.Criteria = new FilterExpression();
                qe.Criteria.Conditions = new ConditionExpression[]{ce};

                /* Next try catch block aims to process entity records to :
                 1 - Read User Record.
                 2 - Find User Roles.
                 3 - Check If User Roles has Salesperson Role name
                 4 - Copies Working Hours to the Specified User from a Data Structure (Can also be read from an XML Data File..) */
                try
                {
                    Guid myUserId = new Guid(); //Dummy initialization
                    BusinessEntityCollection bec = service.RetrieveMultiple(qe);
                    Console.WriteLine("Entity Name = " + bec.EntityName);
                    Console.WriteLine("Entity Count = " + bec.BusinessEntities);
                    foreach (BusinessEntity  refEntity in bec.BusinessEntities)
                    {
                        systemuser myUsers = (systemuser)refEntity;
                        myUserId = myUsers.systemuserid.Value;
                        Console.WriteLine("myUsers.systemuserid: " + myUserId.ToString() );
                        Console.WriteLine("myUsers.lastname: " + myUsers.lastname);
                    }
                    /* Create a QueryExpression to have the new Multi Inner Join Expression between 3 Tables
                     * role, systemuserroles and systemuser 
                    */
                    qe = new QueryExpression();
                    qe.EntityName = "role";
                    qe.ColumnSet = new AllColumns();

                    // Set up the join between the "role" entity and the intersect table "systemuserroles".
                    LinkEntity le = new LinkEntity();
                    le.LinkFromEntityName = "role";
                    le.LinkFromAttributeName = "roleid";
                    le.LinkToEntityName = "systemuserroles";
                    le.LinkToAttributeName = "roleid";

                    // Set up the join between the intersect table "systemuserroles" and the "systemuser" entity.
                    LinkEntity le2 = new LinkEntity();
                    le2.LinkFromEntityName = "systemuserroles";
                    le2.LinkFromAttributeName = "systemuserid";
                    le2.LinkToEntityName = "systemuser";
                    le2.LinkToAttributeName = "systemuserid";

                    // The condition is WHERE user ID = myUserId.
                    ce = new ConditionExpression();
                    ce.AttributeName = "systemuserid";
                    ce.Operator = ConditionOperator.Equal;
                    ce.Values = new object[] { myUserId };

                    le2.LinkCriteria = new FilterExpression();
                    le2.LinkCriteria.Conditions = new ConditionExpression[] { ce };

                    le.LinkEntities = new LinkEntity[] { le2 };
                    qe.LinkEntities = new LinkEntity[] { le };

                    // Execute the query.
                    bec = service.RetrieveMultiple(qe);
                    foreach (BusinessEntity refEntity in bec.BusinessEntities)
                    {
                        role myRoles = (role)refEntity;
                        Console.WriteLine("Role Name: " + myRoles.name);
                        if (myRoles.name.Equals("Salesperson")) /* Now check for a sales person role .. */
                            break;
                        if (bec.MoreRecords == false)
                            return 2;
                    }
                    // Start to Copy working Hours for this User from the internal data structure
                    Console.WriteLine("Copying Working Hours ..");
                    /* ... To be Continued in part 2 of the Code Project Article*/
                    return 0;
                }
                /*
                 * In CRM Web.config Changing the value of <add key="DevErrors" value="Off"/> to <add key="DevErrors" value="On"/>
                 * is a must to have meaningful error details from the catch code..
                 * */
                catch (System.Web.Services.Protocols.SoapException e)
                {
                    Console.WriteLine("Detail = " + e.Detail.InnerText + "\r\nException: " + e.ToString());
                    return 3;
                }

                catch (Exception anyOtherException)
                {
                    Console.WriteLine("Exception: " + anyOtherException.ToString());
                    return 3;
                }
            
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Ayman Soft
Egypt Egypt
With more than 16 years of IT experience, traveled to 6 different countries and worked in many multi-culture environments. Since returning from Sydney To stay in Cairo i have been working for a Microsoft partner in the middle east, focusing on Microsoft Dynamics CRM 4.0 platform, a very interesting business application platform that has state of the art application design and architecture with rich extension tools for developers.
Hope to help some one out there with an idea or a code example .. Smile | :)

Comments and Discussions