예제 #1
0
        public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password)
        {

            if (org != null)
            {
                Uri orgServiceUri = null;
                orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]);
                //if (!string.IsNullOrEmpty(OrganisationServiceHostName))
                //{
                //    UriBuilder builder = new UriBuilder(orgServiceUri);
                //    builder.Host = OrganisationServiceHostName;
                //    orgServiceUri = builder.Uri;
                //}

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

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

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

                Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId));
                return orgService;
            }
            return null;

        }
예제 #2
0
        public IHttpActionResult OrganizationRegister(OrganizationViewModel model)
        {
            var addOrganization = new OrganizationDetail();

            try
            {
                if (ModelState.IsValid)
                {
                    var chkOrganizationexs = db.OrganizationDetails.Where(s => s.EmailId == model.EmailId).FirstOrDefault();
                    if (chkOrganizationexs == null)
                    {
                        addOrganization.EmailId          = model.EmailId;
                        addOrganization.OrganizationName = model.OrganizationName;
                        addOrganization.FirstName        = model.FirstName;
                        addOrganization.LastName         = model.LastName;
                        addOrganization.Password         = model.Password;
                        addOrganization.OTP         = GenerateOTP(0, 0, false, false, false, false);
                        addOrganization.IsActivated = false;
                        addOrganization.CreatedBy   = model.CreatedBy;
                        db.OrganizationDetails.Add(addOrganization);
                        db.SaveChanges();
                        var subject = "OTP for SPOT Organization Registration";
                        var body    = "<b> The OTP is " + addOrganization.OTP + "</b><br/>";


                        var senderEmail    = ConfigurationManager.AppSettings["SenderGmailId"];
                        var senderPassword = ConfigurationManager.AppSettings["SenderGmailPassword"];
                        var smtpServer     = ConfigurationManager.AppSettings["GmailServer"];
                        var portNumber     = Convert.ToInt32(ConfigurationManager.AppSettings["GmailPort"]);
                        var IsSSL          = Convert.ToBoolean(ConfigurationManager.AppSettings["EmailSSL"]);
                        var senderName     = ConfigurationManager.AppSettings["SenderName"];

                        if (!string.IsNullOrWhiteSpace(senderEmail) && !string.IsNullOrWhiteSpace(senderPassword) && !string.IsNullOrWhiteSpace(smtpServer) && portNumber != 0 && IsSSL)
                        {
                            var client = new SmtpClient(smtpServer, portNumber)
                            {
                                Credentials = new NetworkCredential(senderEmail, senderPassword),
                                EnableSsl   = Convert.ToBoolean(IsSSL)
                            };

                            var message = new MailMessage();
                            message.From = new MailAddress(senderEmail, senderName);
                            if (!string.IsNullOrWhiteSpace(addOrganization.EmailId))
                            {
                                message.To.Add(addOrganization.EmailId);
                                message.Subject    = subject;
                                message.IsBodyHtml = true;
                                message.Body       = body;
                                Task.Run(() => client.Send(message));
                            }
                        }

                        return(Ok(addOrganization));
                    }
                    else
                    {
                        return(Ok("Organization Email Address Already Taken."));
                    }
                }
                else
                {
                    return(Ok("Fill All the Mandatory Fields"));
                }
            }
            catch (Exception ex)
            {
                return(Ok("" + ex.Message + ""));
            }
        }
        /// <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>
        internal static OrganizationDetail FindOrganization(string orgUniqueName, OrganizationDetail[] orgDetails)
        {
            if (string.IsNullOrEmpty(orgUniqueName))
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ParamterNullExceptionMessage), new ArgumentNullException("orgUniqueName")) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            if (orgDetails == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ParamterNullExceptionMessage), new ArgumentNullException("orgDetails")) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            foreach (OrganizationDetail detail in orgDetails)
            {
                if (string.CompareOrdinal(detail.UniqueName, orgUniqueName) == 0)
                {
                    return detail;
                }
            }

            return null;
        }
예제 #4
0
        private static Microsoft.Xrm.Sdk.Client.AuthenticationProviderType GuessAuthType(ClientCredentials credential, string appId, OrganizationDetail o)
        {
            var newAuthType = GuessNewAuthType(credential, appId, o);

            switch (newAuthType)
            {
            case AuthenticationType.AD:
                return(Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.ActiveDirectory);

            case AuthenticationType.IFD:
            case AuthenticationType.Claims:
                return(Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.Federation);

            case AuthenticationType.Live:
            case AuthenticationType.Office365:
                return(Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.LiveId);

            case AuthenticationType.OAuth:
            case AuthenticationType.Certificate:
            case AuthenticationType.ClientSecret:
            case AuthenticationType.ExternalTokenManagement:
            case AuthenticationType.InvalidConnection:
                return(Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.None);
            }
            return(Microsoft.Xrm.Sdk.Client.AuthenticationProviderType.None);
        }
예제 #5
0
 private static AuthenticationType GuessNewAuthType(ClientCredentials credential, string appId, OrganizationDetail o)
 {
     if (!string.IsNullOrEmpty(credential.Windows?.ClientCredential?.UserName))
     {
         return(AuthenticationType.AD);
     }
     if (credential.UserName != null)
     {
         if (!string.IsNullOrEmpty(appId))
         {
             if (Guid.TryParse(credential.UserName.UserName, out _))
             {
                 return(AuthenticationType.ClientSecret);
             }
             else
             {
                 return(AuthenticationType.OAuth);
             }
         }
         else
         {
             var url = new Uri(o.Endpoints[EndpointType.WebApplication]);
             if (url.Host.EndsWith("dynamics.com"))
             {
                 return(AuthenticationType.Office365);
             }
             else
             {
                 return(AuthenticationType.IFD);
             }
         }
     }
     return(AuthenticationType.InvalidConnection);
 }
        private static async Task LoadOrganizationDataAsync(OrganizationServiceExtentedProxy service, OrganizationDetail organizationDetail, WhoAmIResponse whoAmIResponse = null)
        {
            try
            {
                Guid?idOrganization = null;

                if (organizationDetail != null)
                {
                    idOrganization = organizationDetail.OrganizationId;

                    service.ConnectionData.OrganizationInformationExpirationDate = DateTime.Now.AddHours(_hoursOrganizationInformation);

                    service.ConnectionData.FriendlyName        = organizationDetail.FriendlyName;
                    service.ConnectionData.OrganizationId      = organizationDetail.OrganizationId;
                    service.ConnectionData.OrganizationVersion = organizationDetail.OrganizationVersion;
                    service.ConnectionData.OrganizationState   = organizationDetail.State.ToString();
                    service.ConnectionData.UniqueOrgName       = organizationDetail.UniqueName;
                    service.ConnectionData.UrlName             = organizationDetail.UrlName;

                    if (organizationDetail.Endpoints.ContainsKey(EndpointType.OrganizationService))
                    {
                        var organizationUrlEndpoint = organizationDetail.Endpoints[EndpointType.OrganizationService];

                        if (string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl) &&
                            !string.IsNullOrEmpty(organizationUrlEndpoint)
                            )
                        {
                            service.ConnectionData.OrganizationUrl = organizationUrlEndpoint;
                        }
                    }

                    if (organizationDetail.Endpoints.ContainsKey(EndpointType.WebApplication))
                    {
                        var publicUrl = organizationDetail.Endpoints[EndpointType.WebApplication];

                        if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) &&
                            !string.IsNullOrEmpty(publicUrl)
                            )
                        {
                            service.ConnectionData.PublicUrl = publicUrl;
                        }
                    }
                }

                if (!idOrganization.HasValue)
                {
                    if (whoAmIResponse == null)
                    {
                        whoAmIResponse = await service.ExecuteAsync <WhoAmIResponse>(new WhoAmIRequest());
                    }

                    idOrganization = whoAmIResponse.OrganizationId;
                }

                service.ConnectionData.DefaultLanguage        = string.Empty;
                service.ConnectionData.BaseCurrency           = string.Empty;
                service.ConnectionData.DefaultLanguage        = string.Empty;
                service.ConnectionData.InstalledLanguagePacks = string.Empty;

                if (idOrganization.HasValue)
                {
                    var organization = await service
                                       .RetrieveAsync <Organization>(Organization.EntityLogicalName, idOrganization.Value, new ColumnSet(Organization.Schema.Attributes.languagecode, Organization.Schema.Attributes.basecurrencyid))
                    ;

                    if (organization.BaseCurrencyId != null)
                    {
                        service.ConnectionData.BaseCurrency = organization.BaseCurrencyId.Name;
                    }

                    var request  = new RetrieveInstalledLanguagePacksRequest();
                    var response = await service.ExecuteAsync <RetrieveInstalledLanguagePacksResponse>(request);

                    var rep = new EntityMetadataRepository(service);

                    var isEntityExists = rep.IsEntityExists(LanguageLocale.EntityLogicalName);

                    if (isEntityExists)
                    {
                        var repository = new LanguageLocaleRepository(service);

                        if (organization.LanguageCode.HasValue)
                        {
                            var lang = (await repository.GetListAsync(organization.LanguageCode.Value)).FirstOrDefault();

                            if (lang != null)
                            {
                                service.ConnectionData.DefaultLanguage = lang.ToString();
                            }
                            else
                            {
                                service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value);
                            }
                        }

                        if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any())
                        {
                            var list = await repository.GetListAsync(response.RetrieveInstalledLanguagePacks);

                            service.ConnectionData.InstalledLanguagePacks = string.Join(",", list.OrderBy(s => s.LocaleId.Value, LocaleComparer.Comparer).Select(l => l.ToString()));
                        }
                    }
                    else
                    {
                        if (organization.LanguageCode.HasValue)
                        {
                            service.ConnectionData.DefaultLanguage = LanguageLocale.GetLocaleName(organization.LanguageCode.Value);
                        }

                        if (response.RetrieveInstalledLanguagePacks != null && response.RetrieveInstalledLanguagePacks.Any())
                        {
                            service.ConnectionData.InstalledLanguagePacks = string.Join(",", response.RetrieveInstalledLanguagePacks.OrderBy(s => s, LocaleComparer.Comparer).Select(l => LanguageLocale.GetLocaleName(l)));
                        }
                    }
                }

                if (string.IsNullOrEmpty(service.ConnectionData.PublicUrl) &&
                    !string.IsNullOrEmpty(service.ConnectionData.OrganizationUrl)
                    )
                {
                    var orgUrl = service.ConnectionData.OrganizationUrl.TrimEnd('/');

                    if (orgUrl.EndsWith("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var lastIndex = orgUrl.LastIndexOf("/XRMServices/2011/Organization.svc", StringComparison.InvariantCultureIgnoreCase);

                        var publicUrl = orgUrl.Substring(0, lastIndex + 1).TrimEnd('/');

                        service.ConnectionData.PublicUrl = publicUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(service.ConnectionData, ex);
            }
        }
예제 #7
0
        static void Main(string[] args)
        {
            #region getAppConfigData
            //Getting username and password from the App.Config
            string connectionString = null;
            Dictionary <string, string> settings;
            //This would be input by the user
            string username = null;
            string password = null;
            try
            {
                connectionString = ConfigurationManager.ConnectionStrings["Connect"].ConnectionString;
                settings         = GetConnectionStringKeysAndValues(connectionString);
                username         = settings["Username"];
                password         = settings["Password"];
            }
            catch (Exception)
            {
                Console.WriteLine("You can set Username and Password in cds/App.config before running this sample.");
                throw;
            }
            #endregion getAppConfigData

            //You could comment out everything in the getAppConfigData region and set these values here:
            //string username = "******";
            //string password = "******";

            //Set the dataCenter if you know it, otherwise use DataCenter.Unknown to search all.
            DataCenter dataCenter = DataCenter.Unknown;

            //Get all environments for the selected data center;
            List <OrganizationDetail> orgs = GetAllOrganizations(username, password, dataCenter);

            if (orgs.Count.Equals(0))
            {
                Console.WriteLine("No valid environments returned for these credentials.");
                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
                return;
            }

            Console.WriteLine("Type the number of the environments you want to use and press Enter.");

            int number = 0;
            orgs.ForEach(o =>
            {
                number++;

                //Get the Organization Service URL
                string fullOrgServiceUrl = o.Endpoints[EndpointType.OrganizationService];

                // Trim '/XRMServices/2011/Organization.svc' from the end.
                string shortOrgServiceUrl = fullOrgServiceUrl.Substring(0, fullOrgServiceUrl.Length - 34);

                Console.WriteLine("{0} Name: {1} URL: {2}", number, o.FriendlyName, shortOrgServiceUrl);
            });

            string typedValue = string.Empty;
            try
            {
                typedValue = Console.ReadLine();
                int selected = int.Parse(typedValue);
                if (selected <= number)
                {
                    OrganizationDetail org = orgs[selected - 1];
                    Console.WriteLine("You selected {0}", org.FriendlyName);

                    //Get the Organization Service URL for the selected environment
                    string serviceUrl = org.Endpoints[EndpointType.OrganizationService];

                    //Use the selected serviceUrl with CrmServiceClient to get the UserId

                    string conn = $@"AuthType=Office365;
                         Url={serviceUrl};
                         UserName={username};
                         Password={password};
                         RequireNewInstance=True";

                    using (CrmServiceClient svc = new CrmServiceClient(conn))
                    {
                        if (svc.IsReady)
                        {
                            try
                            {
                                var response = (WhoAmIResponse)svc.Execute(new WhoAmIRequest());

                                Console.WriteLine("Your UserId for {0} is: {1}", org.FriendlyName, response.UserId);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex.Message);
                            }
                        }
                        else
                        {
                            Console.WriteLine(svc.LastCrmError);
                        }
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException("The selected value is not valid.");
                }
            }
            catch (ArgumentOutOfRangeException aex)
            {
                Console.WriteLine(aex.Message);
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to process value: {0}", typedValue);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
        /// <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, 
            OrganizationDetail[] orgDetails)
        {
            if (String.IsNullOrWhiteSpace(orgFriendlyName))
                throw new ArgumentNullException("orgFriendlyName");
            if (orgDetails == null)
                throw new ArgumentNullException("orgDetails");
            OrganizationDetail orgDetail = null;

            foreach (OrganizationDetail detail in orgDetails)
            {
                if (String.Compare(detail.FriendlyName, orgFriendlyName,
                    StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    orgDetail = detail;
                    break;
                }
            }
            return orgDetail;
        }
예제 #9
0
        private void BValidateClick(object sender, EventArgs e)
        {
            if (tbName.Text.Length == 0)
            {
                MessageBox.Show(this, "You must define a name for this connection!", "Warning", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }

            int serverPort = 80;

            if (tbServerPort.Text.Length > 0)
            {
                if (!int.TryParse(tbServerPort.Text, out serverPort))
                {
                    MessageBox.Show(this, "Server port must be a integer value!", "Warning", MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    return;
                }
            }
            else if (cbUseSsl.Checked)
            {
                serverPort = 443;
            }

            if (proposeToConnect && comboBoxOrganizations.Text.Length == 0 && comboBoxOrganizations.SelectedItem == null &&
                !(cbUseIfd.Checked || cbUseOSDP.Checked))
            {
                MessageBox.Show(this, "You must select an organization!", "Warning", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }

            if (tbUserPassword.Text.Length == 0 && (cbUseIfd.Checked || rbAuthenticationCustom.Checked))
            {
                MessageBox.Show(this, "You must define a password!", "Warning", MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
                return;
            }

            if (detail == null)
            {
                detail = new ConnectionDetail();
            }

            // Save connection details in structure
            detail.ConnectionName = tbName.Text;
            detail.IsCustomAuth   = rbAuthenticationCustom.Checked;
            detail.UseSsl         = cbUseSsl.Checked;
            detail.UseOnline      = cbUseOnline.Checked;
            detail.UseOsdp        = cbUseOSDP.Checked;
            detail.ServerName     = (cbUseOSDP.Checked || cbUseOnline.Checked)
                ? cbbOnlineEnv.SelectedItem.ToString()
                : tbServerName.Text;
            detail.ServerPort   = serverPort;
            detail.UserDomain   = tbUserDomain.Text;
            detail.UserName     = tbUserLogin.Text;
            detail.SavePassword = chkSavePassword.Checked;
            detail.UseIfd       = cbUseIfd.Checked;
            detail.HomeRealmUrl = (tbHomeRealmUrl.Text.Length > 0 ? tbHomeRealmUrl.Text : null);

            if (tbUserPassword.Text != "@@PASSWORD@@" && tbUserPassword.Text != "Please specify the password")
            {
                detail.SetPassword(tbUserPassword.Text);
            }

            TimeSpan timeOut;

            if (!TimeSpan.TryParse(tbTimeoutValue.Text, CultureInfo.InvariantCulture, out timeOut))
            {
                MessageBox.Show(this, "Wrong timeout value!\r\n\r\nExpected format : HH:mm:ss", "Warning",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (isCreationMode && comboBoxOrganizations.SelectedItem == null)
            {
                MessageBox.Show(this, "You must discover organizations and select one to create a connection", "Warning",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            detail.Timeout = timeOut;

            OrganizationDetail selectedOrganization = comboBoxOrganizations.SelectedItem != null
                ? ((Organization)comboBoxOrganizations.SelectedItem).OrganizationDetail
                : null;

            if (selectedOrganization != null)
            {
                detail.OrganizationServiceUrl     = selectedOrganization.Endpoints[EndpointType.OrganizationService];
                detail.OrganizationDataServiceUrl = selectedOrganization.Endpoints[EndpointType.OrganizationDataService];
                detail.WebApplicationUrl          = selectedOrganization.Endpoints[EndpointType.WebApplication];
                detail.Organization             = selectedOrganization.UniqueName;
                detail.OrganizationUrlName      = selectedOrganization.UrlName;
                detail.OrganizationFriendlyName = selectedOrganization.FriendlyName;
                detail.OrganizationVersion      = selectedOrganization.OrganizationVersion;
            }
            else if (initialDetail != null && initialDetail.IsConnectionBrokenWithUpdatedData(detail))
            {
                MessageBox.Show(this,
                                "You changed critical parameters for this connection! Please retrieve organizations to ensure your changes are valid",
                                "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (initialDetail == null || initialDetail.IsConnectionBrokenWithUpdatedData(detail))
                {
                    if (proposeToConnect || isCreationMode)
                    {
                        FillDetails();

                        if (proposeToConnect &&
                            MessageBox.Show(this, "Do you want to connect now to this server?", "Question",
                                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            doConnect = true;
                        }
                    }
                }

                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception error)
            {
                if (detail.OrganizationServiceUrl != null && detail.OrganizationServiceUrl.IndexOf(detail.ServerName, StringComparison.Ordinal) < 0)
                {
                    var uri      = new Uri(detail.OrganizationServiceUrl);
                    var hostName = uri.Host;

                    const string format = "The server name you provided ({0}) is not the same as the one defined in deployment manager ({1}). Please make sure that the server name defined in deployment manager is reachable from you computer.\r\n\r\nError:\r\n{2}";
                    MessageBox.Show(this, string.Format(format, detail.ServerName, hostName, error.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(this, error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Gets the IOrganizationService from a CrmServiceClient (2016) instance using OAuth.
        /// </summary>
        /// <param name="crmUserId">CRMUserId.</param>
        /// <param name="crmPassword">CRMPassword.</param>
        /// <param name="domain">Domain</param>
        /// <param name="homeRealm">HomeRealm</param>
        /// <param name="hostName">HostName</param>
        /// <param name="port">Port</param>
        /// <param name="orgName">OrgName.</param>
        /// <param name="useSsl">UseSSL</param>
        /// <param name="useUniqueInstance">UseUniqueInstance.</param>
        /// <param name="orgDetail">OrgDetail.</param>
        /// <param name="user">User.</param>
        /// <param name="clientId">ClientId.</param>
        /// <param name="redirectUri">RedirectUri.</param>
        /// <param name="tokenCachePath">TokenCachePath.</param>
        /// <param name="externalOrgWebProxyClient">ExternalOrgWebProxyClient.</param>
        /// <param name="promptBehavior">PromptBehavior</param>
        /// <returns>IOrganizationService.</returns>
        public static IOrganizationService Get(string crmUserId, SecureString crmPassword, string domain, string homeRealm, string hostName, string port, string orgName, bool useSsl, bool useUniqueInstance, OrganizationDetail orgDetail, UserIdentifier user, string clientId, Uri redirectUri, string tokenCachePath, OrganizationWebProxyClient externalOrgWebProxyClient, PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            CrmServiceClient crmService = new CrmServiceClient(crmUserId, crmPassword, domain, homeRealm, hostName, port, orgName, useSsl, useUniqueInstance, orgDetail, user, clientId, redirectUri, tokenCachePath, externalOrgWebProxyClient, promptBehavior);

            return(GetOrgaizationService(crmService));
        }
예제 #11
0
        /// <summary>
        /// Gets the IOrganizationService from a CrmServiceClient (2016) instance using a NetworkCredential.
        /// </summary>
        /// <param name="credential">NetworkCredential</param>
        /// <param name="authType">AuthType</param>
        /// <param name="hostName">HostName</param>
        /// <param name="port">Port</param>
        /// <param name="orgName">OrgName</param>
        /// <param name="useUniqueInstance">UseUniqueInstance</param>
        /// <param name="useSsl">UseSSL</param>
        /// <param name="orgDetail">OrgDetail</param>
        /// <returns>IOrganizationService.</returns>
        public static IOrganizationService Get(NetworkCredential credential, AuthenticationType authType, string hostName, string port, string orgName, bool useUniqueInstance = false, bool useSsl = false, OrganizationDetail orgDetail = null)
        {
            CrmServiceClient crmService = new CrmServiceClient(credential, authType, hostName, port, orgName, useUniqueInstance, useSsl, orgDetail);

            return(GetOrgaizationService(crmService));
        }
예제 #12
0
        /// <summary>
        /// Gets the IOrganizationService from a CrmServiceClient (2016) instance using credentials.
        /// </summary>
        /// <param name="userId">UserId</param>
        /// <param name="password">Password</param>
        /// <param name="domain">Domain</param>
        /// <param name="homeRealm">HomeRealm</param>
        /// <param name="hostName">HostName</param>
        /// <param name="port">Port</param>
        /// <param name="orgName">OrgName</param>
        /// <param name="useUniqueInstance">UseUniqueInstance</param>
        /// <param name="useSsl">UseSSL</param>
        /// <param name="orgDetail">OrgDetail</param>
        /// <returns>IOrganizationService.</returns>
        public static IOrganizationService Get(string userId, SecureString password, string domain, string homeRealm, string hostName, string port, string orgName, bool useUniqueInstance = false, bool useSsl = false, OrganizationDetail orgDetail = null)
        {
            CrmServiceClient crmService = new CrmServiceClient(userId, password, domain, homeRealm, hostName, port, orgName, useUniqueInstance, useSsl, orgDetail);

            return(GetOrgaizationService(crmService));
        }
예제 #13
0
        /// <summary>
        /// Gets the IOrganizationService from a CrmServiceClient (2016) instance using credentials.
        /// </summary>
        /// <param name="crmUserId">CRMUserId</param>
        /// <param name="crmPassword">CRMPassword</param>
        /// <param name="crmRegion">CRMRegion</param>
        /// <param name="orgName">OrgName</param>
        /// <param name="useUniqueInstance">UseUniqueInstance</param>
        /// <param name="useSsl">UseSSL</param>
        /// <param name="orgDetail">OrgDetail</param>
        /// <param name="isOffice365"></param>
        /// <returns>IOrganizationService.</returns>
        public static IOrganizationService Get(string crmUserId, SecureString crmPassword, string crmRegion, string orgName, bool useUniqueInstance = false, bool useSsl = false, OrganizationDetail orgDetail = null, bool isOffice365 = false)
        {
            CrmServiceClient crmService = new CrmServiceClient(crmUserId, crmPassword, crmRegion, orgName, useUniqueInstance, useSsl, orgDetail, isOffice365);

            return(GetOrgaizationService(crmService));
        }
        private static async Task <Tuple <OrganizationServiceProxy, OrganizationDetail> > ConnectInternal(ConnectionData connectionData, bool withDiscoveryRequest)
        {
            OrganizationServiceProxy serviceProxy       = null;
            OrganizationDetail       organizationDetail = null;

            Uri orgUri = null;

            if ((withDiscoveryRequest || string.IsNullOrEmpty(connectionData.OrganizationUrl)) &&
                !string.IsNullOrEmpty(connectionData.DiscoveryUrl) &&
                Uri.TryCreate(connectionData.DiscoveryUrl, UriKind.Absolute, out var discoveryUri)
                )
            {
                var disco = CreateDiscoveryService(connectionData, discoveryUri, connectionData.User?.Username, connectionData.User?.Password);

                if (disco != null)
                {
                    using (disco)
                    {
                        var repositoryDiscoveryService = new DiscoveryServiceRepository(disco);

                        var orgs = await repositoryDiscoveryService.DiscoverOrganizationsAsync();

                        if (orgs.Count == 1)
                        {
                            organizationDetail = orgs[0];
                        }
                        else if (orgs.Count > 0)
                        {
                            organizationDetail = orgs.FirstOrDefault(a => string.Equals(a.UniqueName, connectionData.UniqueOrgName, StringComparison.InvariantCultureIgnoreCase));

                            if (organizationDetail == null)
                            {
                                organizationDetail = orgs.FirstOrDefault();
                            }
                        }

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

            if (!string.IsNullOrEmpty(connectionData.OrganizationUrl) &&
                Uri.TryCreate(connectionData.OrganizationUrl, UriKind.RelativeOrAbsolute, out Uri custromOrgUri)
                )
            {
                orgUri = custromOrgUri;
            }

            if (orgUri != null)
            {
                var serviceManagement = GetOrganizationServiceConfiguration(connectionData, orgUri);

                if (serviceManagement != null)
                {
                    var credentials = GetCredentials(serviceManagement, connectionData.User?.Username, connectionData.User?.Password);

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

                        serviceProxy = new OrganizationServiceProxy(serviceManagement, tokenCredentials.SecurityTokenResponse);
                    }
                    else
                    {
                        serviceProxy = new OrganizationServiceProxy(serviceManagement, credentials.ClientCredentials);
                    }

                    serviceProxy.EnableProxyTypes();
                    serviceProxy.Timeout = TimeSpan.FromMinutes(30);
                }
            }

            return(Tuple.Create(serviceProxy, organizationDetail));
        }
예제 #15
0
 public static void ConnectOrganization(OrganizationDetail organization)
 {
     Session.Connect(organization);
 }
예제 #16
0
        /// <summary>
        /// Remplit le détail de connexion avec le contenu
        /// des contrôles du formulaire
        /// </summary>
        /// <returns></returns>
        private void FillDetails()
        {
            bool hasFoundOrg = false;

            OrganizationDetail selectedOrganization = comboBoxOrganizations.SelectedItem != null ? ((Organization)comboBoxOrganizations.SelectedItem).OrganizationDetail : null;

            if (organizations == null || organizations.Count == 0)
            {
                var orgs = RetrieveOrganizations(detail);
                foreach (OrganizationDetail orgDetail in orgs)
                {
                    if (organizations == null)
                    {
                        organizations = new List <OrganizationDetail>();
                    }

                    organizations.Add(orgDetail);

                    comboBoxOrganizations.Items.Add(new Organization {
                        OrganizationDetail = orgDetail
                    });
                    comboBoxOrganizations.SelectedIndex = 0;
                    comboBoxOrganizations.Enabled       = true;
                }
            }

            if (organizations == null)
            {
                MessageBox.Show(this, "Organizations list is empty!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            foreach (OrganizationDetail organization in organizations)
            {
                if (organization.UniqueName == selectedOrganization.UniqueName)
                {
                    detail.OrganizationServiceUrl     = organization.Endpoints[EndpointType.OrganizationService];
                    detail.OrganizationDataServiceUrl = organization.Endpoints[EndpointType.OrganizationDataService];
                    detail.Organization             = organization.UniqueName;
                    detail.OrganizationUrlName      = organization.UrlName;
                    detail.OrganizationFriendlyName = organization.FriendlyName;
                    detail.OrganizationVersion      = organization.OrganizationVersion;

                    detail.ConnectionName = tbName.Text;

                    if (isCreationMode)
                    {
                        detail.ConnectionId = Guid.NewGuid();
                    }

                    hasFoundOrg = true;

                    break;
                }
            }

            if (!hasFoundOrg)
            {
                throw new Exception("Unable to match selected organization with list of organizations in this deployment");
            }
        }
        internal void SetOrgProperties(OrganizationDetail detail)
        {
            // Create the column set object that indicates the properties to be retrieved and retrieve the current organization.
            ColumnSet cols = new ColumnSet(new string[] { "languagecode" });
            Entity org = this.InstallAdapter.OrganizationService.Retrieve("organization", detail.OrganizationId, cols) as Entity;

            if (org != null)
            {
                this.BaseLangCode = org.GetAttributeValue<int>("languagecode");
                TraceLog.Info(string.Format(CultureInfo.CurrentCulture, Resources.OrganizationBaseLanguageMessage, detail.FriendlyName, this.BaseLangCode));
            }
        }
예제 #18
0
 public Organisation(OrganizationDetail organisation)
     : this(organisation.UniqueName, organisation.FriendlyName, organisation.OrganizationVersion, organisation.Endpoints)
 {
 }