private static OrganizationDetailCollection DiscoverOrganizations(DiscoveryServiceProxy service)
        {
            RetrieveOrganizationsRequest request = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)service.Execute(request);

            return response.Details;
        }
        private static IOrganizationService Connect()
        {
            var config = _configurationService.Get <XrmClientConfiguration>();


            Uri dInfo = new Uri(config.XrmUri);
            ClientCredentials clientcred = new ClientCredentials();

            clientcred.UserName.UserName = config.XrmClientCredUserName;
            clientcred.UserName.Password = config.XrmClientCredPassword;


            #region on-premise/online

            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(dInfo, null, clientcred, null);
            dsp.Authenticate();
            RetrieveOrganizationsRequest  rosreq = new Microsoft.Xrm.Sdk.Discovery.RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse r      = (RetrieveOrganizationsResponse)dsp.Execute(rosreq);

            //get the OrganizationService
            ManagedTokenOrganizationServiceProxy _serviceproxy = new ManagedTokenOrganizationServiceProxy(new Uri(config.XrmOrgServiceProxy), clientcred);
            //In order to use the generated types when dealing with the organization service, you have to add the ProxyTypesBehavior to the endpoint Behaviors collection. This instructs the OrganizationServiceProxy to look in the assembly for classes with certain attributes to use. The generated classes are already attributed with these attributes. Simply, this makes all interactions with the organization service to be done using the generated typed classes for each entity instead of the generic Entity class we used earlier.
            _serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.EndpointBehaviors.Add(new ProxyTypesBehavior());
            //Do not forget to include _serviceproxy.EnableProxyTypes();. Without this line,you will be unable to use early binding.
            _serviceproxy.EnableProxyTypes();
            IOrganizationService service = (IOrganizationService)_serviceproxy;

            #endregion
            return(service);
        }
        private string GetCurrentOrganizationName(ServerConnection.Configuration serverConfig)
        {
            using (DiscoveryServiceProxy _discoveryProxy = new DiscoveryServiceProxy(serverConfig.DiscoveryUri,
                                                                                     serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                RetrieveOrganizationsRequest orgsRequest =
                    new RetrieveOrganizationsRequest()
                {
                    AccessType = EndpointAccessType.Default,
                    Release    = OrganizationRelease.Current
                };
                RetrieveOrganizationsResponse organizations =
                    (RetrieveOrganizationsResponse)_discoveryProxy.Execute(orgsRequest);

                foreach (OrganizationDetail organization in organizations.Details)
                {
                    foreach (var endpoint in organization.Endpoints)
                    {
                        if (endpoint.Value.ToLowerInvariant() == serverConfig.OrganizationUri.ToString().ToLowerInvariant())
                        {
                            return(organization.FriendlyName);
                        }
                    }
                }
            }
            return(String.Empty);
        }
        private static OrganizationDetailCollection DiscoverOrganizations(DiscoveryServiceProxy service)
        {
            RetrieveOrganizationsRequest  request  = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)service.Execute(request);

            return(response.Details);
        }
示例#5
0
        static void Main(string[] args)
        {
            Uri local = new Uri("https://disco.crm2.dynamics.com/XRMServices/2011/Discovery.svc");

            ClientCredentials clientcred = new ClientCredentials();

            clientcred.UserName.UserName = lerEntradaCmd("Digite o Usuário");
            clientcred.UserName.Password = lerEntradaCmd("Digite a Senha");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(local, null, clientcred, null);

            dsp.Authenticate();

            RetrieveOrganizationsRequest rosreq = new RetrieveOrganizationsRequest();

            rosreq.AccessType = EndpointAccessType.Default;
            rosreq.Release    = OrganizationRelease.Current;

            RetrieveOrganizationsResponse r = (RetrieveOrganizationsResponse)dsp.Execute(rosreq);

            foreach (var item in r.Details)
            {
                Console.WriteLine("Nome " + item.UniqueName);
                Console.WriteLine("Nome Exibição " + item.FriendlyName);
                foreach (var endpoint in item.Endpoints)
                {
                    Console.WriteLine(endpoint.Key);
                    Console.WriteLine(endpoint.Value);
                }
            }

            Console.ReadLine();
        }
        /// <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()
        {
            try
            {
                // Obtain the discovery service proxy.
                DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(this.config, this.ConfigurationProvider);
                // Checking authentication by invoking some SDK methods.
                discoveryProxy.Execute(new RetrieveOrganizationsRequest());
                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 (!String.IsNullOrWhiteSpace(config.UserPrincipalName) &&
                    ex.Message.Contains("Access is denied."))
                {
                    config.AuthFailureCount += 1;
                }
                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

            // Second trial to obtain the discovery service proxy in case of single sign-on failure.
            return(GetProxy <IDiscoveryService, DiscoveryServiceProxy>(this.config, this.ConfigurationProvider));
        }
        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());
            }
        }
        public static OrganizationDetailCollection GetOrganizations(Settings settings)
        {
            var credentials = new ClientCredentials();

            if (settings.UseIFD || settings.UseOffice365 || settings.UseOnline)
            {
                credentials.UserName.UserName = settings.Username;
                credentials.UserName.Password = settings.Password;
            }
            else
            {
                credentials.Windows.ClientCredential =
                    new System.Net.NetworkCredential(settings.Username, settings.Password, settings.Domain);
            }

            using (var discoveryProxy = new DiscoveryServiceProxy(settings.GetDiscoveryUri(), null, credentials, null))
            {
                discoveryProxy.Authenticate();

                var retrieveOrganizationsRequest = new RetrieveOrganizationsRequest
                {
                    AccessType = EndpointAccessType.Default,
                    Release    = OrganizationRelease.Current
                };

                var retrieveOrganizationsResponse = (RetrieveOrganizationsResponse)discoveryProxy
                                                    .Execute(retrieveOrganizationsRequest);

                return(retrieveOrganizationsResponse.Details);
            }
        }
示例#9
0
        static void Descoberta()
        {
            Uri local = new Uri("https://disco.crm2.dynamics.com/XRMServices/2011/Discovery.svc");

            ClientCredentials clientecred = new ClientCredentials();

            clientecred.UserName.UserName = "******";
            clientecred.UserName.Password = "******";

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(local, null, clientecred, null);

            dsp.Authenticate();

            RetrieveOrganizationsRequest rosreq = new RetrieveOrganizationsRequest();

            rosreq.AccessType = EndpointAccessType.Default;
            rosreq.Release    = OrganizationRelease.Current;

            RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)dsp.Execute(rosreq);

            foreach (var item in response.Details)
            {
                Console.WriteLine("Unique " + item.UniqueName);
                Console.WriteLine("Friendly " + item.FriendlyName);
                foreach (var endpoints in item.Endpoints)
                {
                    Console.WriteLine(endpoints.Key);
                    Console.WriteLine(endpoints.Value);
                }
            }
        }
示例#10
0
        private static string GetOrganizationName(string crmDiscoveryUrl, Guid orgId)
        {
            IServiceConfiguration <IDiscoveryService> dinfo = ServiceConfigurationFactory.CreateConfiguration <IDiscoveryService>(GetDiscoveryServiceUri(crmDiscoveryUrl));

            var creds = new ClientCredentials();

            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(dinfo, creds);

            dsp.Authenticate();
            RetrieveOrganizationsRequest  orgRequest  = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = dsp.Execute(orgRequest) as RetrieveOrganizationsResponse;

            if (orgResponse == null || orgResponse.Details == null || orgResponse.Details.Count == 0)
            {
                throw new Exception("Organization not found");
            }

            return(orgResponse.Details.First(o => o.OrganizationId == orgId).UrlName);
        }
        private string ResolveCrmOnlineUniqueOrg()
        {
            string endpointUri = string.Format("https://disco.{0}/XrmServices/2011/Discovery.svc", ServerName.Remove(0, ServerName.IndexOf('.') + 1));

            DiscoveryServiceProxy discoveryProxy = GetProxy <IDiscoveryService, DiscoveryServiceProxy>(new Uri(endpointUri));

            discoveryProxy.Execute(new RetrieveOrganizationsRequest());

            RetrieveOrganizationsRequest  orgRequest  = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)discoveryProxy.Execute(orgRequest);

            var org = orgResponse.Details.FirstOrDefault(d => d.UrlName == OrganizationUrlName);

            if (org == null)
            {
                throw new Exception("Unable to find the organization based on its url name");
            }

            return(org.UniqueName);
        }
示例#12
0
        private OrganizationServiceProxy GetInfo(DiscoveryServiceProxy serviceProxy)
        {
            var orgsRequest = new RetrieveOrganizationsRequest
            {
                AccessType = EndpointAccessType.Default,
                Release    = OrganizationRelease.Current
            };
            var orgs = (RetrieveOrganizationsResponse)serviceProxy.Execute(orgsRequest);

            foreach (var endpoint in  orgs.Details[0].Endpoints)
            {
                listBox1.Items.Add($"  Name: {endpoint.Key}");
                listBox1.Items.Add($"  URL: {endpoint.Value}");

                if (endpoint.Key == EndpointType.OrganizationService)
                {
                    var orgProxy = new OrganizationServiceProxy(new Uri(endpoint.Value), null, userCred, deviceCred);
                    return(orgProxy);
                }
            }

            return(null);
        }
示例#13
0
        /// <summary>
        /// Get organization data for a specific known region only
        /// </summary>
        /// <param name="creds"></param>
        /// <param name="dataCenter"></param>
        /// <returns></returns>
        public static List <OrganizationDetail> GetOrganizationsForDataCenter(ClientCredentials creds, DataCenter dataCenter)
        {
            if (dataCenter == DataCenter.Unknown)
            {
                throw new ArgumentOutOfRangeException("DataCenter.Unknown cannot be used as a parameter for this method.");
            }

            //Get the DataCenter URL from the Description Attribute applied for the DataCenter member
            var    type       = typeof(DataCenter);
            var    memInfo    = type.GetMember(dataCenter.ToString());
            var    attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            string url        = ((DescriptionAttribute)attributes[0]).Description;

            var organizations = new List <OrganizationDetail>();

            using (var dsvc = new DiscoveryServiceProxy(new Uri(url), null, creds, null))
            {
                RetrieveOrganizationsRequest orgsRequest = new RetrieveOrganizationsRequest()
                {
                    AccessType = EndpointAccessType.Default,
                    Release    = OrganizationRelease.Current
                };

                try
                {
                    RetrieveOrganizationsResponse response = (RetrieveOrganizationsResponse)dsvc.Execute(orgsRequest);

                    organizations = response.Details.ToList();
                }
                catch (System.ServiceModel.Security.SecurityAccessDeniedException)
                {
                    //This error is expected for regions where the user has no organizations
                }
            };
            return(organizations);
        }
        private static IOrganizationService ConnectToCRM()
        {
            #region connect to D365 online

            var appSettings = ConfigurationManager.AppSettings;
            if (appSettings["discoveryService"] == null || appSettings["orgService"] == null)
            {
                Connection.Result = false;
                return(null);
            }


            Uri dInfo = new Uri(appSettings["discoveryService"]);
            ClientCredentials clientcred = new ClientCredentials();
            if (Connection.UserName == null || Connection.Password == null)
            {
                return(null);
            }
            clientcred.UserName.UserName = Connection.UserName;
            clientcred.UserName.Password = Connection.Password;
            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(dInfo, null, clientcred, null);
            try
            {
                dsp.Authenticate();
                Connection.Result = true;
            }
            catch (Exception)
            {
                Connection.Result = false;
                return(null);
            }


            RetrieveOrganizationsRequest  rosreq     = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse retieveOrg = (RetrieveOrganizationsResponse)dsp.Execute(rosreq);

            //get the OrganizationService
            OrganizationServiceProxy _serviceproxy = new OrganizationServiceProxy(new Uri(appSettings["orgService"]), null, clientcred, null);
            _serviceproxy.ServiceConfiguration.CurrentServiceEndpoint.EndpointBehaviors.Add(new ProxyTypesBehavior());
            _serviceproxy.EnableProxyTypes();
            IOrganizationService service = (IOrganizationService)_serviceproxy;

            foreach (OrganizationDetail o in retieveOrg.Details)
            {
                //lblOrg.Text = o.FriendlyName;
                //WhoAmIResponse whoAMIResponse = (WhoAmIResponse)service.Execute(new Microsoft.Crm.Sdk.Messages.WhoAmIRequest());
                //lblUser.Text = whoAMIResponse.UserId.ToString();
                break;
            }

            #endregion
            return(service);
        }
示例#15
0
        public static OrganizationInfo GetOrganizations(string DiscoverServiceURL, string UserName, string Password)
        {
            ClientCredentials credentials = new ClientCredentials();

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

            using (var discoveryProxy = new DiscoveryServiceProxy(new Uri(DiscoverServiceURL), null, credentials, null))
            {
                discoveryProxy.Authenticate();

                // Get all Organizations using Discovery Service

                RetrieveOrganizationsRequest retrieveOrganizationsRequest = new RetrieveOrganizationsRequest()
                {
                    AccessType = EndpointAccessType.Default,
                    Release    = OrganizationRelease.Current
                };

                RetrieveOrganizationsResponse retrieveOrganizationsResponse =
                    (RetrieveOrganizationsResponse)discoveryProxy.Execute(retrieveOrganizationsRequest);

                if (retrieveOrganizationsResponse.Details.Count > 0)
                {
                    var orgs = new List <String>();
                    OrganizationInfo OrgInfo             = new OrganizationInfo();
                    List <string>    FriendlyName        = new List <string>();
                    List <Guid>      OrganizationId      = new List <Guid>();
                    List <string>    OrganizationVersion = new List <string>();
                    List <string>    State                   = new List <string>();
                    List <string>    UniqueName              = new List <string>();
                    List <string>    URlName                 = new List <string>();
                    List <string>    WebApplication          = new List <string>();
                    List <string>    OrganizationService     = new List <string>();
                    List <string>    OrganizationDataService = new List <string>();

                    foreach (OrganizationDetail orgInfo in retrieveOrganizationsResponse.Details)
                    {
                        FriendlyName.Add(orgInfo.FriendlyName);
                        OrganizationId.Add(orgInfo.OrganizationId);
                        OrganizationVersion.Add(orgInfo.OrganizationVersion);
                        State.Add(orgInfo.State.ToString());
                        UniqueName.Add(orgInfo.UniqueName);
                        WebApplication.Add(orgInfo.Endpoints[EndpointType.WebApplication]);
                        OrganizationService.Add(orgInfo.Endpoints[EndpointType.OrganizationService]);
                        OrganizationDataService.Add(orgInfo.Endpoints[EndpointType.OrganizationDataService]);
                        URlName.Add(orgInfo.UrlName);
                    }
                    OrgInfo.FriendlyName        = FriendlyName;
                    OrgInfo.OrganizationId      = OrganizationId;
                    OrgInfo.OrganizationVersion = OrganizationVersion;
                    OrgInfo.State                   = State;
                    OrgInfo.UniqueName              = UniqueName;
                    OrgInfo.WebApplication          = WebApplication;
                    OrgInfo.OrganizationService     = OrganizationService;
                    OrgInfo.OrganizationDataService = OrganizationDataService;
                    OrgInfo.URlName                 = URlName;
                    return(OrgInfo);
                }
                else
                {
                    return(null);
                }
            }
        }
        private static string GetOrganizationName(string crmDiscoveryUrl, Guid orgId)
        {
            IServiceConfiguration<IDiscoveryService> dinfo = ServiceConfigurationFactory.CreateConfiguration<IDiscoveryService>(GetDiscoveryServiceUri(crmDiscoveryUrl));

            var creds = new ClientCredentials();

            DiscoveryServiceProxy dsp = new DiscoveryServiceProxy(dinfo, creds);
            dsp.Authenticate();
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = dsp.Execute(orgRequest) as RetrieveOrganizationsResponse;

            if (orgResponse == null || orgResponse.Details == null || orgResponse.Details.Count == 0)
            {
                throw new Exception("Organization not found");
            }

            return orgResponse.Details.First(o => o.OrganizationId == orgId).UrlName;
        }
        private string GetCurrentOrganizationName(ServerConnection.Configuration serverConfig)
        {
            using (DiscoveryServiceProxy _discoveryProxy = new DiscoveryServiceProxy(serverConfig.DiscoveryUri,
                        serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                RetrieveOrganizationsRequest orgsRequest =
                new RetrieveOrganizationsRequest()
                {
                    AccessType = EndpointAccessType.Default,
                    Release = OrganizationRelease.Current
                };
                RetrieveOrganizationsResponse organizations =
                    (RetrieveOrganizationsResponse)_discoveryProxy.Execute(orgsRequest);

                foreach (OrganizationDetail organization in organizations.Details)
                {
                    foreach (var endpoint in organization.Endpoints)
                    {
                        if (endpoint.Value.ToLowerInvariant() == serverConfig.OrganizationUri.ToString().ToLowerInvariant())
                            return organization.FriendlyName;
                    }
                }
            }
            return String.Empty;
        }