Exemplo n.º 1
0
        /// <summary>
        ///     Return Organisation Service Proxy
        /// </summary>
        /// <returns></returns>
        public OrganizationServiceProxy GetOrgServiceProxy()
        {
            try
            {
                OrganizationServiceProxy organizationProxy = null;


                var endPointType    = EndpointType.OrganizationService;
                var organizationUri = GetEndpointUrl(endPointType);

                if (!String.IsNullOrWhiteSpace(organizationUri))
                {
                    //test branch
                    //noted this code throws a WCF nametable quote exceeded error
                    //when connecting to CRM 2016 with old SDK assembly versions
                    //if this occurs the assemblies will require updating to v8.1+
                    //note this may cause regression for old CRM versions due to new request properties
                    //e.g. the HasFeedback property on the CreateEntityRequest
                    var orgServiceManagement =
                        ServiceConfigurationFactory.CreateManagement <IOrganizationService>(
                            new Uri(organizationUri));

                    // Set the credentials.
                    var credentials = GetCredentials(CrmConfig.AuthenticationProviderType);

                    organizationProxy = GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement,
                                                                                                  credentials);
                }
                return(organizationProxy);
            }
            catch (Exception ex)
            {
                throw new Exception("Error connecting to crm instance - check your crm connection details", ex);
            }
        }
        private void GetOrganizationCollection(object monitorSync, Uri discoveryUri, out OrganizationDetailCollection orgs)
        {
            IServiceManagement <IDiscoveryService> serviceManagement;

            try
            {
                serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(discoveryUri);
            }
            catch (Exception)
            {
                orgs = null;
                return;
            }
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);

            using (DiscoveryServiceProxy discoveryProxy =
                       GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                orgs = DiscoverOrganizations(discoveryProxy);
            }
            lock (monitorSync)
            {
                Monitor.Pulse(monitorSync);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Establishes a service configuration of type TService at <see cref="Uri"/> location using supplied identity details
        /// </summary>
        /// <param name="serviceUri">The service endpoint location</param>
        /// <param name="username">The username of the identity to authenticate</param>
        /// <param name="password">The password of the identity to authenticate</param>
        /// <param name="domain">Optional parameter for specifying the domain (when known)</param>
        /// <param name="homeRealm">Optional parameter for specifying the federated home realm location (when known)</param>
        protected XrmServiceManager(Uri serviceUri, string username, string password, string domain = null, Uri homeRealm = null)
        {
            this.ServiceUri        = serviceUri;
            this.ServiceManagement = ServiceConfigurationFactory.CreateManagement <TService>(serviceUri);

            Authenticate(username, password, domain, homeRealm);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates an OrganizationServiceProxy using the specified settings.  This should always be wrapped in a using statement so the dispose method is called.
        /// </summary>
        /// <param name="crmOrganizationUrl">The CRM organization URL.</param>
        /// <param name="crmSdkServerUrl">The CRM Sdk server URL.</param>
        /// <param name="crmOrganization">The CRM organization.</param>
        /// <param name="impersonationUserId">The impersonation user id.</param>
        /// <param name="enableProxyTypes">if set to <c>true</c> [enable proxy types].</param>
        /// <param name="ifdUserName">IFD's User Name </param>
        /// <param name="ifdPassword">IFD User's Password</param>
        /// <param name="isIfdDeployment">Indicates whether this is an IFD Deployment.</param>
        /// <returns></returns>
        public static OrganizationServiceProxy CreateOrgProxy(string crmOrganizationUrl, string crmSdkServerUrl, string crmOrganization, Guid impersonationUserId = new Guid(), bool enableProxyTypes = true, bool isIfdDeployment = false, string ifdUserName = "", string ifdPassword = "")
        {
            crmOrganization = GetCrmOrganizationName(crmSdkServerUrl, crmOrganization);
            Uri orgUri = GetOrganizationServiceUri(crmOrganizationUrl, crmOrganization, isIfdDeployment);
            IServiceConfiguration <IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(orgUri);

            var creds = new ClientCredentials();

            if (isIfdDeployment)
            {
                creds.UserName.UserName = ifdUserName;
                creds.UserName.Password = ifdPassword;
            }

            OrganizationServiceProxy orgService = new OrganizationServiceProxy(orgConfigInfo, creds);

            if (enableProxyTypes)
            {
                ;
                orgService.EnableProxyTypes(GetEarlyBoundProxyAssembly());
            }

            if (impersonationUserId != Guid.Empty)
            {
                orgService.CallerId = impersonationUserId;
            }

            return(orgService);
        }
Exemplo n.º 5
0
        private static IServiceManagement <IOrganizationService> GetOrganizationServiceConfiguration(ConnectionData connectionData, Uri uri)
        {
            if (_cacheOrganizationServiceManagement.ContainsKey(uri))
            {
                return(_cacheOrganizationServiceManagement[uri]);
            }

            if (!UrlIsAvailable(uri))
            {
                return(null);
            }

            try
            {
                var management = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(uri);

                if (!_cacheOrganizationServiceManagement.ContainsKey(uri))
                {
                    _cacheOrganizationServiceManagement.TryAdd(uri, management);
                }

                return(management);
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(connectionData, ex);
            }

            return(null);
        }
        private static void PlainSdk()
        {
            try
            {
                Console.WriteLine("Testing plain sdk");
                var defaultCredentials = new AuthenticationCredentials()
                {
                    ClientCredentials = new ClientCredentials()
                    {
                        Windows = { ClientCredential = CredentialCache.DefaultNetworkCredentials }
                    }
                };
                IServiceManagement <IOrganizationService> orgServiceManagement =
                    ServiceConfigurationFactory.CreateManagement <IOrganizationService>(serviceUri);

                // go crazy on creating new proxies to simulate, for example, a high traffic web api.
                Parallel.ForEach(Enumerable.Range(0, 100000), (index) =>
                {
                    var proxy = new OrganizationServiceProxy(orgServiceManagement, defaultCredentials.ClientCredentials);

                    // From the link above:
                    // If you enable early-bound types on OrganizationServiceProxy through one of the EnableProxyTypes() methods,
                    // you must do the same on all service proxies that are created from the cached IServiceManagement < TService > object.
                    proxy.EnableProxyTypes();

                    proxy.Execute(new WhoAmIRequest());
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 7
0
        public static OrganizationServiceProxy getProxy()
        {
            IServiceManagement <IOrganizationService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(OrganizationUri));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            if (endpointType == AuthenticationProviderType.LiveId)
            {
                var connectionString = getConnectionString();

                var connection = CrmConnection.Parse(connectionString);
                OrganizationService      servicio = new OrganizationService(connection);
                IOrganizationService     _service = (IOrganizationService)servicio.InnerService;
                OrganizationServiceProxy _proxy   = (OrganizationServiceProxy)_service;
                return(_proxy);
            }
            else if (endpointType == AuthenticationProviderType.ActiveDirectory)
            {
                ClientCredentials credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new System.Net.NetworkCredential(UserName, Password, dominio);
                OrganizationServiceProxy _proxy = new OrganizationServiceProxy(new Uri(OrganizationUri), null, credentials, null);
                return(_proxy);
            }
            else //esta será la que realmente se utilice en el caso del nuevo Crm online
            {
                AuthenticationCredentials authCredentials = new AuthenticationCredentials();
                authCredentials.ClientCredentials.UserName.UserName = UserName;
                authCredentials.ClientCredentials.UserName.Password = Password;

                OrganizationServiceProxy _proxy = GetProxy <IOrganizationService, OrganizationServiceProxy>(serviceManagement, authCredentials);
                return(_proxy);
            }
        }
        //_userId = new Guid("870BEBB1-8C42-E611-80EA-5065F38BF4F1");
        public static IOrganizationService ConnectToMSCRM()
        {
            try
            {
                var discoveryUri = ConfigurationManager.AppSettings["DiscoveryUri"];

                IServiceManagement <IDiscoveryService> serviceManagement =
                    ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                        new Uri(discoveryUri));
                AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

                // Set the credentials.
                AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);

                Uri serviceUri = new Uri(ConfigurationSettings.AppSettings["OrganizationUri"]);

                OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, authCredentials.ClientCredentials, null);
                proxy.EnableProxyTypes();
                IOrganizationService service = (IOrganizationService)proxy;

                return(service);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while connecting to CRM " + ex.Message, "CRM connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
Exemplo n.º 9
0
        public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password)
        {
            if (org != null)
            {
                Uri orgServiceUri = null;
                orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]);
                //if (!string.IsNullOrEmpty(OrganisationServiceHostName))
                //{
                //    UriBuilder builder = new UriBuilder(orgServiceUri);
                //    builder.Host = OrganisationServiceHostName;
                //    orgServiceUri = builder.Uri;
                //}

                IServiceConfiguration <IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(orgServiceUri);

                var creds      = _credentialsProvider.GetCredentials(orgConfigInfo.AuthenticationType, domain, userName, password);
                var orgService = new OrganizationServiceProxy(orgConfigInfo, creds);
                orgService.Timeout = new TimeSpan(0, 5, 0);

                var req      = new WhoAmIRequest();
                var response = (WhoAmIResponse)orgService.Execute(req);

                Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId));
                return(orgService);
            }
            return(null);
        }
Exemplo n.º 10
0
        protected override void BeginProcessing()
        {
            base.BeginProcessing();

            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                var crmEndPoint = new Uri(EndPoint);
                var manager     = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(crmEndPoint);

                var credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = new NetworkCredential(Username, Password);

                var proxy = new OrganizationServiceProxy(manager.CurrentServiceEndpoint.ListenUri, null, credentials,
                                                         null);
                proxy.Timeout = new TimeSpan(0, 0, Timeout == 0 ? DefaultTime : Timeout);
                proxy.EnableProxyTypes();
                OrganizationService = proxy;
            }
            catch (Exception e)
            {
                throw new Exception($"Unable to connect to CRM on endpoint: ${EndPoint}");
            }
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            try
            {
                var crmUrl      = ConfigurationManager.AppSettings["CrmUrl"];
                var url         = new Uri(crmUrl + "/XRMServices/2011/Discovery.svc");
                var config      = ServiceConfigurationFactory.CreateConfiguration <IDiscoveryService>(url);
                var credentials = new ClientCredentials();
                credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                var discoveryService = new DiscoveryServiceProxy(config, credentials);
                discoveryService.Authenticate();
                var request  = new RetrieveOrganizationsRequest();
                var response = (RetrieveOrganizationsResponse)discoveryService.Execute(request);

                foreach (var detail in response.Details)
                {
                    var organizationServiceUrl = detail.Endpoints[EndpointType.OrganizationService];
                    var organizationName       = detail.UniqueName;
                    GetOrganizationInfo(organizationName, organizationServiceUrl);
                }
                Console.WriteLine("Press any key to close the window.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured." + Environment.NewLine + ex.ToString());
            }
        }
Exemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        public void Run()
        {
            //<snippetAuthenticateWithNoHelp1>
            IServiceManagement <IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                    new Uri(_discoveryServiceAddress));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            // Set the credentials.
            AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);


            String organizationUri = String.Empty;

            // Get the discovery service proxy.
            using (DiscoveryServiceProxy discoveryProxy =
                       GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                // Obtain organization information from the Discovery service.
                if (discoveryProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
                    // Obtains the Web address (Uri) of the target organization.
                    organizationUri = FindOrganization(_organizationUniqueName,
                                                       orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
                }
            }
            //</snippetAuthenticateWithNoHelp1>


            if (!String.IsNullOrWhiteSpace(organizationUri))
            {
                //<snippetAuthenticateWithNoHelp3>
                IServiceManagement <IOrganizationService> orgServiceManagement =
                    ServiceConfigurationFactory.CreateManagement <IOrganizationService>(
                        new Uri(organizationUri));

                // Set the credentials.
                AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);

                // Get the organization service proxy.
                using (OrganizationServiceProxy organizationProxy =
                           GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
                {
                    // This statement is required to enable early-bound type support.
                    organizationProxy.EnableProxyTypes();

                    // Now make an SDK call with the organization service proxy.
                    // Display information about the logged on user.
                    Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
                                       new WhoAmIRequest())).UserId;
                    SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
                                                                       new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity <SystemUser>();
                    Console.WriteLine("Logged on user is {0} {1}.",
                                      systemUser.FirstName, systemUser.LastName);
                }
                //</snippetAuthenticateWithNoHelp3>
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Return Organisation Version
        /// </summary>
        /// <returns></returns>
        public string GetOrganisationVersion()
        {
            try
            {
                string result = null;

                // Set the credentials.
                var authCredentials = GetCredentials(CrmConfig.AuthenticationProviderType);

                var serviceManagement =
                    ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                        new Uri(CrmConfig.DiscoveryServiceAddress));

                // Get the discovery service proxy.
                using (var discoveryProxy =
                           GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
                {
                    // Obtain organization information from the Discovery service.
                    if (discoveryProxy != null)
                    {
                        // Obtain information about the organizations that the system user belongs to.
                        var orgs = DiscoverOrganizations(discoveryProxy);
                        // Obtains the Web address (Uri) of the target organization.
                        result = FindOrganization(CrmConfig.OrganizationUniqueName,
                                                  orgs.ToArray()).OrganizationVersion;
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception("Error getting organisation version - check your crm connection details", ex);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        public OrganizationServiceProxy GetOrganizationProxy()
        {
            IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(new Uri(DiscoveryServiceAddress));
            AuthenticationProviderType             endpointType      = serviceManagement.AuthenticationType;
            AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);


            String organizationUri = String.Empty;

            // Get the discovery service proxy.
            using (DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                // Obtain organization information from the Discovery service.
                if (discoveryProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
                    // Obtains the Web address (Uri) of the target organization.
                    organizationUri = FindOrganization(OrganizationUniqueName, orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
                }
            }


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

            // Set the credentials.
            AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);

            // Get the organization service proxy.
            return(GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials));
        }
        private static IServiceManagement <IDiscoveryService> GetDiscoveryServiceConfiguration(ConnectionData connectionData, Uri uri)
        {
            SetServicePointProperties(uri);

            if (_cacheDiscoveryServiceManagement.ContainsKey(uri))
            {
                return(_cacheDiscoveryServiceManagement[uri]);
            }

            if (!UrlIsAvailable(uri))
            {
                return(null);
            }

            try
            {
                var serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(uri);

                if (!_cacheDiscoveryServiceManagement.ContainsKey(uri))
                {
                    _cacheDiscoveryServiceManagement.TryAdd(uri, serviceManagement);
                }

                return(serviceManagement);
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(connectionData, ex);
            }

            return(null);
        }
        public IOrganizationService GetOrgService(string orgname)
        {
            try
            {
                var customerCredentials = new CustomerCredentialsHandler().GetCredentials(orgname);
                var discoveryUri        = customerCredentials.discoveryurl; //ConfigurationManager.AppSettings["DiscoveryUri"];

                IServiceManagement <IDiscoveryService> serviceManagement =
                    ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                        new Uri(discoveryUri));
                AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

                // Set the credentials.
                AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType, customerCredentials);

                Uri serviceUri = new Uri(customerCredentials.orgurl); //ConfigurationSettings.AppSettings["OrganizationUri"]);

                OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, authCredentials.ClientCredentials, null);
                proxy.EnableProxyTypes();
                IOrganizationService service = (IOrganizationService)proxy;

                return(service);
            }
            catch (SoapException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Establishes a service configuration at <see cref="Uri"/> location using supplied <see cref="AuthenticationCredentials"/>
        /// </summary>
        /// <param name="serviceUri">The service endpoint location</param>
        /// <param name="credentials">The auth credentials</param>
        /// <remarks>
        /// <see cref="AuthenticationCredentials"/> can represent AD, Claims, or Cross-realm Claims <see cref="ClientCredentials"/>
        /// The authCredentials may already contain a <see cref="SecurityTokenResponse"/>
        /// For cross-realm (federated) scenarios it can contain a HomeRealm Uri by itself, or also include a <see cref="SecurityTokenResponse"/> from the federated realm
        /// </remarks>
        protected XrmServiceManager(Uri serviceUri, AuthenticationCredentials credentials)
        {
            this.ServiceUri        = serviceUri;
            this.ServiceManagement = ServiceConfigurationFactory.CreateManagement <TService>(serviceUri);

            Authenticate(credentials);
        }
Exemplo n.º 18
0
        private string GetEndpointUrl(EndpointType endPointType)
        {
            string result = null;

            // Set the credentials.
            var authCredentials = GetCredentials(CrmConfig.AuthenticationProviderType);

            var serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                    new Uri(CrmConfig.DiscoveryServiceAddress));

            // Get the discovery service proxy.
            using (var discoveryProxy =
                       GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                // Obtain organization information from the Discovery service.
                if (discoveryProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    var orgs = DiscoverOrganizations(discoveryProxy);
                    // Obtains the Web address (Uri) of the target organization.
                    result = FindOrganization(CrmConfig.OrganizationUniqueName,
                                              orgs.ToArray()).Endpoints[endPointType];
                }
            }

            return(result);
        }
Exemplo n.º 19
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));
        }
        public void SetIServiceManagementForOrganization(ref ServerConnection.Configuration config)
        {
            IServiceManagement <IOrganizationService> orgServiceManagement =
                ServiceConfigurationFactory.CreateManagement <IOrganizationService>(
                    config.OrganizationUri);

            config.OrganizationServiceManagement = orgServiceManagement;
        }
        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);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Obtém o tipo de autenticação.
        /// </summary>
        /// <param name="uri">URI do DicoveryService do CRM.</param>
        /// <returns>Tipo de autenticação.</returns>
        private static AuthenticationProviderType GetServerType(Uri uri)
        {
            if (Authentication == AuthenticationProviderType.None)
            {
                Authentication = ServiceConfigurationFactory.CreateConfiguration <IDiscoveryService>(uri).AuthenticationType;
            }

            return(Authentication);
        }
Exemplo n.º 23
0
        internal OrganizationServiceProxy Authenticate()
        {
            var m     = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(url));
            var ac    = m.Authenticate(GetCredentials());
            var proxy = GetOrganizationServiceProxy(m, ac);

            proxy.ServiceConfiguration.CurrentServiceEndpoint.EndpointBehaviors.Add(new ProxyTypesBehavior());
            return(proxy);
        }
Exemplo n.º 24
0
        public DiscoveryServiceProxy GetDiscoveryServiceProxy(string discoveryServiceAddress, DynamicsCredentials credentials)
        {
            var serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(new Uri(discoveryServiceAddress));

            var endpointType    = serviceManagement.AuthenticationType;
            var authCredentials = GetCredentials(serviceManagement, endpointType, credentials);
            var discoveryProxy  = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials);

            return(discoveryProxy);
        }
        protected virtual IServiceConfiguration <IDiscoveryService> CreateServiceConfiguration(Uri uri)
        {
            var fullServiceUri = uri.AbsolutePath.EndsWith(_discoveryUri, StringComparison.OrdinalIgnoreCase)
                                ? uri
                                : new Uri(uri, uri.AbsolutePath.TrimEnd('/') + _discoveryUri);

            var config = ServiceConfigurationFactory.CreateConfiguration <IDiscoveryService>(fullServiceUri);

            return(config);
        }
Exemplo n.º 26
0
        // ReSharper disable once UnusedMember.Global
        public static Configuration GetConfiguration(string url, string orgName = null, bool useDefaultCredentials = false)
        {
            ClientCredentials clientCredentials;

            if (useDefaultCredentials)
            {
                clientCredentials = new ClientCredentials();
                clientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                var dialog =
                    new CredentialDialog
                {
                    MainInstruction  = "Please enter your CRM credentials",
                    ShowSaveCheckBox = true,
                    UseApplicationInstanceCredentialCache = true,
                    ShowUIForSavedCredentials             = true,
                    Target      = "OwnSpace_CRMSDK_",
                    WindowTitle = "Credentials dialog"
                };
                var dialogResult = dialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    dialog.ConfirmCredentials(true);

                    var authCredentials = new AuthenticationCredentials();
                    authCredentials.ClientCredentials.UserName.UserName = dialog.Credentials.UserName;
                    authCredentials.ClientCredentials.UserName.Password = dialog.Credentials.Password;
                    clientCredentials = authCredentials.ClientCredentials;
                }
                else
                {
                    return(null);
                }
            }

            var organizationServiceUri        = GetOrganizationServiceUri(url, orgName);
            var discoveryServiceUri           = GetDiscoveryServiceUri(url, orgName);
            var organizationServiceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(organizationServiceUri);
            var discoveryServiceManagement    = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(discoveryServiceUri);
            var config =
                new Configuration(url, orgName, organizationServiceManagement.AuthenticationType)
            {
                OrganizationUri = organizationServiceUri,
                DiscoveryUri    = discoveryServiceUri,
                Credentials     = clientCredentials,
                OrganizationServiceManagement = organizationServiceManagement,
                DiscoveryServiceManagement    = discoveryServiceManagement
            };

            config.Credentials = FulfillCredentials(config);

            return(config);
        }
Exemplo n.º 27
0
 private static AuthenticationProviderType GetAuthenticationType(Uri serviceUri)
 {
     try
     {
         var config = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(serviceUri);
         return(config.AuthenticationType);
     }
     catch (Exception e)
     {
         throw new ModelErrorException("OrganizationServiceUrl", "The Organization Service URL is invalid.", e);
     }
 }
Exemplo n.º 28
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));
        }
        public ImportManager(string user, string pwd, string url)
        {
            var credentials = new ClientCredentials();

            credentials.UserName.UserName = user;
            credentials.UserName.Password = pwd;

            var config = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(new Uri(url));

            orgService = new OrganizationServiceProxy(config, credentials);
            IOrganizationService service = (IOrganizationService)orgService;
        }
 private static AuthenticationProviderType GetAuthenticationType(Uri serviceUri)
 {
     try
     {
         var config = ServiceConfigurationFactory.CreateConfiguration <IOrganizationService>(serviceUri);
         return(config.AuthenticationType);
     }
     catch (Exception e)
     {
         throw new ModelErrorException("OrganizationServiceUrl", ResourceManager.GetString("Organization_Service_URL_IsInvalid_Exception"), e);
     }
 }