/// <summary> /// Gets the role. /// </summary> /// <param name="roleName">Name of the role.</param> /// <returns>The role.</returns> public virtual CRMRole GetRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); const string GetRoleKey = "getRole"; ConditionalLog.Info(string.Format("GetRole({0}). Started.", roleName), this, TimerAction.Start, GetRoleKey); var role = (CRMRole)this.CacheService.RoleCache.Get(roleName); if (role != null) { ConditionalLog.Info(string.Format("GetRole({0}). Finished (retrieved role from cache).", roleName), this, TimerAction.Stop, GetRoleKey); return(role); } role = this.GetRoleFromCrm(roleName); if (role != null) { ConditionalLog.Info(string.Format("GetRole({0}). Retrieved role from CRM.", roleName), this, TimerAction.Tick, GetRoleKey); this.CacheService.RoleCache.Add(role); } ConditionalLog.Info(string.Format("GetRole({0}). Finished.", roleName), this, TimerAction.Stop, GetRoleKey); return(role); }
protected override bool RemoveUsersFromRoles(List <CRMUser> users, List <CRMRole> roles) { const string RemoveUsersFromRolesKey = "removeUsersFromRoles"; ConditionalLog.Info("RemoveUsersFromRoles(...). Started.", this, TimerAction.Start, RemoveUsersFromRolesKey); var result = true; foreach (var role in roles) { foreach (var user in users) { var request = new RemoveMemberListRequest(); request.EntityId = user.ID; request.ListId = role.ID; try { this.CrmService.Execute(request); ConditionalLog.Info(String.Format("RemoveUsersFromRoles(...). User {0} has been removed from {1} role.", user.Name, role.Name), this, TimerAction.Tick, RemoveUsersFromRolesKey); this.CacheService.MembersCache.Remove(role.Name); this.CacheService.MemberOfCache.Remove(user.Name); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't remove contact {0} from marketing list {1} in CRM.", user.Name, role.Name), e, this); result = false; } } } ConditionalLog.Info("RemoveUsersFromRoles(...). Finished.", this, TimerAction.Stop, RemoveUsersFromRolesKey); return(result); }
/// <summary> /// Gets all users. /// </summary> /// <param name="pageIndex">Index of the page.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="totalRecords">The total records.</param> /// <returns>The users.</returns> public virtual List <CRMUser> GetAllUsers(Microsoft.Xrm.Sdk.Query.PagingInfo pagingInfo, out int totalRecords) { const string GetAllUsersKey = "getAllUsers"; ConditionalLog.Info(String.Format("GetAllUsers({0}, {1}). Started.", pagingInfo.PageNumber, pagingInfo.Count), this, TimerAction.Start, GetAllUsersKey); var users = this.GetAllUsersFromCrm(pagingInfo, out totalRecords); if (totalRecords == -1) { ConditionalLog.Info("GetAllUsers returned more than 5k users. A precise count cannot be determined.", this); totalRecords = 5000; } ConditionalLog.Info(String.Format("GetAllUsers({0}, {1}). Retrieved {2} user(s) from CRM.", pagingInfo.PageNumber, pagingInfo.Count, users.Count), this, TimerAction.Tick, GetAllUsersKey); var result = new Dictionary <string, CRMUser>(); foreach (var user in users) { if (!result.ContainsKey(user.Name)) { result.Add(user.Name, user); this.CacheService.UserCache.Add(user); } } ConditionalLog.Info(String.Format("GetAllUsers({0}, {1}). Finished.", pagingInfo.PageNumber, pagingInfo.Count), this, TimerAction.Stop, GetAllUsersKey); return(result.Values.ToList()); }
protected override bool AddUsersToRoles(List <CRMUser> users, List <CRMRole> roles) { const string AddUsersToRolesKey = "addUsersToRoles"; ConditionalLog.Info("AddUsersToRoles(...). Started.", this, TimerAction.Start, AddUsersToRolesKey); var result = true; foreach (var role in roles) { foreach (var user in users) { var request = new AddMemberListRequest(); request.EntityId = user.ID; request.ListId = role.ID; try { this.organizationServiceCache.GetOrganizationService().Execute(request); ConditionalLog.Info(String.Format("AddUsersToRoles(...). User {0} has been added to the {1} role.", user.Name, role.Name), this, TimerAction.Tick, AddUsersToRolesKey); this.CacheService.MembersCache.Remove(role.Name); this.CacheService.MemberOfCache.Remove(user.Name); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't add contact {0} to marketing list {1} in CRM.", user.Name, role.Name), e, this); result = false; } } } ConditionalLog.Info("AddUsersToRoles(...). Finished.", this, TimerAction.Stop, AddUsersToRolesKey); return(result); }
/// <summary> /// Gets the user. /// </summary> /// <param name="userId">ID of the user.</param> /// <returns>The user.</returns> public virtual CRMUser GetUser(Guid userId) { this.Attributes = null; const string GetUserKey = "getUserById"; ConditionalLog.Info(String.Format("GetUser({0}). Started.", userId), this, TimerAction.Start, GetUserKey); var user = (CRMUser)this.CacheService.UserCache.Get(userId); if (user != null) { ConditionalLog.Info(String.Format("GetUser({0}). Finished (retrieved user from cache).", userId), this, TimerAction.Stop, GetUserKey); return(user); } user = this.GetUserFromCrm(userId); if (user != null) { ConditionalLog.Info(String.Format("GetUser({0}). Retrieved user from CRM.", userId), this, TimerAction.Tick, GetUserKey); this.CacheService.UserCache.Add(user); } ConditionalLog.Info(String.Format("GetUser({0}). Finished.", userId), this, TimerAction.Stop, GetUserKey); return(user); }
protected override int GetUsersNumber(string propertyName, string propertyValue) { var xmlQuery = new StringBuilder("<fetch mapping='logical' aggregate='true'>"); xmlQuery.Append("<entity name='contact'>"); xmlQuery.Append("<attribute name='contactid' aggregate='count' alias='count' />"); xmlQuery.Append("<filter type='and'>"); xmlQuery.Append("<condition attribute='statecode' operator='eq' value='Active'/>"); xmlQuery.Append(string.Format("<condition attribute='{0}' operator='not-null'/>", Configuration.Settings.UniqueKeyProperty)); xmlQuery.Append(string.Format("<condition attribute='{0}' operator='ne' value=''/>", Configuration.Settings.UniqueKeyProperty)); if (!string.IsNullOrEmpty(propertyName) && !string.IsNullOrEmpty(propertyValue)) { xmlQuery.Append(string.Format("<condition attribute='{0}' operator='like' value='{1}'/>", propertyName, propertyValue)); } xmlQuery.Append("</filter>"); xmlQuery.Append("</entity>"); xmlQuery.Append("</fetch>"); try { var result = this.CrmService.Fetch(xmlQuery.ToString()); var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(result); return(Int32.Parse(xmlDoc.SelectSingleNode("resultset/result").InnerText)); } catch (Exception e) { ConditionalLog.Error("Couldn't get number of contacts from CRM.", e, this); } return(0); }
/// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.</exception> public override void Initialize(string name, NameValueCollection config) { base.Initialize(name, config); try { Error.AssertLicense("Sitecore.MSCRM", "Microsoft Dynamics CRM security provider."); this.ApplicationName = config["applicationName"]; this.ReadOnly = (String.IsNullOrEmpty(config["readOnly"]) || config["readOnly"] == "true"); var connectionStringName = config["connectionStringName"]; var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; var settings = Configuration.ConfigurationSettings.Parse(connectionString); this.profileRepository = this.profileRepositoryFactory.GetRepository(settings); this.userRepository = this.userRepositoryFactory.GetRepository(settings); this.SetupCustomPropertyNames(); this.initialized = true; } catch (Exception e) { this.initialized = false; ConditionalLog.Error("The CRM provider couldn't be initialized.", e, this); } }
/// <summary> /// Deletes profile properties and information for profiles that match the supplied list of contact names. /// </summary> /// <param name="usernames">A string array of contact names for profiles to be deleted.</param> /// <returns>The number of profiles deleted from the CRM system.</returns> public override int DeleteProfiles(string[] usernames) { if (!this.initialized || this.ReadOnly) { return(0); } int numberOfDeletedProfiles = 0; foreach (string userName in usernames) { if (!this.HasProfile(userName)) { continue; } var properties = new Dictionary <string, object>(); this.propertyNames.Keys.ToList().ForEach(propertyName => properties.Add(propertyName, null)); if (properties.Count != 0) { if (this.profileRepository.UpdateUserProperties(userName, properties)) { numberOfDeletedProfiles++; } else { ConditionalLog.Error(String.Format("Couldn't delete profile for the {0} user.", userName), this); } } } return(numberOfDeletedProfiles); }
protected override int GetUsersNumber(string propertyName, string propertyValue) { var xmlQuery = new StringBuilder("<fetch mapping='logical' aggregate='true' nolock='true'>"); xmlQuery.Append("<entity name='contact'>"); xmlQuery.Append("<attribute name='contactid' aggregate='count' alias='count' />"); xmlQuery.Append("<filter type='and'>"); xmlQuery.Append("<condition attribute='statecode' operator='eq' value='Active'/>"); xmlQuery.Append(string.Format("<condition attribute='{0}' operator='not-null'/>", Configuration.Settings.UniqueKeyProperty)); xmlQuery.Append(string.Format("<condition attribute='{0}' operator='ne' value=''/>", Configuration.Settings.UniqueKeyProperty)); if (!string.IsNullOrEmpty(propertyName) && !string.IsNullOrEmpty(propertyValue)) { xmlQuery.Append(string.Format("<condition attribute='{0}' operator='like' value='{1}'/>", propertyName, propertyValue)); } xmlQuery.Append("</filter>"); xmlQuery.Append("</entity>"); xmlQuery.Append("</fetch>"); try { var result = this.organizationServiceCache.GetOrganizationService().RetrieveMultiple(new FetchExpression(xmlQuery.ToString())); foreach (var entity in result.Entities) { return((int)((AliasedValue)entity["count"]).Value); } } catch (Exception e) { ConditionalLog.Error("Couldn't get number of contacts from CRM.", e, this); } return(0); }
/// <summary> /// Finds the users. /// </summary> /// <param name="userName">The user name.</param> /// <param name="pageIndex">Index of the page.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="totalRecords">The total records.</param> /// <returns>The users.</returns> public virtual List <CRMUser> FindUsersByName(string userName, int pageIndex, int pageSize, out int totalRecords) { Assert.ArgumentNotNull(userName, "userName"); const string FindUsersByNameKey = "findUsersByName"; ConditionalLog.Info(String.Format("FindUsersByName({0}, {1}, {2}). Started.", userName, pageIndex, pageSize), this, TimerAction.Start, FindUsersByNameKey); var users = this.FindUsersInCrmByName(userName, pageIndex, pageSize, out totalRecords); ConditionalLog.Info(String.Format("FindUsersByName({0}, {1}, {2}). Retrieved {3} user(s) from CRM.", userName, pageIndex, pageSize, users.Count), this, TimerAction.Tick, FindUsersByNameKey); var result = new Dictionary <string, CRMUser>(); foreach (var user in users) { if (!result.ContainsKey(user.Name)) { result.Add(user.Name, user); this.CacheService.UserCache.Add(user); } } ConditionalLog.Info(String.Format("FindUsersByName({0}, {1}, {2}). Finished.", userName, pageIndex, pageSize), this, TimerAction.Stop, FindUsersByNameKey); return(result.Values.ToList()); }
/// <summary> /// Gets the user. /// </summary> /// <param name="userName">Name of the user.</param> /// <returns>The user.</returns> public virtual CRMUser GetUser(string userName, string[] attributes = null) { Assert.ArgumentNotNull(userName, "userName"); this.Attributes = attributes; const string GetUserKey = "getUserByName"; ConditionalLog.Info(String.Format("GetUser({0}). Started.", userName), this, TimerAction.Start, GetUserKey); var user = (CRMUser)this.CacheService.UserCache.Get(userName); if (user != null) { if (attributes == null || !user.ProfilePropertyNames.Except(attributes.AsEnumerable()).Any()) { ConditionalLog.Info(String.Format("GetUser({0}). Finished (retrieved user from cache).", userName), this, TimerAction.Stop, GetUserKey); return(user); } else { this.CacheService.UserCache.Remove(user.Name); } } user = this.GetUserFromCrm(userName); if (user != null) { ConditionalLog.Info(String.Format("GetUser({0}). Retrieved user from CRM.", userName), this, TimerAction.Tick, GetUserKey); this.CacheService.UserCache.Add(user); } ConditionalLog.Info(String.Format("GetUser({0}). Finished.", userName), this, TimerAction.Stop, GetUserKey); return(user); }
/// <summary> /// Gets the implicit entities count. When explicit count can't be retrieved due to AggregateQueryRecordLimit setting. /// </summary> /// <param name="logicalName">Name of the logical.</param> /// <param name="filterExpression">The filter expression.</param> /// <returns>The number of entities.</returns> private int GetImplicitEntitiesCount(string logicalName, FilterExpression filterExpression) { var entityCollection = this.organizationServiceCache.GetOrganizationService().RetrieveMultiple( new QueryExpression { EntityName = logicalName, Criteria = filterExpression, PageInfo = new PagingInfo { PageNumber = 1, Count = 1, ReturnTotalRecordCount = true } }); if (entityCollection.TotalRecordCountLimitExceeded) { ConditionalLog.Error( string.Format( "The number of '{0}' entities is exceeding AggregrateQueryRecordLimit. Only first {1} can be shown.", logicalName, entityCollection.TotalRecordCount), this); } return(entityCollection.TotalRecordCount); }
public override bool UpdateUserProperties(string userName, Dictionary <string, object> properties) { Assert.ArgumentNotNull(userName, "userName"); Assert.ArgumentNotNull(properties, "properties"); const string UpdateUserProrpertiesKey = "updateUserProperties"; ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Started.", userName), this, TimerAction.Start, UpdateUserProrpertiesKey); var result = false; var user = this.UserRepository.GetUser(userName); if (user != null) { if (properties.ContainsKey("fullname")) { this.ProcessFullNameProperty((string)properties["fullname"], properties); } var propertiesToUpdate = new Dictionary <string, object>(); propertiesToUpdate.Add("contactid", user.ID); foreach (var property in properties) { this.AddPropertyToCollection(property.Key, property.Value, this.GetPropertyType(property.Key), propertiesToUpdate); } var update = new UpdateRequest(); update.Target = new Entity(); update.Target.LogicalName = "contact"; foreach (var property in propertiesToUpdate) { update.Target.Attributes.Add(property.Key, property.Value); } try { this.organizationServiceCache.GetOrganizationService().Execute(update); ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Updated in CRM.", userName), this, TimerAction.Tick, UpdateUserProrpertiesKey); foreach (var property in propertiesToUpdate) { user.SetPropertyValue(property.Key, property.Value); } result = true; } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't save profile changes for the contact {0} in CRM.", userName), e, this); } } ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Finished.", userName), this, TimerAction.Stop, UpdateUserProrpertiesKey); return(result); }
public override string[] GetUsersInRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole"); string text = base.CacheService.MembersCache.Get(roleName); if (text != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole"); return(text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)); } // set up a query for the list to check type ColumnSet columnSet = new ColumnSet(); columnSet.Attributes = new string[] { "listname", "query", "type" }; QueryExpression query = new QueryExpression(); query.ColumnSet = columnSet; ConditionExpression listnameCondition = new ConditionExpression(); listnameCondition.AttributeName = "listname"; listnameCondition.Operator = ConditionOperator.Equal; listnameCondition.Values = new String[] { roleName }; FilterExpression filterList = new FilterExpression(); filterList.Conditions = new ConditionExpression[] { listnameCondition }; filterList.FilterOperator = LogicalOperator.And; query.EntityName = "list"; query.Criteria = filterList; // Execute the query RetrieveMultipleRequest req = new RetrieveMultipleRequest(); req.Query = query; req.ReturnDynamicEntities = true; RetrieveMultipleResponse res = (RetrieveMultipleResponse)CrmService.Execute(req); if (res.BusinessEntityCollection.BusinessEntities.GetLength(0) > 0) { DynamicEntity myList = (DynamicEntity)res.BusinessEntityCollection.BusinessEntities[0]; } return(base.GetUsersInRole(roleName)); }
/// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext"/> describing the current application usage.</param> /// <param name="collection">A <see cref="T:System.Configuration.SettingsPropertyValueCollection"/> representing the group of property settings to set.</param> /// <exception cref="FormatException">The profile property couldn't be parsed.</exception> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { if (this.initialized) { bool showMessage = false; var userName = (string)context["UserName"]; if (string.IsNullOrEmpty(userName) || userName.Contains("\\")) { return; } SettingsPropertyValueCollection relevantPropertyValues = this.GetRelevantPropertyValues(collection); var newPropertyValues = new Dictionary <string, object>(); foreach (CrmSettingsPropertyValue property in relevantPropertyValues) { string propertyName = this.ProcessProperty(property.Property, p => (p as CrmSettingsProperty).CrmName); object propertyValue = property.PropertyValue; if ((propertyName != "contactid") && (property.PropertyValue != null) && !showMessage) { if (this.ReadOnly) { showMessage = property.IsDirty; } else { if (property.IsDirty && this.initialized) { newPropertyValues.Add(propertyName, propertyValue); } } } collection.Remove(property.Name); } if (!this.ReadOnly && (newPropertyValues.Count != 0)) { if (!this.profileRepository.UpdateUserProperties(userName, newPropertyValues)) { ConditionalLog.Error(String.Format("Couldn't save profile changes for the {0} contact in CRM", userName), this); } } if (this.ReadOnly && showMessage) { CrmHelper.ShowMessage("Couldn't update contact properties as the CRM provider is in read-only mode"); } } }
/// <summary> /// Creates CRM organization service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM organization service.</returns> public IOrganizationService CreateOrganizationService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateOrganizationServiceKey = "createOrganizationService"; ConditionalLog.Info("CreateOrganizationService(settings). Started.", this, TimerAction.Start, CreateOrganizationServiceKey); IOrganizationService organizationService = null; try { var serviceManagement = ServiceConfigurationFactory.CreateManagement <IOrganizationService>(new Uri(settings.Url)); var authenticationCredentials = new AuthenticationCredentials(); switch (serviceManagement.AuthenticationType) { case AuthenticationProviderType.ActiveDirectory: authenticationCredentials.ClientCredentials.Windows.ClientCredential = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); organizationService = new OrganizationServiceProxy(serviceManagement, authenticationCredentials.ClientCredentials); break; case AuthenticationProviderType.LiveId: case AuthenticationProviderType.Federation: case AuthenticationProviderType.OnlineFederation: authenticationCredentials.ClientCredentials.UserName.UserName = settings.User; authenticationCredentials.ClientCredentials.UserName.Password = settings.Password; var tokenCredentials = serviceManagement.Authenticate(authenticationCredentials); organizationService = new ManagedTokenOrganizationServiceProxy(tokenCredentials.SecurityTokenResponse, serviceManagement, authenticationCredentials.ClientCredentials); break; } organizationService.Execute(new WhoAmIRequest()); ConditionalLog.Info("CreateOrganizationService(settings). CRM organization service has been created.", this, TimerAction.Tick, CreateOrganizationServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM organization service.", e, this); return(null); } finally { ConditionalLog.Info("CreateOrganizationService(settings). Finished.", this, TimerAction.Stop, CreateOrganizationServiceKey); } return(organizationService); }
/// <summary> /// Processes a request to update the password for a contact. /// </summary> /// <returns>true if the password was updated successfully; otherwise, false.</returns> /// <param name="username">The contact to update the password for. </param> /// <param name="oldPassword">The current password for the specified contact. </param> /// <param name="newPassword">The new password for the specified contact. </param> /// <exception cref="NotSupportedException">Couldn't change password as the CRM provider is in read-only mode.</exception> /// <exception cref="NotSupportedException">The CRM provider is not configured to store password.</exception> public override bool ChangePassword(string username, string oldPassword, string newPassword) { if (this.initialized) { if (this.ReadOnly) { throw new NotSupportedException("Couldn't change password as the CRM provider is in read-only mode."); } if (String.IsNullOrEmpty(this.PasswordFieldName)) { throw new NotSupportedException("The CRM provider is not configured to store password."); } var password = this.profileRepository.GetUserProperty(username, this.PasswordFieldName) as string; if (String.IsNullOrEmpty(password)) { ConditionalLog.Warn(String.Format("CrmSecurityProvider: user \"{0}\" doesn't have a password. You should reset it before changing.", username), this); return(false); } SHA1Managed sha1 = new SHA1Managed(); byte[] oldPasswordBytes = Encoding.UTF8.GetBytes(oldPassword); byte[] hashedOldPasswordBytes = sha1.ComputeHash(oldPasswordBytes); string hashedOldPassword = System.Convert.ToBase64String(hashedOldPasswordBytes); if (password != hashedOldPassword) { return(false); } if (!IsPasswordValid(newPassword)) { return(false); } byte[] newPasswordBytes = Encoding.UTF8.GetBytes(newPassword); byte[] hashedNewPasswordBytes = sha1.ComputeHash(newPasswordBytes); string hashedNewPassword = System.Convert.ToBase64String(hashedNewPasswordBytes); var properties = new Dictionary <string, object>(); properties.Add(PasswordFieldName, hashedNewPassword); return(this.profileRepository.UpdateUserProperties(username, properties)); } return(false); }
public override bool DeactivateUser(string userName) { Assert.ArgumentNotNull(userName, "userName"); const string DeactivateUserKey = "deactivateUser"; ConditionalLog.Info(string.Format("DeactivateUser({0}). Started.", userName), this, TimerAction.Start, DeactivateUserKey); var result = false; var user = this.GetUser(userName); if (user != null) { var request = new SetStateRequest { EntityMoniker = new EntityReference("contact", user.ID), State = new OptionSetValue { Value = 1 }, Status = new OptionSetValue { Value = 2 } }; try { this.organizationServiceCache.GetOrganizationService().Execute(request); ConditionalLog.Info(string.Format("DeactivateUser({0}). User has been deactivated in CRM.", userName), this, TimerAction.Tick, DeactivateUserKey); this.CacheService.MembersCache.Clear(); this.CacheService.MemberOfCache.Remove(userName); this.CacheService.UserCache.Remove(userName); result = true; } catch (Exception e) { ConditionalLog.Error(string.Format("Couldn't deactivate user {0} in CRM.", userName), e, this); } } ConditionalLog.Info(string.Format("DeactivateUser({0}). Finished.", userName), this, TimerAction.Stop, DeactivateUserKey); return(result); }
public override bool DeactivateRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); const string DeactivateRoleKey = "deactivateRole"; ConditionalLog.Info(String.Format("DeactivateRole({0}). Started.", roleName), this, TimerAction.Start, DeactivateRoleKey); var result = false; var role = this.GetRole(roleName); if (role != null) { var request = new SetStateRequest(); request.EntityMoniker = new EntityReference("list", role.ID); request.State = new OptionSetValue { Value = 1 }; request.Status = new OptionSetValue { Value = 1 }; try { this.organizationServiceCache.GetOrganizationService().Execute(request); ConditionalLog.Info(String.Format("DeactivateRole({0}). Role has been deactivated in CRM.", roleName), this, TimerAction.Tick, DeactivateRoleKey); this.CacheService.MemberOfCache.Clear(); this.CacheService.MembersCache.Remove(roleName); this.CacheService.RoleCache.Remove(roleName); result = true; } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't deactivate role {0} in CRM.", roleName), e, this); } } ConditionalLog.Info(String.Format("DeactivateRole({0}). Finished.", roleName), this, TimerAction.Stop, DeactivateRoleKey); return(result); }
/// <summary> /// Creates CRM metadata service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM metadata service.</returns> public IMetadataServiceV4 CreateMetadataService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateMetadataServiceKey = "createMetadataService"; ConditionalLog.Info("CreateMetadataService(settings). Started.", this, TimerAction.Start, CreateMetadataServiceKey); ManagedTokenMetadataService wrapper = null; try { var metadataService = new MetadataService(); metadataService.Url = settings.Url.Replace("crmservice.asmx", "metadataservice.asmx"); metadataService.Timeout = 360 * 1000; metadataService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); metadataService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; metadataService.PreAuthenticate = settings.PreAuthenticate; metadataService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)metadataService.Credentials); metadataService.CrmAuthenticationTokenValue = new crm4.metadataservice.CrmAuthenticationToken { AuthenticationType = (int)settings.AuthenticationType, OrganizationName = settings.Organization }; wrapper = new ManagedTokenMetadataService(metadataService, settings); wrapper.Execute(new RetrieveTimestampRequest()); ConditionalLog.Info("CreateMetadataService(settings). CRM metadata service has been created.", this, TimerAction.Tick, CreateMetadataServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM metadata service.", e, this); return(null); } finally { ConditionalLog.Info("CreateMetadataService(settings). Finished.", this, TimerAction.Stop, CreateMetadataServiceKey); } return(wrapper); }
/// <summary> /// Updates the state status. /// </summary> /// <param name="logicalName">Name of the logical.</param> /// <param name="id">The id.</param> /// <param name="state">The state.</param> /// <param name="status">The status.</param> public void UpdateStateStatus(string logicalName, Guid id, ICrmKeyValueAttribute state, ICrmKeyValueAttribute status) { try { this.crmService.Execute(new SetStateDynamicEntityRequest { Entity = new Moniker { Id = id, Name = logicalName }, Status = status.Key, State = state.Value, }); } catch (Exception e) { ConditionalLog.Error("Couldn't update entity state and status", e, this); if (!e.Message.Contains("is not a valid status code for state code")) { return; } ConditionalLog.Info("Trying to set only state", this); try { this.crmService.Execute(new SetStateDynamicEntityRequest { Entity = new Moniker { Id = id, Name = logicalName }, Status = status.Key, State = state.Value, }); } catch { ConditionalLog.Error("Couldn't update entity state", e, this); } } }
/// <summary> /// Processes a request to update the password question and answer for a contact. /// </summary> /// <returns>true if the password question and answer are updated successfully; otherwise, false.</returns> /// <param name="username">The contact to change the password question and answer for. </param> /// <param name="password">The password for the specified contact. </param> /// <param name="newPasswordQuestion">The new password question for the specified contact. </param> /// <param name="newPasswordAnswer">The new password answer for the specified contact. </param> /// <exception cref="NotSupportedException">Couldn't change password question or(and) password answer as the CRM provider is in read-only mode.</exception> /// <exception cref="NotSupportedException">The CRM provider is not configured to store password.</exception> public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { if (this.initialized) { if (this.ReadOnly) { throw new NotSupportedException("Couldn't change password question or(and) password answer as the CRM provider is in read-only mode."); } if (String.IsNullOrEmpty(this.PasswordFieldName)) { throw new NotSupportedException("The CRM provider is not configured to store password."); } var validPassword = this.profileRepository.GetUserProperty(username, this.PasswordFieldName) as string; if (String.IsNullOrEmpty(validPassword)) { ConditionalLog.Warn(String.Format("CrmSecurityProvider: user \"{0}\" doesn't have a password.", username), this); return(false); } SHA1Managed sha1 = new SHA1Managed(); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); byte[] hashedPasswordBytes = sha1.ComputeHash(passwordBytes); string hashedPassword = System.Convert.ToBase64String(hashedPasswordBytes); if (validPassword != hashedPassword) { return(false); } var properties = new Dictionary <string, object>(); properties.Add(this.PasswordQuestionFieldName, newPasswordQuestion); properties.Add(this.PasswordAnswerFieldName, newPasswordAnswer); return(this.profileRepository.UpdateUserProperties(username, properties)); } return(false); }
public override bool DeactivateRole(string roleName) { Assert.ArgumentNotNull(roleName, "roleName"); const string DeactivateRoleKey = "deactivateRole"; ConditionalLog.Info(String.Format("DeactivateRole({0}). Started.", roleName), this, TimerAction.Start, DeactivateRoleKey); var result = false; var role = this.GetRole(roleName); if (role != null) { var request = new SetStateListRequest(); request.EntityId = role.ID; request.ListState = ListState.Inactive; request.ListStatus = -1; try { this.CrmService.Execute(request); ConditionalLog.Info(String.Format("DeactivateRole({0}). Role has been deactivated in CRM.", roleName), this, TimerAction.Tick, DeactivateRoleKey); this.CacheService.MemberOfCache.Clear(); this.CacheService.MembersCache.Remove(roleName); this.CacheService.RoleCache.Remove(roleName); result = true; } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't deactivate role {0} in CRM.", roleName), e, this); } } ConditionalLog.Info(String.Format("DeactivateRole({0}). Finished.", roleName), this, TimerAction.Stop, DeactivateRoleKey); return(result); }
public override bool DeactivateUser(string userName) { Assert.ArgumentNotNull(userName, "userName"); const string DeactivateUserKey = "deactivateUser"; ConditionalLog.Info(String.Format("DeactivateUser({0}). Started.", userName), this, TimerAction.Start, DeactivateUserKey); var result = false; var user = this.GetUser(userName); if (user != null) { var request = new SetStateContactRequest(); request.EntityId = user.ID; request.ContactState = ContactState.Inactive; request.ContactStatus = 2; try { this.CrmService.Execute(request); ConditionalLog.Info(String.Format("DeactivateUser({0}). User has been deactivated in CRM.", userName), this, TimerAction.Tick, DeactivateUserKey); this.CacheService.MembersCache.Clear(); this.CacheService.MemberOfCache.Remove(userName); this.CacheService.UserCache.Remove(userName); result = true; } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't deactivate user {0} in CRM.", userName), e, this); } } ConditionalLog.Info(String.Format("DeactivateUser({0}). Finished.", userName), this, TimerAction.Stop, DeactivateUserKey); return(result); }
/// <summary> /// Updates the state status. /// </summary> /// <param name="logicalName">Name of the logical.</param> /// <param name="id">The id.</param> /// <param name="state">The state.</param> /// <param name="status">The status.</param> private void UpdateStateStatus(string logicalName, Guid id, ICrmKeyValueAttribute state, ICrmKeyValueAttribute status) { try { this.organizationServiceCache.GetOrganizationService().Execute(new SetStateRequest { EntityMoniker = new EntityReference(logicalName, id), State = new OptionSetValue(state.Key), Status = new OptionSetValue(status.Key) }); } catch (Exception e) { ConditionalLog.Error("Couldn't update entity state and status", e, this); if (!e.Message.Contains("is not a valid status code for state code")) { return; } ConditionalLog.Info("Trying to set state only", this); try { this.organizationServiceCache.GetOrganizationService().Execute(new SetStateRequest { EntityMoniker = new EntityReference(logicalName, id), State = new OptionSetValue(state.Key), Status = new OptionSetValue(-1) }); } catch { ConditionalLog.Error("Couldn't update entity state", e, this); } } }
public override bool CreateRole(string roleName) { Assert.ArgumentNotNullOrEmpty(roleName, "roleName"); const string CreateRoleKey = "createRole"; ConditionalLog.Info(String.Format("CreateRole({0}). Started.", roleName), this, TimerAction.Start, CreateRoleKey); var marketingList = new list(); marketingList.listname = roleName; marketingList.membertype = new CrmNumber { Value = 2 }; marketingList.createdfromcode = new Picklist { Value = 2 }; var result = false; try { var id = this.CrmService.Create(marketingList); ConditionalLog.Info(String.Format("CreateRole({0}). Role has been created in CRM.", roleName), this, TimerAction.Tick, CreateRoleKey); this.CacheService.RoleCache.Add(new CRMRole(roleName, id)); result = true; } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't create role {0} in CRM.", roleName), e, this); } ConditionalLog.Info(String.Format("CreateRole({0}). Finished.", roleName), this, TimerAction.Stop, CreateRoleKey); return(result); }
/// <summary> /// Gets the user properties. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="propertyNames">The property names.</param> /// <returns>The user properties.</returns> public virtual Dictionary <string, object> GetUserProperties(string userName, string[] propertyNames) { Assert.ArgumentNotNull(userName, "userName"); Assert.ArgumentNotNull(propertyNames, "propertyNames"); const string GetUserPropertiesKey = "getUserProperties"; ConditionalLog.Info(String.Format("GetUserProperties({0}). Started.", userName), this, TimerAction.Start, GetUserPropertiesKey); try { var user = this.UserRepository.GetUser(userName, propertyNames); if (user != null) { return(user.ProfilePropertyNames.Where(propertyNames.Contains).ToDictionary(p => p, p => this.GetPropertyValue(user, p))); } return(new Dictionary <string, object>()); } finally { ConditionalLog.Info(String.Format("GetUserProperties({0}). Finished.", userName), this, TimerAction.Stop, GetUserPropertiesKey); } }
/// <summary> /// Creates CRM service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM service.</returns> public ICrmServiceV3 CreateService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateServiceKey = "createService"; ConditionalLog.Info("CreateService(settings). Started.", this, TimerAction.Start, CreateServiceKey); CrmService crmService = null; try { crmService = new CrmService(); crmService.Url = settings.Url; crmService.Timeout = 360 * 1000; crmService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); crmService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; crmService.PreAuthenticate = settings.PreAuthenticate; crmService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)crmService.Credentials); crmService.Execute(new WhoAmIRequest()); ConditionalLog.Info("CreateService(settings). CRM service has been created.", this, TimerAction.Tick, CreateServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM service.", e, this); return(null); } finally { ConditionalLog.Info("CreateService(settings). Finished.", this, TimerAction.Stop, CreateServiceKey); } return(crmService); }
/// <summary> /// Creates CRM metadata service. /// </summary> /// <param name="settings">The configuration settings</param> /// <returns>The CRM metadata service.</returns> public IMetadataServiceV3 CreateMetadataService(ConfigurationSettings settings) { Assert.ArgumentNotNull(settings, "settings"); const string CreateMetadataServiceKey = "createMetadataService"; ConditionalLog.Info("CreateMetadataService(settings). Started.", this, TimerAction.Start, CreateMetadataServiceKey); MetadataService metadataService = null; try { metadataService = new MetadataService(); metadataService.Url = settings.Url.Replace("crmservice.asmx", "metadataservice.asmx"); metadataService.Timeout = 360 * 1000; metadataService.Credentials = CrmHelper.CreateNetworkCredential(settings.User, settings.Password); metadataService.UnsafeAuthenticatedConnectionSharing = settings.UnsafeAuthenticatedConnectionSharing; metadataService.PreAuthenticate = settings.PreAuthenticate; metadataService.ConnectionGroupName = CrmHelper.GetConnectionGroupName((NetworkCredential)metadataService.Credentials); metadataService.GetTimestamp(); ConditionalLog.Info("CreateMetadataService(settings). CRM metadata service has been created.", this, TimerAction.Tick, CreateMetadataServiceKey); } catch (Exception e) { ConditionalLog.Error("Couldn't create CRM metadata service.", e, this); return(null); } finally { ConditionalLog.Info("CreateMetadataService(settings). Finished.", this, TimerAction.Stop, CreateMetadataServiceKey); } return(metadataService); }
/// <summary> /// Gets the users. /// </summary> /// <param name="userNames">The user names.</param> /// <returns>The users.</returns> public virtual List <CRMUser> GetUsers(string[] userNames) { Assert.ArgumentNotNull(userNames, "userNames"); this.Attributes = null; const string GetUsersKey = "getUsers"; ConditionalLog.Info(String.Format("GetUsers({0}). Started.", String.Join(",", userNames)), this, TimerAction.Start, GetUsersKey); var result = new Dictionary <string, CRMUser>(); var users = userNames.Select(n => (CRMUser)this.CacheService.UserCache.Get(n)).Where(u => u != null).ToList(); foreach (var user in users) { ConditionalLog.Info(String.Format("GetUsers({0}). Retrieved user {1} from cache.", String.Join(",", userNames), user.Name), this, TimerAction.Tick, GetUsersKey); result.Add(user.Name, user); } if (result.Count != userNames.Length) { users = this.GetUsersFromCrm(userNames.Except(result.Keys).ToArray()); ConditionalLog.Info(String.Format("GetUsers({0}). Retrieved {1} user(s) from CRM.", String.Join(",", userNames), users.Count), this, TimerAction.Tick, GetUsersKey); foreach (var user in users) { if (!result.ContainsKey(user.Name)) { result.Add(user.Name, user); this.CacheService.UserCache.Add(user); } } } ConditionalLog.Info(String.Format("GetUsers({0}). Finished.", String.Join(",", userNames)), this, TimerAction.Stop, GetUsersKey); return(result.Values.ToList()); }