locked
how to synchronize CRM database with other database? RRS feed

  • Question

  • Hi All,

    I am new to Microsoft Dynamics CRM 4.0.

    I have created one custom entity "Skillset" in CRM.Now i want to store skills of some employees which are there in ESS database in Skillset.

    I have already added the webservice of ESS database in visual studio 2010 and print the Employee name and their skills. Now i want to add these skills to CRM custom entity Skillset. I also want to daily synchronize ESS database and CRM database such that changes in ESS database should update CRM database daily.

    please reply me all the steps to do this and coding if it is there.

    reply in detail.

    Regards,

    Amit


    Amit Kasundra

    Tuesday, February 7, 2012 12:22 PM

Answers

  • Hi Amit,

    In general if you want to do any CRUD functionality in CRM from an external application, you will have to build a custom application by using .Net, CRM SDK and CRM WebService.

    In your scenario you need build a windows service or windows schedule task which will run once in a day and look at the updated/new records in your ESS db, and you need to write some code to connect to your CRM instance by using a CRM account, and create or update the skillset records.

    You need to add the crmdiscoveryservice.wsdl (is available in the SDK) as a web service reference, and build methods to check whether a skillset record exist, if so then retrieve the primary key and update the record, other create a new record.

    You need to read the CRM SDK to get better understanding. Look at the CRM SDK for Web Services: CrmService section, and it has sample code to understand the CRUD functionality

    i have included a serviceutitlity class which creates a CrmService to connect CRM instance by passing organizationName, crmServerUrl, networkUserName, networkPassword, networkDomain

    this class has reference to crm sdk assemblies, also the crmdisconverywebservice reference, when you reference give the name 

    IFD_Authentication.CrmSdk.Discovery

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using Microsoft.Win32;
    using System.Web.Services.Protocols;
    
    using System.Web;
    using System.Web.Security;
    
    using Microsoft.Crm.Sdk;
    using Microsoft.Crm.Sdk.Query;
    using Microsoft.Crm.SdkTypeProxy;
    using Microsoft.Crm.SdkTypeProxy.Metadata;
    
    namespace Oakton.MSCRM.Framework.Utilities
    {
        using IFD_Authentication.CrmSdk.Discovery;
    
        public class ServiceUtiltiy
        {
            public enum enumAuthenticationType
            {
                ActiveDirectory = 0,
                Live = 1,
                IFD = 2
            };
    
            //Not sure the following logic is correct or not?
            public static enumAuthenticationType DetermineOrganizationAuthenticationType(System.Web.HttpContext context)
            {
                enumAuthenticationType authenticationType = enumAuthenticationType.ActiveDirectory;
    
                try
                {
    
                    //On-Premise
                    if (context.User.Identity.AuthenticationType.ToLower() == "negotiate")
                    {
                        authenticationType = enumAuthenticationType.ActiveDirectory;  //AD - 0
                    }
                    else if (context.User.Identity.AuthenticationType.ToLower() == "crmpostauthentication")
                    {
                        //IFD
                        authenticationType = enumAuthenticationType.IFD; //IFD - 2
                    }
    
    
                }
                catch (Exception)
                {
                   
                }
                return authenticationType;
            }
    
            public static CrmService GetIFDConnection(string server, string organization, string username, string password, string domain)
            {
                //Remove any trailing forward slash from the end of the server URL.
                server = server.TrimEnd(new char[] { '/' });
    
                // Initialize an instance of the CrmDiscoveryService Web service proxy.
                CrmDiscoveryService disco = new CrmDiscoveryService();
                disco.Url = server + "/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";
                disco.UseDefaultCredentials = true;
    
                //Retrieve a list of available organizations.
                RetrieveOrganizationsRequest orgRequest =
                    new RetrieveOrganizationsRequest();
    
                //orgRequest.UserId = domain + "\\" + username;
                //orgRequest.Password = password;
    
                RetrieveOrganizationsResponse orgResponse =
                    (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
    
                //Find the desired organization.
                CrmService service = new CrmService();
                foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
                {
                    if (orgdetail.OrganizationName == organization)
                    {
                        //Retrieve the ticket.
                        RetrieveCrmTicketRequest ticketRequest =
                            new RetrieveCrmTicketRequest();
                        ticketRequest.OrganizationName = organization;
                        ticketRequest.UserId = domain + "\\" + username;
                        ticketRequest.Password = password;
                        RetrieveCrmTicketResponse ticketResponse =
                            (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);
    
                        //Create the CrmService Web service proxy.
                        CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
                        sdktoken.AuthenticationType = 2;
                        sdktoken.OrganizationName = organization;
                        sdktoken.CrmTicket = ticketResponse.CrmTicket;
    
                        service.CrmAuthenticationTokenValue = sdktoken;
                        service.Url = orgdetail.CrmServiceUrl;
    
                        //WebApplicationUrl = orgdetail.WebApplicationUrl;
                        //OrganizationId = orgdetail.OrganizationId;
    
                        break;
                    }
                }
    
                return service;
            }
    
            public static CrmService GetCrmService(System.Web.HttpContext context)
            {
                bool online = true;
                string crmUrl;
                string orgName = String.Empty;
                CrmAuthenticationToken token = null;
    
                System.Web.HttpRequest request = context.Request;
                if (request.Url.Host.ToString() == "127.0.0.01")
                {
                    online = false;
                }
    
                if (online)
                {
                    RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
                    string serverUrl = regkey.GetValue("ServerUrl").ToString();
                    crmUrl = serverUrl + "/2007/crmservice.asmx";
                    if (request.QueryString["orgname"] != null)
                    {
                        orgName = request.QueryString["orgname"];
                    }
                    token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(context, orgName);
                }
                else
                {
                    RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
                    orgName = regkey.GetValue("ClientAuthOrganizationName").ToString();
                    string portNumber = regkey.GetValue("CassiniPort").ToString();
    
                    string baseUrl = "http://localhost:" + portNumber + "/mscrmservices/2007/";
                    crmUrl = baseUrl + "crmservice.asmx";
                    token = new CrmAuthenticationToken();
                }
    
                token.OrganizationName = orgName;
                token.AuthenticationType = 0;
    
                CrmService service = new CrmService();
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                service.CrmAuthenticationTokenValue = token;
                service.Url = crmUrl;
                return service;
            }
    
            /// <summary>
            /// Creates a CrmService proxy for plug-ins that execute in the child pipeline
            /// </summary>
            /// <param name="context">The execution context that was passed to the plug-ins Execute method.</</param>
            /// <param name="impersonateUser">Set to True to use impersonation.</param>
            /// <returns>A CrmServce instance.</returns>
            public static CrmService GetCrmService(IPluginExecutionContext context, bool impersonateUser)
            {
                CrmAuthenticationToken authToken = new CrmAuthenticationToken();
                authToken.AuthenticationType = 0;
                authToken.OrganizationName = context.OrganizationName;
    
                // Include support for impersonation.
                if (impersonateUser)
                    authToken.CallerId = context.UserId;
                else
                    authToken.CallerId = context.InitiatingUserId;
    
                CrmService crmService = new CrmService();
                crmService.CrmAuthenticationTokenValue = authToken;
                crmService.UseDefaultCredentials = true;
                crmService.CorrelationTokenValue = new CorrelationToken(context.CorrelationId, context.Depth, context.CorrelationUpdatedTime);
                crmService.Url = String.Concat(GetServerUrlFromRegistry(), "/2007/crmservice.asmx");
                return crmService;
            }
    
            public static CrmService GetCrmService(string organizationName)
            {
                string crmServerUrl = GetServerFromRegistery();
                if (string.IsNullOrEmpty(crmServerUrl)) return null;
                return CrmService_Get(organizationName, crmServerUrl, "", "", "");
            }
    
            /// <summary>
            /// Creates an instance of a CrmService.
            /// </summary>
            /// <param name="organizationName">The name of the CRM organization.</param>
            /// <param name="server">The URL of the CRM server. Path does not need to be included.</param>
            /// <returns>A new CrmService instance.</returns>
            public static CrmService GetCrmService(string organizationName, string crmServerUrl)
            {
                return CrmService_Get(organizationName, crmServerUrl, "", "", "");
            }
    
            /// <summary>
            ///  Creates an instance of a CrmService.
            /// </summary>
            /// <param name="organizationName"></param>
            /// <param name="server"></param>
            /// <param name="networkUserName"></param>
            /// <param name="networkPassword"></param>
            /// <param name="networkDomain"></param>
            /// <returns></returns>
            public static CrmService GetCrmService(string organizationName, string crmServerUrl, string networkUserName, string networkPassword, string networkDomain)
            {
                return CrmService_Get(organizationName, crmServerUrl, networkUserName, networkPassword, networkDomain);
            }
    
            /// <summary>
            /// Creates an instance of a MetadataService.
            /// </summary>
            /// <param name="crmServerUrl">The URL of the CRM server. Path does not need to be included.</param>
            /// <param name="organizationName">The name of the CRM organization.</param>
            /// <returns>A new MetadataService instance.</returns>
            public static MetadataService GetMetadataService(string organizationName, string crmServerUrl)
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.OrganizationName = organizationName;
    
                MetadataService service = new MetadataService();
    
                if (!String.IsNullOrEmpty(crmServerUrl))
                {
                    UriBuilder builder = new UriBuilder(crmServerUrl);
                    builder.Path = "/MSCRMServices/2007/MetadataService.asmx";
                    service.Url = builder.Uri.ToString();
                }
    
                service.UseDefaultCredentials = true;
                service.CrmAuthenticationTokenValue = token;
    
                return service;
            }
    
    
            public static string GetServerUrlFromRegistry()
            {
                using (RegistryKey mscrmKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\MSCRM"))
                {
                    if (mscrmKey != null)
                    {
                        string serverUrl = (string)mscrmKey.GetValue("ServerUrl");
                        if (!String.IsNullOrEmpty(serverUrl))
                        {
                            return serverUrl;
                        }
                    }
                }
    
                using (RegistryKey mscrmKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\MSCRMClient"))
                {
                    if (mscrmKey != null)
                    {
                        string serverUrl = (string)mscrmKey.GetValue("ServerUrl");
                        if (!String.IsNullOrEmpty(serverUrl))
                        {
                            return serverUrl;
                        }
                    }
                }
    
                return String.Empty;
            }
    
            public static string GetDeploymentTypeFromRegistery()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return "ActiveDirectory";
    
                int authMethod = (int)hklm.GetValue("ClientAuthMethod", 0);
    
                hklm.Close();
    
                switch (authMethod)
                {
                    case 0:
                        return "ActiveDirectory";
                    case 1:
                        return "Live";
                    case 2:
                        return "IFD";
    
                    default:
                        return "ActiveDirectory";
                }
    
            }
    
            public static string GetServerFromRegistery()
            {
                RegistryKey hklm = Registry.LocalMachine;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRM", false);
                if (hklm == null)
                {
                    hklm = Registry.CurrentUser;
                    hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
                }
    
                if (hklm == null)
                    return "No Registry";
    
    
                string regServer = (string)hklm.GetValue("ServerUrl", "");
                if (regServer == null)
                    throw new Exception("Unable to get ServerURL key");
                regServer = regServer.Replace(@"/MSCRMServices", "");
                hklm.Close();
    
                return regServer.ToLower();
    
            }
    
            public static string GetOrgFromRegistery()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return "";
    
                string orgName = (string)hklm.GetValue("ClientAuthOrganizationName", "");
    
                hklm.Close();
    
                return orgName;
    
    
            }
    
            public static bool ClientRegisteryExists()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return false;
    
                hklm.Close();
    
                return true;
            }
    
            public static bool ServerRegisteryExists()
            {
                RegistryKey hklm = Registry.LocalMachine;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRM", false);
    
                if (hklm == null)
                    return false;
    
                hklm.Close();
    
                return true;
    
    
            }
    
            private static CrmService CrmService_Get(string organizationName, string server, string networkUserName, string networkPassword, string networkDomain)
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.AuthenticationType = 0; // On-premise
                token.OrganizationName = organizationName;
    
                //Crm Service Object
                CrmService crmService = new CrmService();
                crmService.Url = string.Format("{0}/mscrmservices/2007/crmservice.asmx", server);
                crmService.CrmAuthenticationTokenValue = token;
                
                if (string.IsNullOrEmpty(networkUserName))
                {
                    crmService.UseDefaultCredentials = true;
                    crmService.Credentials = CredentialCache.DefaultCredentials;
                }
                else
                {
                    crmService.Credentials = new NetworkCredential(networkUserName, networkPassword, networkDomain);
                }
                return crmService;
            }
    
            public static Guid Create(object service, DynamicEntity entity)
            {
                Guid resultGuid = Guid.Empty;
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        resultGuid = crmService.Create(entity);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        resultGuid = iCrmService.Create(entity);
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return resultGuid;
            }
    
            public static void Update(object service, DynamicEntity entity)
            {
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        crmService.Update(entity);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        iCrmService.Update(entity);
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            public static void Delete(object service, string entityName,Guid id)
            {
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        crmService.Delete(entityName, id);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        iCrmService.Delete(entityName, id);
    
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
    
        }
    }
    



    Thomas T(MCBMSS) If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".

    Tuesday, February 7, 2012 1:05 PM
  • Created a windows service and schedule it to run on what ever time you want.

    To create a webservice add the reference to ess and crm webservices.

    Then compare the changes and update the system using webservices.

    you may need to add device logic to merge the changes if the reord is changed in both the systems.

    I hope this helps.


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Amreek Singh Senior CRM Consultant CDC Praxa Sydney, Australia http://mscrmshop.blogspot.com http://crm2011usersettings.codeplex.com

    Tuesday, February 7, 2012 12:48 PM
  • You can code this yourself or you can use a tool like Scribe to easily run this type of integration.  You can also have a look at KingsWay SSIS integration tool.  There might be some upfront cost but it should easily be offset by the time you will spend developing, error handling, and maintaining a custom solution.  Here are a few links for your review.

    SSIS Integration

    Scribe Software


    Regards, Donna

    Wednesday, February 8, 2012 12:13 PM

All replies

  • Created a windows service and schedule it to run on what ever time you want.

    To create a webservice add the reference to ess and crm webservices.

    Then compare the changes and update the system using webservices.

    you may need to add device logic to merge the changes if the reord is changed in both the systems.

    I hope this helps.


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Amreek Singh Senior CRM Consultant CDC Praxa Sydney, Australia http://mscrmshop.blogspot.com http://crm2011usersettings.codeplex.com

    Tuesday, February 7, 2012 12:48 PM
  • Hi Amit,

    In general if you want to do any CRUD functionality in CRM from an external application, you will have to build a custom application by using .Net, CRM SDK and CRM WebService.

    In your scenario you need build a windows service or windows schedule task which will run once in a day and look at the updated/new records in your ESS db, and you need to write some code to connect to your CRM instance by using a CRM account, and create or update the skillset records.

    You need to add the crmdiscoveryservice.wsdl (is available in the SDK) as a web service reference, and build methods to check whether a skillset record exist, if so then retrieve the primary key and update the record, other create a new record.

    You need to read the CRM SDK to get better understanding. Look at the CRM SDK for Web Services: CrmService section, and it has sample code to understand the CRUD functionality

    i have included a serviceutitlity class which creates a CrmService to connect CRM instance by passing organizationName, crmServerUrl, networkUserName, networkPassword, networkDomain

    this class has reference to crm sdk assemblies, also the crmdisconverywebservice reference, when you reference give the name 

    IFD_Authentication.CrmSdk.Discovery

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using Microsoft.Win32;
    using System.Web.Services.Protocols;
    
    using System.Web;
    using System.Web.Security;
    
    using Microsoft.Crm.Sdk;
    using Microsoft.Crm.Sdk.Query;
    using Microsoft.Crm.SdkTypeProxy;
    using Microsoft.Crm.SdkTypeProxy.Metadata;
    
    namespace Oakton.MSCRM.Framework.Utilities
    {
        using IFD_Authentication.CrmSdk.Discovery;
    
        public class ServiceUtiltiy
        {
            public enum enumAuthenticationType
            {
                ActiveDirectory = 0,
                Live = 1,
                IFD = 2
            };
    
            //Not sure the following logic is correct or not?
            public static enumAuthenticationType DetermineOrganizationAuthenticationType(System.Web.HttpContext context)
            {
                enumAuthenticationType authenticationType = enumAuthenticationType.ActiveDirectory;
    
                try
                {
    
                    //On-Premise
                    if (context.User.Identity.AuthenticationType.ToLower() == "negotiate")
                    {
                        authenticationType = enumAuthenticationType.ActiveDirectory;  //AD - 0
                    }
                    else if (context.User.Identity.AuthenticationType.ToLower() == "crmpostauthentication")
                    {
                        //IFD
                        authenticationType = enumAuthenticationType.IFD; //IFD - 2
                    }
    
    
                }
                catch (Exception)
                {
                   
                }
                return authenticationType;
            }
    
            public static CrmService GetIFDConnection(string server, string organization, string username, string password, string domain)
            {
                //Remove any trailing forward slash from the end of the server URL.
                server = server.TrimEnd(new char[] { '/' });
    
                // Initialize an instance of the CrmDiscoveryService Web service proxy.
                CrmDiscoveryService disco = new CrmDiscoveryService();
                disco.Url = server + "/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";
                disco.UseDefaultCredentials = true;
    
                //Retrieve a list of available organizations.
                RetrieveOrganizationsRequest orgRequest =
                    new RetrieveOrganizationsRequest();
    
                //orgRequest.UserId = domain + "\\" + username;
                //orgRequest.Password = password;
    
                RetrieveOrganizationsResponse orgResponse =
                    (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
    
                //Find the desired organization.
                CrmService service = new CrmService();
                foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
                {
                    if (orgdetail.OrganizationName == organization)
                    {
                        //Retrieve the ticket.
                        RetrieveCrmTicketRequest ticketRequest =
                            new RetrieveCrmTicketRequest();
                        ticketRequest.OrganizationName = organization;
                        ticketRequest.UserId = domain + "\\" + username;
                        ticketRequest.Password = password;
                        RetrieveCrmTicketResponse ticketResponse =
                            (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);
    
                        //Create the CrmService Web service proxy.
                        CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
                        sdktoken.AuthenticationType = 2;
                        sdktoken.OrganizationName = organization;
                        sdktoken.CrmTicket = ticketResponse.CrmTicket;
    
                        service.CrmAuthenticationTokenValue = sdktoken;
                        service.Url = orgdetail.CrmServiceUrl;
    
                        //WebApplicationUrl = orgdetail.WebApplicationUrl;
                        //OrganizationId = orgdetail.OrganizationId;
    
                        break;
                    }
                }
    
                return service;
            }
    
            public static CrmService GetCrmService(System.Web.HttpContext context)
            {
                bool online = true;
                string crmUrl;
                string orgName = String.Empty;
                CrmAuthenticationToken token = null;
    
                System.Web.HttpRequest request = context.Request;
                if (request.Url.Host.ToString() == "127.0.0.01")
                {
                    online = false;
                }
    
                if (online)
                {
                    RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
                    string serverUrl = regkey.GetValue("ServerUrl").ToString();
                    crmUrl = serverUrl + "/2007/crmservice.asmx";
                    if (request.QueryString["orgname"] != null)
                    {
                        orgName = request.QueryString["orgname"];
                    }
                    token = CrmAuthenticationToken.ExtractCrmAuthenticationToken(context, orgName);
                }
                else
                {
                    RegistryKey regkey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\MSCRMClient");
                    orgName = regkey.GetValue("ClientAuthOrganizationName").ToString();
                    string portNumber = regkey.GetValue("CassiniPort").ToString();
    
                    string baseUrl = "http://localhost:" + portNumber + "/mscrmservices/2007/";
                    crmUrl = baseUrl + "crmservice.asmx";
                    token = new CrmAuthenticationToken();
                }
    
                token.OrganizationName = orgName;
                token.AuthenticationType = 0;
    
                CrmService service = new CrmService();
                service.Credentials = System.Net.CredentialCache.DefaultCredentials;
                service.CrmAuthenticationTokenValue = token;
                service.Url = crmUrl;
                return service;
            }
    
            /// <summary>
            /// Creates a CrmService proxy for plug-ins that execute in the child pipeline
            /// </summary>
            /// <param name="context">The execution context that was passed to the plug-ins Execute method.</</param>
            /// <param name="impersonateUser">Set to True to use impersonation.</param>
            /// <returns>A CrmServce instance.</returns>
            public static CrmService GetCrmService(IPluginExecutionContext context, bool impersonateUser)
            {
                CrmAuthenticationToken authToken = new CrmAuthenticationToken();
                authToken.AuthenticationType = 0;
                authToken.OrganizationName = context.OrganizationName;
    
                // Include support for impersonation.
                if (impersonateUser)
                    authToken.CallerId = context.UserId;
                else
                    authToken.CallerId = context.InitiatingUserId;
    
                CrmService crmService = new CrmService();
                crmService.CrmAuthenticationTokenValue = authToken;
                crmService.UseDefaultCredentials = true;
                crmService.CorrelationTokenValue = new CorrelationToken(context.CorrelationId, context.Depth, context.CorrelationUpdatedTime);
                crmService.Url = String.Concat(GetServerUrlFromRegistry(), "/2007/crmservice.asmx");
                return crmService;
            }
    
            public static CrmService GetCrmService(string organizationName)
            {
                string crmServerUrl = GetServerFromRegistery();
                if (string.IsNullOrEmpty(crmServerUrl)) return null;
                return CrmService_Get(organizationName, crmServerUrl, "", "", "");
            }
    
            /// <summary>
            /// Creates an instance of a CrmService.
            /// </summary>
            /// <param name="organizationName">The name of the CRM organization.</param>
            /// <param name="server">The URL of the CRM server. Path does not need to be included.</param>
            /// <returns>A new CrmService instance.</returns>
            public static CrmService GetCrmService(string organizationName, string crmServerUrl)
            {
                return CrmService_Get(organizationName, crmServerUrl, "", "", "");
            }
    
            /// <summary>
            ///  Creates an instance of a CrmService.
            /// </summary>
            /// <param name="organizationName"></param>
            /// <param name="server"></param>
            /// <param name="networkUserName"></param>
            /// <param name="networkPassword"></param>
            /// <param name="networkDomain"></param>
            /// <returns></returns>
            public static CrmService GetCrmService(string organizationName, string crmServerUrl, string networkUserName, string networkPassword, string networkDomain)
            {
                return CrmService_Get(organizationName, crmServerUrl, networkUserName, networkPassword, networkDomain);
            }
    
            /// <summary>
            /// Creates an instance of a MetadataService.
            /// </summary>
            /// <param name="crmServerUrl">The URL of the CRM server. Path does not need to be included.</param>
            /// <param name="organizationName">The name of the CRM organization.</param>
            /// <returns>A new MetadataService instance.</returns>
            public static MetadataService GetMetadataService(string organizationName, string crmServerUrl)
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.OrganizationName = organizationName;
    
                MetadataService service = new MetadataService();
    
                if (!String.IsNullOrEmpty(crmServerUrl))
                {
                    UriBuilder builder = new UriBuilder(crmServerUrl);
                    builder.Path = "/MSCRMServices/2007/MetadataService.asmx";
                    service.Url = builder.Uri.ToString();
                }
    
                service.UseDefaultCredentials = true;
                service.CrmAuthenticationTokenValue = token;
    
                return service;
            }
    
    
            public static string GetServerUrlFromRegistry()
            {
                using (RegistryKey mscrmKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\MSCRM"))
                {
                    if (mscrmKey != null)
                    {
                        string serverUrl = (string)mscrmKey.GetValue("ServerUrl");
                        if (!String.IsNullOrEmpty(serverUrl))
                        {
                            return serverUrl;
                        }
                    }
                }
    
                using (RegistryKey mscrmKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\MSCRMClient"))
                {
                    if (mscrmKey != null)
                    {
                        string serverUrl = (string)mscrmKey.GetValue("ServerUrl");
                        if (!String.IsNullOrEmpty(serverUrl))
                        {
                            return serverUrl;
                        }
                    }
                }
    
                return String.Empty;
            }
    
            public static string GetDeploymentTypeFromRegistery()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return "ActiveDirectory";
    
                int authMethod = (int)hklm.GetValue("ClientAuthMethod", 0);
    
                hklm.Close();
    
                switch (authMethod)
                {
                    case 0:
                        return "ActiveDirectory";
                    case 1:
                        return "Live";
                    case 2:
                        return "IFD";
    
                    default:
                        return "ActiveDirectory";
                }
    
            }
    
            public static string GetServerFromRegistery()
            {
                RegistryKey hklm = Registry.LocalMachine;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRM", false);
                if (hklm == null)
                {
                    hklm = Registry.CurrentUser;
                    hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
                }
    
                if (hklm == null)
                    return "No Registry";
    
    
                string regServer = (string)hklm.GetValue("ServerUrl", "");
                if (regServer == null)
                    throw new Exception("Unable to get ServerURL key");
                regServer = regServer.Replace(@"/MSCRMServices", "");
                hklm.Close();
    
                return regServer.ToLower();
    
            }
    
            public static string GetOrgFromRegistery()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return "";
    
                string orgName = (string)hklm.GetValue("ClientAuthOrganizationName", "");
    
                hklm.Close();
    
                return orgName;
    
    
            }
    
            public static bool ClientRegisteryExists()
            {
                RegistryKey hklm = Registry.CurrentUser;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRMClient", false);
    
                if (hklm == null)
                    return false;
    
                hklm.Close();
    
                return true;
            }
    
            public static bool ServerRegisteryExists()
            {
                RegistryKey hklm = Registry.LocalMachine;
                hklm = hklm.OpenSubKey("Software\\Microsoft\\MSCRM", false);
    
                if (hklm == null)
                    return false;
    
                hklm.Close();
    
                return true;
    
    
            }
    
            private static CrmService CrmService_Get(string organizationName, string server, string networkUserName, string networkPassword, string networkDomain)
            {
                CrmAuthenticationToken token = new CrmAuthenticationToken();
                token.AuthenticationType = 0; // On-premise
                token.OrganizationName = organizationName;
    
                //Crm Service Object
                CrmService crmService = new CrmService();
                crmService.Url = string.Format("{0}/mscrmservices/2007/crmservice.asmx", server);
                crmService.CrmAuthenticationTokenValue = token;
                
                if (string.IsNullOrEmpty(networkUserName))
                {
                    crmService.UseDefaultCredentials = true;
                    crmService.Credentials = CredentialCache.DefaultCredentials;
                }
                else
                {
                    crmService.Credentials = new NetworkCredential(networkUserName, networkPassword, networkDomain);
                }
                return crmService;
            }
    
            public static Guid Create(object service, DynamicEntity entity)
            {
                Guid resultGuid = Guid.Empty;
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        resultGuid = crmService.Create(entity);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        resultGuid = iCrmService.Create(entity);
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return resultGuid;
            }
    
            public static void Update(object service, DynamicEntity entity)
            {
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        crmService.Update(entity);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        iCrmService.Update(entity);
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
            public static void Delete(object service, string entityName,Guid id)
            {
                try
                {
                    if (service.GetType() == typeof(CrmService))
                    {
                        CrmService crmService = (CrmService)service;
                        crmService.Delete(entityName, id);
                    }
                    else
                    {
                        ICrmService iCrmService = (ICrmService)service;
                        iCrmService.Delete(entityName, id);
    
                    }
                }
                catch (SoapException soEx)
                {
                    throw soEx;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    
    
        }
    }
    



    Thomas T(MCBMSS) If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".

    Tuesday, February 7, 2012 1:05 PM
  • Hi Amreek,

    please describe your steps in some detail as i am new to ms crm 4.0.

    I dont know how to create windows service and schedule it. I also dont know how to compare changes using webservices and how to add device logic to merge the changes.

    I have used one webservice of .svc format from ESS database to display the skills of employees from ESS database in visual studio 2010(added service reference of this webservice in VS 2010). now should i use this webservice to synchronize CRM database to my ESS database ? how?

    please post answer in some detail and post some links that are relevant to my quesion.

    Regards,

    Amit


    Amit Kasundra

    Tuesday, February 7, 2012 1:15 PM
  • hi thomas

    I have done CRUD funtionality successfully with the CRM 4.0.

    thank you for your reply but i am getting one error in this code when i am using

    using WebApplication1.CrmSdk.Discovry;(Here WebApplication1 is my project name)

    in my project and error was : The type or namespace name 'CrmSdk' does not exist in the namespace 'WebApplication1' (are you missing an assembly reference?)

    what i have to do to resolve this error.i have added

    • crmdiscoverywebreference
    • crmwebreference
    • crm.sdk
    • crm.sdk.typeproxy

    do i missing any reference??

    please suggest me any solution...

    Kartik




    Wednesday, February 8, 2012 4:58 AM
  • Hi thomas,

    your code is running successfully but i don't know what is the use of this code.

    what actually done after code is run.

    please explain me.

    Kartik


    Wednesday, February 8, 2012 10:13 AM
  • You can code this yourself or you can use a tool like Scribe to easily run this type of integration.  You can also have a look at KingsWay SSIS integration tool.  There might be some upfront cost but it should easily be offset by the time you will spend developing, error handling, and maintaining a custom solution.  Here are a few links for your review.

    SSIS Integration

    Scribe Software


    Regards, Donna

    Wednesday, February 8, 2012 12:13 PM
  • Hi Thomas,

    your code regards to solution that was suggested by Amreek Singh or any alternative solution for synchronization..??

    I dont understand what this code meant for and how this code can be useful in synchorization of crm database with ess database.

    I have read the Web Services: CrmService section from CRM SDK as u have suggested.but i dont find anything regarding sync with external database.

    So, please explain me in some detail how i can use CrmService for sync with external database and how to update it using CrmService.

    Regards,

    Amit


    Amit Kasundra

    Thursday, February 9, 2012 9:56 AM