/// <summary> /// Updates the QueryExpression's ColumnSet to include the specified attributes only. /// </summary> /// <param name="columnSet">The target CRM ColumnSet.</param> /// <param name="selectExpand">The OData select/expand options.</param> private void UpdateColumnSetFromSelectExpand(ColumnSet columnSet, SelectExpandQueryOption selectExpand) { if (selectExpand == null || selectExpand.SelectExpandClause == null || selectExpand.SelectExpandClause.AllSelected) { foreach (var attributeName in this.EntityMapper.GetAttributeNames()) { columnSet.AddColumn(attributeName); } } else { foreach (var item in selectExpand.SelectExpandClause.SelectedItems.OfType <PathSelectItem>()) { var pathItem = item.SelectedPath.OfType <PropertySegment>().Single(); if (pathItem.Property.Name != "Deleted") { var attributeName = EntityMapper.GetAttributeName(pathItem.Property.Name); columnSet.AddColumn(attributeName); } } } columnSet.Columns.Remove("id"); }
/// <summary> /// Set the additional columns. Associate & disassociate message will have related entities. The primary key attribute related to /// related entities also needs to be added into the columns set /// </summary> /// <param name="entityName">Primary Entity</param> /// <param name="columns">Column set</param> private void SetAdditionalColumns(string entityName, ColumnSet columns) { //check the type of message for the respective entityName var message = this.processingEntities[entityName] as AssociateDisassociateMessage; //if the message is of AssociateDisassociateMessage type add related entities key attributes also. if (message != null) { //add related entity 1 AddColumn(columns, message.RelatedEntity1Name); //add related entity 2 AddColumn(columns, message.RelatedEntity2Name); } //add primary name attribute string primaryNameAttribute = this.TryGetPrimaryNameAttribute(entityName); if (!string.IsNullOrEmpty(primaryNameAttribute)) { columns.AddColumn(primaryNameAttribute); } // add website lookup attribute EntityTrackingInfo info; if (entityInfoList.TryGetValue(entityName, out info) && info.WebsiteLookupAttribute != null) { columns.AddColumn(info.WebsiteLookupAttribute); } }
public Dictionary <string, Guid[]> BuildMassResolverIndex() { ColumnSet columnSet = new ColumnSet(); foreach (var primaryKey in primaryKeyAttributeMetadataDictionary) { columnSet.AddColumn(primaryKey.Key); } if (columnSet.Columns.Contains(entityMetadata.PrimaryIdAttribute) == false) { columnSet.AddColumn(entityMetadata.PrimaryIdAttribute); } List <ConditionExpression> conditions = new List <ConditionExpression>(); foreach (var primaryKey in primaryKeyAttributeMetadataDictionary) { conditions.Add(new ConditionExpression(primaryKey.Key, ConditionOperator.NotNull)); } DataCollection <Entity> existingEntities = Crm2013Wrapper.Crm2013Wrapper.RetrieveMultiple(service, entityMetadata.LogicalName, columnSet, conditions); Dictionary <string, Guid[]> keyDictionary = BuildExistingCheckDictionary(existingEntities, primaryKeyAttributeMetadataDictionary); return(keyDictionary); }
private static Entity GetEntity(IOrganizationService service, string logicalName, Guid id, string emailField) { ColumnSet columnSet = new ColumnSet(); columnSet.AddColumn(emailField); columnSet.AddColumn(logicalName == "systemuser" ? "isdisabled" : "statecode"); return(service.Retrieve(logicalName, id, columnSet)); }
private List <Entity> GetSatisSenetleri(Guid QuoteId) { ConditionExpression conditionExpression1 = new ConditionExpression(); conditionExpression1.AttributeName = "new_quoteid"; conditionExpression1.Operator = ConditionOperator.Equal; conditionExpression1.Values.Add((object)QuoteId); ConditionExpression conditionExpression2 = new ConditionExpression(); conditionExpression2.AttributeName = "statuscode"; conditionExpression2.Values.AddRange((object)2, (object)7); conditionExpression2.Operator = ConditionOperator.NotIn; ConditionExpression conditionExpression3 = new ConditionExpression(); conditionExpression3.AttributeName = "new_isvoucher"; conditionExpression3.Operator = ConditionOperator.Equal; conditionExpression3.Values.Add(true); FilterExpression filterExpression = new FilterExpression(); filterExpression.Conditions.Add(conditionExpression1); filterExpression.Conditions.Add(conditionExpression2); filterExpression.Conditions.Add(conditionExpression3); filterExpression.FilterOperator = LogicalOperator.And; ColumnSet columnSet = new ColumnSet(); columnSet.AddColumn("new_paymentid"); columnSet.AddColumn("new_date"); columnSet.AddColumn("new_paymentamount"); OrderExpression orderExpression = new OrderExpression(); orderExpression.AttributeName = "new_date"; orderExpression.OrderType = OrderType.Ascending; QueryExpression queryExpression = new QueryExpression(); queryExpression.ColumnSet = columnSet; queryExpression.Criteria = filterExpression; queryExpression.EntityName = "new_payment"; queryExpression.Orders.Add(orderExpression); RetrieveMultipleResponse multipleResponse = (RetrieveMultipleResponse)this.service.Execute((OrganizationRequest) new RetrieveMultipleRequest() { Query = (QueryBase)queryExpression }); if (multipleResponse.EntityCollection.Entities != null || multipleResponse.EntityCollection.Entities.Count > 0) { return(Enumerable.ToList <Entity>((IEnumerable <Entity>)multipleResponse.EntityCollection.Entities)); } else { return((List <Entity>)null); } }
/// <summary> /// on Pre Retrive /// </summary> /// <param name="context"></param> void AddSecureFieldIfNotExists(IPluginExecutionContext context, IOrganizationService service) { var primaryEntityName = context.PrimaryEntityName; if (!String.IsNullOrEmpty(primaryEntityName)) { TableRelationation tableRelation = TableRelationation.GetSinglton(); ConfigCaching configCaching = GetCacheConfig(service); // load userTeam if not loaded yet because is in grant user UsersTeam userteam = UsersTeam.GetSinglton(service, configCaching); if (tableRelation.Entities.Contains(primaryEntityName.ToLower())) { if (context.InputParameters.Contains("ColumnSet")) { ColumnSet columns = context.InputParameters["ColumnSet"] as ColumnSet; if (columns != null && !columns.AllColumns) { // Validate if exists if (!columns.Columns.Contains(General.SecureField)) { columns.AddColumn(General.SecureField); } } } } } }
protected override void ExecuteInternal(LocalWorkflowContext context) { var stageNameToSet = this.StageNameInArgument.Get(context.CodeActivityContext).ToUpper(); RetrieveProcessInstancesRequest retrieveProcessInstancesRequest = new RetrieveProcessInstancesRequest { EntityId = context.WorkflowContext.PrimaryEntityId, EntityLogicalName = context.WorkflowContext.PrimaryEntityName }; RetrieveProcessInstancesResponse retrievedProcessInstancesResponse = (RetrieveProcessInstancesResponse)context.OrganizationService.Execute(retrieveProcessInstancesRequest); var activeProcessInstance = retrievedProcessInstancesResponse.Processes.Entities[0]; // First record is the active process instance var workflowReference = (EntityReference)activeProcessInstance.Attributes["processid"]; Process workflow = context.OrganizationService.Retrieve(workflowReference.LogicalName, workflowReference.Id, new ColumnSet(true)).ToEntity <Process>(); RetrieveActivePathRequest pathRequest = new RetrieveActivePathRequest { ProcessInstanceId = activeProcessInstance.Id }; RetrieveActivePathResponse pathResponse = (RetrieveActivePathResponse)context.OrganizationService.Execute(pathRequest); var stageToSetId = (Guid)pathResponse.ProcessStages.Entities.Where(x => x.Attributes["stagename"].ToString().ToUpper() == stageNameToSet).First().Attributes["processstageid"]; ColumnSet columns = new ColumnSet(); columns.AddColumn("activestageid"); Entity retrievedProcessInstance = context.OrganizationService.Retrieve(workflow.UniqueName, activeProcessInstance.Id, columns); // Set the next stage as the active stage retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, stageToSetId); context.OrganizationService.Update(retrievedProcessInstance); }
private Entity RetrieveCustomFields(string pEntity, Dictionary <string, string> attributes, List <string> columns) { Entity retVal = null; try { var query = new QueryByAttribute(pEntity); foreach (var pair in attributes) { query.AddAttributeValue(pair.Key, pair.Value); } if (columns.Count > 0) { ColumnSet col = new ColumnSet(); foreach (var column in columns) { col.AddColumn(column); } query.ColumnSet = col; } var records = this.Manager.GetProxy().RetrieveMultiple(query); if (records.Entities != null && records.Entities.FirstOrDefault() != null) { retVal = records.Entities.FirstOrDefault(); } } catch (Exception ex) { throw new System.ArgumentException("Error on function RetrieveCustomFields. " + errorMaxLength(ex.Message)); } return(retVal); }
private EntityCollection RetrieveCustomFieldsList(string pEntity, Dictionary <string, string> attributes, IEnumerable <string> columns) { EntityCollection records = null; try { var query = new QueryByAttribute(pEntity); foreach (var pair in attributes) { query.AddAttributeValue(pair.Key, pair.Value); } if (columns.Count() > 0) { ColumnSet col = new ColumnSet(); foreach (var column in columns) { col.AddColumn(column); } query.ColumnSet = col; } records = this.Manager.GetProxy().RetrieveMultiple(query); } catch (Exception ex) { throw new System.ArgumentException("Error on function RetrieveCustomFieldsList: " + errorMaxLength(ex.Message)); } return(records); }
protected Guid GetBaseCurrencyId() { if (this.baseCurrencyKey == Guid.Empty) { ColumnSet cols = new ColumnSet(); cols.AddColumn("basecurrencyid"); QueryByAttribute queryAtrib = new QueryByAttribute("organization") { ColumnSet = cols }; try { EntityCollection organizations = this.OrganizationService.RetrieveMultiple(queryAtrib); Entity setupOrg = organizations.Entities.FirstOrDefault(); this.baseCurrencyKey = ((EntityReference)setupOrg["basecurrencyid"]).Id; } catch (Exception ex) { throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.CurrencyRetrievalExceptionMessage, this.OrganizationName), ex) { ExceptionId = ErrorCodes.CrmPlatformException }; } } return(this.baseCurrencyKey); }
public Entity RetrieveSND(Guid sndId, IOrganizationService service) { try { ColumnSet sndColumns = new ColumnSet(); sndColumns.AddColumn(Constant.SNDMethod.SalesMethod); sndColumns.AddColumn(Constant.SNDMethod.RouteNumber); Entity sndRecord = service.Retrieve(Constant.SNDMethod.EntityName, sndId, sndColumns); return(sndRecord); } catch (Exception ex) { throw ex; } }
public Entity RetrieveCustomerData(Guid accountId, IOrganizationService service) { try { ColumnSet accountColumns = new ColumnSet(); accountColumns.AddColumn(Constant.Customer.ProductCustomerFlag); accountColumns.AddColumn(Constant.Customer.Status); Entity accountRecord = service.Retrieve(Constant.Customer.EntityName, accountId, accountColumns); return(accountRecord); } catch (Exception ex) { throw ex; } }
/// <summary> /// Add primary key attribute to column set /// </summary> /// <param name="columns">column set</param> /// <param name="relatedEntityName">related Entity Name</param> private void AddColumn(ColumnSet columns, string relatedEntityName) { string primaryKeyAttribute = this.TryGetPrimaryKey(relatedEntityName); if (!string.IsNullOrEmpty(primaryKeyAttribute)) { columns.AddColumn(primaryKeyAttribute); } }
private ColumnSet GetColumnSet(string [] mappedAttributes) { var columnSet = new ColumnSet(mappedAttributes); if (!columnSet.Columns.Contains(entityMetadata.PrimaryIdAttribute)) { columnSet.AddColumn(entityMetadata.PrimaryIdAttribute); } return(columnSet); }
public void Can_add_single_attribute() { var strongTypeColumnSet = new ColumnSet <xts_entity>(); ColumnSet columnSet = strongTypeColumnSet; strongTypeColumnSet.AddColumn(x => x.AttributeWithCaseChar); Assert.Single(strongTypeColumnSet.Columns); Assert.Single(columnSet.Columns); Assert.Equal("attributewithcasechar", columnSet.Columns[0]); }
/// <summary> /// Creates a ColumnSet object based on the keys in the mapping dictionary /// </summary> /// <returns>A ColumnSet</returns> public static ColumnSet GetColumnsBasedOnMapping(Dictionary<PropertyInfo, string> mapping) { // Create the column set object that indicates the properties to be retrieved. ColumnSet cols = new ColumnSet(); foreach (string attribute in mapping.Values) { cols.AddColumn(attribute); } return cols; }
private ColumnSet createColumnSet(string[] columns) { var columnSet = new ColumnSet(); for (int i = 0; i < columns.Length; i++) { columnSet.AddColumn(columns[i]); } return(columnSet); }
/// <summary> /// Ensure that when we try to read encrypted columns we read both the clear text and ciphertext. /// (We need to add the ciphertext to the list of columns to retreive, so that when we try to decrypt it late rin the pipeline, it is available.)x /// </summary> /// <param name="target"></param> /// <param name="colSet"></param> /// <param name="trace"></param> public void AddAdditionalColumns(EntityReference target, ColumnSet colSet, Action <string> trace) { if (config.ContainsKey(target.LogicalName)) { config[target.LogicalName].ForEach((a, i) => { if (colSet.Columns.Contains(a.Key) && a.Key != a.Value) { colSet.AddColumn(a.Value); } }); } }
public void AddColumn_Test() { // Setup ColumnSet <TestEntity> columnSet = new ColumnSet <TestEntity>(); string expected = nameof(TestEntity.ReferenceTypeProperty).ToLower(); // Act columnSet.AddColumn(t => t.ReferenceTypeProperty); var actual = columnSet.Columns; // Assert Assert.AreEqual(1, actual.Count); Assert.AreEqual(expected, actual[0]); }
public void AddColumnTest() { // Setup string expectedColumn = nameof(TestEntity.ReferenceTypeProperty).ToLower(); // Act ColumnSet columnSet = new ColumnSet(); columnSet.AddColumn <TestEntity>(t => t.ReferenceTypeProperty); // Assert Assert.AreEqual(1, columnSet.Columns.Count); Assert.AreEqual(expectedColumn, columnSet.Columns[0]); }
public static ColumnSet MapColumnSet(MetadataHelper metadataHelper, ColumnSet columnSet) { ColumnSet externalColumnSet = new ColumnSet() { AllColumns = columnSet.AllColumns, }; foreach (var col in columnSet.Columns) { externalColumnSet.AddColumn(metadataHelper.GetExternalAttributeName(col)); } return(externalColumnSet); }
private static bool isDuplicate(string clientid, IOrganizationService orgservice) { //we search CRM to see if clientid is already in use and return true if it is and false otherwise var query = new QueryExpression("account"); var columns = new ColumnSet(); var filter = new FilterExpression(); columns.AddColumn("ergo_clientid"); filter.AddCondition("ergo_clientid", ConditionOperator.Equal, clientid); query.ColumnSet = columns; query.Criteria.AddFilter(filter); if(orgservice.RetrieveMultiple(query).Entities.Any()) return true; return false; }
/// <summary> /// Get Column Set /// </summary> /// <param name="entityName">entity Name</param> /// <returns>Return column set having only ID column or set it to pull all columns</returns> private ColumnSet GetColumnSet(string entityName) { string primaryKeyAttribute = this.TryGetPrimaryKey(entityName); ColumnSet columns = new ColumnSet(); if (string.IsNullOrEmpty(primaryKeyAttribute)) { columns.AllColumns = true; } else { columns.AddColumn(primaryKeyAttribute); SetAdditionalColumns(entityName, columns); } return(columns); }
public static ColumnSet GetColumnSet <T>() where T : CrmEntityBase, new() { var propHelpers = PropertyHelper.GetProperties(typeof(T)); var crmAttributes = propHelpers .Where(p => p.CRMFieldBaseAttribute != null) .Select(p => p.CRMFieldBaseAttribute.AttributeName) .Where(an => !an.Contains(".")) .Distinct(); var columnSet = new ColumnSet(crmAttributes.ToArray()); var logicalName = new T().LogicalName; columnSet.AddColumn($"{logicalName}id"); return(columnSet); }
public static ColumnSet GetColumnSetByFields(params Expression <Func <T, Object> >[] fields) { ColumnSet columns = new ColumnSet(); foreach (var obj in fields) { // TODO: magic? CRMAttribute attr = GetAttributeFromExpression(obj?.Body, typeof(CRMAttribute)) as CRMAttribute; if (attr != null) { columns.AddColumn(attr.FieldName); } } return(columns); }
/// <summary> /// Method to Get a Record and return /// it in the form of a Dynamic Entity Object /// to the calling function /// </summary> /// <param name="poGuid"></param> /// <param name="psEntityName"></param> /// <param name="psAttributeName"></param> /// <param name="poService"></param> /// <param name="paColumnSet"></param> /// <returns></returns> public static DynamicEntity GetDynamicEntityBasedOnGuid(Guid poGuid, string psEntityName, string psAttributeName, CrmService poService, ArrayList paColumnSet) { CrmService loService = poService; QueryExpression loQuery = new QueryExpression(); DynamicEntity loDynamicEntity = null; ColumnSet loColSet = new ColumnSet(); foreach (string lsColumnItem in paColumnSet) { loColSet.AddColumn(lsColumnItem); } try { ConditionExpression loCondition = new ConditionExpression(psAttributeName, ConditionOperator.Equal, poGuid); FilterExpression loFilter = new FilterExpression(); loQuery.EntityName = psEntityName; loQuery.ColumnSet = loColSet; loFilter.Conditions.Add(loCondition); loQuery.Criteria = loFilter; RetrieveMultipleRequest loRetrieve = new RetrieveMultipleRequest(); loRetrieve.Query = loQuery; loRetrieve.ReturnDynamicEntities = true; RetrieveMultipleResponse loResponse = (RetrieveMultipleResponse)loService.Execute(loRetrieve); if (loResponse.BusinessEntityCollection.BusinessEntities.Count > 0) { loDynamicEntity = (DynamicEntity)loResponse.BusinessEntityCollection.BusinessEntities[0]; } } catch (System.Web.Services.Protocols.SoapException ex) { MessageBox.Show("Error: " + ex.Detail.InnerXml.ToString()); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message.ToString()); } return(loDynamicEntity); }
private void LoadMissingAttributesForRecord(Entity record, string entity, IEnumerable <BulkActionItem> attributes) { var newcols = new ColumnSet(attributes.Select(a => a.Attribute.Metadata.LogicalName).ToArray()); if (newcols.Columns.Contains("statuscode")) { newcols.AddColumn("statecode"); } var newrecord = Service.Retrieve(entity, record.Id, newcols); foreach (var attribute in newrecord.Attributes.Keys) { if (newrecord.Contains(attribute) && !record.Contains(attribute)) { record.Attributes.Add(attribute, newrecord[attribute]); } } }
/// <summary> /// To get ISO2 Code of source market /// </summary> /// <param name="sourceMarketId"></param> /// <returns></returns> protected string GetSourceMarketISO2Code(Guid sourceMarketId) { trace.Trace("GetSourceMarketISO2Code - Start"); var sourceMarket = string.Empty; var columns = new ColumnSet(); columns.AddColumn(Attributes.Country.ISO2Code); var country = service.Retrieve(Entities.Country, sourceMarketId, columns); if (country != null && country.Attributes.Count > 0) { if (country.Attributes.Contains(Attributes.Country.ISO2Code) && country.Attributes[Attributes.Country.ISO2Code] != null) { sourceMarket = country.Attributes[Attributes.Country.ISO2Code].ToString(); } } trace.Trace("GetSourceMarketISO2Code - End"); return(sourceMarket); }
public static void ChangeStage(IOrganizationService service, Guid op) { // Get Process Instances RetrieveProcessInstancesRequest processInstanceRequest = new RetrieveProcessInstancesRequest { EntityId = op, EntityLogicalName = Opportunity.EntityLogicalName }; RetrieveProcessInstancesResponse processInstanceResponse = (RetrieveProcessInstancesResponse)service.Execute(processInstanceRequest); // Declare variables to store values returned in response int processCount = processInstanceResponse.Processes.Entities.Count; Entity activeProcessInstance = processInstanceResponse.Processes.Entities[0]; // First record is the active process instance Guid activeProcessInstanceID = activeProcessInstance.Id; // Id of the active process instance, which will be used later to retrieve the active path of the process instance // Retrieve the active stage ID of in the active process instance Guid activeStageID = new Guid(activeProcessInstance.Attributes["processstageid"].ToString()); // Retrieve the process stages in the active path of the current process instance RetrieveActivePathRequest pathReq = new RetrieveActivePathRequest { ProcessInstanceId = activeProcessInstanceID }; RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)service.Execute(pathReq); // Retrieve the stage ID of the next stage that you want to set as active activeStageID = (Guid)pathResp.ProcessStages.Entities[4].Attributes["processstageid"]; // Retrieve the process instance record to update its active stage ColumnSet cols1 = new ColumnSet(); cols1.AddColumn("activestageid"); Entity retrievedProcessInstance = service.Retrieve("opportunitysalesprocess", activeProcessInstanceID, cols1); // Set the next stage as the active stage retrievedProcessInstance["activestageid"] = new EntityReference(OpportunitySalesProcess.EntityLogicalName, activeStageID); service.Update(retrievedProcessInstance); }
private ColumnSet VisitColumnSet(ColumnSet columnSet, int?topCount) { var columns = "*"; if (columnSet != null && !columnSet.AllColumns && columnSet.Columns.Count > 0) { columnSet.AddColumn(_metadata.PrimaryIdAttribute); var columnNames = columnSet.Columns.Select(x => tableAlias + "." + _mapper.MapAttributeNameExternal(x)).Distinct(); columns = string.Join(", ", columnNames); } var top = string.Empty; if (topCount != null) { top = $"TOP {topCount}"; } Query += $"SELECT {top} {columns} FROM {_metadata.ExternalCollectionName} {tableAlias}"; return(columnSet); }
private Entity GetContactDetail(Guid id, string[] columns) { ConditionExpression conditionExpression = new ConditionExpression(); conditionExpression.AttributeName = "contactid"; conditionExpression.Operator = ConditionOperator.Equal; conditionExpression.Values.Add((object)id); FilterExpression filterExpression = new FilterExpression(); filterExpression.Conditions.Add(conditionExpression); filterExpression.FilterOperator = LogicalOperator.And; ColumnSet columnSet = new ColumnSet(); foreach (string column in columns) { columnSet.AddColumn(column); } RetrieveMultipleResponse multipleResponse = (RetrieveMultipleResponse)this.service.Execute((OrganizationRequest) new RetrieveMultipleRequest() { Query = (QueryBase) new QueryExpression() { ColumnSet = columnSet, Criteria = filterExpression, EntityName = "contact" } }); if (multipleResponse.EntityCollection.Entities != null && multipleResponse.EntityCollection.Entities.Count > 0) { return(Enumerable.First <Entity>((IEnumerable <Entity>)multipleResponse.EntityCollection.Entities)); } else { return((Entity)null); } }
/// <summary> /// This method is used to get attributes from a specified entity. It returns Dictionary containing all the required attributes values. /// </summary> /// <param name="entityGuid">GUID of the entity</param> /// <param name="entityName_">The entity name type (contact,lead,...)</param> ///<param name="entityAttributes">The ArrayList containing the attributes names types you want to retrieve (firstname,lastname,...)</param> public Dictionary<string, string> getEntity(Guid entityGuid, string entityName_, ArrayList entityAttributes) { Dictionary<string, string> arrayData = new Dictionary<string, string>(); try { isconnected(); ArrayList arrayResults = new ArrayList(); // Create the retrieve target. TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic(); // Set the properties of the target. targetRetrieve.EntityName = entityName_; targetRetrieve.EntityId = entityGuid; // Create the request object. RetrieveRequest retrieve = new RetrieveRequest(); ColumnSet col = new ColumnSet(); // Set the properties of the request object. retrieve.Target = targetRetrieve; for (int i = 0; i < entityAttributes.Count; i++) { col.AddColumn(entityAttributes[i].ToString()); } retrieve.ColumnSet = col; // Indicate that the BusinessEntity should be retrieved as a // DynamicEntity. retrieve.ReturnDynamicEntities = true; // Execute the request. RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve); // Extract the DynamicEntity from the request. DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity; Microsoft.Crm.Sdk.CrmDateTime crmDateTimeVar = new Microsoft.Crm.Sdk.CrmDateTime(); Microsoft.Crm.Sdk.CrmNumber crmNumberVar = new Microsoft.Crm.Sdk.CrmNumber(); Picklist crmPickList = new Picklist(); Guid crmGuid = new Guid(); Microsoft.Crm.Sdk.Key keyVar = new Microsoft.Crm.Sdk.Key(); Lookup lookupVar = new Lookup(); Microsoft.Crm.Sdk.CrmBoolean boolVar = new Microsoft.Crm.Sdk.CrmBoolean(); for (int i = 0; i < entityAttributes.Count; i++) { if (entity.Properties.Contains(entityAttributes[i].ToString())) { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmDateTimeVar.GetType())) { crmDateTimeVar = (Microsoft.Crm.Sdk.CrmDateTime)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(),crmDateTimeVar.date.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmNumberVar.GetType())) { crmNumberVar = (Microsoft.Crm.Sdk.CrmNumber)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmNumberVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(keyVar.GetType())) { keyVar = (Microsoft.Crm.Sdk.Key)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), keyVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(lookupVar.GetType())) { lookupVar = (Microsoft.Crm.Sdk.Lookup)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), lookupVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(boolVar.GetType())) { boolVar = (Microsoft.Crm.Sdk.CrmBoolean)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), boolVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmPickList.GetType())) { crmPickList = (Microsoft.Crm.Sdk.Picklist)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmPickList.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmGuid.GetType())) { crmGuid = (Guid)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmGuid.ToString()); } else { arrayData.Add(entityAttributes[i].ToString(), entity.Properties[entityAttributes[i].ToString()].ToString()); } } } } } } } } else { arrayData.Add(entityAttributes[i].ToString(), ""); } } return arrayData; } catch (SoapException ex) { throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText); } catch (Exception ex) { throw new ESC_CRM_EX.getEntityException(ex.Message, entityName_, entityGuid); } }
public bool campaignExists(string campaignID) { try { isconnected(); ArrayList arrayResults = new ArrayList(); // Create the retrieve target. TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic(); // Set the properties of the target. targetRetrieve.EntityName = "campaign"; targetRetrieve.EntityId = new Guid(campaignID); // Create the request object. RetrieveRequest retrieve = new RetrieveRequest(); ColumnSet col = new ColumnSet(); // Set the properties of the request object. retrieve.Target = targetRetrieve; col.AddColumn("name"); retrieve.ColumnSet = col; // Indicate that the BusinessEntity should be retrieved as a // DynamicEntity. retrieve.ReturnDynamicEntities = true; // Execute the request. RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve); // Extract the DynamicEntity from the request. DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity; if (entity.Properties["name"].Equals(null)) return false; return true; } catch (Exception) { return false; } }
public static ColumnSet GetXrmColumnSet(this Type type) { if (type.GetInterface(typeof(IXrmEntity).FullName) != null) { var properties = new List<PropertyInfo>(); foreach (var p in type.GetProperties()) { if (!p.HasXrmAttributeNameDeclared()) { properties.Add(p); } } if(properties.Count < 1) { throw new XrmAttributeMappingMissingException("No attributes have been mapped for the type '{0}'.", type.FullName); } var columnSet = new ColumnSet(); foreach (var property in properties) { columnSet.AddColumn(property.GetXrmAttributeName()); } return columnSet; } throw new ArgumentException(string.Format("Invalid type: Provided type '{0}' should implement {1}.", type.FullName, typeof(IXrmEntity).FullName)); }
public void Execute(IServiceProvider serviceProvider) { //Extract the tracing service for use in debugging sandboxed plug-ins. ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); // Obtain the organization service reference. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference) { EntityReference reference = (EntityReference)context.InputParameters["Target"]; Entity translateEntity = service.Retrieve(reference.LogicalName, reference.Id, new ColumnSet("isprimary", "isrootarticle", "title", "keywords", "description", "content", "languagelocaleid", "parentarticlecontentid")); TranslateApiSettings apiSettings = MicrosoftTranslateHelper.GetTranslatorAPISettings(service, tracingService); // Update the knowledge article entity record with the translated text only if it is only // translation (isprimary= false, isrootarticle=false) and if isautotranslationenabled is true if (((bool)translateEntity["isprimary"]) == false && ((bool)translateEntity["isrootarticle"]) == false) { ColumnSet columns = new ColumnSet(); columns.AddColumn("languagelocaleid"); // Get the primary entity to retrieve the source language code EntityReference parentArticleReference = (EntityReference)translateEntity["parentarticlecontentid"]; Entity primaryEntity = service.Retrieve("knowledgearticle", parentArticleReference.Id, columns); EntityReference languageLocaleReference = (EntityReference)primaryEntity["languagelocaleid"]; new ColumnSet(); columns.AddColumn("code"); Entity languageLocaleEntity = service.Retrieve("languagelocale", languageLocaleReference.Id, columns); string sourceLanguageCode = languageLocaleEntity["code"].ToString(); // Get the language code of the knowledge article being translated languageLocaleReference = (EntityReference)translateEntity["languagelocaleid"]; languageLocaleEntity = service.Retrieve("languagelocale", languageLocaleReference.Id, columns); string destinationLanguageCode = languageLocaleEntity["code"].ToString(); tracingService.Trace("knowledgeArticleId of the parent article: " + parentArticleReference.Id.ToString()); tracingService.Trace("Translating from <" + sourceLanguageCode + "> to <" + destinationLanguageCode + ">"); try { if (translateEntity.Attributes.ContainsKey("title")) { translateEntity["title"] = MicrosoftTranslateHelper.Translate(translateEntity["title"].ToString(), sourceLanguageCode, destinationLanguageCode, apiSettings.ClientSecret, apiSettings.ClientID); } tracingService.Trace("Translated <title>: {0}", translateEntity["title"].ToString()); if (translateEntity.Attributes.ContainsKey("keywords")) { translateEntity["keywords"] = MicrosoftTranslateHelper.Translate(translateEntity["keywords"].ToString(), sourceLanguageCode, destinationLanguageCode, apiSettings.ClientSecret, apiSettings.ClientID); } if (translateEntity.Attributes.ContainsKey("description")) { translateEntity["description"] = MicrosoftTranslateHelper.Translate(translateEntity["description"].ToString(), sourceLanguageCode, destinationLanguageCode, apiSettings.ClientSecret, apiSettings.ClientID); } if (translateEntity.Attributes.ContainsKey("content")) { translateEntity["content"] = MicrosoftTranslateHelper.Translate(translateEntity["content"].ToString(), sourceLanguageCode, destinationLanguageCode, apiSettings.ClientSecret, apiSettings.ClientID); } service.Update(translateEntity); } catch (FaultException <OrganizationServiceFault> ex) { tracingService.Trace("KnowledgeArticleTranslation: {0}", ex.ToString()); throw new Exception(ex.Message); } catch (Exception ex) { tracingService.Trace("KnowledgeArticleTranslationSolution: {0}", ex.ToString()); throw new Exception(ex.Message); } } } }
private void UpdateSettings() { if (string.IsNullOrWhiteSpace(this.OrganizationUrl) || !Uri.IsWellFormedUriString(this.OrganizationUrl, UriKind.Absolute)) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Organization Url is not valid. {0}", this.OrganizationUrl)); return; } if (this.Settings == null) { Log.LogError("Required parameter missing: Settings"); return; } Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to Organization {0}.", this.OrganizationUrl)); string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout); var connection = CrmConnection.Parse(connectionString); using (var serviceContext = new CrmOrganizationServiceContext(connection)) { try { var request = new RetrieveEntityRequest { EntityFilters = EntityFilters.Attributes, LogicalName = "organization" }; var response = serviceContext.Execute(request) as RetrieveEntityResponse; if (response == null) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "No response was received while retrieving settings for Organization with Url {0}", this.OrganizationUrl)); return; } var columnSet = new ColumnSet(); foreach (var settingItem in this.Settings) { string settingName = settingItem.ItemSpec; columnSet.AddColumn(settingName); var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName); if (setting == null || setting.AttributeType == null) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "No meta data for setting {0} was found.", settingName)); return; } } var entityCollection = serviceContext.RetrieveMultiple( new QueryExpression("organization") { ColumnSet = columnSet }); if (entityCollection == null || entityCollection.Entities.Count == 0) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "No setting was found for one of the settings")); return; } var entity = entityCollection.Entities.First(); foreach (var settingItem in this.Settings) { string settingName = settingItem.ItemSpec; string settingValue = settingItem.GetMetadata("value"); var setting = response.EntityMetadata.Attributes.First(e => e.LogicalName == settingName); if (setting == null || setting.AttributeType == null) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "No meta data was found for setting with Name {0} was found.", settingName)); return; } entity.Attributes[settingName] = ConvertCrmTypeToDotNetType(setting.AttributeType.Value, settingValue); } serviceContext.Update(entity); Log.LogMessage(MessageImportance.High, "The organization settings were updated successfully."); } catch (Exception exception) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred while update settings for Organization with Url {0}. [{1}]", this.OrganizationUrl, exception.Message)); } } }