public static List <string> GetOrganizations(string url, string domain, string username, string password)
        {
            var results = new List <string>()
            {
            };
            var credentials = GetCredentials(url, domain, username, password);
            ClientCredentials deviceCredentials = null;

            if (url.IndexOf("dynamics.com", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                deviceCredentials = DeviceIdManager.LoadOrRegisterDevice(new Guid());   // TODO this was failing with some online connections
            }

            using (DiscoveryServiceProxy disco = new DiscoveryServiceProxy(new Uri(url), null, credentials, deviceCredentials))
            {
                if (disco != null)
                {
                    OrganizationDetailCollection orgs = DiscoverOrganizations(disco);
                    if (orgs.Count > 0)
                    {
                        results = orgs.Select(o => o.FriendlyName).ToList();
                    }
                }
            }

            return(results);
        }
예제 #2
0
파일: Program.cs 프로젝트: mpkg/Trading
        private static IOrganizationService CreateService()
        {
            ClientCredentials Credentials        = new ClientCredentials();
            ClientCredentials devivceCredentials = new ClientCredentials();

            Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

            //This URL needs to be updated to match the servername and Organization for the environment.

            //The following URLs should be used to access the Organization service(SOAP endpoint):
            //https://{Organization Name}.api.crm.dynamics.com/XrmServices/2011/Organization.svc (North America)
            //https://{Organization Name}.api.crm4.dynamics.com/XrmServices/2011/Organization.svc (EMEA)
            //https://{Organization Name}.api.crm5.dynamics.com/XrmServices/2011/Organization.svc (APAC)

            Uri OrganizationUri = new Uri("https://unizap.api.crm5.dynamics.com/XRMServices/2011/Organization.svc");  //Here I am using APAC.

            Uri HomeRealmUri = null;

            //To get device id and password.
            //Online: For online version, we need to call this method to get device id.
            devivceCredentials = DeviceIdManager.LoadDeviceCredentials();

            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, devivceCredentials))
            {
                serviceProxy.ClientCredentials.UserName.UserName = "******"; // Your Online username.Eg:[email protected]";
                serviceProxy.ClientCredentials.UserName.Password = "******";          //Your Online password
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                _service = (IOrganizationService)serviceProxy;
            }
            return(_service);
        }
예제 #3
0
        //CrmServiceClient를 사용하여 Microsoft Dynamics 365(온라인 및 온-프레미스) 웹 서비스에 연결한다.
        /// <summary>
        /// Deprecated (Ws-Trust)
        /// connect to the Organization service.
        /// Connect to the Microsoft Dynamics 365 (online & on-premises) web service using the CrmServiceClient
        /// </summary>
        /// <see cref="https://msdn.microsoft.com/en-us/library/jj602970.aspx"/>
        /// <seealso cref="https://rajeevpentyala.com/2016/12/11/code-snippet-connect-to-dynamics-crm-using-organization-service-c/"/>
        /// <param name="connectionString">Provides service connection information</param>
        /// <param name="orgName"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="location"></param>
        public Guid ConnectService(string orgName, string userName, string password, Definition.Enum.Location location)
        {
            var uri = new System.Uri($"https://{orgName}.api.crm{location.GetStringValue()}.dynamics.com/XRMServices/2011/Organization.svc");

            //기본인증정보 설정.
            if (!string.IsNullOrEmpty(userName) || !string.IsNullOrEmpty(password))
            {
                if (ClientCredentials == null)
                {
                    ClientCredentials = new ClientCredentials();
                }
                ClientCredentials.UserName.UserName = userName;
                ClientCredentials.UserName.Password = password;
            }

            if (_deviceCredentials == null)
            {
                _deviceCredentials = DeviceIdManager.LoadOrRegisterDevice();
            }

            var organizationServiceProxy = new OrganizationServiceProxy(uri, null, ClientCredentials, _deviceCredentials);

            Service = new CrmServiceClient(organizationServiceProxy);

            return(((WhoAmIResponse)Service.Execute(new WhoAmIRequest())).UserId);
        }
예제 #4
0
        public string GetDiscoveryCrmConnectionString()
        {
            //var connectionString = string.Format("Url={0}://{1}:{2};",
            //    UseSsl ? "https" : "http",
            //    UseIfd ? ServerName : UseOsdp ? "disco." + ServerName : UseOnline ? "" + ServerName : ServerName,
            //    ServerPort.Length == 0 ? (UseSsl ? 443 : 80) : int.Parse(ServerPort));
            var connectionString = string.Format("Url={0}://{1};",
                                                 UseSsl ? "https" : "http",
                                                 UseIfd ? ServerName : UseOsdp ? "disco." + ServerName : UseOnline ? "" + ServerName : ServerName);

            if (IsCustomAuth)
            {
                if (!UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        connectionString += string.Format("Domain={0};", UserDomain);
                    }
                }

                string username = UserName;
                if (UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        username = string.Format("{0}\\{1}", UserDomain, UserName);
                    }
                }

                connectionString += string.Format("Username={0};Password={1};", username, UserPassword);
            }

            if (UseOnline && !UseOsdp)
            {
                ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl);
            }

            return(connectionString);
        }
        private void btnGo_Click(object sender, RoutedEventArgs e)
        {
            var progress = new ProgressDialog
            {
                Title         = "Connect to Microsoft Dynamics CRM Server",
                Indeterminate = true,
                CaptionText   = "Retrieving authentication settings...",
                Owner         = (NavigationWindow)Parent
            };

            var worker = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };

            progress.Cancel += GetCancel(worker);

            worker.DoWork += (s, args) =>
            {
                Uri uri;

                if (Uri.TryCreate(args.Argument as string, UriKind.Absolute, out uri))
                {
                    var config = CreateServiceConfiguration(uri);

                    if (config != null)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                        {
                            _connectionData.AuthenticationType = (AuthenticationTypeCode)(int)config.AuthenticationType;

                            _connectionData.IntegratedEnabled = config.AuthenticationType == AuthenticationProviderType.ActiveDirectory;
                            _connectionData.Domain            = string.Empty;
                            _connectionData.Username          = string.Empty;
                            _connectionData.FormPassword      = string.Empty;

                            if (config.AuthenticationType == AuthenticationProviderType.LiveId)
                            {
                                var deviceCredentials = DeviceIdManager.LoadDeviceCredentials();

                                if (deviceCredentials != null)
                                {
                                    var deviceId             = deviceCredentials.UserName.UserName ?? string.Empty;
                                    _connectionData.DeviceId = deviceId.StartsWith(DeviceIdManager.DevicePrefix) & deviceId.Length > DeviceIdManager.MaxDeviceNameLength
                                                                                ? deviceId.Substring(DeviceIdManager.DevicePrefix.Length)
                                                                                : deviceId;
                                    _connectionData.DevicePassword = deviceCredentials.UserName.Password ?? string.Empty;
                                }
                            }
                        }));
                    }
                }
            };

            worker.RunWorkerCompleted += GetWorkerCompleted(progress, "Failed to retrieve authentication settings.");

            worker.RunWorkerAsync(txtServerUrl.Text);

            progress.ShowDialog();
        }
        private void AuthenticateLiveIdCredentials(ClientCredentials clientCredentials)
        {
            var deviceCredentials = this.ServiceManagement.IssuerEndpoints.ContainsKey("Username")
                ? DeviceIdManager.LoadOrRegisterDevice(this.ServiceManagement.IssuerEndpoints["Username"].IssuerAddress.Uri)
                : DeviceIdManager.LoadOrRegisterDevice();

            AuthenticateLiveIdCredentials(clientCredentials, deviceCredentials);
        }
예제 #7
0
        /// <summary>
        /// Prepare and authenticate client credentials and supporting device credentials for LiveID scenario
        /// </summary>
        /// <param name="clientCredentials">The client credentials (Microsoft Account)</param>
        /// <remarks>Implicitly registers device credentials using deviceidmanager.cs helper</remarks>
        private void AuthenticateLiveIdCredentials(ClientCredentials clientCredentials)
        {
            //Attempt to call .LoadOrRegisterDevice using IssuerEndpoint to load existing and/or persist to file.
            var deviceCredentials = this.ServiceManagement.IssuerEndpoints.ContainsKey("Username")
                ? DeviceIdManager.LoadOrRegisterDevice(this.ServiceManagement.IssuerEndpoints["Username"].IssuerAddress.Uri)
                : DeviceIdManager.LoadOrRegisterDevice();

            AuthenticateLiveIdCredentials(clientCredentials, deviceCredentials);
        }
예제 #8
0
        public string GetDiscoveryCrmConnectionString()
        {
            var connectionString = string.Format("Url={0}://{1}:{2};",
                                                 UseSSL ? "https" : "http",
                                                 UseIFD ? ServerName : UseOffice365 ? "disco." + ServerName : UseOnline ? "dev." + ServerName : ServerName,
                                                 ServerPort.Length == 0 ? (UseSSL ? 443 : 80) : int.Parse(ServerPort));

            if (!UseWindowsAuth)
            {
                if (!UseIFD)
                {
                    if (!string.IsNullOrEmpty(Domain))
                    {
                        connectionString += string.Format("Domain={0};", Domain);
                    }
                }

                string sUsername = Username;
                if (UseIFD)
                {
                    if (!string.IsNullOrEmpty(Domain))
                    {
                        sUsername = string.Format("{0}\\{1}", Domain, Username);
                    }
                }

                connectionString += string.Format("Username={0};Password={1};", sUsername, Password);
            }

            if (UseOnline && !UseOffice365)
            {
                System.ServiceModel.Description.ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIFD && !string.IsNullOrEmpty(HomeRealm))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealm);
            }

            return(connectionString);
        }
예제 #9
0
        /// <summary>
        /// Authenticates the device token
        /// </summary>
        /// <returns>Generated SecurityTokenResponse for the device</returns>
        public SecurityTokenResponse AuthenticateDevice()
        {
            if (null == this._deviceCredentials)
            {
                this._deviceCredentials = DeviceIdManager.LoadOrRegisterDevice(
                    this._proxy.ServiceConfiguration.CurrentIssuer.IssuerAddress.Uri);
            }

            return(this._proxy.ServiceConfiguration.AuthenticateDevice(this._deviceCredentials));
        }
예제 #10
0
        /// <summary>
        /// Obtain the AuthenticationCredentials based on AuthenticationProviderType.
        /// </summary>
        /// <param name="service">A service management object.</param>
        /// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param>
        /// <returns>Get filled credentials.</returns>
        private AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType)
        {
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            _userName = username.Text;
            _password = txtPassword.Text;

            switch (endpointType)
            {
            case AuthenticationProviderType.ActiveDirectory:
                authCredentials.ClientCredentials.Windows.ClientCredential =
                    new System.Net.NetworkCredential(_userName,
                                                     _password,
                                                     _domain);
                break;

            case AuthenticationProviderType.LiveId:
                authCredentials.ClientCredentials.UserName.UserName = _userName;
                authCredentials.ClientCredentials.UserName.Password = _password;
                authCredentials.SupportingCredentials = new AuthenticationCredentials();
                //authCredentials.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                break;

            default:     // For Federated and OnlineFederated environments.
                authCredentials.ClientCredentials.UserName.UserName = _userName;
                authCredentials.ClientCredentials.UserName.Password = _password;
                // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.
                // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  // Windows Kerberos

                // The service is configured for User Id authentication, but the user might provide Microsoft
                // account credentials. If so, the supporting credentials must contain the device credentials.
                if (endpointType == AuthenticationProviderType.OnlineFederation)
                {
                    IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName);
                    if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId)
                    {
                        authCredentials.SupportingCredentials = new AuthenticationCredentials();
                        //authCredentials.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                        authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice();
                    }
                }

                break;
            }

            return(authCredentials);
        }
예제 #11
0
        /// <summary>
        /// Obtain the AuthenticationCredentials based on AuthenticationProviderType.
        /// </summary>
        /// <see href="https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/sample-authenticate-users-web-services"/>
        /// <typeparam name="TService"></typeparam>
        /// <param name="service">A service management object.</param>
        /// <param name="endpointType">An <code>AuthenticationProviderType</code> of the CRM environment.</param>
        /// <param name="userid"></param>
        /// <param name="userpw"></param>
        /// <param name="domain"></param>
        /// <returns>Get filled <code>AuthenticationCredentials</code>.</returns>
        public AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service,
                                                                   AuthenticationProviderType endpointType, string userid, string userpw, string domain)
        {
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            switch (endpointType)
            {
            case AuthenticationProviderType.ActiveDirectory:
                authCredentials.ClientCredentials.Windows.ClientCredential = new NetworkCredential(userid, userpw, domain);
                break;

            case AuthenticationProviderType.LiveId:
                authCredentials.ClientCredentials.UserName.UserName = userid;
                authCredentials.ClientCredentials.UserName.Password = userpw;
                authCredentials.SupportingCredentials = new AuthenticationCredentials();
                authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice();
                break;

            case AuthenticationProviderType.Federation:
            case AuthenticationProviderType.None:
                break;

            case AuthenticationProviderType.OnlineFederation:
                // For Federated and OnlineFederated environments.
                authCredentials.ClientCredentials.UserName.UserName = userid;
                authCredentials.ClientCredentials.UserName.Password = userpw;
                // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.
                // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  // Windows Kerberos

                // The service is configured for User Id authentication, but the user might provide Microsoft
                // account credentials. If so, the supporting credentials must contain the device credentials.

                IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName);
                if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId)
                {
                    authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    authCredentials.SupportingCredentials.ClientCredentials =
                        DeviceIdManager.LoadOrRegisterDevice();
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(endpointType), endpointType, null);
            }

            return(authCredentials);
        }
        public static IOrganizationService Connect(string url, string domain, string username, string password, string organization)
        {
            //var connectionString = @"Url=" + url + "; Username="******"; password="******";";
            //var connection = new Microsoft.Xrm.Client.CrmConnection(connectionString);
            //var test = new Microsoft.Xrm.Client.Services.OrganizationService(connection);
            //return test;

            var credentials = GetCredentials(url, domain, username, password);
            ClientCredentials deviceCredentials = null;

            if (url.IndexOf("dynamics.com", StringComparison.InvariantCultureIgnoreCase) > -1)
            {
                deviceCredentials = DeviceIdManager.LoadOrRegisterDevice(new Guid());
            }

            Uri orgUri = null;
            OrganizationServiceProxy sdk = null;

            using (DiscoveryServiceProxy disco = new DiscoveryServiceProxy(new Uri(url), null, credentials, deviceCredentials))
            {
                if (disco != null)
                {
                    OrganizationDetailCollection orgs = DiscoverOrganizations(disco);
                    if (orgs.Count > 0)
                    {
                        var found = orgs.ToList()
                                    .Where(a => a.UniqueName.Equals(organization, StringComparison.InvariantCultureIgnoreCase))
                                    .Take(1).SingleOrDefault();

                        if (found != null)
                        {
                            orgUri = new Uri(found.Endpoints[EndpointType.OrganizationService]);
                        }
                    }
                }
            }

            if (orgUri != null)
            {
                sdk = new OrganizationServiceProxy(orgUri, null, credentials, deviceCredentials);
            }

            return(sdk);
        }
예제 #13
0
        public static OrganizationServiceProxy GetOrganizationServiceProxy(ConnectionDetail detail)
        {
            var    serviceUrl   = detail.OrganizationServiceUrl;
            string homeRealmUrl = null;

            ClientCredentials clientCredentials = new ClientCredentials();
            ClientCredentials deviceCredentials = null;

            if (detail.IsCustomAuth)
            {
                string username = detail.UserName;
                if (!string.IsNullOrEmpty(detail.UserDomain))
                {
                    username = $"{detail.UserDomain}\\{detail.UserName}";
                }
                clientCredentials.UserName.UserName = username;
                clientCredentials.UserName.Password = detail.UserPassword;
            }

            if (detail.UseOnline && !detail.UseOsdp)
            {
                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));
            }

            if (detail.UseIfd && !string.IsNullOrEmpty(detail.HomeRealmUrl))
            {
                homeRealmUrl = detail.HomeRealmUrl;
            }

            Uri serviceUri   = new Uri(serviceUrl);
            Uri homeRealmUri = homeRealmUrl == null ? null : Uri.IsWellFormedUriString(homeRealmUrl, UriKind.RelativeOrAbsolute) ? new Uri(homeRealmUrl) : null;

            return(new OrganizationServiceProxy(serviceUri, homeRealmUri, clientCredentials, deviceCredentials));
        }
예제 #14
0
        /// <summary>
        /// DepreCated (WS-Trust)
        /// Set clientCredential and Connect Server by Client using OrganizationServiceProxy to Custom URL
        /// </summary>
        /// <param name="organizationServiceUri"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Guid ConnectService(Uri organizationServiceUri, string userName, string password)
        {
            return(Guid.Empty);

            //기본인증정보 설정.
            if (!string.IsNullOrEmpty(userName) || !string.IsNullOrEmpty(password))
            {
                if (ClientCredentials == null)
                {
                    ClientCredentials = new ClientCredentials();
                }
                ClientCredentials.UserName.UserName = userName;
                ClientCredentials.UserName.Password = password;
            }

            if (_deviceCredentials == null)
            {
                _deviceCredentials = DeviceIdManager.LoadOrRegisterDevice();
            }

            OrganizationServiceProxy organizationServiceProxy = null;


            ServicePointManager.SecurityProtocol =
                SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
            try
            {
                organizationServiceProxy = new OrganizationServiceProxy(organizationServiceUri, null,
                                                                        ClientCredentials, _deviceCredentials);
            }
            catch
            {
                organizationServiceProxy = new OrganizationServiceProxy(organizationServiceUri, null,
                                                                        ClientCredentials, null);
            }

            organizationServiceProxy.Authenticate();

            Service = new CrmServiceClient(organizationServiceProxy);

            return(((WhoAmIResponse)Service.Execute(new WhoAmIRequest())).UserId);
        }
예제 #15
0
        public CrmConnector(string userName, string password, string organizationUrl)
        {
            var credentials = new ClientCredentials();

            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            var authCredentials = new AuthenticationCredentials
            {
                ClientCredentials     = credentials,
                SupportingCredentials = new AuthenticationCredentials
                {
                    ClientCredentials = DeviceIdManager.LoadOrRegisterDevice()
                }
            };

            orgServiceManagement =
                ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(organizationUrl));
            var tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

            organizationTokenResponse = tokenCredentials.SecurityTokenResponse;
        }
예제 #16
0
        private string GetOrganizationCrmConnectionString()
        {
            var connectionString = string.Format("Url={0};", OrganizationServiceUrl.Replace("/XRMServices/2011/Organization.svc", ""));

            if (IsCustomAuth)
            {
                if (!UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        connectionString += string.Format("Domain={0};", UserDomain);
                    }
                }

                string username = UserName;
                if (UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        username = string.Format("{0}\\{1}", UserDomain, UserName);
                    }
                }

                if (string.IsNullOrEmpty(userPassword))
                {
                    throw new Exception("User password cannot be null. If the user password is not stored in configuration file, you should request it from the end user");
                }

                var decryptedPassword = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                              ConnectionManager.CryptoSaltValue,
                                                              ConnectionManager.CryptoHashAlgorythm,
                                                              ConnectionManager.CryptoPasswordIterations,
                                                              ConnectionManager.CryptoInitVector,
                                                              ConnectionManager.CryptoKeySize);

                connectionString += string.Format("Username={0};Password={1};", username, decryptedPassword);
            }

            if (UseOnline)
            {
                ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl);
            }

            //append timeout in seconds to connectionstring
            connectionString += string.Format("Timeout={0};", Timeout.ToString(@"hh\:mm\:ss"));
            return(connectionString);
        }
        private static void DoWorkWriteDevice(object sender, DoWorkEventArgs e)
        {
            var deviceCredentials = e.Argument as ClientCredentials;

            DeviceIdManager.WriteDevice(deviceCredentials);
        }
        private static void DoWorkRegisterDevice(object sender, DoWorkEventArgs e)
        {
            var persistToFile = e.Argument is bool && (bool)e.Argument;

            e.Result = DeviceIdManager.RegisterDevice(persistToFile);
        }
예제 #19
0
        protected bool RegisterDeviceCredentials(ClientCredentials deviceCredentials)
        {
            var response = DeviceIdManager.RegisterDevice(deviceCredentials);

            return(response.IsSuccess);
        }
        public void LoadOrRegisterDeviceTest()
        {
            ClientCredentials clientCredentials = DeviceIdManager.LoadOrRegisterDevice();

            Assert.IsNotNull(clientCredentials);
        }
        public void LoadOrRegisterDeviceWithNameAndPasswordTest()
        {
            ClientCredentials clientCredentials = DeviceIdManager.LoadOrRegisterDevice("deviceName", "devicePasssword");

            Assert.IsNotNull(clientCredentials);
        }
예제 #22
0
        public static OrganizationDetailCollection GetOrganizations(Settings settings)
        {
            try
            {
                //System.Windows.MessageBox.Show(typeof(GuidList).Assembly.Location);
                string DiscoveryUrl = string.Format("{0}://{1}:{2}/XRMServices/2011/Discovery.svc",
                                                    settings.UseSSL ? "https" : "http",
                                                    settings.UseIFD ? settings.ServerName : settings.UseOffice365 ? "disco." + settings.ServerName : settings.UseOnline ? "dev." + settings.ServerName : settings.ServerName,
                                                    settings.ServerPort.Length == 0 ? (settings.UseSSL ? 443 : 80) : int.Parse(settings.ServerPort));
                string            domain            = null;
                string            login             = settings.Username;
                ClientCredentials deviceCredentials = null;
                Uri homeRealm = null;
                if (!settings.UseWindowsAuth)
                {
                    if (!settings.UseIFD)
                    {
                        if (!string.IsNullOrEmpty(settings.Domain))
                        {
                            domain = settings.Domain;
                            //connectionString += string.Format("Domain={0};", settings.Domain);
                        }
                    }

                    string sUsername = settings.Username;
                    if (settings.UseIFD)
                    {
                        if (!string.IsNullOrEmpty(settings.Domain))
                        {
                            // sUsername = string.Format("{0}\\{1}", settings.Domain, settings.Username);
                            login = string.Format("{0}\\{1}", settings.Domain, settings.Username);
                        }
                    }
                }

                if (settings.UseOnline && !settings.UseOffice365)
                {
                    do
                    {
                        deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                            DeviceIdManager.RegisterDevice();
                    } while (deviceCredentials.UserName.Password.Contains(";") ||
                             deviceCredentials.UserName.Password.Contains("=") ||
                             deviceCredentials.UserName.Password.Contains(" ") ||
                             deviceCredentials.UserName.UserName.Contains(";") ||
                             deviceCredentials.UserName.UserName.Contains("=") ||
                             deviceCredentials.UserName.UserName.Contains(" "));

                    //connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                    //                                  deviceCredentials.UserName.UserName,
                    //                                  deviceCredentials.UserName.Password);
                }

                if (settings.UseIFD && !string.IsNullOrEmpty(settings.HomeRealm))
                {
                    //connectionString += string.Format("HomeRealmUri={0};", settings.HomeRealm);
                    homeRealm = new Uri(settings.HomeRealm);
                }
                NetworkCredential userCredentials;
                if (!string.IsNullOrWhiteSpace(domain))
                {
                    userCredentials = new NetworkCredential(login, settings.Password, domain);
                }
                else if (settings.UseWindowsAuth)
                {
                    userCredentials = CredentialCache.DefaultNetworkCredentials;
                }
                else
                {
                    userCredentials = new NetworkCredential(login, settings.Password);
                }
                if (settings.UseOnline && settings.UseOffice365)
                {
                    ClientCredentials client = new ClientCredentials();
                    client.UserName.UserName = login;
                    client.UserName.Password = settings.Password;
                    return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, client, null));
                    //return CrmServiceClient.DiscoverOrganizations(new Uri("https://disco.crm4.dynamics.com/XRMServices/2011/Discovery.svc"), homeRealm, client, null);
                }
                if (deviceCredentials == null)
                {
                    return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, userCredentials));
                }
                else
                {
                    return(CrmServiceClient.DiscoverOrganizations(new Uri(DiscoveryUrl), homeRealm, null, deviceCredentials));
                }

                // var connection = new CrmServiceClient(settings.GetDiscoveryCrmConnectionString());

                //CrmServiceClient.DiscoverOrganizations()

                // var request = new RetrieveOrganizationsRequest();
                // var response = (Microsoft.Xrm.Sdk.Discovery.RetrieveOrganizationsResponse)service.Execute(request);
                // return connection.DiscoverOrganizations();
            }
            catch (System.IO.FileNotFoundException e)
            {
                if (e.Message.Contains("Microsoft.IdentityModel"))
                {
                    throw new Exception("Unable to load Windows Identity Foundation 3.5.  This is a feature that can be enabled on windows 8+ or downloaded for earlier versions ->  https://www.microsoft.com/en-nz/download/details.aspx?id=17331 ", e);
                }
                else
                {
                    throw e;
                }
            }
        }
예제 #23
0
        public string GetOrganizationCrmConnectionString()
        {
            var currentServerName = string.Empty;

            var orgDetails = ConnectionHelper.GetOrganizationDetails(this);

            if (UseOffice365 || UseOnline)
            {
                currentServerName = string.Format("{0}.{1}", orgDetails.UrlName, ServerName);
            }
            else if (UseIFD)
            {
                var serverNameParts = ServerName.Split('.');

                serverNameParts[0] = orgDetails.UrlName;


                currentServerName = string.Format("{0}:{1}",
                                                  string.Join(".", serverNameParts),
                                                  ServerPort.Length == 0 ? (UseSSL ? 443 : 80) : int.Parse(ServerPort));
            }
            else
            {
                currentServerName = string.Format("{0}:{1}/{2}",
                                                  ServerName,
                                                  ServerPort.Length == 0 ? (UseSSL ? 443 : 80) : int.Parse(ServerPort),
                                                  CrmOrg);
            }

            //var connectionString = string.Format("Url={0}://{1};",
            //                                     UseSSL ? "https" : "http",
            //                                     currentServerName);

            var connectionString = string.Format("Url={0};", orgDetails.Endpoints[EndpointType.OrganizationService].Replace("/XRMServices/2011/Organization.svc", ""));

            if (!UseWindowsAuth)
            {
                if (!UseIFD)
                {
                    if (!string.IsNullOrEmpty(Domain))
                    {
                        connectionString += string.Format("Domain={0};", Domain);
                    }
                }

                string username = Username;
                if (UseIFD)
                {
                    if (!string.IsNullOrEmpty(Domain))
                    {
                        username = string.Format("{0}\\{1}", Domain, Username);
                    }
                }

                connectionString += string.Format("Username={0};Password={1};", username, Password);
            }

            if (UseOnline)
            {
                System.ServiceModel.Description.ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIFD && !string.IsNullOrEmpty(HomeRealm))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealm);
            }

            //append timeout in seconds to connectionstring
            //connectionString += string.Format("Timeout={0};", Timeout.ToString(@"hh\:mm\:ss"));
            return(connectionString);
        }
        public void LoadDeviceCredentialsTest()
        {
            ClientCredentials clientCredentials = DeviceIdManager.LoadDeviceCredentials();

            Assert.IsNotNull(clientCredentials);
        }
예제 #25
0
 protected virtual ClientCredentials GetDeviceCredentials()
 {
     return(DeviceIdManager.LoadOrRegisterDevice());
 }
예제 #26
0
        private string GetDiscoveryCrmConnectionString()
        {
            var connectionString = string.Format("Url={0}://{1}:{2};",
                                                 UseSsl ? "https" : "http",
                                                 UseIfd ? ServerName : UseOsdp ? "disco." + ServerName : UseOnline ? "dev." + ServerName : ServerName,
                                                 ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort);

            if (IsCustomAuth)
            {
                if (!UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        connectionString += string.Format("Domain={0};", UserDomain);
                    }
                }

                string username = UserName;
                if (UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        username = string.Format("{0}\\{1}", UserDomain, UserName);
                    }
                }

                if (string.IsNullOrEmpty(userPassword))
                {
                    throw new Exception("User password cannot be null. If the user password is not stored in configuration file, you should request it from the end user");
                }

                var decryptedPassword = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase,
                                                              ConnectionManager.CryptoSaltValue,
                                                              ConnectionManager.CryptoHashAlgorythm,
                                                              ConnectionManager.CryptoPasswordIterations,
                                                              ConnectionManager.CryptoInitVector,
                                                              ConnectionManager.CryptoKeySize);

                connectionString += string.Format("Username={0};Password={1};", username, decryptedPassword);
            }

            if (UseOnline && !UseOsdp)
            {
                ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl);
            }

            return(connectionString);
        }
예제 #27
0
        public string GetOrganizationCrmConnectionString()
        {
            var currentServerName = string.Empty;

            if (UseOsdp || UseOnline)
            {
                currentServerName = string.Format("{0}.{1}", OrganizationUrlName, ServerName);
            }
            else if (UseIfd)
            {
                var serverNameParts = ServerName.Split('.');

                serverNameParts[0] = OrganizationUrlName;


                currentServerName = string.Format("{0}:{1}",
                                                  string.Join(".", serverNameParts),
                                                  ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort);
            }
            else
            {
                currentServerName = string.Format("{0}:{1}/{2}",
                                                  ServerName,
                                                  ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort,
                                                  Organization);
            }

            //var connectionString = string.Format("Url={0}://{1};",
            //                                     UseSsl ? "https" : "http",
            //                                     currentServerName);

            var connectionString = string.Format("Url={0};", OrganizationServiceUrl.Replace("/XRMServices/2011/Organization.svc", ""));

            if (IsCustomAuth)
            {
                if (!UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        connectionString += string.Format("Domain={0};", UserDomain);
                    }
                }

                string username = UserName;
                if (UseIfd)
                {
                    if (!string.IsNullOrEmpty(UserDomain))
                    {
                        username = string.Format("{0}\\{1}", UserDomain, UserName);
                    }
                }

                connectionString += string.Format("Username={0};Password={1};", username, UserPassword);
            }

            if (UseOnline)
            {
                ClientCredentials deviceCredentials;

                do
                {
                    deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ??
                                        DeviceIdManager.RegisterDevice();
                } while (deviceCredentials.UserName.Password.Contains(";") ||
                         deviceCredentials.UserName.Password.Contains("=") ||
                         deviceCredentials.UserName.Password.Contains(" ") ||
                         deviceCredentials.UserName.UserName.Contains(";") ||
                         deviceCredentials.UserName.UserName.Contains("=") ||
                         deviceCredentials.UserName.UserName.Contains(" "));

                connectionString += string.Format("DeviceID={0};DevicePassword={1};",
                                                  deviceCredentials.UserName.UserName,
                                                  deviceCredentials.UserName.Password);
            }

            if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl))
            {
                connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl);
            }

            //append timeout in seconds to connectionstring
            connectionString += string.Format("Timeout={0};", Timeout.ToString(@"hh\:mm\:ss"));
            return(connectionString);
        }
예제 #28
0
        // USE AT YOUR OWN RISK.
        // PLEASE BE AWARE THAT ANY INFORMATION YOU MAY FIND HERE MAY BE INACCURATE, MISLEADING, DANGEROUS, ADDICTIVE, UNETHICAL OR ILLEGAL (as-is from Wikipedia!)

        // This example retrives data from CRM Online using pure SOAP calls only and no additional assemblies to illustrate the underlying SOAP interactions.
        // It is useful if you're planning to interact with CRM Online web services from a non-.NET environment.
        // The soap messages were based on Fiddler (http://www.fiddler2.com/) traffic capture of sample code from the CRM 2011 SDK (http://msdn.microsoft.com/en-us/library/gg309408.aspx).

        // This may look like a lot of code because it's completely done using raw SOAP calls and no C# wrappers or proxies.
        // For optimal source code, please use the .NET assemblies that ship with CRM SDK or a wrapper around these methods in the programming language of your choice.

        static void Main(string[] args)
        {
            string Username = "******";
            string Password = "******";
            string CRMUrl   = "https://yourcrmorganization.api.crm.dynamics.com/XRMServices/2011/Organization.svc";

            // Change this to an account record guid from your CRM Online system to test Step #2
            // This can usually be found by opening an account record in the browser and looking at the URL's query string
            // Tip: David Cabaniuk has written a nice & simple post that shows you how to find a sample account ID: http://www.crmcodex.com/2012/01/tip-get-record-id-quickly-and-easily/
            string accountId = "05C92E5C-1B29-E011-8691-1CC1DEF177C2";

            #region Step 0: Get URN address and STS Enpoint dynamically from WSDL

            string WSDL          = GetMethod(CRMUrl + "?wsdl");
            string WSDLImportURL = GetValueFromXML(WSDL, @"//*[local-name()='import' and namespace-uri()='http://schemas.xmlsoap.org/wsdl/']/@location");
            string WSDKImport    = GetMethod(WSDLImportURL);
            string URNAddress    = GetValueFromXML(WSDKImport, @"//*[local-name()='AuthenticationPolicy' and namespace-uri()='http://schemas.microsoft.com/xrm/2011/Contracts/Services']/*[local-name()='SecureTokenService' and namespace-uri()='http://schemas.microsoft.com/xrm/2011/Contracts/Services']//*[local-name()='AppliesTo' and namespace-uri()='http://schemas.microsoft.com/xrm/2011/Contracts/Services']/text()");
            string STSEnpoint    = GetValueFromXML(WSDKImport, @"//*[local-name()='Issuer' and namespace-uri()='http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702']/*[local-name()='Address' and namespace-uri()='http://www.w3.org/2005/08/addressing']/text()");

            #endregion

            #region Step 1: Determine which authentication method (LiveID or OCP) and authenticate to get tokens and key.
            string keyIdentifier  = null;
            string securityToken0 = null;
            string securityToken1 = null;
            if ((STSEnpoint != null) && (STSEnpoint.StartsWith("https://login.live.com")))
            {
                #region WLID Authenciation
                #region Step A: Get Windows Live Device Credentials

                // Please note that this step uses a modified version of DeviceIdManager class from the one that ships with the SDK.
                // The modifications have been made to remove any writes to local disk which unfortunately removes the caching of device id as well.

                // Generates random credentials (Username, Password & Application ID) for the device
                // Sends the credentials to WLID and gets a PUID back
                DeviceIdManager.DeviceCredentials deviceCredentials = DeviceIdManager.RegisterDevice();

                #endregion

                #region Step B: Register Device Credentials and get binaryDAToken
                string deviceCredentialsSoapTemplate = @"<s:Envelope xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
                xmlns:a=""http://www.w3.org/2005/08/addressing""
                xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">

                    <s:Header>
                    <a:Action s:mustUnderstand=""1"">
                    http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
                    <a:MessageID>
                    urn:uuid:{4:MessageID}</a:MessageID>
                    <a:ReplyTo>
                        <a:Address>
                        http://www.w3.org/2005/08/addressing/anonymous</a:Address>
                    </a:ReplyTo>
                    <VsDebuggerCausalityData xmlns=""http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink"">
                    uIDPoy9Ez+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>
                    <a:To s:mustUnderstand=""1"">
                    {4:STSEndpoint}</a:To>
                    <o:Security s:mustUnderstand=""1""
                    xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
                        <u:Timestamp u:Id=""_0"">
                        <u:Created>{0:timeCreated}Z</u:Created>
                        <u:Expires>{1:timeExpires}Z</u:Expires>
                        </u:Timestamp>
                        <o:UsernameToken u:Id=""devicesoftware"">
                        <o:Username>{2:deviceUserName}</o:Username>
                        <o:Password Type=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"">{3:devicePassword}</o:Password>
                        </o:UsernameToken>
                    </o:Security>
                    </s:Header>
                    <s:Body>
                    <t:RequestSecurityToken xmlns:t=""http://schemas.xmlsoap.org/ws/2005/02/trust"">
                        <wsp:AppliesTo xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy"">
                        <a:EndpointReference>
                            <a:Address>http://passport.net/tb</a:Address>
                        </a:EndpointReference>
                        </wsp:AppliesTo>
                        <t:RequestType>
                        http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
                    </t:RequestSecurityToken>
                    </s:Body>
                </s:Envelope>
                ";

                DateTime binaryDARequestCreatedTime = DateTime.Now.ToUniversalTime();
                string   binaryDATokenXML           = GetSOAPResponse(STSEnpoint, string.Format(deviceCredentialsSoapTemplate
                                                                                                , binaryDARequestCreatedTime.ToString("s") + "." + binaryDARequestCreatedTime.Millisecond
                                                                                                , binaryDARequestCreatedTime.AddMinutes(5.0).ToString("s") + "." + binaryDARequestCreatedTime.Millisecond
                                                                                                , "11" + deviceCredentials.DeviceName, deviceCredentials.Password, Guid.NewGuid().ToString(), STSEnpoint));
                string binaryDAToken = GetValueFromXML(binaryDATokenXML, @"//*[local-name()='CipherValue']/text()");

                #endregion

                #region Step C: Get Security Token by sending WLID username, password and device binaryDAToken

                string   securityTokenSoapTemplate       = @"
                <s:Envelope xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
                xmlns:a=""http://www.w3.org/2005/08/addressing""
                xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">
                  <s:Header>
                    <a:Action s:mustUnderstand=""1"">
                    http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
                    <a:MessageID>
                    urn:uuid:{5:MessageID}</a:MessageID>
                    <a:ReplyTo>
                      <a:Address>
                      http://www.w3.org/2005/08/addressing/anonymous</a:Address>
                    </a:ReplyTo>
                    <VsDebuggerCausalityData xmlns=""http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink"">
                    uIDPozBEz+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>
                    <a:To s:mustUnderstand=""1"">
                    {7:STSEndpoint}</a:To>
                    <o:Security s:mustUnderstand=""1""
                    xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
                      <u:Timestamp u:Id=""_0"">
                        <u:Created>{0:timeCreated}Z</u:Created>
                        <u:Expires>{1:timeExpires}Z</u:Expires>
                      </u:Timestamp>
                      <o:UsernameToken u:Id=""user"">
                        <o:Username>{2:UserName}</o:Username>
                        <o:Password Type=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"">
                        {3:Password}</o:Password>
                      </o:UsernameToken>
                      <wsse:BinarySecurityToken ValueType=""urn:liveid:device""
                      xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
                        <EncryptedData Id=""BinaryDAToken0""
                        Type=""http://www.w3.org/2001/04/xmlenc#Element""
                        xmlns=""http://www.w3.org/2001/04/xmlenc#"">
                          <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#tripledes-cbc"">
                          </EncryptionMethod>
                          <ds:KeyInfo xmlns:ds=""http://www.w3.org/2000/09/xmldsig#"">
                            <ds:KeyName>http://Passport.NET/STS</ds:KeyName>
                          </ds:KeyInfo>
                          <CipherData>
                            <CipherValue>
                                {4:BinaryDAToken}
                            </CipherValue>
                          </CipherData>
                        </EncryptedData>
                      </wsse:BinarySecurityToken>
                    </o:Security>
                  </s:Header>
                  <s:Body>
                    <t:RequestSecurityToken xmlns:t=""http://schemas.xmlsoap.org/ws/2005/02/trust"">
                      <wsp:AppliesTo xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy"">
                        <a:EndpointReference>
                          <a:Address>{6:URNAddress}</a:Address>
                        </a:EndpointReference>
                      </wsp:AppliesTo>
                      <wsp:PolicyReference URI=""MBI_FED_SSL""
                      xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy"" />
                      <t:RequestType>
                      http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
                    </t:RequestSecurityToken>
                  </s:Body>
                </s:Envelope>
                ";
                DateTime securityTokenRequestCreatedTime = DateTime.Now.ToUniversalTime();
                string   securityTokenXML = GetSOAPResponse(STSEnpoint, string.Format(securityTokenSoapTemplate
                                                                                      , securityTokenRequestCreatedTime.ToString("s") + "." + securityTokenRequestCreatedTime.Millisecond
                                                                                      , securityTokenRequestCreatedTime.AddMinutes(5.0).ToString("s") + "." + securityTokenRequestCreatedTime.Millisecond
                                                                                      , Username, Password, binaryDAToken
                                                                                      , Guid.NewGuid().ToString(), URNAddress, STSEnpoint));
                securityToken0 = GetValueFromXML(securityTokenXML, @"//*[local-name()='CipherValue']/text()");
                securityToken1 = GetValueFromXML(securityTokenXML, @"//*[local-name()='CipherValue']/text()", 1);
                keyIdentifier  = GetValueFromXML(securityTokenXML, @"//*[local-name()='KeyIdentifier']/text()");

                #endregion
                #endregion
            }
            else
            {
                #region OCP Authentication
                #region Step A: Get Security Token by sending OCP username, password

                string securityTokenSoapTemplate = @"
                <s:Envelope xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
	                xmlns:a=""http://www.w3.org/2005/08/addressing""
	                xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">
	                <s:Header>
		                <a:Action s:mustUnderstand=""1"">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue
		                </a:Action>
		                <a:MessageID>urn:uuid:{4:MessageID}
		                </a:MessageID>
		                <a:ReplyTo>
			                <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
		                </a:ReplyTo>
		                <VsDebuggerCausalityData
			                xmlns=""http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink"">uIDPo4TBVw9fIMZFmc7ZFxBXIcYAAAAAbd1LF/fnfUOzaja8sGev0GKsBdINtR5Jt13WPsZ9dPgACQAA
		                </VsDebuggerCausalityData>
		                <a:To s:mustUnderstand=""1"">{6:STSEndpoint}
		                </a:To>
		                <o:Security s:mustUnderstand=""1""
			                xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
			                <u:Timestamp u:Id=""_0"">
				                <u:Created>{0:timeCreated}Z</u:Created>
				                <u:Expires>{1:timeExpires}Z</u:Expires>
			                </u:Timestamp>
			                <o:UsernameToken u:Id=""uuid-14bed392-2320-44ae-859d-fa4ec83df57a-1"">
				                <o:Username>{2:UserName}</o:Username>
				                <o:Password
					                Type=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"">{3:Password}</o:Password>
			                </o:UsernameToken>
		                </o:Security>
	                </s:Header>
	                <s:Body>
		                <t:RequestSecurityToken xmlns:t=""http://schemas.xmlsoap.org/ws/2005/02/trust"">
			                <wsp:AppliesTo xmlns:wsp=""http://schemas.xmlsoap.org/ws/2004/09/policy"">
				                <a:EndpointReference>
					                <a:Address>{5:URNAddress}</a:Address>
				                </a:EndpointReference>
			                </wsp:AppliesTo>
			                <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue
			                </t:RequestType>
		                </t:RequestSecurityToken>
	                </s:Body>
                </s:Envelope>
                ";

                DateTime securityTokenRequestCreatedTime = DateTime.Now.ToUniversalTime();
                string   securityTokenXML = GetSOAPResponse(STSEnpoint, string.Format(securityTokenSoapTemplate
                                                                                      , securityTokenRequestCreatedTime.ToString("s") + "." + securityTokenRequestCreatedTime.Millisecond
                                                                                      , securityTokenRequestCreatedTime.AddMinutes(5.0).ToString("s") + "." + securityTokenRequestCreatedTime.Millisecond
                                                                                      , Username, Password
                                                                                      , Guid.NewGuid().ToString(), URNAddress, STSEnpoint));
                securityToken0 = GetValueFromXML(securityTokenXML, @"//*[local-name()='CipherValue']/text()");
                securityToken1 = GetValueFromXML(securityTokenXML, @"//*[local-name()='CipherValue']/text()", 1);
                keyIdentifier  = GetValueFromXML(securityTokenXML, @"//*[local-name()='KeyIdentifier']/text()");

                #endregion
                #endregion
            }
            #endregion

            #region Step 2: Get / Set CRM Data by sending FetchXML Query
            string crmSoapRequestHeader        = @"
                <s:Envelope xmlns:s=""http://www.w3.org/2003/05/soap-envelope""
                xmlns:a=""http://www.w3.org/2005/08/addressing""
                xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"">
                  <s:Header>
                    <a:Action s:mustUnderstand=""1"">
                    http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/{7:Action}</a:Action>
                    <a:MessageID>
                    urn:uuid:{6:MessageID}</a:MessageID>
                    <a:ReplyTo>
                      <a:Address>
                      http://www.w3.org/2005/08/addressing/anonymous</a:Address>
                    </a:ReplyTo>
                    <VsDebuggerCausalityData xmlns=""http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink"">
                    uIDPozJEz+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>
                    <a:To s:mustUnderstand=""1"">
                    {2:CRMURL}</a:To>
                    <o:Security s:mustUnderstand=""1""
                    xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">
                      <u:Timestamp u:Id=""_0"">
                        <u:Created>{0:timeCreated}Z</u:Created>
                        <u:Expires>{1:timeExpires}Z</u:Expires>
                      </u:Timestamp>
                      <EncryptedData Id=""Assertion0""
                      Type=""http://www.w3.org/2001/04/xmlenc#Element""
                      xmlns=""http://www.w3.org/2001/04/xmlenc#"">
                        <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#tripledes-cbc"">
                        </EncryptionMethod>
                        <ds:KeyInfo xmlns:ds=""http://www.w3.org/2000/09/xmldsig#"">
                          <EncryptedKey>
                            <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"">
                            </EncryptionMethod>
                            <ds:KeyInfo Id=""keyinfo"">
                              <wsse:SecurityTokenReference xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"">

                                <wsse:KeyIdentifier EncodingType=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary""
                                ValueType=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier"">
                                {3:KeyIdentifier}</wsse:KeyIdentifier>
                              </wsse:SecurityTokenReference>
                            </ds:KeyInfo>
                            <CipherData>
                              <CipherValue>
                              {4:SecurityToken0}</CipherValue>
                            </CipherData>
                          </EncryptedKey>
                        </ds:KeyInfo>
                        <CipherData>
                          <CipherValue>
                          {5:SecurityToken1}</CipherValue>
                        </CipherData>
                      </EncryptedData>
                    </o:Security>
                  </s:Header>
                  ";
            string retrieveRequestBodyTemplate = @"<s:Body>
                    <Retrieve xmlns=""http://schemas.microsoft.com/xrm/2011/Contracts/Services"">
                      <entityName>account</entityName>
                      <id>{8:AccountID}</id>
                      <columnSet xmlns:b=""http://schemas.microsoft.com/xrm/2011/Contracts""
                      xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
                        <b:AllColumns>false</b:AllColumns>
                        <b:Columns xmlns:c=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
                          <c:string>name</c:string>
                          <c:string>address1_postalcode</c:string>
                          <c:string>lastusedincampaign</c:string>
                        </b:Columns>
                      </columnSet>
                    </Retrieve>
                  </s:Body>
                </s:Envelope>
                ";

            string   retrieveRequestSoapTemplate = crmSoapRequestHeader + retrieveRequestBodyTemplate;
            DateTime retrieveRequestCreatedTime  = DateTime.Now.ToUniversalTime();
            string   retrieveResponseXML         = GetSOAPResponse(CRMUrl, string.Format(retrieveRequestSoapTemplate
                                                                                         , retrieveRequestCreatedTime.ToString("s") + "." + retrieveRequestCreatedTime.Millisecond
                                                                                         , retrieveRequestCreatedTime.AddMinutes(5.0).ToString("s") + "." + retrieveRequestCreatedTime.Millisecond
                                                                                         , CRMUrl
                                                                                         , keyIdentifier
                                                                                         , securityToken0
                                                                                         , securityToken1
                                                                                         , Guid.NewGuid().ToString()
                                                                                         , "Retrieve"
                                                                                         , accountId
                                                                                         ));
            string[,] namespaces =
            {
                { "b", "http://schemas.microsoft.com/xrm/2011/Contracts"                    },
                { "c", "http://schemas.datacontract.org/2004/07/System.Collections.Generic" }
            };
            string accountName = GetValueFromXML(retrieveResponseXML, @"//b:KeyValuePairOfstringanyType[c:key='name']/c:value/text()", 0, namespaces);
            string zipcode     = GetValueFromXML(retrieveResponseXML, @"//b:KeyValuePairOfstringanyType[c:key='address1_postalcode']/c:value/text()", 0, namespaces);
            Console.WriteLine(accountName);
            Console.WriteLine(zipcode);

            #endregion

            #region Step 3: Retrieve Multiple records by sending FetchXML Query
            string   retrieveMultipleRequestBodyTemplate = @"
              <s:Body>
                <RetrieveMultiple xmlns=""http://schemas.microsoft.com/xrm/2011/Contracts/Services"">
                  <query i:type=""b:QueryExpression""
                  xmlns:b=""http://schemas.microsoft.com/xrm/2011/Contracts""
                  xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
                    <b:ColumnSet>
                      <b:AllColumns>false</b:AllColumns>
                      <b:Columns xmlns:c=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
                        <c:string>accountid</c:string>
                        <c:string>name</c:string>
                      </b:Columns>
                    </b:ColumnSet>
                    <b:Criteria>
                      <b:Conditions />
                      <b:FilterOperator>And</b:FilterOperator>
                      <b:Filters />
                    </b:Criteria>
                    <b:Distinct>false</b:Distinct>
                    <b:EntityName>account</b:EntityName>
                    <b:LinkEntities />
                    <b:Orders />
                    <b:PageInfo>
                      <b:Count>0</b:Count>
                      <b:PageNumber>0</b:PageNumber>
                      <b:PagingCookie i:nil=""true"" />
                      <b:ReturnTotalRecordCount>
                      false</b:ReturnTotalRecordCount>
                    </b:PageInfo>
                  </query>
                </RetrieveMultiple>
              </s:Body>
            </s:Envelope>
            ";
            string   retrieveMultipleRequestSoapTemplate = crmSoapRequestHeader + retrieveMultipleRequestBodyTemplate;
            DateTime retrieveMultipleRequestCreatedTime  = DateTime.Now.ToUniversalTime();
            string   retrieveMultipleResponseXML         = GetSOAPResponse(CRMUrl, string.Format(retrieveMultipleRequestSoapTemplate
                                                                                                 , retrieveMultipleRequestCreatedTime.ToString("s") + "." + retrieveMultipleRequestCreatedTime.Millisecond
                                                                                                 , retrieveMultipleRequestCreatedTime.AddMinutes(5.0).ToString("s") + "." + retrieveMultipleRequestCreatedTime.Millisecond
                                                                                                 , CRMUrl
                                                                                                 , keyIdentifier
                                                                                                 , securityToken0
                                                                                                 , securityToken1
                                                                                                 , Guid.NewGuid().ToString()
                                                                                                 , "RetrieveMultiple"
                                                                                                 ));

            //Temp XML Code
            string      xPathQuery = "//b:Entity/b:Attributes";
            XmlDocument document   = new XmlDocument();
            XmlNodeList nodes;
            document.LoadXml(retrieveMultipleResponseXML);

            XmlNamespaceManager nsManager = new XmlNamespaceManager(document.NameTable);
            for (int i = 0; i < namespaces.Length / namespaces.Rank; i++)
            {
                nsManager.AddNamespace(namespaces[i, 0], namespaces[i, 1]);
            }
            nodes = document.SelectNodes(xPathQuery, nsManager);
            foreach (XmlNode node in nodes)
            {
                Console.WriteLine("Account ID:  " + node.SelectSingleNode(".//b:KeyValuePairOfstringanyType[c:key='accountid']/c:value/text()", nsManager).Value);
                Console.WriteLine("Account Name:" + node.SelectSingleNode(".//b:KeyValuePairOfstringanyType[c:key='name']/c:value/text()", nsManager).Value);
            }
            #endregion

            Console.Read();
        }