/// <summary> /// Saves Crm connections list to file /// </summary> public void SaveConnectionsFile() { if (!string.IsNullOrEmpty(ConnectionsList.Password)) { ConnectionsList.Password = CryptoManager.Encrypt(ConnectionsList.Password, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } ConnectionsList.SerializeToFile(ConfigFileName); }
private CrmServiceClient ConnectOnline(bool isOffice365, bool useSsl, string expliciteOrgName = null) { var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); string region, orgName; bool isOnPrem; Utilities.GetOrgnameAndOnlineRegionFromServiceUri(new Uri(OriginalUrl), out region, out orgName, out isOnPrem); //return new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), GetOnlineRegion(ServerName), expliciteOrgName ?? OrganizationUrlName, true, useSsl, isOffice365: isOffice365); return(new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), region, orgName, true, useSsl, isOffice365: isOffice365)); }
public void SetPassword(string password, bool isEncrypted = false) { if (!string.IsNullOrEmpty(password)) { if (isEncrypted) { userPassword = password; } else { userPassword = CryptoManager.Encrypt(password, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); } } }
private void ConnectOnline() { AuthType = AuthenticationProviderType.OnlineFederation; var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); Utilities.GetOrgnameAndOnlineRegionFromServiceUri(new Uri(OriginalUrl), out var region, out var orgName, out _); if (UseMfa) { var path = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"), "oauth-cache.txt"); crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), region, orgName, false, null, null, AzureAdAppId.ToString(), new Uri(ReplyUrl), path, null); } crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), region, orgName, true, true, null, true); }
public CrmServiceClient GetCrmServiceClient(bool forceNewService = false) { if (forceNewService == false && crmSvc != null) { return(crmSvc); } if (UseConnectionString) { if (ConnectionString.IndexOf("RequireNewInstance=", StringComparison.Ordinal) < 0) { if (!ConnectionString.EndsWith(";")) { ConnectionString += ";"; } ConnectionString += "RequireNewInstance=True;"; } crmSvc = new CrmServiceClient(ConnectionString); if (crmSvc.IsReady) { OrganizationFriendlyName = crmSvc.ConnectedOrgFriendlyName; OrganizationDataServiceUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationDataService]; OrganizationServiceUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.OrganizationService]; WebApplicationUrl = crmSvc.ConnectedOrgPublishedEndpoints[EndpointType.WebApplication]; Organization = crmSvc.ConnectedOrgUniqueName; OrganizationVersion = crmSvc.ConnectedOrgVersion.ToString(); var webAppURi = new Uri(WebApplicationUrl); ServerName = webAppURi.Host; ServerPort = webAppURi.Port; UseOnline = crmSvc.CrmConnectOrgUriActual.Host.Contains(".dynamics.com"); UseOsdp = crmSvc.CrmConnectOrgUriActual.Host.Contains(".dynamics.com"); UseSsl = crmSvc.CrmConnectOrgUriActual.AbsoluteUri.ToLower().StartsWith("https"); UseIfd = crmSvc.ActiveAuthenticationType == AuthenticationType.IFD; switch (crmSvc.ActiveAuthenticationType) { case AuthenticationType.AD: case AuthenticationType.Claims: AuthType = AuthenticationProviderType.ActiveDirectory; break; case AuthenticationType.IFD: AuthType = AuthenticationProviderType.Federation; break; case AuthenticationType.Live: AuthType = AuthenticationProviderType.LiveId; break; case AuthenticationType.OAuth: // TODO add new property in ConnectionDetail class? break; case AuthenticationType.Office365: AuthType = AuthenticationProviderType.OnlineFederation; break; } IsCustomAuth = ConnectionString.ToLower().Contains("username="); } return(crmSvc); } if (UseOnline) { var tasks = new List <Task <CrmServiceClient> > { Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, true)), Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, false)) }; tasks[0].Wait(); tasks[1].Wait(); crmSvc = tasks.FirstOrDefault(t => t.Result.IsReady)?.Result; if (crmSvc == null) { var uniqueName = ResolveCrmOnlineUniqueOrg(); crmSvc = ConnectOnline(UseOsdp, true, uniqueName); if (crmSvc == null) { // None of the attempts above were successful, so get a failed one to be able to display correct error message crmSvc = tasks.FirstOrDefault(t => t.Result != null).Result; } } // crmSvc = ConnectOnline(UseOsdp); AuthType = AuthenticationProviderType.OnlineFederation; } else if (UseIfd) { var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain, HomeRealmUrl, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl); AuthType = AuthenticationProviderType.Federation; } else { NetworkCredential credential; if (!IsCustomAuth) { credential = CredentialCache.DefaultNetworkCredentials; } else { var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); credential = new NetworkCredential(UserName, password, UserDomain); } crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl); AuthType = AuthenticationProviderType.ActiveDirectory; } if (!crmSvc.IsReady) { var error = crmSvc.LastCrmError; crmSvc = null; throw new Exception(error); } if (crmSvc.OrganizationServiceProxy != null) { crmSvc.OrganizationServiceProxy.Timeout = Timeout; } return(crmSvc); }
/// <summary> /// Saves Crm connections list to file /// </summary> public void SaveConnectionsFile(CrmConnections connectionsList) { if (!string.IsNullOrEmpty(connectionsList.Password)) { connectionsList.Password = CryptoManager.Encrypt(connectionsList.Password, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } var cache = new Dictionary <Guid, string>(); lock (connectionsList.Connections) { foreach (var detail in connectionsList.Connections) { if (!detail.ConnectionId.HasValue) { continue; } cache.Add(detail.ConnectionId.Value, detail.UserPassword); if (detail.SavePassword) { if (!string.IsNullOrEmpty(detail.UserPassword)) { detail.UserPassword = CryptoManager.Encrypt(detail.UserPassword, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } } else { detail.UserPassword = null; } } XmlSerializerHelper.SerializeToFile(connectionsList, ConfigFileName); foreach (var detail in connectionsList.Connections) { if (!detail.ConnectionId.HasValue) { continue; } if (detail.UserPassword == null) { detail.UserPassword = cache[detail.ConnectionId.Value]; continue; } if (!string.IsNullOrEmpty(detail.UserPassword)) { detail.UserPassword = CryptoManager.Decrypt(detail.UserPassword, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } } } }
/// <summary> /// Restore Crm connections list from the file /// </summary> /// <returns>List of Crm connections</returns> public CrmConnections LoadConnectionsList() { CrmConnections crmConnections; try { if (File.Exists(ConfigFileName)) { using (var configReader = new StreamReader(ConfigFileName)) { crmConnections = (CrmConnections)XmlSerializerHelper.Deserialize(configReader.ReadToEnd(), typeof(CrmConnections)); } if (!string.IsNullOrEmpty(crmConnections.Password)) { crmConnections.Password = CryptoManager.Decrypt(crmConnections.Password, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } foreach (var detail in crmConnections.Connections) { if (!string.IsNullOrEmpty(detail.UserPassword)) { detail.UserPassword = CryptoManager.Decrypt(detail.UserPassword, CryptoPassPhrase, CryptoSaltValue, CryptoHashAlgorythm, CryptoPasswordIterations, CryptoInitVector, CryptoKeySize); } // Fix for new connection code if (string.IsNullOrEmpty(detail.OrganizationUrlName)) { if (detail.UseIfd || detail.UseOnline || detail.UseOsdp) { var uri = new Uri(detail.OrganizationServiceUrl); detail.OrganizationUrlName = uri.Host.Split('.')[0]; } else { detail.OrganizationUrlName = detail.Organization; } } } } else { crmConnections = new CrmConnections { Connections = new List <ConnectionDetail>() }; } return(crmConnections); } catch (Exception error) { throw new Exception("Error while deserializing configuration file. Details: " + error.Message); } }
public CrmServiceClient GetCrmServiceClient(bool forceNewService = false) { if (forceNewService == false && crmSvc != null) { return(crmSvc); } //return new CrmServiceClient(GetOrganizationCrmConnectionString()); if (UseOnline) { var tasks = new List <Task <CrmServiceClient> > { Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, true)), Task <CrmServiceClient> .Factory.StartNew(() => ConnectOnline(UseOsdp, false)) }; tasks[0].Wait(); tasks[1].Wait(); crmSvc = tasks.FirstOrDefault(t => t.Result != null && t.Result.IsReady)?.Result; if (crmSvc == null) { // None of the attempts above were successful, so get a failed one to be able to display correct error message crmSvc = tasks.FirstOrDefault(t => t.Result != null).Result; } // crmSvc = ConnectOnline(UseOsdp); AuthType = AuthenticationProviderType.OnlineFederation; } else if (UseIfd) { var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); crmSvc = new CrmServiceClient(UserName, CrmServiceClient.MakeSecureString(password), UserDomain, HomeRealmUrl, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl); AuthType = AuthenticationProviderType.Federation; } else { NetworkCredential credential; if (!IsCustomAuth) { credential = CredentialCache.DefaultNetworkCredentials; } else { var password = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); credential = new NetworkCredential(UserName, password, UserDomain); } crmSvc = new CrmServiceClient(credential, AuthenticationType.AD, ServerName, ServerPort.ToString(), OrganizationUrlName, true, UseSsl); AuthType = AuthenticationProviderType.ActiveDirectory; } if (!crmSvc.IsReady) { var error = crmSvc.LastCrmError; crmSvc = null; throw new Exception(error); } return(crmSvc); }
private string GetOrganizationCrmConnectionString() { var connectionString = string.Format("Url={0};", OrganizationServiceUrl.Replace("/XRMServices/2011/Organization.svc", "")); if (IsCustomAuth) { if (!UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { connectionString += string.Format("Domain={0};", UserDomain); } } string username = UserName; if (UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { username = string.Format("{0}\\{1}", UserDomain, UserName); } } if (string.IsNullOrEmpty(userPassword)) { throw new Exception("User password cannot be null. If the user password is not stored in configuration file, you should request it from the end user"); } var decryptedPassword = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); connectionString += string.Format("Username={0};Password={1};", username, decryptedPassword); } if (UseOnline) { ClientCredentials deviceCredentials; do { deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ?? DeviceIdManager.RegisterDevice(); } while (deviceCredentials.UserName.Password.Contains(";") || deviceCredentials.UserName.Password.Contains("=") || deviceCredentials.UserName.Password.Contains(" ") || deviceCredentials.UserName.UserName.Contains(";") || deviceCredentials.UserName.UserName.Contains("=") || deviceCredentials.UserName.UserName.Contains(" ")); connectionString += string.Format("DeviceID={0};DevicePassword={1};", deviceCredentials.UserName.UserName, deviceCredentials.UserName.Password); } if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl)) { connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl); } //append timeout in seconds to connectionstring connectionString += string.Format("Timeout={0};", Timeout.ToString(@"hh\:mm\:ss")); return(connectionString); }
private string GetDiscoveryCrmConnectionString() { var connectionString = string.Format("Url={0}://{1}:{2};", UseSsl ? "https" : "http", UseIfd ? ServerName : UseOsdp ? "disco." + ServerName : UseOnline ? "dev." + ServerName : ServerName, ServerPort == 0 ? (UseSsl ? 443 : 80) : ServerPort); if (IsCustomAuth) { if (!UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { connectionString += string.Format("Domain={0};", UserDomain); } } string username = UserName; if (UseIfd) { if (!string.IsNullOrEmpty(UserDomain)) { username = string.Format("{0}\\{1}", UserDomain, UserName); } } if (string.IsNullOrEmpty(userPassword)) { throw new Exception("User password cannot be null. If the user password is not stored in configuration file, you should request it from the end user"); } var decryptedPassword = CryptoManager.Decrypt(userPassword, ConnectionManager.CryptoPassPhrase, ConnectionManager.CryptoSaltValue, ConnectionManager.CryptoHashAlgorythm, ConnectionManager.CryptoPasswordIterations, ConnectionManager.CryptoInitVector, ConnectionManager.CryptoKeySize); connectionString += string.Format("Username={0};Password={1};", username, decryptedPassword); } if (UseOnline && !UseOsdp) { ClientCredentials deviceCredentials; do { deviceCredentials = DeviceIdManager.LoadDeviceCredentials() ?? DeviceIdManager.RegisterDevice(); } while (deviceCredentials.UserName.Password.Contains(";") || deviceCredentials.UserName.Password.Contains("=") || deviceCredentials.UserName.Password.Contains(" ") || deviceCredentials.UserName.UserName.Contains(";") || deviceCredentials.UserName.UserName.Contains("=") || deviceCredentials.UserName.UserName.Contains(" ")); connectionString += string.Format("DeviceID={0};DevicePassword={1};", deviceCredentials.UserName.UserName, deviceCredentials.UserName.Password); } if (UseIfd && !string.IsNullOrEmpty(HomeRealmUrl)) { connectionString += string.Format("HomeRealmUri={0};", HomeRealmUrl); } return(connectionString); }