protected virtual Uri GetOrganizationAddress(Uri discoveryServiceUri, string orgName)
        {
            using (DiscoveryServiceProxy _serviceProxy = ServerConnection.GetProxy <IDiscoveryService, DiscoveryServiceProxy>(config))
            {
                // Obtain organization information from the Discovery service.
                if (_serviceProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(_serviceProxy);

                    OrganizationDetail org = orgs.Where(x => x.UniqueName.ToLower() == orgName.ToLower()).FirstOrDefault();

                    if (org != null)
                    {
                        return(new System.Uri(org.Endpoints[EndpointType.OrganizationService]));
                    }
                    else
                    {
                        throw new InvalidOperationException("That OrgName does not exist on that server.");
                    }
                }
                else
                {
                    throw new Exception("An invalid server name was specified.");
                }
            }
        }
        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);
            }
        }
        /// <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));
        }
Exemple #4
0
        /// <summary>
        /// obtém o endereço do serviço do CRM 2011.
        /// </summary>
        /// <param name="discoveryServiceUri">URI do Discovery Service CRM 2011</param>
        /// <param name="organization">Organização.</param>
        /// <returns></returns>
        protected virtual Uri GetOrganizationAddress(Uri discoveryServiceUri, string organization)
        {
            Uri organizationAddress = GetOrganizationAddress(organization, Organizations);

            if (organizationAddress == null)
            {
                //using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
                using (DiscoveryServiceProxy serviceProxy = this.DiscoveryService)
                {
                    if (serviceProxy == null)
                    {
                        throw new ArgumentException("Servidor informado no arquivo de configuração é inválido ");
                    }

                    OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);
                    if (orgs == null || orgs.Count == 0)
                    {
                        throw new ArgumentException("Usuário informado não possui nenhuma organização.");
                    }

                    for (int index = 0; index < orgs.Count; index++)
                    {
                        if (orgs[index].UniqueName.ToUpper() != organization.ToUpper())
                        {
                            continue;
                        }

                        organizationAddress = new Uri(orgs[index].Endpoints[EndpointType.OrganizationService]);
                        break;
                    }
                }
            }
            return(organizationAddress);
        }
        public static List <string> GetOrganizations(string url, string domain, string username, string password)
        {
            var results = new List <string>()
            {
            };
            var credentials = GetCredentials(url, domain, username, password);
            ClientCredentials deviceCredentials = null;

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

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

            return(results);
        }
Exemple #6
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>
            }
        }
Exemple #7
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 OrganizationDetailCollection GetOrganizationAddressesAsList(ServerConnection.Configuration config)
 {
     OrganizationDetailCollection orgs = new OrganizationDetailCollection();
     using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy(config)) {
         // Obtain organization information from the Discovery service.
         if (serviceProxy != null)
             orgs = DiscoverOrganizations(serviceProxy);
     }
     return orgs;
 }
Exemple #9
0
        public Microsoft.Xrm.Sdk.IOrganizationService GetService(string serverURL, string userName, string userPassword, string userDomain, string organizationCRM)
        {
            //to ignore certificates errors
            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(AcceptAllCertificatePolicy);

            IServiceManagement <IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                    new Uri(string.Format("{0}/XRMServices/2011/Discovery.svc", serverURL)));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            // Set the credentials.
            AuthenticationCredentials authCredentials = GetCredentials(endpointType, userName, userPassword, userDomain);

            String organizationUri = String.Empty;

            // Get the discovery service proxy.
            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(organizationCRM,
                                                   orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
            }


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

                // Set the credentials.
                AuthenticationCredentials credentials = GetCredentials(endpointType, userName, userPassword, userDomain);

                // Get the organization service proxy.
                OrganizationServiceProxy organizationProxy =
                    GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials);

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

                return(organizationProxy);
            }

            return(null);
        }
        public OrganizationDetailCollection GetOrganizationAddressesAsList(ServerConnection.Configuration config)
        {
            OrganizationDetailCollection orgs = new OrganizationDetailCollection();

            using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy(config)) {
                // Obtain organization information from the Discovery service.
                if (serviceProxy != null)
                {
                    orgs = DiscoverOrganizations(serviceProxy);
                }
            }
            return(orgs);
        }
        /// <summary>
        /// Obtains the Web address (Uri) of the target organization.
        /// </summary>
        /// <param name="discoveryServiceUri">The Uri of the CRM Discovery service.</param>
        /// <returns>Uri of the organization service or an empty string.</returns>
        protected virtual Uri GetOrganizationAddress(Uri discoveryServiceUri)
        {
            using (DiscoveryServiceProxy serviceProxy = new DiscoveryServiceProxy(discoveryServiceUri, null, config.Credentials, config.DeviceCredentials))
            {
                // Obtain organization information from the Discovery service.
                if (serviceProxy != null)
                {
                    // Obtain information about the organizations that the system user belongs to.
                    OrganizationDetailCollection orgs = DiscoverOrganizations(serviceProxy);

                    if (orgs.Count > 0)
                    {
                        Console.WriteLine("\nList of organizations that you belong to:");
                        for (int n = 0; n < orgs.Count; n++)
                        {
                            Console.Write("\n({0}) {1} ({2})\t", n + 1, orgs[n].FriendlyName, orgs[n].UrlName);
                        }

                        Console.Write("\n\nSpecify an organization number (1-{0}) [1]: ", orgs.Count);
                        String input = Console.ReadLine();
                        if (input == String.Empty)
                        {
                            input = "1";
                        }
                        int orgNumber = Int32.Parse(input);

                        if (orgNumber > 0 && orgNumber <= orgs.Count)
                        {
                            config.OrganizationName = orgs[orgNumber - 1].FriendlyName;
                            // Return the organization Uri.
                            return(new System.Uri(orgs[orgNumber - 1].Endpoints[EndpointType.OrganizationService]));
                        }
                        else
                        {
                            throw new Exception("The specified organization does not exist.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("\nYou do not belong to any organizations on the specified server.");
                        return(new System.Uri(String.Empty));
                    }
                }
                else
                {
                    throw new Exception("An invalid server name was specified.");
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="discoveryService"></param>
        public ServiceModel(string discoveryService)
        {
            _discoveryManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(new Uri(discoveryService));
            _type = _discoveryManagement.AuthenticationType;

            OrgUri = string.Empty;

            using (_discoveryProxy)
            {
                if (_discoveryProxy != null)
                {
                    OrganizationDetailCollection organizationDetails = DiscoverOrganizations(_discoveryProxy);
                    OrgUri = FindOrganization(_orgUniqueName, organizationDetails.ToArray()).Endpoints[EndpointType.OrganizationService];
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// returns ( if possible ) the org detail for a given organization name from the list of orgs in discovery
        /// </summary>
        /// <param name="orgList">OrgList to Parse though</param>
        /// <param name="organizationName">Name to find</param>
        /// <returns>Found Organization Instance or Null</returns>
        public static OrganizationDetail DeterminOrgDataFromOrgInfo(OrganizationDetailCollection orgList, string organizationName)
        {
            OrganizationDetail orgDetail = orgList.Where(o => o.UniqueName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (orgDetail == null)
            {
                orgDetail = orgList.Where(o => o.FriendlyName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            }

            // still not found... try by URI name.
            if (orgDetail == null)
            {
                string formatedOrgName = string.Format("://{0}.", organizationName).ToLowerInvariant();
                orgDetail = orgList.Where(o => o.Endpoints[EndpointType.WebApplication].Contains(formatedOrgName)).FirstOrDefault();
            }
            return(orgDetail);
        }
 /// <summary>
 /// Obtains the web address (Uri) of the target organization.
 /// </summary>
 /// <returns>Uri of the organization service or an empty string.</returns>
 protected virtual OrganizationDetailCollection GetOrganizationAddress()
 {
     using (DiscoveryServiceProxy serviceProxy = GetDiscoveryProxy())
     {
         // Obtain organization information from the Discovery service.
         if (serviceProxy != null)
         {
             // Obtain information about the organizations that the system user belongs to.
             organizations = DiscoverOrganizations(serviceProxy);
             return(organizations);
         }
         else
         {
             throw new Exception("An invalid server name was specified.");
         }
     }
 }
        public static IOrganizationService Connect(string url, string domain, string username, string password, string organization)
        {
            //var connectionString = @"Url=" + url + "; Username="******"; password="******";";
            //var connection = new Microsoft.Xrm.Client.CrmConnection(connectionString);
            //var test = new Microsoft.Xrm.Client.Services.OrganizationService(connection);
            //return test;

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

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

            Uri orgUri = null;
            OrganizationServiceProxy sdk = null;

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

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

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

            return(sdk);
        }
        private Tuple <bool, string> GetOrganizations()
        {
            try
            {
                //creating discovery url
                var serverUrl = _serverUrl;
                if (!serverUrl.StartsWith("http"))
                {
                    serverUrl = string.Format("{0}{1}", _isSsl ? "https://" : "http://", serverUrl);
                }
                var portNumber   = string.IsNullOrWhiteSpace(_portNumber) ? "" : ":" + _portNumber;
                var discoveryUri = new Uri(string.Format("{0}{1}/XrmServices/2011/Discovery.svc", serverUrl, portNumber));

                //getting organizations with 10 seconds timeout
                OrganizationDetailCollection orgs = new OrganizationDetailCollection();
                object monitorSync = new object();
                Action longMethod  = () => GetOrganizationCollection(monitorSync, discoveryUri, out orgs);
                bool   timedOut;
                lock (monitorSync)
                {
                    longMethod.BeginInvoke(null, null);
                    timedOut = !Monitor.Wait(monitorSync, TimeSpan.FromSeconds(15)); // waiting 15 secs
                }
                if (timedOut)
                {
                    return(Tuple.Create(false, "Error : Timeout(15 s)"));
                }
                if (orgs == null)
                {
                    return(Tuple.Create(false, "Error : Organization not found."));
                }
                _organizationsDictionary = new Dictionary <string, string>();
                foreach (var org in orgs)
                {
                    AddItemToComboBox(org.FriendlyName);
                    _organizationsDictionary.Add(org.FriendlyName, org.Endpoints[EndpointType.WebApplication]);
                }
                return(Tuple.Create(true, "Successfully connected."));
            }
            catch (Exception)
            {
                return(Tuple.Create(false, "Error : Connection failed."));
            }
        }
Exemple #17
0
        public static OrganizationServiceProxy GetOrganizationService(string username, string password, string domain, string organizationUniqueName, string _discoveryServiceAddress)
        {
            string _organizationUniqueName = organizationUniqueName;

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

            // Set the credentials.
            AuthenticationCredentials authCredentials = GetCredentials(username, password, domain, 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.
                    OrganizationDetail orgDetail = FindOrganization(_organizationUniqueName, orgs.ToArray());
                    if (orgDetail == null)
                    {
                        return(null);
                    }
                    organizationUri = orgDetail.Endpoints[EndpointType.OrganizationService];

                    if (!String.IsNullOrWhiteSpace(organizationUri))
                    {
                        IServiceManagement <IOrganizationService> orgServiceManagement =
                            ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(organizationUri));
                        // Get the organization service proxy.
                        return(GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, authCredentials));
                    }
                }
            }
            return(null);
        }
Exemple #18
0
        public OrganizationServiceProxy getOrganizationServiceProxy()
        {
            IServiceManagement <IDiscoveryService> serviceManagement =
                ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(
                    new Uri(discoveryServiceAddress));

            var endpointType    = serviceManagement.AuthenticationType;
            var authCredentials = GetCredentials(serviceManagement, endpointType);

            var organizationUri = String.Empty;

            using (DiscoveryServiceProxy discoveryProxy =
                       GetProxy <IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
            {
                if (discoveryProxy != null)
                {
                    organizations          = DiscoverOrganizations(discoveryProxy);
                    organizationUniqueName = String.IsNullOrEmpty(organizationUniqueName) ? organizations.ToArray()[0].UniqueName : organizationUniqueName;

                    organizationUri = FindOrganization(organizationUniqueName,
                                                       organizations.ToArray()).Endpoints[EndpointType.OrganizationService];
                }
            }

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

                var credentials = GetCredentials(orgServiceManagement, endpointType);

                using (organizationServiceProxy =
                           GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
                {
                    organizationServiceProxy.EnableProxyTypes();
                }
            }

            return(organizationServiceProxy);
        }
Exemple #19
0
        public DynamicsService(DynamicsCredentials credentials)
        {
            string organizationEndpoint;

            if (!string.IsNullOrEmpty(credentials.Domain))
            {
                var discoveryProxy = GetDiscoveryServiceProxy(credentials.DiscoveryUrl, credentials);
                organizations = DiscoverOrganizations(discoveryProxy);
                var organization = organizations.FirstOrDefault(detail => detail.UniqueName.Equals(credentials.Organization)) ?? organizations.FirstOrDefault();

                organizationEndpoint = organization?.Endpoints[EndpointType.OrganizationService];
            }
            else
            {
                //Bygger upp organizationEndpoint Url med hjälp av discoveryUrl
                organizationEndpoint = credentials.DiscoveryUrl.Remove(credentials.DiscoveryUrl.LastIndexOf('/') + 1);
                organizationEndpoint = string.Concat(organizationEndpoint, "Organization.svc");
            }

            organizationServiceProxy = GetOrganizationServiceProxy(organizationEndpoint, credentials);
        }
        public IOrganizationService GetOrganizationService()
        {
            IServiceManagement <IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement <IDiscoveryService>(new Uri(_discoveryServiceAddress));
            AuthenticationProviderType             endpointType      = serviceManagement.AuthenticationType;

            // Set the credentials.
            AuthenticationCredentials authCredentials = GetCredentials(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];
                }
            }

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

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

                // Get the organization service proxy.
                OrganizationServiceProxy organizationProxy = GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials);
                // This statement is required to enable early-bound type support.
                organizationProxy.EnableProxyTypes();
                return(organizationProxy);
            }
            throw new Exception("Could not get service");
        }
Exemple #21
0
        private Uri GetOrganizationAddress(string organization, OrganizationDetailCollection orgs)
        {
            if (orgs == null)
            {
                return(null);
            }

            Uri organizationAddress = null;

            for (int index = 0; index < orgs.Count; index++)
            {
                if (orgs[index].UniqueName.ToUpper() != organization.ToUpper())
                {
                    continue;
                }

                organizationAddress = new Uri(orgs[index].Endpoints[EndpointType.OrganizationService]);
                break;
            }

            return(organizationAddress);
        }
        /// <summary>
        /// Finds a specific organization detail in the array of organization details
        /// returned from the Discovery service.
        /// </summary>
        /// <param name="orgFriendlyName">The friendly name of the organization to find.</param>
        /// <param name="orgDetails">Array of organization detail object returned from the discovery service.</param>
        /// <returns>Organization details or null if the organization was not found.</returns>
        /// <seealso cref="DiscoveryOrganizations"/>
        public OrganizationDetail FindOrganization(string orgFriendlyName, OrganizationDetailCollection orgDetails)
        {
            if (String.IsNullOrWhiteSpace(orgFriendlyName))
            {
                throw new ArgumentNullException("orgFriendlyName");
            }
            if (orgDetails == null)
            {
                throw new ArgumentNullException("orgDetails");
            }
            OrganizationDetail orgDetail = new OrganizationDetail();

            foreach (OrganizationDetail detail in orgDetails)
            {
                if (String.Compare(detail.FriendlyName, orgFriendlyName,
                                   StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    orgDetail = detail;
                    break;
                }
            }
            return(orgDetail);
        }
Exemple #23
0
        public CRMUserAuthenticateModel DataInsertTimeUserAuthenticate(string orgName, string ServerUrl, string UserName, string Password)
        {
            //    String _discoveryServiceAddress = "https://disco.crm8.dynamics.com/XRMServices/2011/Discovery.svc";
            // String _organizationUniqueName = "orgb51959c4";
            //// Provide your user name and password.
            // String _userName = "******";
            // String _password = "******";

            //// Provide domain name for the On-Premises org.
            // String _domain = "mydomain";

            string finalUrl   = "";
            var    strorgName = ServerUrl.Split('.');

            if (strorgName.Contains("api"))
            {
                finalUrl = strorgName[2] + "." + strorgName[3] + "." + strorgName[4].Replace("\"", "");
            }
            else
            {
                finalUrl = strorgName[1] + "." + strorgName[2] + "." + strorgName[3].Replace("\"", "");
            }



            // for uk
            String _discoveryServiceAddress = "https://disco." + finalUrl + "/XRMServices/2011/Discovery.svc";
            String _organizationUniqueName  = orgName;
            // Provide your user name and password.
            String _userName = UserName;
            String _password = Password;

            // Provide domain name for the On-Premises org.
            String _domain = "mydomain";
            //var model = new UserAuthenticateModel();
            var model = new CRMUserAuthenticateModel();

            try
            {
                //CrmConnection connection = CrmConnection.Parse(PortalPage.GetServiceConfiguration());

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

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


                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];
                    }
                }


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

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

                    // 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);
                        model.FirstName = systemUser.FirstName;
                        model.LastName  = systemUser.LastName;
                        model.IsSuccess = true;
                    }
                }


                return(model);
            }
            catch (Exception ex)
            {
                model.IsSuccess = false;
                model.Error     = ex.Message;
                return(model);
            }
        }
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            ResetLabels();
            bool isError = false;

            if (String.IsNullOrWhiteSpace(tbxServerAddr.Text))
            {
                lblServerAddr.ForeColor = Color.Red;
                lblServerAddr.Text      = "* " + lblServerAddr.Text;
                isError = true;
            }

            if (String.IsNullOrWhiteSpace(tbxDomainUsername.Text))
            {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text      = "* " + lblDomainAndUsername.Text;
                isError = true;
            }
            if (String.IsNullOrWhiteSpace(tbxPassword.Text))
            {
                lblPassword.ForeColor = Color.Red;
                lblPassword.Text      = "* " + lblPassword.Text;
                isError = true;
            }

            if (isError)
            {
                return;
            }

            String[] domainAndUserName = tbxDomainUsername.Text.Split('\\');

            if (domainAndUserName.Count() != 2)
            {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text      = "* " + lblDomainAndUsername.Text;
                return;
            }

            _newConfig = new ServerConnection.Configuration {
                ServerAddress = tbxServerAddr.Text
            };

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

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

                    // Get or set the device credentials. This is required for Windows Live ID authentication.
                    _newConfig.DeviceCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                }
            }
            // Check if the server uses Secure Socket Layer (https).
            else if (cbxHttps.Checked)
            {
                _newConfig.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));
            }
            else
            {
                _newConfig.DiscoveryUri = new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));
            }

            // Get Login Credentials
            ClientCredentials credentials = new ClientCredentials();

            credentials.Windows.ClientCredential = new System.Net.NetworkCredential(domainAndUserName[1], tbxPassword.Text, domainAndUserName[0]);
            _newConfig.Credentials = credentials;

            // Get Target Organization
            OrganizationDetailCollection organizations = new OrganizationDetailCollection();

            try {
                organizations = _myCrmHelper.GetOrganizationAddressesAsList(_newConfig);
            }
            catch (System.IO.FileNotFoundException ex) {
                MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }

            // If there's only one organization then use that. Otherwise present the user with the multiple options.
            if (organizations.Count == 1)
            {
                _newConfig.OrganizationName = organizations[0].FriendlyName;
                _newConfig.OrganizationUri  = new Uri(organizations[0].Endpoints[EndpointType.OrganizationService]);
                SaveConfiguration();
            }
            else
            {
                this.Height                   = 510;
                gbxOrgs.Visible               = true;
                lbOrganizations.DataSource    = organizations;
                lbOrganizations.DisplayMember = "FriendlyName";
            }
        }
        /// <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));
        }
Exemple #26
0
        public CRMUserAuthenticateModel UserAuthenticate(string FirstName, string LastName, string Company, string ContactNo, string Email, string Address, string Country, string State, string City, string PostalCode, string SubscriptionType, string orgName, string ServerUrl, string UserName, string Password, string RegisterId)
        {
            //string orgName = paramsObject.orgName;
            //string UserName = paramsObject.UserName;
            //string Password = paramsObject.Password;

            //    String _discoveryServiceAddress = "https://disco.crm8.dynamics.com/XRMServices/2011/Discovery.svc";
            // String _organizationUniqueName = "orgb51959c4";
            //// Provide your user name and password.
            // String _userName = "******";
            // String _password = "******";

            //// Provide domain name for the On-Premises org.
            // String _domain = "mydomain";

            string finalUrl   = "";
            var    strorgName = ServerUrl.Split('.');

            if (strorgName.Contains("api"))
            {
                finalUrl = strorgName[2] + "." + strorgName[3] + "." + strorgName[4].Replace("\"", "");
            }
            else
            {
                finalUrl = strorgName[1] + "." + strorgName[2] + "." + strorgName[3].Replace("\"", "");
            }



            // for uk
            String _discoveryServiceAddress = "https://disco." + finalUrl + "/XRMServices/2011/Discovery.svc";
            String _organizationUniqueName  = orgName;
            // Provide your user name and password.
            String _userName = UserName;
            String _password = Password;

            // Provide domain name for the On-Premises org.
            String _domain = "mydomain";
            //var model = new UserAuthenticateModel();
            var model = new CRMUserAuthenticateModel();

            try
            {
                //CrmConnection connection = CrmConnection.Parse(PortalPage.GetServiceConfiguration());

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

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

                //for stop 5 second to response some server
                System.Threading.Thread.Sleep(5000);

                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];
                    }
                }


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

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

                    // 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);
                        Guid registerId = Guid.Empty;
                        if (RegisterId != null)
                        {
                            registerId = Guid.Parse(RegisterId);
                        }

                        tbl_Configuration tblConfig = new tbl_Configuration();
                        var update = Obj.tbl_Configuration.SingleOrDefault(o => o.Id == registerId);
                        if (update != null)
                        {
                            update.FirstName        = FirstName;
                            update.LastName         = LastName;
                            update.Company          = Company;
                            update.ContactNo        = ContactNo;
                            update.Email            = Email;
                            update.Address          = Address;
                            update.Country          = Country;
                            update.State            = State;
                            update.City             = City;
                            update.PostalCode       = PostalCode;
                            update.UserName         = UserName;
                            update.Password         = Password;
                            update.OrgUniqueName    = orgName;
                            update.ServerUrl        = ServerUrl;
                            update.SubscriptionType = SubscriptionType;
                            update.SolutionName     = "LeadCreation";
                            update.ModifyDate       = DateTime.Now;
                            update.IsCreated        = false;
                            // tblConfig.ExpireDate = DateTime.Now.AddDays(trialTimePeriodInDays);
                            Obj.SaveChanges();
                        }

                        else
                        {
                            tblConfig.Id               = Guid.NewGuid();
                            tblConfig.FirstName        = FirstName;
                            tblConfig.LastName         = LastName;
                            tblConfig.Company          = Company;
                            tblConfig.ContactNo        = ContactNo;
                            tblConfig.Email            = Email;
                            tblConfig.Address          = Address;
                            tblConfig.Country          = Country;
                            tblConfig.State            = State;
                            tblConfig.City             = City;
                            tblConfig.PostalCode       = PostalCode;
                            tblConfig.UserName         = UserName;
                            tblConfig.Password         = Password;
                            tblConfig.OrgUniqueName    = orgName;
                            tblConfig.ServerUrl        = ServerUrl;
                            tblConfig.SubscriptionType = SubscriptionType;
                            tblConfig.SolutionName     = "LeadCreation";
                            tblConfig.CreateDate       = DateTime.Now;
                            tblConfig.ModifyDate       = null;
                            tblConfig.ExpireDate       = DateTime.Now.AddDays(trialTimePeriodInDays);
                            tblConfig.IsCreated        = true;
                            Obj.tbl_Configuration.Add(tblConfig);
                            Obj.SaveChanges();
                        }

                        //return model
                        string EncrypyUserName = "", EncryptPassword = "";
                        Guid   Id = Guid.Empty;
                        if (update != null)
                        {
                            model.Id        = update.Id;
                            model.IsCreated = update.IsCreated;
                        }
                        else
                        {
                            model.Id        = tblConfig.Id;
                            model.IsCreated = tblConfig.IsCreated;
                        }
                        model.FirstName  = FirstName;
                        model.LastName   = LastName;
                        model.Company    = Company;
                        model.ContactNo  = ContactNo;
                        model.Email      = Email;
                        model.Address    = Address;
                        model.Country    = Country;
                        model.State      = State;
                        model.City       = City;
                        model.PostalCode = PostalCode;

                        if (UserName != null)
                        {
                            EncrypyUserName = EncryptString(UserName, "@123");
                        }
                        if (Password != null)
                        {
                            EncryptPassword = EncryptString(Password, "@123");
                        }


                        model.UserName         = EncrypyUserName;
                        model.EPassword        = EncryptPassword;
                        model.SubscriptionType = SubscriptionType;

                        model.IsSuccess = true;
                    }
                }


                return(model);
            }
            catch (Exception ex)
            {
                model.IsSuccess = false;
                model.Error     = ex.Message;
                return(model);
            }
        }
Exemple #27
0
        log4net.ILog log = log4net.LogManager.GetLogger("fileLog");//获取一个日志记录器

        #endregion Class Level Members

        #region How To Sample Code
        /// <summary>
        ///
        /// </summary>
        public OrganizationServiceProxy getCrmService()
        {
            try
            {
                if (organizationProxy == null)
                {
                    flag--;
                    //<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 (organizationProxy =
                                   GetProxy <IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
                        {
                            // This statement is required to enable early-bound type support.
                            organizationProxy.EnableProxyTypes();
                            TimeSpan time = new TimeSpan(0, 5, 0);//TimeSpan(H,M,S)
                            organizationProxy.Timeout = time;

                            log.Info("create crm organizationProxy success!" + organizationProxy.UserPrincipalName);
                            // 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;

                            //Entity account = new Entity("account");
                            //account["name"] = "Fourth Coffee";
                            //organizationProxy.Create(account);
                            //return organizationProxy;
                        }
                        //</snippetAuthenticateWithNoHelp3>
                    }
                }
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                log.Info("create crm organizationProxy failure!");
                //尝试5次
                if (flag > 0)
                {
                    getCrmService();
                }
            }

            //RenewTokenIfRequired(organizationProxy);
            return(organizationProxy);
        }
Exemple #28
0
        private void btn365Connect_Click(object sender, EventArgs e)
        {
            _discoveryServiceAddress = discoverySvcUrl.Text;
            _organizationUniqueName  = txtOrg.Text;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            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];
                }
            }


            if (!String.IsNullOrWhiteSpace(organizationUri))
            {
                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;
                    IOrganizationService service = null;
                    service = (IOrganizationService)organizationProxy;
                    DownloadAttachment obj1 = new DownloadAttachment(service);
                    obj1.Show();
                    this.Hide();
                    //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);
                }
            }
        }
        /*private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Text = "Connecting";
            btnConnect.Enabled = false;

            if (cmb_configurations.SelectedIndex >= 0 && cmb_configurations.SelectedItem.ToString() != "<< Create new server configuration >>") {
                try {
                    ServerConnection.Configuration config = _myCrmHelper.Configurations[cmb_configurations.SelectedIndex];
                    config.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("tnd_dlagrew", "Welcome1", "tnd");
                    //config.Credentials.Windows.ClientCredential.UserName = "******";
                    //config.Credentials.Windows.ClientCredential.Password = "******";
                    // Set IServiceManagement for the current organization.
                    _myCrmHelper.SetIServiceManagementForOrganization(ref config);

                    btnConnect.Enabled = true;
                    btnConnect.Text = "Connect";

                    Views.RibbonDownloadForm ribbonDlForm = new RibbonDownloadForm(config);
                    ribbonDlForm.Text = config.ServerAddress.ToString() + ": " + config.OrganizationName;
                    ribbonDlForm.MdiParent = this.MdiParent;
                    ribbonDlForm.Show();

                    this.Close();
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
        }*/
        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            ResetLabels();
            bool isError = false;
            if (String.IsNullOrWhiteSpace(tbxServerAddr.Text)) {
                lblServerAddr.ForeColor = Color.Red;
                lblServerAddr.Text = "* " + lblServerAddr.Text;
                isError = true;
            }

            if (String.IsNullOrWhiteSpace(tbxDomainUsername.Text)) {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text = "* " + lblDomainAndUsername.Text;
                isError = true;
            }
            if (String.IsNullOrWhiteSpace(tbxPassword.Text)) {
                lblPassword.ForeColor = Color.Red;
                lblPassword.Text = "* " + lblPassword.Text;
                isError = true;
            }

            if (isError) return;

            String[] domainAndUserName = tbxDomainUsername.Text.Split('\\');

            if (domainAndUserName.Count() != 2) {
                lblDomainAndUsername.ForeColor = Color.Red;
                lblDomainAndUsername.Text = "* " + lblDomainAndUsername.Text;
                return;
            }

            _newConfig = new ServerConnection.Configuration { ServerAddress = tbxServerAddr.Text };

            if (String.IsNullOrWhiteSpace(_newConfig.ServerAddress))
                _newConfig.ServerAddress = "crm.dynamics.com";

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

                    // Get or set the device credentials. This is required for Windows Live ID authentication.
                    _newConfig.DeviceCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
                }
            }
            // Check if the server uses Secure Socket Layer (https).
            else if (cbxHttps.Checked)
                _newConfig.DiscoveryUri = new Uri(String.Format("https://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));
            else
                _newConfig.DiscoveryUri = new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", _newConfig.ServerAddress));

            // Get Login Credentials
            ClientCredentials creds = new ClientCredentials();
            creds.Windows.ClientCredential = new System.Net.NetworkCredential(domainAndUserName[1], tbxPassword.Text, domainAndUserName[0]);
            _newConfig.Credentials = creds;

            // Get Target Organization
            OrganizationDetailCollection organizations = new OrganizationDetailCollection();
            try {
                organizations = _myCrmHelper.GetOrganizationAddressesAsList(_newConfig);
            }
            catch (System.IO.FileNotFoundException ex) {
                MessageBox.Show(String.Format("Error: {0}", ex.Message));
            }

            // If there's only one organization then use that. Otherwise present the user with the multiple options.
            if (organizations.Count == 1) {
                _newConfig.OrganizationName = organizations[0].FriendlyName;
                _newConfig.OrganizationUri = new Uri(organizations[0].Endpoints[EndpointType.OrganizationService]);
                SaveConfiguration();
            }
            else {
                this.Height = 510;
                gbxOrgs.Visible = true;
                lbOrganizations.DataSource = organizations;
                lbOrganizations.DisplayMember = "FriendlyName";
            }
        }