Example #1
0
        public async Task <Tuple <string, string> > ConnectToMSCRMAsync()
        {
            string connectionCode = "0";
            string errorMessage   = "";

            try
            {
                ClientCredentials credentials = new ClientCredentials();
                credentials.UserName.UserName = _username;
                credentials.UserName.Password = _password;
                Uri serviceUri = new Uri(_soapUri);

                using (OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null))
                {
                    await Task.Run(() => proxy.Authenticate());

                    service = proxy;
                }
            }
            catch (Exception ex)
            {
                connectionCode = "-1";
                errorMessage   = ex.Message;
            }

            return(new Tuple <string, string>(connectionCode, errorMessage));
        }
Example #2
0
        public IOrganizationService Connect(string userName, string password)
        {
            ClientCredentials clientCredentials = new ClientCredentials();

            clientCredentials.UserName.UserName = userName;
            clientCredentials.UserName.Password = password;

            // For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            // Get the URL from CRM, Navigate to Settings -> Customizations -> Developer Resources
            // Copy and Paste Organization Service Endpoint Address URL
            var proxy = new OrganizationServiceProxy(new Uri(_url),
                                                     null, clientCredentials, null);

            try
            {
                proxy.Authenticate();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && ex.InnerException.Message == "Authentication Failure")
                {
                    throw new Exception($"Failed to connect Url: {_url}, UserName: ${userName}");
                }
                throw;
            }
            return((IOrganizationService)proxy);
        }
        public static IOrganizationService GetClientContext(ISiteSetting siteSetting)
        {
            try
            {
                if (cachedServices.ContainsKey(siteSetting.ID) == false)
                {
                    IOrganizationService organizationService = null;
                    Uri uri = new Uri(siteSetting.Url + "/XRMServices/2011/Organization.svc");

                    var credentials = new ClientCredentials();
                    if (siteSetting.UseDefaultCredential == true)
                    {
                        credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        string[] userNameValues = siteSetting.Username.Split(new string[] { "\\" }, StringSplitOptions.None);
                        string   domainName     = string.Empty;
                        string   userName       = string.Empty;
                        if (userNameValues.Length > 1)
                        {
                            domainName = userNameValues[0];
                            userName   = userNameValues[1];
                        }
                        else
                        {
                            userName = userNameValues[0];
                        }

                        if (string.IsNullOrEmpty(domainName) == true)
                        {
                            credentials.UserName.UserName = userName;
                            credentials.UserName.Password = siteSetting.Password;
                        }
                        else
                        {
                            credentials.Windows.ClientCredential =
                                new System.Net.NetworkCredential(userName,
                                                                 siteSetting.Password,
                                                                 domainName);
                        }
                    }

                    using (OrganizationServiceProxy organizationServiceProxy = new OrganizationServiceProxy(uri, null, credentials, null))
                    {
                        organizationServiceProxy.Authenticate();
                        organizationService = (IOrganizationService)organizationServiceProxy;
                    }

                    cachedServices.Add(siteSetting.ID, organizationService);
                }

                return(cachedServices[siteSetting.ID]);
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            //new Program().ss();

            string UserName = @"softline\savchinvv";
            string Password = @"IH@veToBeABoss";
            var    creds    = new ClientCredentials();

            creds.UserName.UserName = UserName;
            creds.UserName.Password = Password;

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"http://msk02crm13web06/UkraineTest13/XRMServices/2011/Organization.svc"), null, creds, null);

            serviceProxy.EnableProxyTypes();
            serviceProxy.Authenticate();
            var serviceCRM = (IOrganizationService)serviceProxy;;

            using (var orgContext = new OrganizationServiceContext(serviceCRM))
            {
                var ann = (from q in orgContext.CreateQuery <Annotation>()
                           select q).FirstOrDefault();

                //if (!ann.IsDocument.Value || ann.ObjectId.LogicalName.ToLower() != "quote") return;

                var tempFile = SaveFile(ann.FileName, ann.DocumentBody);

                //Scopes for use with the Google Drive API
                string[] scopes = new string[] { DriveService.Scope.Drive,
                                                 DriveService.Scope.DriveFile };
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential =
                    GoogleWebAuthorizationBroker
                    .AuthorizeAsync(new ClientSecrets
                {
                    ClientId = @"560656622534-clntle0fod1nerinp6tp9o0ovdnnq570.apps.googleusercontent.com"
                    ,
                    ClientSecret = "zkYePr5TCLt9JwL9gSJGd5PZ",
                }
                                    , scopes
                                    , Environment.UserName
                                    , CancellationToken.None
                                    , new FileDataStore("Daimto.GoogleDrive.Auth.Store")
                                    ).Result;

                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "Drive API Sample",
                });
                var file = uploadFile(service, tempFile, "Drive");
            }
        }
Example #5
0
        private IOrganizationService GetService()
        {
            // Get services and contexten
            IOrganizationService     service;
            OrganizationServiceProxy serviceProxy;

            try
            {
                var creds = new ClientCredentials();
                creds.UserName.UserName = @"SL\s_crm";
                creds.UserName.Password = @"Pa$$w0rd";

                ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
                serviceProxy = new OrganizationServiceProxy(new Uri(@"https://crm.softline.az/SoftlineInternationalLtd/XRMServices/2011/Organization.svc"), null, creds, null);

                serviceProxy.EnableProxyTypes();
                serviceProxy.Authenticate();
                service = (IOrganizationService)serviceProxy;

                /*IServiceConfiguration<IOrganizationService> orgConfigInfo =
                 *  ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(
                 *      new Uri("https://crm.softline.az/SoftlineInternationalLtd/XRMServices/2011/Organization.svc")
                 *  );
                 * var creds = new System.ServiceModel.Description.ClientCredentials();
                 * creds.Windows.ClientCredential =
                 *  new System.Net.NetworkCredential(
                 *      @"SL\s_crm", @"Pa$$w0rd"
                 *  );*/

                //IServiceConfiguration<IOrganizationService> orgConfigInfo =
                //    ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(
                //        new Uri("http://192.168.1.127/softline1/XRMServices/2011/Organization.svc")
                //    );
                //var creds = new System.ServiceModel.Description.ClientCredentials();
                //creds.Windows.ClientCredential =
                //    new System.Net.NetworkCredential(
                //        @"crm2011net\crmdemoadmin", @"1234Qwer"
                //    );

                /* using (serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
                 * {
                 *   serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                 *   service = (IOrganizationService)serviceProxy;
                 * }*/
            }
            catch (Exception ex)
            {
                throw;
            }

            return(service);
        }
Example #6
0
        public IOrganizationService Connect()
        {
            var creds = new ClientCredentials();
            creds.UserName.UserName = UserName;
            creds.UserName.Password = Password;

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"https://ukraine.crm.softlinegroup.com/XrmServices/2011/Organization.svc"), null, creds, null);

            serviceProxy.EnableProxyTypes();
            serviceProxy.Authenticate();
            return (IOrganizationService)serviceProxy;
        }
Example #7
0
        static void Main(string[] args)
        {
            //new Program().ss();

            string UserName = @"softline\savchinvv";
            string Password = @"IH@veToBeABoss";
            var creds = new ClientCredentials();
            creds.UserName.UserName = UserName;
            creds.UserName.Password = Password;

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"http://msk02crm13web06/UkraineTest13/XRMServices/2011/Organization.svc"), null, creds, null);

            serviceProxy.EnableProxyTypes();
            serviceProxy.Authenticate();
            var serviceCRM = (IOrganizationService)serviceProxy; ;
            using (var orgContext = new OrganizationServiceContext(serviceCRM))
            {
                var ann = (from q in orgContext.CreateQuery<Annotation>()
                           select q).FirstOrDefault();

                //if (!ann.IsDocument.Value || ann.ObjectId.LogicalName.ToLower() != "quote") return;

                var tempFile = SaveFile(ann.FileName, ann.DocumentBody);

                //Scopes for use with the Google Drive API
                string[] scopes = new string[] { DriveService.Scope.Drive,
                                 DriveService.Scope.DriveFile};
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential =
                            GoogleWebAuthorizationBroker
                                          .AuthorizeAsync(new ClientSecrets
                                          {
                                              ClientId = @"560656622534-clntle0fod1nerinp6tp9o0ovdnnq570.apps.googleusercontent.com"
                                          ,
                                              ClientSecret = "zkYePr5TCLt9JwL9gSJGd5PZ",
                                          }
                                                          , scopes
                                                          , Environment.UserName
                                                          , CancellationToken.None
                                                          , new FileDataStore("Daimto.GoogleDrive.Auth.Store")
                                                          ).Result;

                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Sample",
                });
                var file = uploadFile(service, tempFile,"Drive");
            }
        }
Example #8
0
        public IOrganizationService Connect()
        {
            var creds = new ClientCredentials();

            creds.UserName.UserName = UserName;
            creds.UserName.Password = Password;

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };
            OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(new Uri(@"https://ukraine.crm.softlinegroup.com/XrmServices/2011/Organization.svc"), null, creds, null);

            serviceProxy.EnableProxyTypes();
            serviceProxy.Authenticate();
            return((IOrganizationService)serviceProxy);
        }
Example #9
0
        private void Connect(string serviceUrl, string username, string password)
        {
            Console.WriteLine($"Establishing new CRM connection to {serviceUrl} for {username}...");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            ClientCredentials credentials = new ClientCredentials();

            credentials.UserName.UserName = username;
            credentials.UserName.Password = password;

            IServiceManagement <IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(serviceUrl));

            OrganizationService = new OrganizationServiceProxy(orgServiceManagement, credentials);
            OrganizationService.Authenticate();
        }
Example #10
0
        //connecting via sushil method working
        //private CRMServiceConn()
        //{
        //    var discoUri = GetDiscoveryServiceUri("https://disco.crm5.dynamics.com");
        //    IServiceConfiguration<IDiscoveryService> dinfo = ServiceConfigurationFactory.CreateConfiguration<IDiscoveryService>(discoUri);
        //    _ClientCreds = new ClientCredentials();
        //    //_ClientCreds.UserName.UserName = "******";
        //    //_ClientCreds.UserName.Password = "******";
        //    _ClientCreds.UserName.UserName = "******";
        //    _ClientCreds.UserName.Password = "******";
        //    _DeviceCreds = DeviceIdManager.LoadOrRegisterDevice();
        //    DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(discoUri, null, _ClientCreds, _DeviceCreds);

        //    dsp.Authenticate();
        //    var orgRequest = new RetrieveOrganizationsRequest();
        //    var orgResponse = dsp.Execute(orgRequest) as RetrieveOrganizationsResponse;
        //    //comboOrgs.DataSource = orgResponse.Details;
        //    //comboOrgs.DisplayMember = "FriendlyName";
        //    //comboOrgs.ValueMember = "UrlName";


        //    foreach (var resp in orgResponse.Details)
        //    {
        //     //   if (resp.UniqueName == "testingdsm"
        //            if (resp.UniqueName == "testdsm")

        //        {
        //            this.CurrentOrganizationDetail = resp as OrganizationDetail;
        //            Uri orgServiceUri = new Uri(CurrentOrganizationDetail.Endpoints[EndpointType.OrganizationService]);
        //            OrgService = new OrganizationServiceProxy(orgServiceUri, null, _ClientCreds, _DeviceCreds);
        //        }
        //    }

        //}

        // Lock synchronization object

        //connecting via prasads method a context is created...
        private CRMServiceConn()
        {
            ClientCredentials credentials = new ClientCredentials();

            //When creating a CRM online trial version, through Microsoft Online services you will setup a username and password
            credentials.UserName.UserName = "******";
            credentials.UserName.Password = "******";

            OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(
                //new Uri("https://testdsm.api.crm5.dynamics.com/XRMServices/2011/Organization.svc"),
                new Uri("https://testdsm.api.crm5.dynamics.com/XRMServices/2011/Organization.svc"),
                null,
                credentials, null);

            orgProxy.EnableProxyTypes();
            orgProxy.Authenticate();
            service = (IOrganizationService)orgProxy;
            context = new xrmdemo5(service);
        }
Example #11
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);
        }
Example #12
0
 /// <summary>
 /// Renew the token(if it is near expiration or has expired)
 /// </summary>
 /// <param name="_proxy"></param>
 /// <see cref="https://alisharifiblog.wordpress.com/2017/02/13/refresh-security-token-for-microsoft-dynamics-crm/"/>
 /// <see cref="https://stackoverflow.com/questions/27154282/is-there-an-organizationservice-connection-keep-alive-setting"/>
 /// <see cref="https://blog.thomasfaulkner.nz/post/2015/03/crm-organization-service-(re)authentication"/>
 public static void RenewTokenIfRequired(OrganizationServiceProxy _proxy)
 {
     if (null != _proxy.SecurityTokenResponse &&
         DateTime.UtcNow.AddMinutes(15) >= _proxy.SecurityTokenResponse.Response.Lifetime.Expires)
     {
         try
         {
             _proxy.Authenticate();
         }
         catch (CommunicationException)
         {
             if (null == _proxy.SecurityTokenResponse ||
                 DateTime.UtcNow >= _proxy.SecurityTokenResponse.Response.Lifetime.Expires)
             {
                 throw;
             }
             // Ignore the exception
         }
     }
 }
        public void Connect()
        {
            // Obtain the target organization's Web address and client logon
            // credentials from the user.
            _serverConnection = new ServerConnection();
            _serverConfig     = _serverConnection.GetServerConfiguration();

            _serviceProxy = new OrganizationServiceProxy(_serverConfig.OrganizationUri, _serverConfig.HomeRealmUri, _serverConfig.Credentials, _serverConfig.DeviceCredentials);

            _serviceProxy.Authenticate();

            // This statement is required to enable early-bound type support.
            _serviceProxy.EnableProxyTypes();

            if (!_serviceProxy.IsAuthenticated)
            {
                throw new InvalidOperationException("Authentication could not be completed");
            }

            Console.WriteLine($"Successfully connected to :\n=> {_serverConfig.OrganizationUri}\n");
        }