Tuesday, August 12, 2014

Simple Console App to connect to MS CRM

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Description;
//using XrmClasses; // Early Binding Classes

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            CreateAccount();
            Console.ReadLine();
        }


        private static void CreateAccount()
        {

            try
            {
                _service = GetCRMService("<CRM Org Service URL>", false, "<UserName>", "<Password>", "<Domain>");

                //Late Binding
                Entity account = new Entity("account");
                account["name"] = "New Account1";
                _service.Create(account);

                //Early Binding
                //Account newAccount = new Account();
                //newAccount.Name = "New Account2";
                //_service.Create(newAccount);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                WriteLog(ex.Message);
            }
        }


        public static IOrganizationService _service = null;

        // GetCRMService for CRM on premises

        public static IOrganizationService GetCRMService(string CrmUrl, string  isDefaultCredential, string UserName, string Password, string Domain)
        {
            if (_service == null)
            {
               
                //string CrmUrl = (ConfigurationManager.AppSettings["CrmUrl"] != null) ? ConfigurationManager.AppSettings["CrmUrl"] : string.Empty;

                //string isDefaultCredential = (ConfigurationManager.AppSettings["DefaultCredential"] != null) ? ConfigurationManager.AppSettings["DefaultCredential"] 
: string.Empty;

                //string Domain = (ConfigurationManager.AppSettings["Domain"] != null) ? ConfigurationManager.AppSettings["Domain"] : string.Empty;

                //string UserName = (ConfigurationManager.AppSettings["Username"] != null) ? ConfigurationManager.AppSettings["Username"] : string.Empty;

                //string Password = (ConfigurationManager.AppSettings["Password"] != null) ? ConfigurationManager.AppSettings["Password"] : string.Empty;

                //CrmUrl += "/XRMServices/2011/Organization.svc";

                ClientCredentials credentials = new ClientCredentials();

                if (isDefaultCredential == "true")
                {
                    credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password) || string.IsNullOrEmpty(Domain))
                    {
                        throw new Exception("Error: Non-default connection requires username, password and domain!");
                    }
                    else
                    {
                        credentials.Windows.ClientCredential = new System.Net.NetworkCredential(UserName, Password, Domain);
                    }

                }

                if (!string.IsNullOrEmpty(CrmUrl) && CrmUrl.Contains("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain,

                   SslPolicyErrors sslPolicyErrors) { return true; };
                }

                OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(CrmUrl), null, credentials, null);
                orgServiceProxy.EnableProxyTypes();
                orgServiceProxy.Timeout = new TimeSpan(0, 10, 0);

                _service = (IOrganizationService)orgServiceProxy;
                return _service;
            }
            else
            {
                return _service;
            }
        }

        // GetCRMService for CRM Online
        public static IOrganizationService GetOnlineService()
        {
            IOrganizationService _service;
           
            var liveIDCreds = new ClientCredentials();
            liveIDCreds.UserName.UserName = "username";

            liveIDCreds.UserName.Password = "password";

            var deviceIDcreds = new ClientCredentials();
            deviceIDcreds.UserName.UserName = "11ltfz36jrxd4sdycpkfk7a0gq";

            deviceIDcreds.UserName.Password = "aeKwQN#c/V`RR!!ObqFA,Pz7";
            OrganizationServiceProxy orgServiceProxy =
new OrganizationServiceProxy(new Uri("orgnizationurl"), null, liveIDCreds, deviceIDcreds);

            orgServiceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
           
            orgServiceProxy.EnableProxyTypes();

            _service = (IOrganizationService)orgServiceProxy;
           
            return _service;
        }
                   
    }
}

static string logFilePath = @"D:\IntegrationLog.txt";

public static void WriteLog(string Message)
        {
            using (StreamWriter sw = new StreamWriter(logFilePath, true))
            {
                sw.WriteLine(Message);
            }

        }

Note:

In AD :-

ClientCredentials clientCredentials=new ClientCredentials();

clientCredentials.Windows.ClientCredential = new NetworkCredential(userName, password,domain);

In IFD :-
clientCredentials.UserName.UserName =domain + @"\" + userName;
clientCredentials.UserName.Password = password;


OrganizationServiceProxy service = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(organizationUri, HomeRealmUri, credentials, null);


for more details: