/// <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'>"); 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> /// 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); }
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); }
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); }
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); }
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); }
/// <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); }
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); } } }
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); }
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 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> /// 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); } } }
/// <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> /// 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); }
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 Entity(); marketingList.LogicalName = "list"; marketingList["listname"] = roleName; marketingList["membertype"] = 2; marketingList["createdfromcode"] = new OptionSetValue { Value = 2 }; var result = false; try { var id = this.organizationServiceCache.GetOrganizationService().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); }
public override SupportedTypes GetPropertyType(string propertyName) { Assert.ArgumentNotNullOrEmpty(propertyName, "propertyName"); const string GetPropertyTypeKey = "getPropertyType"; ConditionalLog.Info(String.Format("GetPropertyType({0}). Started.", propertyName), this, TimerAction.Start, GetPropertyTypeKey); SupportedTypes propertyType; ContactAttribute contactAttribute; if (this.CacheService.MetadataCache.ContainsKey(propertyName)) { contactAttribute = (ContactAttribute)this.CacheService.MetadataCache[propertyName]; propertyType = contactAttribute.Type; ConditionalLog.Info(String.Format("GetPropertyType({0}). Retrieved from cache.", propertyName), this, TimerAction.Tick, GetPropertyTypeKey); } else { AttributeMetadata attributeMetadata; Dictionary <string, int> options = null; var request = new RetrieveAttributeRequest { EntityLogicalName = EntityName.contact.ToString(), LogicalName = propertyName }; try { var response = (RetrieveAttributeResponse)this.CrmMetadataService.Execute(request); attributeMetadata = response.AttributeMetadata; ConditionalLog.Info(String.Format("GetPropertyType({0}). Retrieved from CRM.", propertyName), this, TimerAction.Tick, GetPropertyTypeKey); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't retrieve metadata for the {0} attribute from CRM.", propertyName), e, this); throw new ProviderException(String.Format("Couldn't retrieve metadata for the {0} attribute from CRM.", propertyName), e); } switch (attributeMetadata.AttributeType.Value) { case AttributeType.String: case AttributeType.Memo: propertyType = SupportedTypes.String; break; case AttributeType.Boolean: propertyType = SupportedTypes.CrmBoolean; break; case AttributeType.DateTime: propertyType = SupportedTypes.CrmDateTime; break; case AttributeType.Float: propertyType = SupportedTypes.CrmFloat; break; case AttributeType.Decimal: propertyType = SupportedTypes.CrmDecimal; break; case AttributeType.Money: propertyType = SupportedTypes.CrmMoney; break; case AttributeType.Integer: propertyType = SupportedTypes.CrmNumber; break; case AttributeType.Picklist: propertyType = SupportedTypes.Picklist; var picklistAttributeMetadata = attributeMetadata as PicklistAttributeMetadata; if (picklistAttributeMetadata != null) { options = new Dictionary <string, int>(); picklistAttributeMetadata.Options.ToList().ForEach(option => options.Add(option.Label.UserLocLabel.Label, option.Value.Value)); } break; default: ConditionalLog.Info(String.Format("The {0} attribute is of unsupported ({1}) type.", propertyName, attributeMetadata.AttributeType.Value), this, TimerAction.Tick, GetPropertyTypeKey); throw new ProviderException(String.Format("The {0} attribute is of unsupported ({1}) type.", propertyName, attributeMetadata.AttributeType.Value)); } contactAttribute = (options != null) ? new PicklistContactAttribute(propertyType, options) : new ContactAttribute(propertyType); this.CacheService.MetadataCache.Add(propertyName, contactAttribute); } ConditionalLog.Info(String.Format("GetPropertyType({0}). Finished.", propertyName), this, TimerAction.Stop, GetPropertyTypeKey); return(propertyType); }
/// <summary> /// Gets the marketing lists. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="conditionOperator">Condition operator.</param> /// <param name="values">The values of the property.</param> /// <returns>The marketing lists.</returns> protected IEnumerable <list> GetMarketingLists(string propertyName, ConditionOperator conditionOperator, params object[] values) { var propertyConditionExpression = new ConditionExpression(); propertyConditionExpression.AttributeName = propertyName; propertyConditionExpression.Operator = conditionOperator; propertyConditionExpression.Values = values; var memberTypeConditionExpression = new ConditionExpression(); memberTypeConditionExpression.AttributeName = "membertype"; memberTypeConditionExpression.Operator = ConditionOperator.Equal; memberTypeConditionExpression.Values = new object[] { 2 }; var stateCodeConditionExpression = new ConditionExpression(); stateCodeConditionExpression.AttributeName = "statecode"; stateCodeConditionExpression.Operator = ConditionOperator.Equal; stateCodeConditionExpression.Values = new object[] { "Active" }; var filterExpression = new FilterExpression(); filterExpression.Conditions = new ConditionExpression[] { propertyConditionExpression, memberTypeConditionExpression, stateCodeConditionExpression }; filterExpression.FilterOperator = LogicalOperator.And; var pagingInfo = new PagingInfo { PageNumber = 1, Count = Configuration.Settings.FetchThrottlingPageSize }; var queryExpression = new QueryExpression(); queryExpression.PageInfo = pagingInfo; queryExpression.ColumnSet = new ColumnSet { Attributes = this.Attributes }; queryExpression.Criteria = filterExpression; queryExpression.EntityName = EntityName.list.ToString(); var returnValue = new HashSet <list>(new ListEqualityComparer()); try { while (true) { var entities = this.CrmService.RetrieveMultiple(queryExpression); if (entities == null) { break; } foreach (var list in entities.BusinessEntities.Cast <list>()) { returnValue.Add(list); } if (!entities.MoreRecords) { break; } pagingInfo.PageNumber++; pagingInfo.PagingCookie = entities.PagingCookie; } } catch (Exception e) { ConditionalLog.Error("Couldn't get the marketing list(s) from CRM.", e, this); } return(returnValue.ToArray()); }
public override CRMUser CreateUser(string userName, string email, Guid providerUserKey) { Assert.ArgumentNotNullOrEmpty(userName, "userName"); Assert.ArgumentNotNullOrEmpty(email, "email"); const string CreateUserKey = "createUser"; ConditionalLog.Info(string.Format("CreateUser({0}, {1}, {2}). Started.", userName, email, providerUserKey), this, TimerAction.Start, CreateUserKey); var contact = new Entity { LogicalName = "contact" }; if (Configuration.Settings.UniqueKeyProperty != "fullname") { contact[Configuration.Settings.UniqueKeyProperty] = userName; } else { var nameParts = new List <string>(userName.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); contact["firstname"] = nameParts[0]; if (nameParts.Count > 1) { contact["lastname"] = string.Join(" ", nameParts.GetRange(1, nameParts.Count - 1).ToArray()); } } if ((email != null) && (Configuration.Settings.UniqueKeyProperty != "emailaddress1")) { contact["emailaddress1"] = email; } if (providerUserKey != Guid.Empty) { contact["contactid"] = providerUserKey; } CRMUser user = null; try { providerUserKey = this.organizationServiceCache.GetOrganizationService().Create(contact); ConditionalLog.Info(string.Format("CreateUser({0}, {1}, {2}). User has been created in CRM.", userName, email, providerUserKey), this, TimerAction.Tick, CreateUserKey); user = new CRMUser( userName, providerUserKey, email, null, string.Empty, true, false, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue); this.CacheService.UserCache.Add(user); } catch (Exception e) { ConditionalLog.Error(string.Format("Couldn't create user {0} in CRM.", userName), e, this); } ConditionalLog.Info(string.Format("CreateUser({0}, {1}, {2}). Finished.", userName, email, providerUserKey), this, TimerAction.Stop, CreateUserKey); return(user); }
/// <summary> /// Gets the contacs. /// </summary> /// <param name="pagingInfo">The paging info.</param> /// <param name="totalRecords">The total records.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="conditionOperator">Condition operator.</param> /// <param name="values">The values of the property.</param> /// <returns> /// The contacts. /// </returns> protected IEnumerable <Entity> GetContacts(PagingInfo pagingInfo, out int totalRecords, string propertyName, ConditionOperator conditionOperator, params object[] values) { totalRecords = 0; var propertyConditionExpression = new ConditionExpression { AttributeName = propertyName, Operator = conditionOperator }; propertyConditionExpression.Values.AddRange(values); var stateCodeConditionExpression = new ConditionExpression { AttributeName = "statecode", Operator = ConditionOperator.Equal }; stateCodeConditionExpression.Values.Add("Active"); var uniquePropertyNotNullConditionExpression = new ConditionExpression { AttributeName = Configuration.Settings.UniqueKeyProperty, Operator = ConditionOperator.NotNull }; var uniquePropertyNotEmptyConditionExpression = new ConditionExpression { AttributeName = Configuration.Settings.UniqueKeyProperty, Operator = ConditionOperator.NotEqual }; uniquePropertyNotEmptyConditionExpression.Values.Add(string.Empty); var filterExpression = new FilterExpression(); filterExpression.Conditions.AddRange( propertyConditionExpression, stateCodeConditionExpression, uniquePropertyNotNullConditionExpression, uniquePropertyNotEmptyConditionExpression); filterExpression.FilterOperator = LogicalOperator.And; var queryExpression = new QueryExpression { ColumnSet = new ColumnSet(this.Attributes), Criteria = filterExpression, EntityName = "contact", PageInfo = pagingInfo, NoLock = true }; var request = new RetrieveMultipleRequest { Query = queryExpression }; try { var service = this.organizationServiceCache.GetOrganizationService(); if (service == null) { ConditionalLog.Error("[CRM_GetContacts]Service is null", this); return(new Entity[0]); } var response = service.Execute(request) as RetrieveMultipleResponse; if ((response != null) && (response.EntityCollection != null)) { totalRecords = response.EntityCollection.TotalRecordCount; if (response.EntityCollection.TotalRecordCountLimitExceeded) { ConditionalLog.Error( string.Format( "The number of '{0}' entities is exceeding TotalRecordCountLimit. Only first {1} can be shown.", queryExpression.EntityName, totalRecords), this); } if (pagingInfo != null) { pagingInfo.PagingCookie = response.EntityCollection.PagingCookie; } return(response.EntityCollection.Entities); } } catch (Exception e) { ConditionalLog.Error("Couldn't get contact(s) from CRM.", e, this); } return(new Entity[0]); }
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 List <Property>(); var keyProperty = new KeyProperty(); keyProperty.Name = "contactid"; keyProperty.Value = new crm4.webservice.Key(); keyProperty.Value.Value = user.ID; propertiesToUpdate.Add(keyProperty); foreach (var property in properties) { this.AddPropertyToCollection(property.Key, property.Value, this.GetPropertyType(property.Key), propertiesToUpdate); } var update = new UpdateRequest { Target = new TargetUpdateDynamic { Entity = new DynamicEntity { Name = EntityName.contact.ToString(), Properties = propertiesToUpdate.ToArray() } } }; try { this.CrmService.Execute(update); ConditionalLog.Info(String.Format("UpdateUserProperties({0}). Updated in CRM.", userName), this, TimerAction.Tick, UpdateUserProrpertiesKey); var propertyToValueConverter = new PropertyToValueConverterV4(); foreach (var property in propertiesToUpdate) { user.SetPropertyValue(property.Name, propertyToValueConverter.Convert(property)); } 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 bool CreateContactAttribute(string attributeName, SupportedTypes attributeType, bool throwIfExists) { Assert.ArgumentNotNull(attributeName, "attributeName"); var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = EntityName.contact.ToString(), LogicalName = attributeName, RetrieveAsIfPublished = true }; try { var retrieveAttributeResponse = (RetrieveAttributeResponse)this.CrmMetadataService.Execute(retrieveAttributeRequest); if (retrieveAttributeResponse != null && retrieveAttributeResponse.AttributeMetadata != null) { if (throwIfExists) { throw new ProviderException("The attribute can't be created because it already exists."); } return(true); } } catch (Exception e) { if (!e.Message.Contains("Could not find an attribute with specified name:")) { ConditionalLog.Error("Couldn't get attribute metadata from CRM", e, this); return(false); } } var request = new RetrieveMultipleRequest() { Query = new QueryExpression() { ColumnSet = new ColumnSet() { Attributes = new[] { "languagecode" } }, EntityName = EntityName.organization.ToString() }, ReturnDynamicEntities = true, }; var languagecode = 0; try { var response = (RetrieveMultipleResponse)this.CrmService.Execute(request); if ((response != null) && (response.BusinessEntityCollection != null)) { var entity = response.BusinessEntityCollection.BusinessEntities.Cast <DynamicEntity>().First(); var property = (CrmNumberProperty)entity.Properties.ByName("languagecode"); languagecode = property.Value.Value; } } catch (Exception e) { ConditionalLog.Error("Couldn't get organization from CRM.", e, this); return(false); } var attributeRequest = new CreateAttributeRequest { EntityName = EntityName.contact.ToString() }; AttributeType crmAttributeType; switch (attributeType) { case SupportedTypes.CrmBoolean: crmAttributeType = AttributeType.Boolean; var booleanAttribute = new BooleanAttributeMetadata(); var falseLabel = new crm4.metadataservice.LocLabel { Label = "False", LanguageCode = new crm4.metadataservice.CrmNumber { Value = languagecode } }; var falseCrmLabel = new crm4.metadataservice.CrmLabel { LocLabels = new[] { falseLabel } }; booleanAttribute.FalseOption = new Option { Label = falseCrmLabel, Value = new crm4.metadataservice.CrmNumber { Value = 0 } }; var trueLabel = new crm4.metadataservice.LocLabel { Label = "True", LanguageCode = new crm4.metadataservice.CrmNumber { Value = languagecode } }; var trueCrmLabel = new crm4.metadataservice.CrmLabel { LocLabels = new[] { trueLabel } }; booleanAttribute.TrueOption = new Option { Label = trueCrmLabel, Value = new crm4.metadataservice.CrmNumber { Value = 1 } }; attributeRequest.Attribute = booleanAttribute; break; case SupportedTypes.CrmDateTime: crmAttributeType = AttributeType.DateTime; attributeRequest.Attribute = new DateTimeAttributeMetadata(); break; case SupportedTypes.CrmNumber: crmAttributeType = AttributeType.Integer; attributeRequest.Attribute = new IntegerAttributeMetadata(); break; case SupportedTypes.CrmFloat: crmAttributeType = AttributeType.Float; attributeRequest.Attribute = new FloatAttributeMetadata(); break; case SupportedTypes.CrmDecimal: crmAttributeType = AttributeType.Decimal; attributeRequest.Attribute = new DecimalAttributeMetadata(); break; case SupportedTypes.CrmMoney: crmAttributeType = AttributeType.Money; attributeRequest.Attribute = new MoneyAttributeMetadata(); break; case SupportedTypes.Picklist: crmAttributeType = AttributeType.Picklist; attributeRequest.Attribute = new PicklistAttributeMetadata { Options = new Option[] { } }; break; default: crmAttributeType = AttributeType.String; attributeRequest.Attribute = new StringAttributeMetadata { MaxLength = new crm4.metadataservice.CrmNumber { IsNull = false, IsNullSpecified = false, Value = 256 } }; break; } attributeRequest.Attribute.MetadataId = new crm4.metadataservice.Key { Value = Guid.NewGuid() }; attributeRequest.Attribute.AttributeType = new CrmAttributeType { IsNull = false, IsNullSpecified = false, Value = crmAttributeType }; attributeRequest.Attribute.SchemaName = attributeName; attributeRequest.Attribute.DisplayName = new crm4.metadataservice.CrmLabel { LocLabels = new[] { new crm4.metadataservice.LocLabel { Label = attributeName, LanguageCode = new crm4.metadataservice.CrmNumber { Value = languagecode } } } }; attributeRequest.Attribute.IsCustomField = new crm4.metadataservice.CrmBoolean { Value = true }; attributeRequest.Attribute.RequiredLevel = new CrmAttributeRequiredLevel { Value = AttributeRequiredLevel.None }; attributeRequest.Attribute.EntityLogicalName = EntityName.contact.ToString(); try { this.CrmMetadataService.Execute(attributeRequest); return(true); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't create attribute '{0}' of {1} type.", attributeName, crmAttributeType), e, this); return(false); } }
public override CRMUser CreateUser(string userName, string email, Guid providerUserKey) { Assert.ArgumentNotNullOrEmpty(userName, "userName"); Assert.ArgumentNotNullOrEmpty(email, "email"); const string CreateUserKey = "createUser"; ConditionalLog.Info(String.Format("CreateUser({0}, {1}, {2}). Started.", userName, email, providerUserKey), this, TimerAction.Start, CreateUserKey); var properties = new List <Property>(); if (Configuration.Settings.UniqueKeyProperty != "fullname") { properties.Add(new StringProperty { Name = Configuration.Settings.UniqueKeyProperty, Value = userName }); } else { var nameParts = new List <string>(userName.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); properties.Add(new StringProperty { Name = "firstname", Value = nameParts[0] }); if (nameParts.Count > 1) { properties.Add(new StringProperty { Name = "lastname", Value = String.Join(" ", nameParts.GetRange(1, nameParts.Count - 1).ToArray()) }); } } if ((email != null) && (Configuration.Settings.UniqueKeyProperty != "emailaddress1")) { properties.Add(new StringProperty { Name = "emailaddress1", Value = email }); } if (providerUserKey != Guid.Empty) { properties.Add(new KeyProperty { Name = "contactid", Value = new Key { Value = providerUserKey } }); } var contact = new DynamicEntity(); contact.Name = EntityName.contact.ToString(); contact.Properties = properties.ToArray(); CRMUser user = null; try { providerUserKey = this.CrmService.Create(contact); ConditionalLog.Info(String.Format("CreateUser({0}, {1}, {2}). User has been created in CRM.", userName, email, providerUserKey), this, TimerAction.Tick, CreateUserKey); user = new CRMUser( userName, providerUserKey, email, null, String.Empty, true, false, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue); this.CacheService.UserCache.Add(user); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't create user {0} in CRM.", userName), e, this); } ConditionalLog.Info(String.Format("CreateUser({0}, {1}, {2}). Finished.", userName, email, providerUserKey), this, TimerAction.Stop, CreateUserKey); return(user); }
/// <summary> /// Gets the contacs. /// </summary> /// <param name="pagingInfo">The paging info.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="conditionOperator">Condition operator.</param> /// <param name="values">The values of the property.</param> /// <returns>The contacts.</returns> protected IEnumerable <DynamicEntity> GetContacts(PagingInfo pagingInfo, string propertyName, ConditionOperator conditionOperator, params object[] values) { var propertyConditionExpression = new ConditionExpression(); propertyConditionExpression.AttributeName = propertyName; propertyConditionExpression.Operator = conditionOperator; propertyConditionExpression.Values = values; var stateCodeConditionExpression = new ConditionExpression(); stateCodeConditionExpression.AttributeName = "statecode"; stateCodeConditionExpression.Operator = ConditionOperator.Equal; stateCodeConditionExpression.Values = new object[] { "Active" }; var uniquePropertyNotNullConditionExpression = new ConditionExpression(); uniquePropertyNotNullConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty; uniquePropertyNotNullConditionExpression.Operator = ConditionOperator.NotNull; var uniquePropertyNotEmptyConditionExpression = new ConditionExpression(); uniquePropertyNotEmptyConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty; uniquePropertyNotEmptyConditionExpression.Operator = ConditionOperator.NotEqual; uniquePropertyNotEmptyConditionExpression.Values = new object[] { String.Empty }; var filterExpression = new FilterExpression(); filterExpression.Conditions = new ConditionExpression[] { propertyConditionExpression, stateCodeConditionExpression, uniquePropertyNotNullConditionExpression, uniquePropertyNotEmptyConditionExpression }; filterExpression.FilterOperator = LogicalOperator.And; var queryExpression = new QueryExpression(); queryExpression.ColumnSet = new ColumnSet() { Attributes = this.Attributes }; queryExpression.Criteria = filterExpression; queryExpression.EntityName = EntityName.contact.ToString(); queryExpression.PageInfo = pagingInfo; var request = new RetrieveMultipleRequest(); request.Query = queryExpression; request.ReturnDynamicEntities = true; try { var response = (RetrieveMultipleResponse)this.CrmService.Execute(request); if ((response != null) && (response.BusinessEntityCollection != null)) { return(response.BusinessEntityCollection.BusinessEntities.Cast <DynamicEntity>()); } } catch (Exception e) { ConditionalLog.Error("Couldn't get contact(s) from CRM.", e, this); } return(new DynamicEntity[0]); }
/// <summary> /// Method to get users in given Role. in CRM Marketing list. /// This method has been customized to support dynamic lists. /// </summary> /// <param name="roleName"></param> /// <returns></returns> public override string[] GetUsersInRole(string roleName) { //setting that disabled the dynamic list functionality. if (SitecoreUtility.GetSitecoreSetting <bool>("AlphaSolutions.ExtendedCRMProvider.Disable.DynamicLists", false)) { return(base.GetUsersInRole(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 Microsoft.Xrm.Sdk.Query.ColumnSet columnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "listname", "query", "type" }); Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression(); query.ColumnSet = columnSet; Microsoft.Xrm.Sdk.Query.ConditionExpression listnameCondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression(); listnameCondition.AttributeName = "listname"; listnameCondition.Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal; listnameCondition.Values.Add(roleName); Microsoft.Xrm.Sdk.Query.FilterExpression filterList = new Microsoft.Xrm.Sdk.Query.FilterExpression(); filterList.Conditions.Add(listnameCondition); filterList.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And; query.EntityName = "list"; query.Criteria = filterList; // Execute the query Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest req = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest(); req.Query = query; Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse res = (Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse) this.OrganizationService.Execute(req); if (res != null && res.EntityCollection != null && res.EntityCollection.Entities.Count > 0) { Entity myList = res.EntityCollection.Entities[0]; if (myList.Attributes.Keys.Contains("query")) { // Define the fetch attributes. // Set the number of records per page to retrieve. int fetchCount = Settings.FetchThrottlingPageSize; // Initialize the page number. int pageNumber = 1; // Initialize the number of records. int recordCount = 0; // Specify the current paging cookie. For retrieving the first page, // pagingCookie should be null. string pagingCookie = null; //Convert fetchXML to Query Expression var xml = myList["query"].ToString(); HashSet <string> hashSet = new HashSet <string>(); try { while (true) { string xmlpaging = CreateXml(xml, pagingCookie, pageNumber, fetchCount, Settings.UniqueKeyProperty); Microsoft.Xrm.Sdk.Query.FetchExpression f = new Microsoft.Xrm.Sdk.Query.FetchExpression(xmlpaging); RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest(); retrieveMultipleRequest.Query = f; RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)this.OrganizationService.Execute(retrieveMultipleRequest); if (retrieveMultipleResponse != null && retrieveMultipleResponse.EntityCollection != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, retrieveMultipleResponse.EntityCollection.Entities.Count), this, TimerAction.Tick, "getUsersInRole"); foreach (Entity current in retrieveMultipleResponse.EntityCollection.Entities) { try { base.CacheService.UserCache.Add(this.ContactToUserConverter.Convert(current)); hashSet.Add((string)current[Settings.UniqueKeyProperty]); } catch (Exception e) { ConditionalLog.Error(string.Format("GetUsersInRole({0}). Error in converting contact to user. Number of attributes gotten: {1}", current.LogicalName, current.Attributes.Count), e, this); } } // Check for morerecords, if it returns 1. if (retrieveMultipleResponse.EntityCollection.MoreRecords) { // Increment the page number to retrieve the next page. pageNumber++; } else { // If no more records in the result nodes, exit the loop. break; } pagingCookie = retrieveMultipleResponse.EntityCollection.PagingCookie; } } var ret = hashSet.ToArray <string>(); base.CacheService.MembersCache.Add(roleName, string.Join("|", ret)); return(ret); } catch (System.Exception sourceException) { ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), sourceException, this); } } else { return(base.GetUsersInRole(roleName)); } } return(new string[0]); }