Example #1
0
        /// <summary>
        /// Get the discovery service proxy based on existing configuration data.
        /// Added new way of getting discovery proxy.
        /// Also preserving old way of getting discovery proxy to support old scenarios.
        /// </summary>
        /// <returns>An instance of DiscoveryServiceProxy</returns>
        private DiscoveryServiceProxy GetDiscoveryProxy()
        {
            IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(DiscoveryUri);

            Authentication = serviceManagement.AuthenticationType;

            // Get the logon credentials.
            _userCredentials = GetUserLogonCredentials(this._user, this._password, this._domain);

            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            if (!String.IsNullOrWhiteSpace(this.UserPrincipalName))
            {
                // Try to authenticate the Federated Identity organization with UserPrinicipalName.
                authCredentials.UserPrincipalName = this.UserPrincipalName;
                try
                {
                    AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials);
                    DiscoveryServiceProxy     discoveryProxy   = new DiscoveryServiceProxy(serviceManagement, tokenCredentials.SecurityTokenResponse);
                    // Checking authentication by invoking some SDK methods.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
                    return(discoveryProxy);
                }
                catch (System.ServiceModel.Security.SecurityAccessDeniedException ex)
                {
                    // If authentication failed using current UserPrincipalName,
                    // request UserName and Password to try to authenticate using user credentials.
                    if (ex.Message.Contains("Access is denied."))
                    {
                        this.AuthFailureCount            += 1;
                        authCredentials.UserPrincipalName = String.Empty;

                        _userCredentials = GetUserLogonCredentials(this._user, this._password, this._domain);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }

            // Resetting credentials in the AuthenicationCredentials.
            if (Authentication != AuthenticationProviderType.ActiveDirectory)
            {
                authCredentials = new AuthenticationCredentials();
                authCredentials.ClientCredentials = UserCredentials;

                if (Authentication == AuthenticationProviderType.LiveId)
                {
                    authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    authCredentials.SupportingCredentials.ClientCredentials = UserCredentials;
                }
                // Try to authenticate with the user credentials.
                AuthenticationCredentials tokenCredentials1 = serviceManagement.Authenticate(authCredentials);
                return(new DiscoveryServiceProxy(serviceManagement, tokenCredentials1.SecurityTokenResponse));
            }
            // For an on-premises environment.
            return(new DiscoveryServiceProxy(serviceManagement, UserCredentials));
        }
Example #2
0
        /// <summary>
        ///     Generic method to obtain discovery/organization service proxy instance.
        /// </summary>
        /// <typeparam name="TService">
        ///     Set IDiscoveryService or IOrganizationService type to request respective service proxy instance.
        /// </typeparam>
        /// <typeparam name="TProxy">
        ///     Set the return type to either DiscoveryServiceProxy or OrganizationServiceProxy type based on TService type.
        /// </typeparam>
        /// <param name="serviceManagement">An instance of IServiceManagement</param>
        /// <param name="authCredentials">The user's Microsoft Dynamics CRM logon credentials.</param>
        /// <returns></returns>
        private TProxy GetProxy <TService, TProxy>(IServiceManagement <TService> serviceManagement,
                                                   AuthenticationCredentials authCredentials) where TService : class
            where TProxy : ServiceProxy <TService>
        {
            var classType = typeof(TProxy);

            if (serviceManagement.AuthenticationType !=
                AuthenticationProviderType.ActiveDirectory)
            {
                var tokenCredentials =
                    serviceManagement.Authenticate(authCredentials);
                // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.
                // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.

                if (tokenCredentials.SecurityTokenResponse == null)
                {
                    throw new NullReferenceException("There was an error creating the service connection as the SecurityTokenResponse is null. Check you have the correct authentication type and connection details");
                }

                return((TProxy)classType
                       .GetConstructor(new[]
                {
                    typeof(IServiceManagement <TService>),
                    typeof(SecurityTokenResponse)
                })
                       .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse }));
            }

            // Obtain discovery/organization service proxy for ActiveDirectory environment.
            // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
            return((TProxy)classType
                   .GetConstructor(new[]
                                   { typeof(IServiceManagement <TService>), typeof(ClientCredentials) })
                   .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials }));
        }
        /// <summary>
        /// Generic method to obtain discovery/organization service proxy instance.
        /// </summary>
        /// <typeparam name="TService">
        /// Set IDiscoveryService or IOrganizationService type to request respective service proxy instance.
        /// </typeparam>
        /// <typeparam name="TProxy">
        /// Set the return type to either DiscoveryServiceProxy or OrganizationServiceProxy type based on TService type.
        /// </typeparam>
        /// <param name="serviceManagement">An instance of IServiceManagement</param>
        /// <param name="authCredentials">The user's Microsoft Dynamics CRM logon credentials.</param>
        /// <returns></returns>
        private TProxy GetProxy <TService, TProxy>(
            IServiceManagement <TService> serviceManagement,
            AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            Type classType = typeof(TProxy);

            if (serviceManagement.AuthenticationType !=
                AuthenticationProviderType.ActiveDirectory)
            {
                AuthenticationCredentials tokenCredentials =
                    serviceManagement.Authenticate(authCredentials);
                // Obtain discovery/organization service proxy for Federated, LiveId and OnlineFederated environments.
                // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and SecurityTokenResponse.
                return((TProxy)classType
                       .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) })
                       .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse }));
            }

            // Obtain discovery/organization service proxy for ActiveDirectory environment.
            // Instantiate a new class of type using the 2 parameter constructor of type IServiceManagement and ClientCredentials.
            return((TProxy)classType
                   .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(ClientCredentials) })
                   .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials }));
        }
        private TProxy GetProxy <TService, TProxy>(Uri discoveryUri)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            // Get appropriate Uri from Configuration.
            Uri serviceUri = discoveryUri;

            // Set service management for either organization service Uri or discovery service Uri.
            // For organization service Uri, if service management exists
            // then use it from cache. Otherwise create new service management for current organization.
            IServiceManagement <TService> serviceManagement = ServiceConfigurationFactory.CreateManagement <TService>(
                serviceUri);

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

            var credentials = new ClientCredentials();

            credentials.UserName.UserName = UserName;
            credentials.UserName.Password = decryptedPassword;

            // Set the credentials.
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            authCredentials.ClientCredentials = credentials;

            Type classType;

            // Obtain discovery/organization service proxy for Federated,
            // Microsoft account and OnlineFederated environments.

            AuthenticationCredentials tokenCredentials =
                serviceManagement.Authenticate(
                    authCredentials);

            // Set classType to ManagedTokenDiscoveryServiceProxy.
            classType = typeof(ManagedTokenDiscoveryServiceProxy);

            // Invokes ManagedTokenOrganizationServiceProxy or ManagedTokenDiscoveryServiceProxy
            // (IServiceManagement<TService>, SecurityTokenResponse) constructor.
            var obj = (TProxy)classType
                      .GetConstructor(new Type[]
            {
                typeof(IServiceManagement <TService>),
                typeof(SecurityTokenResponse)
            })
                      .Invoke(new object[]
            {
                serviceManagement,
                tokenCredentials.SecurityTokenResponse
            });

            return(obj);
        }
Example #5
0
        protected XrmServiceContext CreateXrmServiceContext(MergeOption?mergeOption = null)
        {
            string organizationUri = ConfigurationManager.AppSettings["organizationUri"];

            //IServiceManagement<IOrganizationService> OrganizationServiceManagement = null;
            //AuthenticationProviderType OrgAuthType;
            //AuthenticationCredentials authCredentials = null;
            //AuthenticationCredentials tokenCredentials = null;
            //OrganizationServiceProxy organizationProxy = null;
            //SecurityTokenResponse responseToken = null;

            //try
            //{
            //    OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri));
            //    OrgAuthType = OrganizationServiceManagement.AuthenticationType;
            //    authCredentials = GetCredentials(OrgAuthType);
            //    tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials);
            //    organizationProxy = null;
            //    responseToken = tokenCredentials.SecurityTokenResponse;
            //}
            //catch
            //{

            //}

            IServiceManagement <IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(organizationUri));
            AuthenticationProviderType OrgAuthType       = OrganizationServiceManagement.AuthenticationType;
            AuthenticationCredentials  authCredentials   = GetCredentials(OrgAuthType);
            AuthenticationCredentials  tokenCredentials  = OrganizationServiceManagement.Authenticate(authCredentials);
            OrganizationServiceProxy   organizationProxy = null;
            SecurityTokenResponse      responseToken     = tokenCredentials.SecurityTokenResponse;

            if (ConfigurationManager.AppSettings["CRM_AuthenticationType"] == "ActiveDirectory")
            {
                using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, authCredentials.ClientCredentials))
                {
                    organizationProxy.EnableProxyTypes();
                }
            }
            else
            {
                using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken))
                {
                    organizationProxy.EnableProxyTypes();
                }
            }

            IOrganizationService service = (IOrganizationService)organizationProxy;

            var context = new XrmServiceContext(service);

            if (context != null && mergeOption != null)
            {
                context.MergeOption = mergeOption.Value;
            }
            return(context);
        }
Example #6
0
        public static OrganizationServiceProxy GetOrganizationService()
        {
            IServiceManagement <IOrganizationService> orgServiceManagement =
                ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri("https://nishantcrm365.crm.dynamics.com/XRMServices/2011/Organization.svc"));
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            authCredentials.ClientCredentials.UserName.UserName = "******";
            authCredentials.ClientCredentials.UserName.Password = "******";
            AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);

            return(new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse));
        }
Example #7
0
        private static TProxy GetProxy <TService, TProxy>(
            IServiceManagement <TService> serviceManagement,
            AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            Type classType = typeof(TProxy);
            AuthenticationCredentials tokenCredentials =
                serviceManagement.Authenticate(authCredentials);

            return((TProxy)classType
                   .GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) })
                   .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse }));
        }
        private static TProxy GetProxy <TService, TProxy>(IServiceManagement <TService> serviceManagement, AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            var classType = typeof(TProxy);

            if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory)
            {
                AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials);
                return((TProxy)classType.GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(SecurityTokenResponse) }).Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse }));
            }

            return((TProxy)classType.GetConstructor(new Type[] { typeof(IServiceManagement <TService>), typeof(ClientCredentials) }).Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials }));
        }
Example #9
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         authGroup.Enabled = false;
         txtOrganizationServiceUrl.Enabled = false;
         serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(txtOrganizationServiceUrl.Text));
         authCredentials   = new AuthenticationCredentials();
         if (IfdSelected)
         {
             authCredentials.ClientCredentials.UserName.UserName = txtUsername.Text;
             authCredentials.ClientCredentials.UserName.Password = txtPassword.Text;
             authCredentials = serviceManagement.Authenticate(authCredentials);
             proxy           = new OrganizationServiceProxy(serviceManagement, authCredentials.SecurityTokenResponse);
         }
         else
         {
             authCredentials.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
             proxy = new OrganizationServiceProxy(serviceManagement, authCredentials.ClientCredentials);
         }
         BinaryStorageOptions.Configuration.IConfigurationProvider annotationConfigProvider =
             BinaryStorageOptions.Configuration.Factory.GetConfigurationProvider(proxy, BinaryStorageOptions.CrmConstants.AnnotationEntityName, GetUnsecurePluginConfiguration(proxy, BinaryStorageOptions.CrmConstants.AnnotationEntityName), GetSecurePluginConfiguration());
         if (annotationConfigProvider.StorageProviderType == BinaryStorageOptions.Providers.BinaryStorageProviderType.CrmDefault)
         {
             MessageBox.Show("The provider is set to 'CrmDefault'.  This means no migration will happen.", "Default Settings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         BinaryStorageOptions.Configuration.IConfigurationProvider attachmentConfigProvider =
             BinaryStorageOptions.Configuration.Factory.GetConfigurationProvider(proxy, BinaryStorageOptions.CrmConstants.AttachmentEntityName, GetUnsecurePluginConfiguration(proxy, BinaryStorageOptions.CrmConstants.AttachmentEntityName), GetSecurePluginConfiguration());
         if (attachmentConfigProvider.StorageProviderType == BinaryStorageOptions.Providers.BinaryStorageProviderType.CrmDefault)
         {
             MessageBox.Show("The provider is set to 'CrmDefault'.  This means no migration will happen.", "Default Settings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             return;
         }
         migrateGroup.Text    = string.Format("Connected. External Storage Provider : {0}, {1}", GetExternalPath(annotationConfigProvider), GetExternalPath(attachmentConfigProvider));
         migrateGroup.Enabled = true;
     }
     catch (Exception ex)
     {
         MessageBox.Show("Something very bad happened : " + ex.ToString(), "Oops", MessageBoxButtons.OK, MessageBoxIcon.Error);
         authGroup.Enabled = true;
         txtOrganizationServiceUrl.Enabled = false;
     }
 }
Example #10
0
        private CrmSession(Uri discoveryUri, NetworkCredential credential, bool isOnPremises)
        {
            IServiceManagement <IDiscoveryService> discoveryServiceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(discoveryUri);
            ClientCredentials clientCredentials = InitializeClientCredentials(credential, discoveryServiceManagement);

            AuthenticationCredentials authCredentials = new AuthenticationCredentials()
            {
                ClientCredentials = clientCredentials
            };

            if (isOnPremises && discoveryServiceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory)
            {
                //authCredentials.HomeRealm = discoveryUri;
            }

            _tokenCredentials = discoveryServiceManagement.Authenticate(authCredentials);

            DiscoveryProxy = GetService <IDiscoveryService>(discoveryServiceManagement, _tokenCredentials);
        }
        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;
        }
        public static DiscoveryServiceProxy CreateDiscoveryService(IServiceManagement <IDiscoveryService> serviceManagement, string username, string password)
        {
            DiscoveryServiceProxy service = null;

            var credentials = GetCredentials(serviceManagement, username, password);

            if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory &&
                serviceManagement.AuthenticationType != AuthenticationProviderType.None
                )
            {
                AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(credentials);

                service = new DiscoveryServiceProxy(serviceManagement, tokenCredentials.SecurityTokenResponse);
            }
            else
            {
                service = new DiscoveryServiceProxy(serviceManagement, credentials.ClientCredentials);
            }

            service.Timeout = TimeSpan.FromMinutes(30);

            return(service);
        }
        /// <summary>
        /// Get the discovery service proxy based on existing configuration data.
        /// Added new way of getting discovery proxy.
        /// Also preserving old way of getting discovery proxy to support old scenarios.
        /// </summary>
        /// <returns>An instance of DiscoveryServiceProxy</returns>
        private DiscoveryServiceProxy GetDiscoveryProxy(ServerConnection.Configuration config)
        {
            IServiceManagement <IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                    config.DiscoveryUri);

            // Get the EndpointType.
            config.EndpointType = serviceManagement.AuthenticationType;

            // Get the logon credentials.
            //config.Credentials = GetUserLogonCredentials();

            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            if (!String.IsNullOrWhiteSpace(config.UserPrincipalName))
            {
                // Try to authenticate the Federated Identity organization with UserPrinicipalName.
                authCredentials.UserPrincipalName = config.UserPrincipalName;

                try {
                    AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(
                        authCredentials);
                    DiscoveryServiceProxy discoveryProxy = new DiscoveryServiceProxy(serviceManagement,
                                                                                     tokenCredentials.SecurityTokenResponse);
                    // Checking authentication by invoking some SDK methods.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
                    return(discoveryProxy);
                }
                catch (System.ServiceModel.Security.SecurityAccessDeniedException ex) {
                    // If authentication failed using current UserPrincipalName,
                    // request UserName and Password to try to authenticate using user credentials.
                    if (ex.Message.Contains("Access is denied."))
                    {
                        config.AuthFailureCount          += 1;
                        authCredentials.UserPrincipalName = String.Empty;

                        //config.Credentials = GetUserLogonCredentials();
                    }
                    else
                    {
                        throw ex;
                    }
                }
                // You can also catch other exceptions to handle a specific situation in your code, for example,
                //      System.ServiceModel.Security.ExpiredSecurityTokenException
                //      System.ServiceModel.Security.MessageSecurityException
                //      System.ServiceModel.Security.SecurityNegotiationException
            }

            // Resetting credentials in the AuthenicationCredentials.
            if (config.EndpointType != AuthenticationProviderType.ActiveDirectory)
            {
                authCredentials = new AuthenticationCredentials();
                authCredentials.ClientCredentials = config.Credentials;

                if (config.EndpointType == AuthenticationProviderType.LiveId)
                {
                    authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials;
                }
                // Try to authenticate with the user credentials.
                AuthenticationCredentials tokenCredentials1 = serviceManagement.Authenticate(
                    authCredentials);
                return(new DiscoveryServiceProxy(serviceManagement,
                                                 tokenCredentials1.SecurityTokenResponse));
            }
            // For an on-premises environment.
            return(new DiscoveryServiceProxy(serviceManagement, config.Credentials));
        }
Example #14
0
        // http://www.cub-e.net/en/post/improve-microsoft-dynamics-365-crm-service-channel-allocation-performance
        public static CrmServiceContext Create()
        {
            if (_tokenCredentials == null)
            {
                var dbConnectionStringBuilder = new DbConnectionStringBuilder
                {
                    ConnectionString = ConfigurationManager.AppSettings["CrmConnectionString"]
                };

                var serviceUrl = $"{dbConnectionStringBuilder["Url"]}/XRMServices/2011/Organization.svc";

                _serviceManagement = (IServiceManagement <IOrganizationService>)ServiceConfigurationFactory
                                     .CreateConfiguration <IOrganizationService>(new Uri(serviceUrl));

                _tokenCredentials = _serviceManagement.Authenticate(new AuthenticationCredentials()
                {
                    ClientCredentials =
                    {
                        UserName     =
                        {
                            UserName = (string)dbConnectionStringBuilder["Username"],
                            Password = (string)dbConnectionStringBuilder["Password"],
                        }
                    }
                });
            }

            OrganizationServiceProxy service = null;

            switch (_serviceManagement.AuthenticationType)
            {
            case AuthenticationProviderType.ActiveDirectory:
                service = new OrganizationServiceProxy(_serviceManagement, _tokenCredentials.ClientCredentials);
                break;

            case AuthenticationProviderType.None:
                break;

            case AuthenticationProviderType.Federation:
                break;

            case AuthenticationProviderType.LiveId:
                break;

            // using this for 365
            case AuthenticationProviderType.OnlineFederation:
                service = new OrganizationServiceProxy(_serviceManagement, _tokenCredentials.SecurityTokenResponse);
                break;

            default:
                service = new OrganizationServiceProxy(_serviceManagement, _tokenCredentials.SecurityTokenResponse);
                break;
            }

            if (service == null)
            {
                throw new NotImplementedException("AuthenticationProviderType");
            }

            service.EnableProxyTypes();

            return(new CrmServiceContext(service));
        }
        /// CRON interval is set to run every 30 minutes
        /// The Azure function takes 7 minutes to run
        /// ClickDimensions allows us to send up to 200K emails per year
        /// With this interval; approximately 17,500 +/- emails will be sent per year
        public static void Run([TimerTrigger("0 */30 * * * *")]TimerInfo myTimer, TraceWriter log)
        {

            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");


            /// Connecting to Exchange Server for CRM Online Service User
            /// This function will mark the last message in the ClickDBox as READ
            /// This will prevent any conflict with previously ran functions
            ExchangeService _service1;
            {
                try
                {
                    log.Info("Registering Initial Exchange Connection");
                    _service1 = new ExchangeService
                    {
                        Credentials = new WebCredentials(username, password)
                    };
                }

                catch
                {
                    log.Info("New ExchangeService failed to connect.");
                    return;
                }

                _service1.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");


                SearchFilter sf = new SearchFilter.SearchFilterCollection(
                        LogicalOperator.And, new SearchFilter.IsEqualTo(ItemSchema.Subject, "ClickDimensions Uptime Monitoring"));

                foreach (EmailMessage email in _service1.FindItems(ClickDBox, sf, new ItemView(1)))
                {
                    if (!email.IsRead)
                    {
                        log.Info("Old Unread Messages Present");

                        email.IsRead = true;
                        email.Update(ConflictResolutionMode.AutoResolve);
                        log.Info("MarkedAsRead");

                    }

                    else
                    {
                        if (email.IsRead)
                        {
                            log.Info("No New Emails");

                        }


                    }


                }

            }



            /// Connection to CRM
            /// For testing purposes, this code may reflect setup in Mural Dynamics 365 CRM Mural Sandbox Instance
            /// Ensure that this configuration has been checked prior to implementing into production
            IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.
                CreateManagement<IOrganizationService>(new Uri(url));
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();
            authCredentials.ClientCredentials.UserName.UserName = username;
            authCredentials.ClientCredentials.UserName.Password = password;
            AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);
            OrganizationServiceProxy organizationProxy = new OrganizationServiceProxy
                (orgServiceManagement, tokenCredentials.SecurityTokenResponse);


            log.Info("Connected To CRM");


            /// Run pre-built workflow in CRM
            /// This workflow will send a ClickDimensions Email to a contact
            /// Contact will be the CRM Online User
            /// For testing purposes, this code may reflect setup in Mural Dynamics 365 CRM Mural Sandbox Instance
            /// Ensure that this configuration has been checked prior to implementing into production
            ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
            {
                /// For testing purposes only
                // WorkflowId = _workflowId,
                // EntityId = _entityId,

                WorkflowId = _workflowId2,
                EntityId = _entityId2,

            };

            ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)organizationProxy.Execute(request);


            if (request == null)
            {
                log.Info("Workflow Failed");
            }

            else
            {
                log.Info("Workflow Triggered");
            }



            /// Put this process to sleep for 7 minutes
            /// This will give ClickDimensions enough time for the email to be delivered
            /// After 7 minutes, the process will check to see if email was delivered
            /// Ensure that this configuration has been checked prior to implementing into production
            {
                for (int i = 0; i < 1; i++)
                {
                    log.Info("Sleep for 7 minutes.");
                    Thread.Sleep(420000);

                }
                log.Info("Wake");
            }


            /// Connect to CRM Online Service User Email
            ExchangeService _service2;
            {
                try
                {
                    log.Info("Registering Exchange Connection");
                    _service2 = new ExchangeService
                    {

                        /// Connection credentials for CRM Online User to access email 
                        /// For testing purposes, this code may reflect process owners Mural Office 365 credentials
                        /// Ensure that this configuration has been checked prior to implementing into production
                        Credentials = new WebCredentials(username, password)

                    };
                }

                catch
                {

                    log.Info("New ExchangeService failed to connect.");
                    return;

                }

                _service2.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

                try
                {


                    /*
                      
                    /// This will search the Mailbox for the top level folders and display their Ids
                    /// Use this function to obtain the Id necessary for this code                  

                    /// Get all the folders in the message's root folder.
                    Folder rootfolder = Folder.Bind(_service2, WellKnownFolderName.MsgFolderRoot);

                    log.Info("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders.");

                    /// A GetFolder operation has been performed.
                    /// Now display each folder's name and ID.
                    rootfolder.Load();

                    foreach (Folder folder in rootfolder.FindFolders(new FolderView(100)))
                    {
                        log.Info("\nName: " + folder.DisplayName + "\n  Id: " + folder.Id);
                    }

                    */


                    log.Info("Reading mail");


                    /// HTML email string for ClickDIsDown Email
                    string HTML = @"<font size=6><font color=red> ClickDimensions Uptime Monitoring <font size=3><font color=black><br /><br /><br />
                                                The ClickDimensions emailing system may not be working at this time or has become slow. Please check the integration and 
                                                    alert the appropriate teams if necessary.<br /> <br /> Regards,<br /><br /> Business & Product Development Team <br /> 
                                            Email: [email protected] <br /> Mural Consulting <br /> https://mural365.com <br /><br />";



                    /// This will view the last email in the mailbox
                    /// Search for "ClickD Uptime Monitoring System" in Subject line
                    SearchFilter sf = new SearchFilter.SearchFilterCollection(
                        LogicalOperator.And, new SearchFilter.IsEqualTo(ItemSchema.Subject, "ClickDimensions Uptime Monitoring"));

                    foreach (EmailMessage email in _service2.FindItems(ClickDBox, sf, new ItemView(1)))
                    {

                        /// If the email was sent (unread email = ClickD is working)
                        /// Mark the email as read
                        /// This folder SHOULD NOT contain any UNREAD emails
                        if (!email.IsRead)
                        {
                            log.Info("Email: " + email.Subject);
                            log.Info("Email Sent: " + email.DateTimeSent + " Email Received: " +
                                email.DateTimeReceived + " Email Created: " + email.DateTimeCreated);


                            email.IsRead = true;
                            email.Update(ConflictResolutionMode.AutoResolve);
                            log.Info("MarkedAsRead");

                            isClickDUp = 1;

                        }

                        else
                        {
                            /// If the email was not sent (no unread email = no email)
                            /// Send the alert email via SMTP client from CRM Online Service User
                            if (email.IsRead)
                            {
                                string SUBJECT = "ClickDimensions May be Failing";

                                string BODY = HTML;
                                // string BODY = "Please check ClickDimensions Integration";

                                MailMessage message = new MailMessage
                                {
                                    IsBodyHtml = true,
                                    From = new MailAddress(FROM, FROMNAME)
                                };
                                message.To.Add(new MailAddress(TO));
                                message.Subject = SUBJECT;
                                message.Body = BODY;

                                message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);

                                isClickDUp = 0;


                                using (var client = new SmtpClient(HOST, PORT))
                                {
                                    /// Pass SMTP credentials
                                    client.Credentials =
                                        new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);

                                    /// Enable SSL encryption
                                    client.EnableSsl = true;

                                    try
                                    {
                                        log.Info("Attempting to send email...");
                                        client.Send(message);
                                        log.Info("Email sent!");

                                    }
                                    catch (Exception ex)
                                    {
                                        log.Info("The email was not sent.");
                                        log.Info("Error message: " + ex.Message);

                                    }

                                }


                            }


                        }

                        /// This will mark the email as read as a backup
                        email.IsRead = true;
                        email.Update(ConflictResolutionMode.AutoResolve);
                        log.Info("BackupMarkedAsRead");

                    }

                }

                catch (Exception e)
                {
                    log.Info("An error has occured. \n:" + e.Message);
                }

            }


            if (DateTime.Compare(DateTime.Today, new DateTime(2018, 12, 10, 0, 0, 0)) >= 0)
            {


                string monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).ToString("yyyy-MM-dd");
                string lastMonday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday).AddDays(-7).ToString("yyyy-MM-dd");


                string path = @"D:\home\site\wwwroot\Function2\ClickDUptime Weekly Report " + monday + ".csv";
                DateTime localDate2 = DateTime.Now;
                str = localDate2.ToString() + "," + isClickDUp;

                if (!File.Exists(path))
                {
                    log.Info("Creating & Updating Excel");

                    /// Create a file to write to.
                    string createText = "Timestamp,ClickDimensions Status" + Environment.NewLine + str;
                    File.WriteAllText(path, createText);


                    /// path is reset to old file here
                    path = @"D:\home\site\wwwroot\Function2\ClickDUptime Weekly Report " + lastMonday + ".csv";


                    /// Send email for last weeks excel sheet
                    if (File.Exists(path))
                    {
                        MailMessage mail = new MailMessage();
                        SmtpClient SmtpServer = new SmtpClient(HOST);
                        mail.From = new MailAddress(FROM);

                        // mail.To.Add("");
                        mail.To.Add("");

                        mail.Subject = "ClickDUptime Monitoring Report " + monday;
                        mail.Body = "";

                        log.Info("Sending Excel");

                        try
                        {
                            System.Net.Mail.Attachment attachment;
                            attachment = new System.Net.Mail.Attachment(path);
                            mail.Attachments.Add(attachment);

                            SmtpServer.Port = 587;
                            SmtpServer.Credentials = new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
                            SmtpServer.EnableSsl = true;
                            SmtpServer.Send(mail);

                            log.Info("Excel Sent");

                        }
                        catch (Exception)
                        {
                            /// mail send failure
                            /// figure out what to do here
                            log.Info("Failing");

                        }

                    }

                }

                else
                {
                    /// This text is always added, making the file longer over time
                    /// if it is not deleted.
                    string appendText = Environment.NewLine + str;
                    File.AppendAllText(path, appendText);

                    /// Open the file to read from.
                    string readText = File.ReadAllText(path);

                }
            }

        }
Example #16
0
        public static TProxy GetProxy <TService, TProxy>(ServerConnection.Configuration currentConfig)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            Boolean isOrgServiceRequest = typeof(TService).Equals(typeof(IOrganizationService));
            Uri     serviceUri          = isOrgServiceRequest ?
                                          currentConfig.OrganizationUri : currentConfig.DiscoveryUri;
            IServiceManagement <TService> serviceManagement =
                (isOrgServiceRequest && null != currentConfig.OrganizationServiceManagement) ?
                (IServiceManagement <TService>)currentConfig.OrganizationServiceManagement :
                ServiceConfigurationFactory.CreateManagement <TService>(
                    serviceUri);

            if (isOrgServiceRequest)
            {
                if (currentConfig.OrganizationTokenResponse == null)
                {
                    currentConfig.OrganizationServiceManagement =
                        (IServiceManagement <IOrganizationService>)serviceManagement;
                }
            }
            else
            {
                currentConfig.EndpointType = serviceManagement.AuthenticationType;
                currentConfig.Credentials  = GetUserLogonCredentials(currentConfig);
            }
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            if (!String.IsNullOrWhiteSpace(currentConfig.UserPrincipalName))
            {
                authCredentials.UserPrincipalName = currentConfig.UserPrincipalName;
            }
            else
            {
                authCredentials.ClientCredentials = currentConfig.Credentials;
            }
            Type classType;

            AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials);

            if (isOrgServiceRequest)
            {
                currentConfig.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse;
                classType = typeof(ManagedTokenOrganizationServiceProxy);
            }
            else
            {
                classType = typeof(ManagedTokenDiscoveryServiceProxy);
            }
            return((TProxy)classType
                   .GetConstructor(new Type[]
            {
                typeof(IServiceManagement <TService>),
                typeof(ClientCredentials)
            })
                   .Invoke(new object[]
            {
                serviceManagement,
                authCredentials.ClientCredentials
            }));
        }
        /// <summary>
        /// Generic method to obtain discovery/organization service proxy instance.
        /// </summary>
        /// <typeparam name="TService">
        /// Set IDiscoveryService or IOrganizationService type
        /// to request respective service proxy instance.
        /// </typeparam>
        /// <typeparam name="TProxy">
        /// Set the return type to either DiscoveryServiceProxy
        /// or OrganizationServiceProxy type based on TService type.
        /// </typeparam>
        /// <param name="currentConfig">An instance of existing Configuration</param>
        /// <returns>An instance of TProxy
        /// i.e. DiscoveryServiceProxy or OrganizationServiceProxy</returns>
        public static TProxy GetProxy <TService, TProxy>(ServerConnection.Configuration currentConfig,
                                                         IConfigurationProvider configurationProvider)
            where TService : class
            where TProxy : ServiceProxy <TService>
        {
            // Check if it is organization service proxy request.
            Boolean isOrgServiceRequest = typeof(TService).Equals(typeof(IOrganizationService));

            // Get appropriate Uri from Configuration.
            Uri serviceUri = isOrgServiceRequest ?
                             currentConfig.OrganizationUri : currentConfig.DiscoveryUri;

            // Set service management for either organization service Uri or discovery service Uri.
            // For organization service Uri, if service management exists
            // then use it from cache. Otherwise create new service management for current organization.
            IServiceManagement <TService> serviceManagement =
                (isOrgServiceRequest && null != currentConfig.OrganizationServiceManagement) ?
                (IServiceManagement <TService>)currentConfig.OrganizationServiceManagement :
                ServiceConfigurationFactory.CreateManagement <TService>(
                    serviceUri);

            if (isOrgServiceRequest)
            {
                if (currentConfig.OrganizationTokenResponse == null)
                {
                    currentConfig.OrganizationServiceManagement =
                        (IServiceManagement <IOrganizationService>)serviceManagement;
                }
            }
            // Set the EndpointType in the current Configuration object
            // while adding new configuration using discovery service proxy.
            else
            {
                // Get the EndpointType.
                currentConfig.EndpointType = serviceManagement.AuthenticationType;

                ClientCredentials credentials = new ClientCredentials();

                credentials.UserName.UserName = configurationProvider.GetConfigurationSettingValue("CRMUserAccount"); //"*****@*****.**";
                credentials.UserName.Password = configurationProvider.GetConfigurationSettingValue("CRMAccountPwd");  //"pass@word1";

                currentConfig.Credentials = credentials;
            }

            // Set the credentials.
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            // If UserPrincipalName exists, use it. Otherwise, set the logon credentials from the configuration.
            if (!String.IsNullOrWhiteSpace(currentConfig.UserPrincipalName))
            {
                // Single sing-on with the Federated Identity organization using current UserPrinicipalName.
                authCredentials.UserPrincipalName = currentConfig.UserPrincipalName;
            }
            else
            {
                authCredentials.ClientCredentials = currentConfig.Credentials;
            }

            Type classType;

            // Obtain discovery/organization service proxy for Federated,
            // Microsoft account and OnlineFederated environments.
            if (currentConfig.EndpointType !=
                AuthenticationProviderType.ActiveDirectory)
            {
                if (currentConfig.EndpointType == AuthenticationProviderType.LiveId)
                {
                    authCredentials.SupportingCredentials = new AuthenticationCredentials();
                    authCredentials.SupportingCredentials.ClientCredentials =
                        currentConfig.DeviceCredentials;
                }

                AuthenticationCredentials tokenCredentials =
                    serviceManagement.Authenticate(
                        authCredentials);

                if (isOrgServiceRequest)
                {
                    // Set SecurityTokenResponse for the current organization.
                    currentConfig.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse;
                    // Set classType to ManagedTokenOrganizationServiceProxy.
                    classType = typeof(ManagedTokenOrganizationServiceProxy);
                }
                else
                {
                    // Set classType to ManagedTokenDiscoveryServiceProxy.
                    classType = typeof(ManagedTokenDiscoveryServiceProxy);
                }

                // Invokes ManagedTokenOrganizationServiceProxy or ManagedTokenDiscoveryServiceProxy
                // (IServiceManagement<TService>, SecurityTokenResponse) constructor.
                return((TProxy)classType
                       .GetConstructor(new Type[]
                {
                    typeof(IServiceManagement <TService>),
                    typeof(SecurityTokenResponse)
                })
                       .Invoke(new object[]
                {
                    serviceManagement,
                    tokenCredentials.SecurityTokenResponse
                }));
            }

            // Obtain discovery/organization service proxy for ActiveDirectory environment.
            if (isOrgServiceRequest)
            {
                classType = typeof(ManagedTokenOrganizationServiceProxy);
            }
            else
            {
                classType = typeof(ManagedTokenDiscoveryServiceProxy);
            }

            // Invokes ManagedTokenDiscoveryServiceProxy or ManagedTokenOrganizationServiceProxy
            // (IServiceManagement<TService>, ClientCredentials) constructor.
            return((TProxy)classType
                   .GetConstructor(new Type[]
            {
                typeof(IServiceManagement <TService>),
                typeof(ClientCredentials)
            })
                   .Invoke(new object[]
            {
                serviceManagement,
                authCredentials.ClientCredentials
            }));
        }
        /// <summary>
        /// Obtains the server connection information including the target organization's
        /// Uri and user logon credentials from the user.
        /// </summary>
        public virtual Configuration GetServerConfiguration()
        //public List<ServerConfigurationItem> GetServerConfigurations()
        {
            Boolean ssl;
            Boolean addConfig;
            int     configNumber;
            // Read the configuration from the disk, if it exists, at C:\Users\<username>\AppData\Roaming\CrmServer\Credentials.xml.
            Boolean isConfigExist = ReadConfigurations();

            // Check if server configuration settings are already available on the disk.
            if (isConfigExist)
            {
                // List of server configurations that are available from earlier saved settings.
                Console.Write("\n(0) Add New Server Configuration (Maximum number up to 9)\t");
                for (int n = 0; n < configurations.Count; n++)
                {
                    String user;

                    switch (configurations[n].EndpointType)
                    {
                    case AuthenticationProviderType.ActiveDirectory:
                        if (configurations[n].Credentials != null)
                        {
                            user = configurations[n].Credentials.Windows.ClientCredential.Domain + "\\"
                                   + configurations[n].Credentials.Windows.ClientCredential.UserName;
                        }
                        else
                        {
                            user = "******";
                        }
                        break;

                    default:
                        if (configurations[n].Credentials != null)
                        {
                            user = configurations[n].Credentials.UserName.UserName;
                        }
                        else
                        {
                            user = "******";
                        }
                        break;
                    }

                    Console.Write("\n({0}) Server: {1},  Org: {2},  User: {3}\t",
                                  n + 1, configurations[n].ServerAddress, configurations[n].OrganizationName, user);
                }

                Console.WriteLine();

                Console.Write("\nSpecify the saved server configuration number (1-{0}) [{0}] : ", configurations.Count);
                String input = Console.ReadLine();
                Console.WriteLine();
                if (input == String.Empty)
                {
                    input = configurations.Count.ToString();
                }
                if (!Int32.TryParse(input, out configNumber))
                {
                    configNumber = -1;
                }

                if (configNumber == 0)
                {
                    addConfig = true;
                }
                else if (configNumber > 0 && configNumber <= configurations.Count)
                {
                    // Return the organization Uri.
                    config = configurations[configNumber - 1];
                    // Reorder the configuration list and save it to file to save the recent configuration as a latest one.
                    if (configNumber != configurations.Count)
                    {
                        Configuration temp = configurations[configurations.Count - 1];
                        configurations[configurations.Count - 1] = configurations[configNumber - 1];
                        configurations[configNumber - 1]         = temp;
                        SaveConfigurations();
                    }
                    addConfig = false;
                }
                else
                {
                    throw new Exception("The specified server configuration does not exist.");
                }
            }
            else
            {
                addConfig = true;
            }

            if (addConfig)
            {
                // Get the server address. If no value is entered, default to Microsoft Dynamics
                // CRM Online in the North American data center.
                config.ServerAddress = GetServerAddress(out ssl);

                if (String.IsNullOrWhiteSpace(config.ServerAddress))
                {
                    config.ServerAddress = "crm.dynamics.com";
                }


                // One of the Microsoft Dynamics CRM Online data centers.
                if (config.ServerAddress.EndsWith(".dynamics.com", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Check if the organization is provisioned in Microsoft Office 365.
                    if (GetOrgType(config.ServerAddress))
                    {
                        config.DiscoveryUri =
                            new Uri(String.Format("https://disco.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));
                    }
                    else
                    {
                        config.DiscoveryUri =
                            new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));

                        // Get or set the device credentials. This is required for Windows Live ID authentication.
                        config.DeviceCredentials = GetDeviceCredentials();
                    }
                }
                // Check if the server uses Secure Socket Layer (https).
                else if (ssl)
                {
                    config.DiscoveryUri =
                        new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));
                }
                else
                {
                    config.DiscoveryUri =
                        new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", config.ServerAddress));
                }

                // Get the target organization.
                config.OrganizationUri = GetOrganizationAddress();
                configurations.Add(config);
                int length = configurations.Count;
                int i      = length - 2;
                // Check if a new configuration already exists.
                // If found, reorder list to show latest in use.
                while (i > 0)
                {
                    if (configurations[configurations.Count - 1].Equals(configurations[i]))
                    {
                        configurations.RemoveAt(i);
                    }
                    i--;
                }
                // Set max configurations to 9 otherwise overwrite existing one.
                if (configurations.Count > 9)
                {
                    configurations.RemoveAt(0);
                }
                SaveConfigurations();
            }
            else
            {
                // Get the existing user's logon credentials.
                config.Credentials = GetUserLogonCredentials();
            }

            // Set IServiceManagement for the current organization.
            IServiceManagement <IOrganizationService> orgServiceManagement =
                ServiceConfigurationFactory.CreateManagement <IOrganizationService>(
                    config.OrganizationUri);

            config.OrganizationServiceManagement = orgServiceManagement;

            // Set SecurityTokenResponse for the current organization.
            if (config.EndpointType != AuthenticationProviderType.ActiveDirectory)
            {
                // Set the credentials.
                AuthenticationCredentials authCredentials = new AuthenticationCredentials();
                // If UserPrincipalName exists, use it. Otherwise, set the logon credentials from the configuration.
                if (!String.IsNullOrWhiteSpace(config.UserPrincipalName))
                {
                    authCredentials.UserPrincipalName = config.UserPrincipalName;
                }
                else
                {
                    authCredentials.ClientCredentials = config.Credentials;
                    if (config.EndpointType == AuthenticationProviderType.LiveId)
                    {
                        authCredentials.SupportingCredentials = new AuthenticationCredentials();
                        authCredentials.SupportingCredentials.ClientCredentials = config.DeviceCredentials;
                    }
                }
                AuthenticationCredentials tokenCredentials =
                    orgServiceManagement.Authenticate(authCredentials);

                if (tokenCredentials != null)
                {
                    if (tokenCredentials.SecurityTokenResponse != null)
                    {
                        config.OrganizationTokenResponse = tokenCredentials.SecurityTokenResponse;
                    }
                }
            }

            return(config);
        }
Example #19
0
        public IOrganizationService CreateOrganizationService(ConfigurationSettings settings)
        {
            Assert.ArgumentNotNull(settings, "settings");
            ConditionalLog.Info("CreateOrganizationService(settings). Started.", this, TimerAction.Start, "createOrganizationService");
            IOrganizationService service = null;

            try
            {
                IServiceManagement <IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(settings.Url));
                AuthenticationCredentials authenticationCredentials         = new AuthenticationCredentials();
                switch (serviceManagement.AuthenticationType)
                {
                case AuthenticationProviderType.ActiveDirectory:
                    authenticationCredentials.ClientCredentials.Windows.ClientCredential = CrmHelper.CreateNetworkCredential(settings.User, settings.Password);
                    service = new OrganizationServiceProxy(serviceManagement, authenticationCredentials.ClientCredentials);
                    break;

                case AuthenticationProviderType.Federation:
                case AuthenticationProviderType.LiveId:
                case AuthenticationProviderType.OnlineFederation:
                {
                    authenticationCredentials.ClientCredentials.UserName.UserName = settings.User;
                    authenticationCredentials.ClientCredentials.UserName.Password = settings.Password;

                    AuthenticationCredentials credentials2 = serviceManagement.Authenticate(authenticationCredentials);

                    //setting to be able to configure using the custom token service proxy
                    if (
                        SitecoreUtility.GetSitecoreSetting <bool>(
                            "AlphaSolutions.ExtendedCRMProvider.V5.Disable.AuthenticationCustomization", false))
                    {
                        service = new CRMSecurityProvider.Repository.V5.ManagedTokenOrganizationServiceProxy(serviceManagement, credentials2.SecurityTokenResponse);
                    }
                    else
                    {
                        service = new ManagedTokenOrganizationServiceProxy(serviceManagement,
                                                                           credentials2.SecurityTokenResponse, authenticationCredentials);
                    }
                    break;
                }
                }

                if (service == null)
                {
                    ConditionalLog.Error("CreateOrganizationService(settings). service could not be initialized.", this);
                    return(null);
                }

                service.Execute(new WhoAmIRequest());
                ConditionalLog.Info("CreateOrganizationService(settings). CRM organization service has been created.", this, TimerAction.Tick, "createOrganizationService");
            }
            catch (Exception exception)
            {
                ConditionalLog.Error("Couldn't create CRM organization service.", exception, this);
                return(null);
            }
            finally
            {
                ConditionalLog.Info("CreateOrganizationService(settings). Finished.", this, TimerAction.Stop, "createOrganizationService");
            }
            return(service);
        }