public SynchronousWorkflow(Entity workflow) { this.workflow = workflow; initialRank = Rank; // Stage if (workflow.GetAttributeValue<bool>("triggeroncreate")) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("createstage"); Stage = stageCode != null ? stageCode.Value : 40; Message = "Create"; } else if (workflow.GetAttributeValue<bool>("triggeronupdate") || !string.IsNullOrEmpty(workflow.GetAttributeValue<string>("triggeronupdateattributelist"))) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("updatestage"); Stage = stageCode != null ? stageCode.Value : 40; Message = "Update"; } else if (workflow.GetAttributeValue<bool>("triggerondelete")) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("deletestage"); Stage = stageCode != null ? stageCode.Value : 20; Message = "Delete"; } }
public SynchronousWorkflow(Entity workflow) { this.workflow = workflow; initialRank = Rank; // Stage if (workflow.GetAttributeValue<bool>("triggeroncreate")) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("createstage"); Stage = stageCode != null ? stageCode.Value : 40; Message = "Create"; } else if (workflow.GetAttributeValue<bool>("triggeronupdate")) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("updatestage"); Stage = stageCode != null ? stageCode.Value : 40; Message = "Update"; } else if (workflow.GetAttributeValue<bool>("triggerondelete")) { var stageCode = workflow.GetAttributeValue<OptionSetValue>("deletestage"); Stage = stageCode != null ? stageCode.Value : 20; Message = "Delete"; } else { // throw new Exception("Unexpected stage data"); } }
private static string updateString(Entity preEntity, Entity postEntity) { string new_spdescription = ""; if (preEntity.Contains("name")) { if (preEntity?.GetAttributeValue <string>("name") != postEntity?.GetAttributeValue <string>("name")) { new_spdescription += (new_spdescription == "") ? "" : "\n"; new_spdescription += $"name from [{preEntity?.GetAttributeValue<string>("name")}] to [{postEntity?.GetAttributeValue<string>("name")}]"; } } if (preEntity.Contains("fullname")) { if (preEntity?.GetAttributeValue <string>("fullname") != postEntity?.GetAttributeValue <string>("fullname")) { new_spdescription += (new_spdescription == "") ? "" : "\n"; new_spdescription += $"fullname from [{preEntity?.GetAttributeValue<string>("fullname")}] to [{postEntity?.GetAttributeValue<string>("fullname")}]"; } } return(new_spdescription); }
public PluginStep(Entity pluginStep, IEnumerable<Entity> sdkMessageFilers, IEnumerable<Entity> sdkMessages) { this.pluginStep = pluginStep; initialRank = Rank; // EntityLogicalName var messageFilter = sdkMessageFilers.FirstOrDefault( s => pluginStep.GetAttributeValue<EntityReference>("sdkmessagefilterid") != null && s.Id == pluginStep.GetAttributeValue<EntityReference>("sdkmessagefilterid").Id); if (messageFilter != null) { EntityLogicalName = messageFilter.GetAttributeValue<string>("primaryobjecttypecode"); if (EntityLogicalName.Length == 0) { EntityLogicalName = "None"; } var message = sdkMessages.FirstOrDefault( m => m.Id == messageFilter.GetAttributeValue<EntityReference>("sdkmessageid").Id); if (message != null) { Message = message.GetAttributeValue<string>("name"); } } else { EntityLogicalName = "(none)"; var message = sdkMessages.FirstOrDefault( m => m.Id == pluginStep.GetAttributeValue<EntityReference>("sdkmessageid").Id); if (message != null) { Message = message.GetAttributeValue<string>("name"); } } }
public static Entity GetAccountAccessByContact(this OrganizationServiceContext context, Entity contact) { contact.AssertEntityName("contact"); if (contact == null) { return(null); } var parentCustomerAccount = contact.GetRelatedEntity(context, "contact_customer_accounts"); if (parentCustomerAccount == null) { return(null); } var findAccountAccess = from aa in context.CreateQuery("adx_accountaccess").ToList() let c = aa.GetRelatedEntity(context, "adx_contact_accountaccess") let a = aa.GetRelatedEntity(context, "adx_account_accountaccess") where c != null && c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid") && a != null && a.GetAttributeValue <Guid>("accountid") == parentCustomerAccount.GetAttributeValue <Guid>("accountid") select aa; return(findAccountAccess.FirstOrDefault()); }
public static Entity GetContactAccessByContact(this OrganizationServiceContext context, Entity contact) { contact.AssertEntityName("contact"); if (contact == null) { return(null); } var findContactAccess = from ca in context.CreateQuery("adx_contactaccess").ToList() let c = ca.GetRelatedEntity(context, "adx_contact_contactaccess") where c != null && c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid") select ca; return(findContactAccess.FirstOrDefault()); }
public static Guid GetEntityReferenceId(this Entity entity, string attributeName) { return(entity.GetAttributeValue <EntityReference>(attributeName) != null?entity.GetAttributeValue <EntityReference>(attributeName).Id : Guid.Empty); }
private Entity GetPrimaryContactAndSetCompanyName() { if (OpenOpportunity == null) { return(null); } Entity primaryContact = null; var customer = OpenOpportunity.GetAttributeValue <EntityReference>("customerid"); if (customer.LogicalName == "account") { var account = XrmContext.CreateQuery("account").First(a => a.GetAttributeValue <Guid>("accountid") == customer.Id); CompanyName.Text = account.GetAttributeValue <string>("name"); primaryContact = account.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact")); var channelPermission = XrmContext.GetChannelAccessByContact(Contact); var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue <bool?>("adx_write").GetValueOrDefault(false)); var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue <bool?>("adx_read").GetValueOrDefault(false)); var parentAccount = (account.GetAttributeValue <EntityReference>("msa_managingpartnerid") != null) ? XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue <Guid>("accountid") == account.GetAttributeValue <EntityReference>("msa_managingpartnerid").Id) : null; if (parentAccount != null && ((channelPermission != null && channelPermission.GetAttributeValue <EntityReference>("adx_accountid") != null) && channelPermission.GetAttributeValue <EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference())) && (parentAccount.GetAttributeValue <OptionSetValue>("accountclassificationcode") != null && parentAccount.GetAttributeValue <OptionSetValue>("accountclassificationcode").Value == 100000000)) { if (channelWriteAccess) { CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>", HttpUtility.HtmlEncode(EditAccountUrl(account.GetAttributeValue <Guid>("accountid"))), HttpUtility.HtmlEncode(CompanyName.Text)); } else if (channelReadAccess) { CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>", HttpUtility.HtmlEncode(ReadOnlyAccountUrl(account.GetAttributeValue <Guid>("accountid"))), HttpUtility.HtmlEncode(CompanyName.Text)); } } //CompanyName.Attributes.Add("style", "white-space: nowrap;"); } else if (customer.LogicalName == "contact") { primaryContact = XrmContext.CreateQuery("contact").First(c => c.GetAttributeValue <Guid>("contactid") == customer.Id); var account = primaryContact.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact")); CompanyName.Text = account != null?account.GetAttributeValue <string>("name") : primaryContact.GetAttributeValue <string>("adx_organizationname"); } return(primaryContact); }
protected void Page_Load(object sender, EventArgs e) { var reference = Entity.GetAttributeValue <EntityReference>("adx_entityform"); var entityFormRecord = XrmContext.CreateQuery("adx_entityform").FirstOrDefault(ef => ef.GetAttributeValue <Guid>("adx_entityformid") == reference.Id); if (entityFormRecord != null) { var recordEntityLogicalName = entityFormRecord.GetAttributeValue <string>("adx_entityname"); Guid recordId; if (Guid.TryParse(Request["id"], out recordId)) { var metadataRequest = new RetrieveEntityRequest { LogicalName = recordEntityLogicalName, EntityFilters = EntityFilters.Attributes }; var metadataResponse = (RetrieveEntityResponse)XrmContext.Execute(metadataRequest); var primaryFieldLogicalName = metadataResponse.EntityMetadata.PrimaryIdAttribute; var permitRecord = XrmContext.CreateQuery(recordEntityLogicalName).FirstOrDefault(r => r.GetAttributeValue <Guid>(primaryFieldLogicalName) == recordId); var permitTypeReference = permitRecord.GetAttributeValue <EntityReference>("adx_permittype"); var permitType = XrmContext.CreateQuery("adx_permittype").FirstOrDefault( srt => srt.GetAttributeValue <Guid>("adx_permittypeid") == permitTypeReference.Id); var entityName = permitType.GetAttributeValue <string>("adx_entityname"); RegardingContactFieldName = permitType.GetAttributeValue <string>("adx_regardingcontactfieldname"); var trueMetadataRequest = new RetrieveEntityRequest { LogicalName = entityName, EntityFilters = EntityFilters.Attributes }; var trueMetadataResponse = (RetrieveEntityResponse)XrmContext.Execute(trueMetadataRequest); var primaryFieldName = trueMetadataResponse.EntityMetadata.PrimaryIdAttribute; var entityId = permitRecord.GetAttributeValue <string>("adx_entityid"); var trueRecordId = Guid.Parse(entityId); var trueRecord = XrmContext.CreateQuery(entityName).FirstOrDefault(r => r.GetAttributeValue <Guid>(primaryFieldName) == trueRecordId); Permit = trueRecord; var permitDataSource = CreateDataSource("PermitDataSource", entityName, primaryFieldName, trueRecordId); var permitFormView = new CrmEntityFormView() { FormName = "Details Form", Mode = FormViewMode.Edit, EntityName = entityName, CssClass = "crmEntityFormView", AutoGenerateSteps = false }; var languageCodeSetting = OrganizationServiceContextExtensions.GetSiteSettingValueByName(ServiceContext, Portal.Website, "Language Code"); if (!string.IsNullOrWhiteSpace(languageCodeSetting)) { int languageCode; if (int.TryParse(languageCodeSetting, out languageCode)) { permitFormView.LanguageCode = languageCode; permitFormView.ContextName = languageCode.ToString(CultureInfo.InvariantCulture); permitDataSource.CrmDataContextName = languageCode.ToString(CultureInfo.InvariantCulture); } } CrmEntityFormViewPanel.Controls.Add(permitFormView); permitFormView.DataSourceID = permitDataSource.ID; var regardingContact = Permit.GetAttributeValue <EntityReference>(RegardingContactFieldName); if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id) { PermitControls.Enabled = false; PermitControls.Visible = false; AddNoteInline.Visible = false; AddNoteInline.Enabled = false; } else { var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName); var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var annotations = dataAdapter.GetAnnotations(Permit.ToEntityReference(), new List <Order> { new Order("createdon") }); NotesList.DataSource = annotations; NotesList.DataBind(); } } } }
//Create By: Jessica Casupanan, Created On: 12/06/2016 /* /* Purpose: Check if the customer information has an existing record that is fraudulent. * Registration Details: * Event/Message: * Post/Update: * Primary Entity: Prospect Inquiry */ public bool CheckForExistingRecords(Entity ProspectInquiryEntity) { _tracingService.Trace("Checking for existing records.."); String firstName = ProspectInquiryEntity.Contains("firstname") ? ProspectInquiryEntity.GetAttributeValue <string>("firstname") : String.Empty; String lastName = ProspectInquiryEntity.Contains("lastname") ? ProspectInquiryEntity.GetAttributeValue <string>("lastname") : String.Empty; String birthDate = ProspectInquiryEntity.Contains("gsc_birthday") ? ProspectInquiryEntity.GetAttributeValue <DateTime>("gsc_birthday").AddHours(8).ToShortDateString() : String.Empty; String mobileNo = ProspectInquiryEntity.Contains("mobilephone") ? ProspectInquiryEntity.GetAttributeValue <string>("mobilephone") : String.Empty; String companyName = ProspectInquiryEntity.Contains("companyname") ? ProspectInquiryEntity.GetAttributeValue <string>("companyname") : String.Empty; if (ProspectInquiryEntity.FormattedValues["gsc_prospecttype"].Equals("Individual")) { _tracingService.Trace("Individual"); //check for contact with similar record as prospect inquiry var contactConditionList = new List <ConditionExpression> { new ConditionExpression("firstname", ConditionOperator.Equal, firstName), new ConditionExpression("lastname", ConditionOperator.Equal, lastName), new ConditionExpression("birthdate", ConditionOperator.Equal, birthDate), new ConditionExpression("mobilephone", ConditionOperator.Equal, mobileNo), new ConditionExpression("gsc_recordtype", ConditionOperator.Equal, 100000001) }; EntityCollection contactEC = CommonHandler.RetrieveRecordsByConditions("contact", contactConditionList, _organizationService, null, OrderType.Ascending, new[] { "contactid", "firstname", "lastname", "birthdate", "mobilephone", "gsc_fraud", "gsc_ispotential" }); _tracingService.Trace(String.Concat(contactEC.Entities.Count)); if (contactEC.Entities.Count > 0) { _tracingService.Trace("Existing record found..." + contactEC.Entities.Count.ToString() + "records. Lastname: " + contactEC.Entities[0].GetAttributeValue <string>("lastname").ToString() + contactEC.Entities[0].GetAttributeValue <DateTime>("birthdate").ToString() + contactEC.Entities[0].GetAttributeValue <bool>("gsc_fraud").ToString()); //check if record is fraudulent if (contactEC.Entities[0].GetAttributeValue <bool>("gsc_fraud").Equals(true)) { _tracingService.Trace("Existing record fraudulent..."); return(true); } else { if (contactEC.Entities[0].GetAttributeValue <bool>("gsc_ispotential").Equals(true)) { throw new InvalidPluginExecutionException("A duplicate error was found. There is an already existing prospect record with the same information."); } else { throw new InvalidPluginExecutionException("A duplicate error was found. There is an already existing customer record with the same information."); } } } } else { _tracingService.Trace("Account"); EntityCollection accountCollection = CommonHandler.RetrieveRecordsByOneValue("account", "name", companyName, _organizationService, null, OrderType.Ascending, new[] { "gsc_ispotential", "gsc_fraud" }); if (accountCollection != null && accountCollection.Entities.Count > 0) { if (accountCollection.Entities[0].GetAttributeValue <bool>("gsc_fraud").Equals(true)) { _tracingService.Trace("Existing record fraudulent..."); return(true); } else { if (accountCollection.Entities[0].GetAttributeValue <bool>("gsc_ispotential").Equals(true)) { throw new InvalidPluginExecutionException("A duplicate error was found. There is an already existing prospect account with the same company name."); } else { throw new InvalidPluginExecutionException("A duplicate error was found. There is an already existing corporate account with the same company name."); } } } } _tracingService.Trace("Ending CheckForExistingRecords method..."); // throw new InvalidPluginExecutionException("test"); return(false); }
private List <Entity> RetrieveLatestPriceList(Entity entity, Int32 transactionType, List <Entity> effectivePriceList, Int32 priceListType) { var dateToday = DateTime.Now.ToShortDateString(); var branchId = entity.GetAttributeValue <EntityReference>("gsc_branchid") != null ? entity.GetAttributeValue <EntityReference>("gsc_branchid").Id : Guid.Empty; QueryExpression retrievePriceList = new QueryExpression("pricelevel"); retrievePriceList.ColumnSet.AddColumns("name", "gsc_transactiontype", "begindate", "enddate", "gsc_taxstatus"); retrievePriceList.AddOrder("createdon", OrderType.Descending); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("gsc_promo", ConditionOperator.Equal, false)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("gsc_transactiontype", ConditionOperator.Equal, transactionType)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.Equal, 0)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("gsc_branchid", ConditionOperator.Equal, branchId)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("begindate", ConditionOperator.LessEqual, dateToday)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("enddate", ConditionOperator.GreaterEqual, dateToday)); retrievePriceList.Criteria.Conditions.Add(new ConditionExpression("gsc_default", ConditionOperator.LessEqual, false)); if (transactionType == 100000000) { retrievePriceList.LinkEntities.Add(new LinkEntity("pricelevel", "gsc_cmn_classmaintenance", "gsc_pricelisttype", "gsc_cmn_classmaintenanceid", JoinOperator.Inner)); retrievePriceList.LinkEntities[0].LinkCriteria.AddCondition(new ConditionExpression("gsc_type", ConditionOperator.Equal, priceListType)); if (itemType == 1) { retrievePriceList.LinkEntities[0].LinkCriteria.AddCondition(new ConditionExpression("gsc_classmaintenancepn", ConditionOperator.Like, "%Accessory")); } else if (itemType == 2) { retrievePriceList.LinkEntities[0].LinkCriteria.AddCondition(new ConditionExpression("gsc_classmaintenancepn", ConditionOperator.Like, "%Chassis")); } } EntityCollection priceListCollection = _organizationService.RetrieveMultiple(retrievePriceList); if (priceListCollection != null && priceListCollection.Entities.Count > 0) { Entity priceList = priceListCollection.Entities[0]; effectivePriceList = GetPriceListitem(entity, priceList, effectivePriceList); if (effectivePriceList.Count != 0) { effectivePriceList.Add(priceList); } } else { throw new InvalidPluginExecutionException("There is no effecive Price List for the selected Vehicle."); } return(effectivePriceList); }
private Guid CreateCustomerIndividual(Entity prospectInquiryEntity) { _tracingService.Trace("Started CreateCustomerIndividual method..."); Entity contact = new Entity("contact"); contact["firstname"] = prospectInquiryEntity.Contains("firstname") ? prospectInquiryEntity.GetAttributeValue <String>("firstname") : null; contact["middlename"] = prospectInquiryEntity.Contains("middlename") ? prospectInquiryEntity.GetAttributeValue <String>("middlename") : null; contact["lastname"] = prospectInquiryEntity.Contains("lastname") ? prospectInquiryEntity.GetAttributeValue <String>("lastname") : null; contact["mobilephone"] = prospectInquiryEntity.Contains("mobilephone") ? prospectInquiryEntity.GetAttributeValue <String>("mobilephone") : null; contact["telephone1"] = prospectInquiryEntity.Contains("gsc_alternatecontactno") ? prospectInquiryEntity.GetAttributeValue <String>("gsc_alternatecontactno") : null; contact["fax"] = prospectInquiryEntity.Contains("fax") ? prospectInquiryEntity.GetAttributeValue <String>("fax") : null; contact["emailaddress1"] = prospectInquiryEntity.Contains("emailaddress1") ? prospectInquiryEntity.GetAttributeValue <String>("emailaddress1") : null; contact["gendercode"] = prospectInquiryEntity.Contains("gsc_gender") ? prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_gender") : null; contact["familystatuscode"] = prospectInquiryEntity.Contains("gsc_maritalstatus") ? prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_maritalstatus") : null; contact["birthdate"] = prospectInquiryEntity.Contains("gsc_birthday") ? prospectInquiryEntity.GetAttributeValue <DateTime>("gsc_birthday") : (DateTime?)null; contact["gsc_age"] = prospectInquiryEntity.Contains("gsc_age") ? Convert.ToInt32(prospectInquiryEntity.GetAttributeValue <String>("gsc_age")) : 0; contact["gsc_countryid"] = prospectInquiryEntity.Contains("gsc_countryid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_countryid") : null; contact["gsc_regionid"] = prospectInquiryEntity.Contains("gsc_regionid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_regionid") : null; contact["gsc_provinceid"] = prospectInquiryEntity.Contains("gsc_provinceid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_provinceid") : null; contact["gsc_cityid"] = prospectInquiryEntity.Contains("gsc_cityid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_cityid") : null; contact["address1_line1"] = prospectInquiryEntity.Contains("address1_line1") ? prospectInquiryEntity.GetAttributeValue <String>("address1_line1") : null; contact["address1_postalcode"] = prospectInquiryEntity.Contains("address1_postalcode") ? prospectInquiryEntity.GetAttributeValue <String>("address1_postalcode") : null; contact["gsc_salesexecutiveid"] = prospectInquiryEntity.Contains("gsc_salesexecutiveid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_salesexecutiveid") : null; contact["gsc_dealerid"] = prospectInquiryEntity.Contains("gsc_dealerid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_dealerid") : null; contact["gsc_branchid"] = prospectInquiryEntity.Contains("gsc_branchid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_branchid") : null; contact["gsc_recordownerid"] = prospectInquiryEntity.Contains("gsc_recordownerid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid") : null; contact["gsc_recordtype"] = new OptionSetValue(100000001); contact["gsc_ispotential"] = true; contact["gsc_prospect"] = true; Entity DefaultCustomerTax = GetDefaultTax(); contact["gsc_taxid"] = new EntityReference(DefaultCustomerTax.LogicalName, DefaultCustomerTax.Id); contact["gsc_tin"] = prospectInquiryEntity.Contains("gsc_tin") ? prospectInquiryEntity.GetAttributeValue <String>("gsc_tin") : String.Empty; _tracingService.Trace("Customer Record Created..."); _tracingService.Trace("Ended CreateCustomerIndividual method..."); var contactid = _organizationService.Create(contact); return(contactid); }
private Guid CreateCorporateCustomer(Entity prospectInquiryEntity) { _tracingService.Trace("Started CreateCorporateCustomer method..."); _tracingService.Trace("Creating Corporate Customer ..."); Entity account = new Entity("account"); account["gsc_customertype"] = prospectInquiryEntity.Contains("gsc_prospecttype") ? new OptionSetValue(prospectInquiryEntity.GetAttributeValue <OptionSetValue>("gsc_prospecttype").Value - 1) : null; account["gsc_firstname"] = prospectInquiryEntity.Contains("firstname") ? prospectInquiryEntity.GetAttributeValue <String>("firstname") : null; account["gsc_middlename"] = prospectInquiryEntity.Contains("middlename") ? prospectInquiryEntity.GetAttributeValue <String>("middlename") : null; account["gsc_lastname"] = prospectInquiryEntity.Contains("lastname") ? prospectInquiryEntity.GetAttributeValue <String>("lastname") : null; account["telephone2"] = prospectInquiryEntity.Contains("mobilephone") ? prospectInquiryEntity.GetAttributeValue <String>("mobilephone") : null; account["telephone3"] = prospectInquiryEntity.Contains("gsc_alternatecontactno") ? prospectInquiryEntity.GetAttributeValue <String>("gsc_alternatecontactno") : null; account["fax"] = prospectInquiryEntity.Contains("fax") ? prospectInquiryEntity.GetAttributeValue <String>("fax") : null; account["emailaddress1"] = prospectInquiryEntity.Contains("emailaddress1") ? prospectInquiryEntity.GetAttributeValue <String>("emailaddress1") : null; account["name"] = prospectInquiryEntity.Contains("companyname") ? prospectInquiryEntity.GetAttributeValue <String>("companyname") : null; account["telephone1"] = prospectInquiryEntity.Contains("telephone1") ? prospectInquiryEntity.GetAttributeValue <String>("telephone1") : null; account["fax"] = prospectInquiryEntity.Contains("fax") ? prospectInquiryEntity.GetAttributeValue <String>("fax") : null; account["websiteurl"] = prospectInquiryEntity.Contains("websiteurl") ? prospectInquiryEntity.GetAttributeValue <String>("websiteurl") : null; account["gsc_countryid"] = prospectInquiryEntity.Contains("gsc_countryid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_countryid") : null; account["gsc_regionid"] = prospectInquiryEntity.Contains("gsc_regionid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_regionid") : null; account["gsc_provinceid"] = prospectInquiryEntity.Contains("gsc_provinceid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_provinceid") : null; account["gsc_cityid"] = prospectInquiryEntity.Contains("gsc_cityid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_cityid") : null; account["address1_line1"] = prospectInquiryEntity.Contains("address1_line1") ? prospectInquiryEntity.GetAttributeValue <String>("address1_line1") : null; account["address1_postalcode"] = prospectInquiryEntity.Contains("address1_postalcode") ? prospectInquiryEntity.GetAttributeValue <String>("address1_postalcode") : null; account["gsc_salesexecutiveid"] = prospectInquiryEntity.Contains("gsc_salesexecutiveid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_salesexecutiveid") : null; account["gsc_dealerid"] = prospectInquiryEntity.Contains("gsc_dealerid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_dealerid") : null; account["gsc_branchid"] = prospectInquiryEntity.Contains("gsc_branchid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_branchid") : null; account["gsc_recordownerid"] = prospectInquiryEntity.Contains("gsc_recordownerid") ? prospectInquiryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid") : null; account["gsc_recordtype"] = new OptionSetValue(100000003); account["gsc_ispotential"] = true; account["gsc_prospect"] = true; account["gsc_tin"] = prospectInquiryEntity.Contains("gsc_tin") ? prospectInquiryEntity.GetAttributeValue <String>("gsc_tin") : String.Empty; Entity DefaultCustomerTax = GetDefaultTax(); account["gsc_taxid"] = new EntityReference(DefaultCustomerTax.LogicalName, DefaultCustomerTax.Id); var accountid = _organizationService.Create(account); _tracingService.Trace("Corporate Customer Created ..."); _tracingService.Trace("Ended CreateCorporateCustomer method..."); return(accountid); }
protected override void ProcessRequest(HttpContext context, ICmsEntityServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Entity entity, CmsEntityMetadata entityMetadata, ICrmEntitySecurityProvider security) { var relationshipSchemaName = string.IsNullOrWhiteSpace(RelationshipSchemaName) ? context.Request.Params["relationshipSchemaName"] : RelationshipSchemaName; if (string.IsNullOrWhiteSpace(relationshipSchemaName)) { throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request."); } var match = _relationshipSchemaNameRegex.Match(relationshipSchemaName); if (!match.Success) { throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request."); } var schemaName = match.Groups["schemaName"].Value; if (string.IsNullOrWhiteSpace(schemaName)) { throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to determine entity relationship schema name from request."); } var entityRole = match.Groups["entityRole"].Value; EntityRole parsedRole; var relationship = new Relationship(schemaName) { PrimaryEntityRole = Enum.TryParse(entityRole, true, out parsedRole) ? new EntityRole?(parsedRole) : null }; CmsEntityRelationshipInfo relationshipInfo; if (!entityMetadata.TryGetRelationshipInfo(relationship, out relationshipInfo)) { throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Entity relationship not found."); } // If the current request entity is the current website, do security handling here, since we skipped it earlier. if (entity.ToEntityReference().Equals(portal.Website.ToEntityReference())) { AssertRequestEntitySecurity(portal, serviceContext, entity, security, CreateWebsiteAccessPermissionProvider(portal), relationshipInfo); } if (IsRequestMethod(context.Request, "GET")) { if (relationshipInfo.IsCollection) { var readableRelatedEntities = entity.GetRelatedEntities(serviceContext, relationship) .Where(e => security.TryAssert(serviceContext, e, CrmEntityRight.Read)); var entityMetadataLookup = new Dictionary <string, CmsEntityMetadata>(); var entityJsonObjects = readableRelatedEntities.Select(e => { CmsEntityMetadata relatedEntityMetadata; if (!entityMetadataLookup.TryGetValue(e.LogicalName, out relatedEntityMetadata)) { relatedEntityMetadata = new CmsEntityMetadata(serviceContext, e.LogicalName); entityMetadataLookup[e.LogicalName] = relatedEntityMetadata; } return(GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, e, relatedEntityMetadata)); }); WriteResponse(context.Response, new JObject { { "d", new JArray(entityJsonObjects) } }); } else { var relatedEntity = entity.GetRelatedEntity(serviceContext, relationship); if (relatedEntity == null) { throw new CmsEntityServiceException(HttpStatusCode.NotFound, "Related entity not found."); } if (!security.TryAssert(serviceContext, relatedEntity, CrmEntityRight.Read)) { throw new CmsEntityServiceException(HttpStatusCode.Forbidden, "Related entity access denied."); } WriteResponse(context.Response, new JObject { { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, relatedEntity, new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName)) } }); } return; } if (IsRequestMethod(context.Request, "POST")) { if (relationshipInfo.IsCollection) { OneToManyRelationshipMetadata relationshipMetadata; if (!entityMetadata.TryGetOneToManyRelationshipMetadata(relationship, out relationshipMetadata)) { throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the one-to-many relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName)); } var relatedEntity = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencingEntity); var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName); var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata); var preImage = relatedEntity.Clone(false); // Ensure the reference to the target entity is set. relatedEntity.SetAttributeValue(relationshipMetadata.ReferencingAttribute, new EntityReference(entity.LogicalName, entity.GetAttributeValue <Guid>(relationshipMetadata.ReferencedAttribute))); serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create, preImage); serviceContext.AddObject(relatedEntity); serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create); serviceContext.SaveChanges(); var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName) .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id); if (refetchedEntity == null) { throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity."); } WriteResponse(context.Response, new JObject { { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) } }, HttpStatusCode.Created); } else { OneToManyRelationshipMetadata relationshipMetadata; if (!entityMetadata.TryGetManyToOneRelationshipMetadata(relationship, out relationshipMetadata)) { throw new CmsEntityServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the many-to-one relationship metadata for relationship {0} on entity type".FormatWith(relationship.ToSchemaName("."), entity.LogicalName)); } var relatedEntity = CreateEntityOfType(serviceContext, relationshipMetadata.ReferencedEntity); var relatedEntityMetadata = new CmsEntityMetadata(serviceContext, relatedEntity.LogicalName); var extensions = UpdateEntityFromJsonRequestBody(context.Request, serviceContext, relatedEntity, relatedEntityMetadata); serviceProvider.InterceptChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, CmsEntityOperation.Create); serviceContext.AddObject(relatedEntity); serviceContext.AddLink(relatedEntity, relationship, entity); serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEntity, relatedEntityMetadata, extensions, CmsEntityOperation.Create); serviceContext.SaveChanges(); var refetchedEntity = serviceContext.CreateQuery(relatedEntity.LogicalName) .FirstOrDefault(e => e.GetAttributeValue <Guid>(relatedEntityMetadata.PrimaryIdAttribute) == relatedEntity.Id); if (refetchedEntity == null) { throw new CmsEntityServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created entity."); } WriteResponse(context.Response, new JObject { { "d", GetEntityJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEntity, relatedEntityMetadata) } }, HttpStatusCode.Created); } return; } throw new CmsEntityServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod)); }
private void CheckForDuplicateStandardRules(Entity targetAppLine) { EntityCollection appLines = GetApplicationLines(this.ApplicationEntity.Id); // Check for duplicate Standard rules for this Application if (targetAppLine != null && targetAppLine.Attributes.Contains(ApplicationLine.StandardRule)) { foreach (Entity appLineRetrieved in appLines.Entities) { if (appLineRetrieved.Contains(ApplicationLine.StandardRule)) { if (appLineRetrieved.GetAttributeValue <EntityReference>(ApplicationLine.StandardRule).Id == targetAppLine.GetAttributeValue <EntityReference>(ApplicationLine.StandardRule).Id) { // Can't have the same Standard Rule more than once on an application throw new InvalidPluginExecutionException(string.Format("An Application Line with Standard Rule {0} already exists on this Application", appLineRetrieved.GetAttributeValue <EntityReference>(ApplicationLine.StandardRule).Id.ToString())); } } } } }
/// <summary> /// Updates the Application entity /// </summary> private void UpdateApplication(Entity targetAppLine, ApplicationLineStates?newApplicationLineState) { _TracingService.Trace("UpdateApplication() newApplicationLineState {0}", newApplicationLineState); if (this.UpdatedApplicationEntity == null || this.UpdatedApplicationEntity.Id == Guid.Empty) { return; } // If application line type is not regulated facility then don't want to update the application if (targetAppLine.Attributes.Contains("defra_linetype") && targetAppLine.GetAttributeValue <OptionSetValue>("defra_linetype").Value != (int)ApplicationLineTypeValues.RegulatedFacility) { return; } EntityCollection appLines = GetApplicationLines(this.ApplicationEntity.Id); // Update the NPS Determination required flag to No only if no line is determined by NPS (all lines NPS determination is No) Note! Default value is Yes // And update the Location Screening required flag to No only if no line has Location Screening required Note! Default value is Yes if (targetAppLine != null && targetAppLine.Attributes.Contains("defra_npsdetermination")) { //Update the Application NPS Determination to No if all lines NPS Determination are No bool allLinesNPSDetAreNo = (bool)targetAppLine["defra_npsdetermination"] == true ? false : true; _TracingService.Trace("Retrieve the NPS determination flag for all Standard rules lines"); foreach (Entity appLineRetrieved in appLines.Entities) { if (appLineRetrieved.Id == targetAppLine.Id) { // Only handle the current app line under certain conditions if (_Context.MessageName == PluginMessages.Update || _Context.MessageName == PluginMessages.Delete) { // We are not using the retrieved record from DB on Update or Delete _TracingService.Trace("UpdateApplication() We are not using the retrieved record from DB on Update or Delete"); continue; } if ((_Context.MessageName == PluginMessages.SetState || _Context.MessageName == PluginMessages.SetStateDynamicEntity) && newApplicationLineState.HasValue && newApplicationLineState == ApplicationLineStates.Inactive) { // Target App line has been deactivated, ignore it. _TracingService.Trace("UpdateApplication() Target App line has been deactivated, ignore it."); continue; } } if (appLineRetrieved.Attributes.Contains("defra_npsdetermination") && (bool)appLineRetrieved["defra_npsdetermination"]) { allLinesNPSDetAreNo = false; } } _TracingService.Trace("UpdateApplication() ApplicationEntity.Contains([defra_npsdetermination)={0}", ApplicationEntity.Contains("defra_npsdetermination")); if (!allLinesNPSDetAreNo != (bool)ApplicationEntity["defra_npsdetermination"]) { _TracingService.Trace("Add to the Application upated entity the NPS Determination flag set to {0}", !allLinesNPSDetAreNo); this.UpdatedApplicationEntity.Attributes.Add("defra_npsdetermination", !allLinesNPSDetAreNo); } } if (targetAppLine != null && targetAppLine.Attributes.Contains("defra_locationscreeningrequired")) { //Update the Application Location Screening Required to No if all lines Location Screening Required are No bool allLinesLocationScreeningNo = (bool)targetAppLine["defra_locationscreeningrequired"] == true ? false : true; _TracingService.Trace("Retrieve the Location Screening Required for all Standard rules lines"); foreach (Entity appLineRetrieved in appLines.Entities) { if (appLineRetrieved.Id == targetAppLine.Id) { // Only handle the current app line under certain conditions if (_Context.MessageName == PluginMessages.Update || _Context.MessageName == PluginMessages.Delete) { // We are not using the retrieved record from DB on Update or Delete _TracingService.Trace("UpdateApplication() We are not using the retrieved record from DB on Update or Delete"); continue; } if ((_Context.MessageName == PluginMessages.SetState || _Context.MessageName == PluginMessages.SetStateDynamicEntity) && newApplicationLineState.HasValue && newApplicationLineState == ApplicationLineStates.Inactive) { // Target App line has been deactivated, ignore it. _TracingService.Trace("UpdateApplication() Target App line has been deactivated, ignore it."); continue; } } if (appLineRetrieved.Attributes.Contains("defra_locationscreeningrequired") && (bool)appLineRetrieved["defra_locationscreeningrequired"]) { allLinesLocationScreeningNo = false; } } _TracingService.Trace("UpdateApplication() ApplicationEntity.Contains([defra_locationscreeningrequired)={0}", ApplicationEntity.Contains("defra_locationscreeningrequired")); if (!ApplicationEntity.Contains("defra_locationscreeningrequired") || !allLinesLocationScreeningNo != (bool)ApplicationEntity["defra_locationscreeningrequired"]) { _TracingService.Trace("Add to the Application upated entity the Location Screening Required flag set to {0}", !allLinesLocationScreeningNo); this.UpdatedApplicationEntity.Attributes.Add("defra_locationscreeningrequired", !allLinesLocationScreeningNo); } } // This is now done via a separate code activity GetActiveApplicationLines // Set the Active Lines field in the application if appropriate //bool activeLinesExist = DoActiveLinesExist(targetAppLine, newApplicationLineState, appLines); //this.UpdatedApplicationEntity.Attributes.Add(Model.Waste.Crm.Application.ActiveLinesExist, activeLinesExist); if (this.UpdatedApplicationEntity.Attributes.Count > 0) { _TracingService.Trace("Update the application with id {0}", this.UpdatedApplicationEntity.Id); _AdminService.Update(this.UpdatedApplicationEntity); } }
protected override bool TryAssert(OrganizationServiceContext context, Entity forum, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map) { forum.AssertEntityName("adx_communityforum"); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Testing right {0} on forum '{1}' ({2}).", right, forum.GetAttributeValue <string>("adx_name"), forum.Id)); this.AddDependencies(dependencies, forum, new [] { "adx_webrole", "adx_communityforumaccesspermission" }); if (!Roles.Enabled) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Roles are not enabled for this application. Allowing Read, but not Change."); // If roles are not enabled on the site, grant Read, deny Change. return(right == CrmEntityRight.Read); } var userRoles = this.GetUserRoles(); // Get all rules applicable to the forum, grouping equivalent rules. (Rules that // target the same forum and confer the same right are equivalent.) var ruleGroupings = from rule in this.GetRulesApplicableToForum(forum, dependencies, map) let forumReference = rule.GetAttributeValue <EntityReference>("adx_forumid") let rightOption = rule.GetAttributeValue <OptionSetValue>("adx_right") where forumReference != null && rightOption != null group rule by new { ForumID = forumReference.Id, Right = ParseRightOption(rightOption.Value) } into ruleGrouping select ruleGrouping; var websiteReference = forum.GetAttributeValue <EntityReference>("adx_websiteid"); // Order the rule groupings so that all GrantChange rules will be evaluated first. ruleGroupings = ruleGroupings.OrderByDescending(grouping => grouping.Key.Right, new RightOptionComparer()); foreach (var ruleGrouping in ruleGroupings) { // Collect the names of all the roles that apply to this rule grouping var ruleGroupingRoles = ruleGrouping.SelectMany(rule => GetRolesForGrouping(map, rule, websiteReference)); // Determine if the user belongs to any of the roles that apply to this rule grouping var userIsInAnyRoleForThisRule = ruleGroupingRoles.Any(role => userRoles.Any(userRole => userRole == role)); // If the user belongs to one of the roles... if (userIsInAnyRoleForThisRule) { // ...and the rule is GrantChange... if (ruleGrouping.Key.Right == RightOption.GrantChange) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User has right Change on forum ({0}). Permission granted.", ruleGrouping.Key.ForumID)); // ...the user has all rights. return(true); } } // If the user does not belong to any of the roles, the rule restricts read, and the desired right // is read... else if (ruleGrouping.Key.Right == RightOption.RestrictRead && right == CrmEntityRight.Read) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("User does not have right Read due to read restriction on forum ({0}). Permission denied.", ruleGrouping.Key.ForumID)); // ...the user has no right. return(false); } } // If none of the above rules apply, assert on parent webpage. var parentWebPage = forum.GetAttributeValue <EntityReference>("adx_parentpageid"); WebPageNode parentPageNode; map.TryGetValue(parentWebPage, out parentPageNode); // If there is no parent web page, grant Read by default, and deny Change. if (parentWebPage == null || parentPageNode == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Allowing Read, but not Change."); return(right == CrmEntityRight.Read); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "No access control rules apply to the current user and forum. Asserting right on parent web page."); return(this._webPageAccessControlProvider.TryAssert(context, parentPageNode.ToEntity(), right, dependencies)); }
public static string UserImageUrl(this UrlHelper urlHelper, Entity contact, int?size = null) { return(contact == null ? null : urlHelper.UserImageUrl(contact.GetAttributeValue <string>("emailaddress1"), size)); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> /// protected override void Execute(CodeActivityContext executionContext) { ITracingService tracer = executionContext.GetExtension <ITracingService>(); IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { DateTime originalDate = OriginalDate.Get(executionContext); int businessDaysToAdd = BusinessDaysToAdd.Get(executionContext); EntityReference holidaySchedule = HolidayClosureCalendar.Get(executionContext); Boolean ishighLevel = IsHighLevel.Get(executionContext); Int32 decreaseHours = DecreaseHours.Get(executionContext); Entity calendar = null; EntityCollection calendarRules = null; if (holidaySchedule != null) { calendar = service.Retrieve("calendar", holidaySchedule.Id, new ColumnSet(true)); if (calendar != null) { calendarRules = calendar.GetAttributeValue <EntityCollection>("calendarrules"); } } DateTime tempDate = originalDate; DateTime tempDateHours = originalDate; /* * * Test segment */ if (ishighLevel) { Int32 DecreaseHoursNegative = decreaseHours * -1; tempDateHours = tempDateHours.AddHours(DecreaseHoursNegative); if (tempDateHours.Day != tempDate.Day) { businessDaysToAdd = -1; tempDate = tempDate.AddHours(DecreaseHoursNegative); } } /****************/ if (businessDaysToAdd > 0) { while (businessDaysToAdd > 0) { tempDate = tempDate.AddDays(1); if (tempDate.DayOfWeek == DayOfWeek.Sunday || tempDate.DayOfWeek == DayOfWeek.Saturday) { continue; } if (calendar == null) { businessDaysToAdd--; continue; } bool isHoliday = false; foreach (Entity calendarRule in calendarRules.Entities) { DateTime startTime = calendarRule.GetAttributeValue <DateTime>("starttime"); //Not same date if (!startTime.Date.Equals(tempDate.Date)) { continue; } //Not full day event if (startTime.Subtract(startTime.TimeOfDay) != startTime || calendarRule.GetAttributeValue <int>("duration") != 1440) { continue; } isHoliday = true; break; } if (!isHoliday) { businessDaysToAdd--; } } } else if (businessDaysToAdd < 0) { while (businessDaysToAdd < 0) { tempDate = tempDate.AddDays(-1); if (tempDate.DayOfWeek == DayOfWeek.Sunday || tempDate.DayOfWeek == DayOfWeek.Saturday) { continue; } if (calendar == null) { businessDaysToAdd++; continue; } bool isHoliday = false; foreach (Entity calendarRule in calendarRules.Entities) { DateTime startTime = calendarRule.GetAttributeValue <DateTime>("starttime"); //Not same date if (!startTime.Date.Equals(tempDate.Date)) { continue; } //Not full day event if (startTime.Subtract(startTime.TimeOfDay) != startTime || calendarRule.GetAttributeValue <int>("duration") != 1440) { continue; } isHoliday = true; break; } if (!isHoliday) { businessDaysToAdd++; } } } DateTime updatedDate = tempDate; UpdatedDate.Set(executionContext, updatedDate); } catch (Exception ex) { tracer.Trace("Exception: {0}", ex.ToString()); } }
//Created By : Jerome Anthony Gerero, Created On : 8/31/2016 /*Purpose: Update Inventory record fields on Vehicle Adjustment/Variance Entry record delete * Registration Details: * Event/Message: * Pre-Validate/Delete: gsc_sls_adjustmentvarianceid * Post/Update: * Post/Create: * Primary Entity: Vehicle Adjustment/Variance Entry Detail */ public Entity AdjustInventoryOnUnpostedDelete(Entity vehicleAdjustmentVarianceEntryEntity) { _tracingService.Trace("Started AdjustInventoryOnUnpostedDelete Method..."); if (vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Posted")) { throw new InvalidPluginExecutionException("Unable to delete already posted Vehicle Adjustment/Variance Entry"); } else if (vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Cancelled")) { throw new InvalidPluginExecutionException("Unable to delete cancelled Vehicle Adjustment/Variance Entry"); } //Retrieve Vehicle Adjustment/Variance Entry Detail records EntityCollection vehicleAdjustmentVarianceEntryDetailRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_adjustmentvariancedetail", "gsc_vehicleadjustmentvarianceentryid", vehicleAdjustmentVarianceEntryEntity.Id, _organizationService, null, OrderType.Ascending, new[] { "gsc_inventoryid" }); if (vehicleAdjustmentVarianceEntryDetailRecords != null && vehicleAdjustmentVarianceEntryDetailRecords.Entities.Count > 0) { foreach (Entity vehicleAdjustmentVarianceEntryDetail in vehicleAdjustmentVarianceEntryDetailRecords.Entities) { Guid inventoryId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid").Id : Guid.Empty; //Retrieve Inventory records EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_productquantityid", "gsc_optioncode", "gsc_productid", "gsc_modelcode", "gsc_modelyear", "gsc_siteid", "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno" }); if (inventoryRecords != null && inventoryRecords.Entities.Count > 0) { Entity inventory = inventoryRecords.Entities[0]; inventory["gsc_status"] = new OptionSetValue(100000000); _organizationService.Update(inventory); Guid productQuantityId = inventory.GetAttributeValue <EntityReference>("gsc_productquantityid") != null ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id : Guid.Empty; //Retrieve Product Quantity records EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending, new[] { "gsc_allocated", "gsc_available", "gsc_vehiclecolorid", "gsc_vehiclemodelid" }); if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0) { Entity productQuantity = productQuantityRecords.Entities[0]; Int32 allocatedCount = productQuantity.Contains("gsc_allocated") ? productQuantity.GetAttributeValue <Int32>("gsc_allocated") : 1; Int32 availableCount = productQuantity.Contains("gsc_available") ? productQuantity.GetAttributeValue <Int32>("gsc_available") : 0; if (allocatedCount != 0) { productQuantity["gsc_allocated"] = allocatedCount - 1; } productQuantity["gsc_available"] = availableCount + 1; _organizationService.Update(productQuantity); //Create inventory history log InventoryMovementHandler inventoryMovement = new InventoryMovementHandler(_organizationService, _tracingService); inventoryMovement.CreateInventoryQuantityAllocated(vehicleAdjustmentVarianceEntryEntity, inventory, productQuantity, vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"), DateTime.UtcNow, "Deleted", Guid.Empty, 100000005); } } _organizationService.Delete("gsc_sls_adjustmentvariancedetail", vehicleAdjustmentVarianceEntryDetail.Id); } } _tracingService.Trace("Ended AdjustInventoryOnUnpostedDelete Method..."); return(vehicleAdjustmentVarianceEntryEntity); }
protected void OpportunityUpdated(object sender, CrmEntityFormViewUpdatedEventArgs e) { var context = PortalCrmConfigurationManager.CreateServiceContext(); var opportunity = context.CreateQuery("opportunity").First(o => o.GetAttributeValue <Guid>("opportunityid") == e.Entity.Id); var partnerReference = opportunity.GetAttributeValue <EntityReference>("msa_partnerid"); if (partnerReference == null) { return; } var partner = context.CreateQuery("account").First(p => p.GetAttributeValue <Guid>("accountid") == partnerReference.Id); if (partner.GetAttributeValue <int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(0) == 0) { partner.SetAttributeValue("adx_numberofopportunitiesaccepted", 1); } var oppnote = new Entity("adx_opportunitynote"); var oppnote2 = new Entity("adx_opportunitynote"); var feedbackrate = (double)(partner.GetAttributeValue <int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0)) / (partner.GetAttributeValue <int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1)); if (UpdatePipelinePhase.Checked) { context.SetOpportunityStatusAndSave(opportunity, "Open", 0); opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.InProgress)); if (!opportunity.GetAttributeValue <bool?>("adx_feedbackyet").GetValueOrDefault(false)) { if (!(opportunity.GetAttributeValue <bool?>("adx_partnercreated").GetValueOrDefault(false))) { partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue <int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1); partner.SetAttributeValue("adx_feedbackrate", feedbackrate); opportunity.SetAttributeValue("adx_feedbackyet", true); } } oppnote.SetAttributeValue("adx_name", PipelinePhase.SelectedItem.Text); oppnote.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote.SetAttributeValue("adx_description", PipelineUpdateDetails.Text); } else if (WinOpportunity.Checked) { context.SetOpportunityStatusAndSave(opportunity, "Won", 0); opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Purchased)); if (!opportunity.GetAttributeValue <bool?>("adx_feedbackyet").GetValueOrDefault(false)) { if (!(opportunity.GetAttributeValue <bool?>("adx_partnercreated").GetValueOrDefault(false))) { partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue <int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1); partner.SetAttributeValue("adx_feedbackrate", feedbackrate); opportunity.SetAttributeValue("adx_feedbackyet", true); } } opportunity.SetAttributeValue("adx_wondate", DateTime.UtcNow); var wonSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue <string>("adx_name") == "Won Opportunity Note"); var wonNote = "Won"; wonNote = (wonSetting != null) ? wonSetting.GetAttributeValue <string>("adx_value") : wonNote; oppnote.SetAttributeValue("adx_name", wonNote); oppnote.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote.SetAttributeValue("adx_description", WonDetails.Text); } else if (CancelOpportunity.Checked) { context.SetOpportunityStatusAndSave(opportunity, "Lost", 0); opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Canceled)); if (!opportunity.GetAttributeValue <bool?>("adx_feedbackyet").GetValueOrDefault(false)) { if (!(opportunity.GetAttributeValue <bool?>("adx_partnercreated").GetValueOrDefault(false))) { partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue <int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1); partner.SetAttributeValue("adx_feedbackrate", feedbackrate); opportunity.SetAttributeValue("adx_feedbackyet", true); } } var cancelSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue <string>("adx_name") == "Cancel Opportunity Note"); var cancelNote = "Canceled"; cancelNote = (cancelSetting != null) ? cancelSetting.GetAttributeValue <string>("adx_value") : cancelNote; oppnote.SetAttributeValue("adx_name", cancelNote); oppnote.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote.SetAttributeValue("adx_description", CancelDetails.Text); } else if (AddContactCheckBox.Checked) { var selectedGuid = new Guid(AddContactList.SelectedItem.Value); var contact = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == selectedGuid); var contactCrossover = opportunity.GetRelatedEntities(context, new Relationship("adx_opportunity_contact")).FirstOrDefault(c => c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid")); if (contactCrossover == null) { context.AddLink(opportunity, new Relationship("adx_opportunity_contact"), contact); oppnote2.SetAttributeValue("adx_name", "Contact Added: " + contact.GetAttributeValue <string>("fullname")); oppnote2.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote2.SetAttributeValue("adx_description", "Contact Added: " + contact.GetAttributeValue <string>("fullname")); context.UpdateObject(contact); } //var opportunity = OpenOpportunity; } else if (ReturnToNetwork.Checked) { context.SetOpportunityStatusAndSave(opportunity, "Lost", 0); opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Returned)); if (!(opportunity.GetAttributeValue <bool?>("adx_partnercreated").GetValueOrDefault(false))) { partner.SetAttributeValue("adx_numberofreturnedopportunities", partner.GetAttributeValue <int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) + 1); partner.SetAttributeValue("adx_returnrate", (double)partner.GetAttributeValue <int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) / (partner.GetAttributeValue <int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1))); } var returnSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue <string>("adx_name") == "Return Opportunity Note"); var returnNote = "Returned to Network"; returnNote = (returnSetting != null) ? returnSetting.GetAttributeValue <string>("adx_value") : returnNote; oppnote.SetAttributeValue("adx_name", returnNote); oppnote.SetAttributeValue("adx_date", DateTime.UtcNow); oppnote.SetAttributeValue("adx_description", ReasonForReturn.SelectedItem.Text); //add the OpportunityNote entity } var calculatePartnerDetailsAction = new Entity("adx_calculatepartnercapacityworkflowaction"); calculatePartnerDetailsAction.SetAttributeValue("adx_accountid", partner.ToEntityReference()); var assignedto = opportunity.GetRelatedEntity(context, new Relationship("msa_contact_opportunity")); if (!String.IsNullOrEmpty(oppnote.GetAttributeValue <string>("adx_name"))) { oppnote.SetAttributeValue("adx_opportunityid", opportunity.ToEntityReference()); oppnote.SetAttributeValue("adx_assignedto", assignedto != null ? assignedto.GetAttributeValue <string>("fullname") : string.Empty); context.AddObject(oppnote); } if (!String.IsNullOrEmpty(oppnote2.GetAttributeValue <string>("adx_name"))) { oppnote2.SetAttributeValue("adx_opportunityid", opportunity.ToEntityReference()); oppnote2.SetAttributeValue("adx_assignedto", assignedto != null ? assignedto.GetAttributeValue <string>("fullname") : string.Empty); context.AddObject(oppnote2); } var oppID = opportunity.Id; context.UpdateObject(partner); context.UpdateObject(opportunity); context.SaveChanges(); if (!(opportunity.GetAttributeValue <bool?>("adx_partnercreated").GetValueOrDefault(false))) { context.AddObject(calculatePartnerDetailsAction); } context.SaveChanges(); var opp = context.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue <Guid>("opportunityid") == oppID); if (opp != null) { CurrentlyAssignedToLabel.Text = assignedto != null?assignedto.GetAttributeValue <string>("fullname") : string.Empty; PipelinePhaseText.Text = HttpUtility.HtmlEncode(opp.GetAttributeValue <string>("stepname")); } DisableControlsBasedOnPipelinePhaseAndAccessPermissions(); BindPipelinePhaseDetails(); GetLeadHistory(); GetContactList(); ConfirmationMessage.Visible = true; }
//Created By : Jerome Anthony Gerero, Created On : 9/2/2016 //Modified By : Jessica Casupanan, Modified On : 01/10/2017 /*Purpose: Update Inventory record fields on Vehicle Adjustment/Variance Entry 'Posted' status * Registration Details: * Event/Message: * Pre-Validate/Delete: * Post/Update: gsc_adjustmentvariancestatus * Post/Create: * Primary Entity: Vehicle Adjustment/Variance Entry Detail */ public Entity PostVehicleAdjustmentVarianceEntry(Entity vehicleAdjustmentVarianceEntryEntity) { _tracingService.Trace("Started PostVehicleAdjustmentVarianceEntry Method..."); if (!vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Posted")) { return(null); } String transactionNumber = vehicleAdjustmentVarianceEntryEntity.Contains("gsc_vehicleadjustmentvarianceentrypn") ? vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_vehicleadjustmentvarianceentrypn") : String.Empty; DateTime transactionDate = DateTime.UtcNow; InventoryMovementHandler inventoryMovementHandler = new InventoryMovementHandler(_organizationService, _tracingService); _tracingService.Trace("Retrieve Vehicle Adjustment/Variance Entry Detail records"); EntityCollection vehicleAdjustmentVarianceEntryDetailRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_adjustmentvariancedetail", "gsc_vehicleadjustmentvarianceentryid", vehicleAdjustmentVarianceEntryEntity.Id, _organizationService, null, OrderType.Ascending, new[] { "gsc_vehiclebasemodelid", "gsc_vehiclecolorid", "gsc_csno", "gsc_engineno", "gsc_modelcode", "gsc_productid", "gsc_modelyear", "gsc_optioncode", "gsc_productionno", "gsc_siteid", "gsc_vin", "gsc_operation", "gsc_inventoryid", "statecode", "gsc_quantity" }); if (vehicleAdjustmentVarianceEntryDetailRecords != null && vehicleAdjustmentVarianceEntryDetailRecords.Entities.Count > 0) { foreach (Entity vehicleAdjustmentVarianceEntryDetail in vehicleAdjustmentVarianceEntryDetailRecords.Entities) { Int32 quantity = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_quantity") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <Int32>("gsc_quantity") : 0; #region Subtract if (vehicleAdjustmentVarianceEntryDetail.FormattedValues["gsc_operation"].Equals("Subtract")) { Guid inventoryId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_inventoryid").Id : Guid.Empty; _tracingService.Trace("Retrieve Inventory records using value from Inventory field"); EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_productquantityid", "gsc_optioncode", "gsc_productid", "gsc_modelcode", "gsc_modelyear", "gsc_siteid", "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno" }); if (inventoryRecords != null && inventoryRecords.Entities.Count > 0) { Entity inventory = inventoryRecords.Entities[0]; Guid productQuantityId = inventory.GetAttributeValue <EntityReference>("gsc_productquantityid") != null ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id : Guid.Empty; _tracingService.Trace("Retrieve Product Quantity record using value from Product Quantity field"); EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending, new[] { "gsc_allocated", "gsc_onhand", "gsc_available", "gsc_siteid", "gsc_vehiclecolorid", "gsc_vehiclemodelid", "gsc_productid" }); if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0) { Entity productQuantity = productQuantityRecords.Entities[0]; Int32 allocatedCount = productQuantity.Contains("gsc_allocated") ? productQuantity.GetAttributeValue <Int32>("gsc_allocated") : 1; Int32 availableCount = productQuantity.Contains("gsc_available") ? productQuantity.GetAttributeValue <Int32>("gsc_available") : 0; Int32 onHandCount = productQuantity.Contains("gsc_onhand") ? productQuantity.GetAttributeValue <Int32>("gsc_onhand") : 1; _tracingService.Trace("Adjust Allocated count"); if (allocatedCount != 0) { productQuantity["gsc_allocated"] = allocatedCount - 1; } _tracingService.Trace("Adjust On Hand count"); if (onHandCount != 0) { productQuantity["gsc_onhand"] = onHandCount - 1; } _organizationService.Update(productQuantity); Guid fromSite = productQuantity.Contains("gsc_siteid") ? productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id : Guid.Empty; inventoryMovementHandler.CreateInventoryHistory("Negative Adjustment", null, null, transactionNumber, transactionDate, 1, 0, onHandCount - 1, Guid.Empty, fromSite, fromSite, inventory, productQuantity, true, true); inventoryMovementHandler.CreateInventoryQuantityAllocated(vehicleAdjustmentVarianceEntryEntity, inventory, productQuantity, vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"), DateTime.UtcNow, "Posted", Guid.Empty, 100000008); _tracingService.Trace("Deactivate record"); if (vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <OptionSetValue>("statecode").Value == 0) { SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = inventory.Id, LogicalName = inventory.LogicalName, }, State = new OptionSetValue(1), Status = new OptionSetValue(2) }; _organizationService.Execute(setStateRequest); } } } } #endregion #region Add else if (vehicleAdjustmentVarianceEntryDetail.FormattedValues["gsc_operation"].Equals("Add")) { _tracingService.Trace("Get Vehicle Adjustment/Variance Entry Detail fields"); Guid vehicleBaseModelId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id : Guid.Empty; String color = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Name : String.Empty; Guid colorId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Id : Guid.Empty; String csNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_csno") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_csno") : String.Empty; String engineNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_engineno") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_engineno") : String.Empty; String modelCode = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_modelcode") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_modelcode") : String.Empty; Guid productId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid").Id : Guid.Empty; String productName = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_productid").Name : String.Empty; String modelYear = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_modelyear") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_modelyear") : String.Empty; String optionCode = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_optioncode") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_optioncode") : String.Empty; String productionNo = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_productionno") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_productionno") : String.Empty; Guid siteId = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid").Id : Guid.Empty; String siteName = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid").Name : String.Empty; String vin = vehicleAdjustmentVarianceEntryDetail.Contains("gsc_vin") ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <String>("gsc_vin") : String.Empty; _tracingService.Trace("Create filter for Product in Product Relationship entity"); var productQuantityConditionList = new List <ConditionExpression> { new ConditionExpression("gsc_productid", ConditionOperator.Equal, productId), new ConditionExpression("gsc_siteid", ConditionOperator.Equal, siteId), new ConditionExpression("gsc_vehiclecolorid", ConditionOperator.Equal, colorId) }; _tracingService.Trace("Retrieve Product Quantity records"); EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByConditions("gsc_iv_productquantity", productQuantityConditionList, _organizationService, null, OrderType.Ascending, new[] { "gsc_onhand", "gsc_available", "gsc_siteid", "gsc_vehiclecolorid", "gsc_vehiclemodelid", "gsc_productid" }); Entity productQuantity; Entity inventory = new Entity("gsc_iv_inventory"); Int32 onHandCount = 0; Int32 availableCount; if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0) { _tracingService.Trace("Update existing product quantity record"); productQuantity = productQuantityRecords.Entities[0]; onHandCount = productQuantity.Contains("gsc_onhand") ? productQuantity.GetAttributeValue <Int32>("gsc_onhand") : 0; availableCount = productQuantity.Contains("gsc_available") ? productQuantity.GetAttributeValue <Int32>("gsc_available") : 0; _tracingService.Trace("Set product quantity count"); productQuantity["gsc_onhand"] = onHandCount + 1; productQuantity["gsc_available"] = availableCount + 1; _organizationService.Update(productQuantity); inventory["gsc_productquantityid"] = new EntityReference("gsc_iv_productquantity", productQuantity.Id); } else { _tracingService.Trace("Create new product quantity product"); productQuantity = new Entity("gsc_iv_productquantity"); _tracingService.Trace("Set product quantity count"); productQuantity["gsc_onhand"] = 1; productQuantity["gsc_available"] = 1; _tracingService.Trace("Set site field"); if (siteId != Guid.Empty) { productQuantity["gsc_siteid"] = new EntityReference("gsc_iv_site", siteId); } _tracingService.Trace("Set Vehicle Base Model field"); if (vehicleBaseModelId != Guid.Empty) { productQuantity["gsc_vehiclemodelid"] = new EntityReference("gsc_iv_vehiclebasemodel", vehicleBaseModelId); } if (colorId != Guid.Empty) { productQuantity["gsc_vehiclecolorid"] = new EntityReference("gsc_cmn_vehiclecolor", colorId); } _tracingService.Trace("Set Product Name field"); productQuantity["gsc_productid"] = new EntityReference("product", productId); productQuantity["gsc_productquantitypn"] = productName; Guid newProductQuantityId = _organizationService.Create(productQuantity); inventory["gsc_productquantityid"] = new EntityReference("gsc_iv_productquantity", newProductQuantityId); } _tracingService.Trace("Create Inventory record"); inventory["gsc_inventorypn"] = productName + "-" + siteName; inventory["gsc_status"] = new OptionSetValue(100000000); inventory["gsc_color"] = color; inventory["gsc_engineno"] = engineNo; inventory["gsc_csno"] = csNo; inventory["gsc_productionno"] = productionNo; inventory["gsc_vin"] = vin; inventory["gsc_modelcode"] = modelCode; inventory["gsc_optioncode"] = optionCode; inventory["gsc_modelyear"] = modelYear; inventory["gsc_siteid"] = vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") != null ? vehicleAdjustmentVarianceEntryDetail.GetAttributeValue <EntityReference>("gsc_siteid") : null; Guid inventoryId = _organizationService.Create(inventory); EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_productquantityid", "gsc_modelcode", "gsc_optioncode", "gsc_productid", "gsc_modelyear", "gsc_siteid", "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno" }); if (inventoryRecords != null && inventoryRecords.Entities.Count > 0) { Entity inventoryE = inventoryRecords.Entities[0]; Guid fromSite = productQuantity.Contains("gsc_siteid") ? productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id : Guid.Empty; inventoryMovementHandler.CreateInventoryHistory("Positive Adjustment", null, null, transactionNumber, transactionDate, 0, 1, onHandCount + 1, Guid.Empty, fromSite, fromSite, inventoryE, productQuantity, true, true); } } #endregion } } _tracingService.Trace("Ended PostVehicleAdjustmentVarianceEntry Method..."); return(vehicleAdjustmentVarianceEntryEntity); }
protected override void Execute(CodeActivityContext activityContext) { //Create the tracing service. ITracingService tracingService = activityContext.GetExtension <ITracingService>(); //Create the context. IWorkflowContext workflowContext = activityContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = activityContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId); //Check the InArgument value. if (this.Arg_WO != null) { //Get the Work Order Record. Entity workOrder = service.Retrieve("msdyn_workorder", this.Arg_WO.Get <EntityReference>(activityContext).Id, new ColumnSet(true)); //Retrieve the standards collection for this work order. EntityCollection standards = getWorkOrderStandards(service, workOrder.Id); //Retrieve the domains collection for this work order. EntityCollection domains = getWorkOrderDomains(service, workOrder.Id); //Retieve the elements collection for this work order. EntityCollection elements = getWorkOrderElements(service, workOrder.Id); #region Domain Calculation if (domains != null) { //Retrieve each domain and update it. foreach (Entity domain in domains.Entities) { Entity domainRecord = service.Retrieve("msdyn_workorderservice", domain.Id, new ColumnSet(true)); CalculateRollupFieldRequest totalApplicableElementRequest = new CalculateRollupFieldRequest { Target = new EntityReference("msdyn_workorderservice", domainRecord.Id), FieldName = "net_totalnumberofapplicableelements" }; CalculateRollupFieldResponse totalApplicableElementResponse = (CalculateRollupFieldResponse)service.Execute(totalApplicableElementRequest); domainRecord = totalApplicableElementResponse.Entity; //service.Update(workOrder); CalculateRollupFieldRequest SumOfJudgmentRequest = new CalculateRollupFieldRequest { Target = new EntityReference("msdyn_workorderservice", domainRecord.Id), FieldName = "net_sumofjudgment" }; CalculateRollupFieldResponse sumOfJudgmentResponse = (CalculateRollupFieldResponse)service.Execute(SumOfJudgmentRequest); domainRecord = sumOfJudgmentResponse.Entity; service.Update(domainRecord); Entity domainUpdated = service.Retrieve("msdyn_workorderservice", domainRecord.Id, new ColumnSet(true)); int totalApplicableELement = domainUpdated.GetAttributeValue <int>("net_totalnumberofapplicableelements"); int sumOfJudgement = domainUpdated.GetAttributeValue <int>("net_sumofjudgment"); int AgreePercentage = 0; if (totalApplicableELement != 0) { AgreePercentage = sumOfJudgement * 100 / (totalApplicableELement * 2); } else { AgreePercentage = 0; } domainUpdated["net_agreepercentage"] = AgreePercentage; service.Update(domainUpdated); } } #endregion #region Standard Calculation if (standards != null) { //Retrieve the elements in each standard foreach (Entity standard in standards.Entities) { //define the numebr of applicable element. int totalNumberofApplicableElement = 0; //define the sum of judgment. int sumOfJudgment = 0; //define the weight. int sumOfWeight = 0; //define the Overall Judgment Percentage Decimal overallJudgmentPercentage = 0; //define the weighted score. Decimal weightedScore = 0; //define the weighted score percentage. Decimal weightedScorePercentage = 0; //fetch all elements in the standard EntityCollection elementStandards = getStandardElements(service, standard.Id); foreach (Entity element in elementStandards.Entities) { //Get the compliance status OptionSetValue complianceStatus = element.GetAttributeValue <OptionSetValue>("net_compliantcoordinator"); if (complianceStatus != null) { int elementStatus = complianceStatus.Value; //if status != N/A if (elementStatus != 3) { //increment the total number of applicable element. totalNumberofApplicableElement = totalNumberofApplicableElement + 1; } } int elementJudgment = element.GetAttributeValue <int>("net_inspectionjudgement"); //add the element judgment to the sum of judgment. sumOfJudgment = sumOfJudgment + elementJudgment; //get the weight. int weight = element.GetAttributeValue <int>("net_weight"); //add the weight to the sumofweight. sumOfWeight = sumOfWeight + weight; weightedScore = weightedScore + (elementJudgment * weight); } if (totalNumberofApplicableElement != 0) { overallJudgmentPercentage = (Decimal)(sumOfJudgment) * (Decimal)100 / (Decimal)(2 * totalNumberofApplicableElement); } else { overallJudgmentPercentage = 0; } if (sumOfWeight != 0) { weightedScore = weightedScore / sumOfWeight; } else { weightedScore = 0; } weightedScorePercentage = weightedScore / 2 * 100; standard["net_totalofapplicableelement"] = totalNumberofApplicableElement; standard["net_sumofjudgment"] = sumOfJudgment; standard["net_compliancepercentage"] = overallJudgmentPercentage; standard["net_weightedscore"] = weightedScore; standard["net_weightedscorepercentage"] = weightedScorePercentage; service.Update(standard); } } #endregion #region Update the Rollup Fields CalculateRollupFieldRequest rollupRequest = new CalculateRollupFieldRequest { Target = new EntityReference("msdyn_workorder", workOrder.Id), FieldName = "net_totalnumberofapplicableelements" }; CalculateRollupFieldResponse response = (CalculateRollupFieldResponse)service.Execute(rollupRequest); workOrder = response.Entity; //service.Update(workOrder); CalculateRollupFieldRequest rollupRequestSumOfJudgment = new CalculateRollupFieldRequest { Target = new EntityReference("msdyn_workorder", workOrder.Id), FieldName = "net_sumofjudgment" }; CalculateRollupFieldResponse responseSumOfJudgment = (CalculateRollupFieldResponse)service.Execute(rollupRequestSumOfJudgment); workOrder = responseSumOfJudgment.Entity; service.Update(workOrder); #endregion #region Work Order Calculation Entity updatedWorkOrder = service.Retrieve("msdyn_workorder", workOrder.Id, new ColumnSet(true)); int totalOfApplicableElements = updatedWorkOrder.GetAttributeValue <int>("net_totalnumberofapplicableelements"); int workOrderSumOfJudgment = updatedWorkOrder.GetAttributeValue <int>("net_sumofjudgment"); //int maxPossibleScore = workOrder.GetAttributeValue<int>("net_maxpossiblescore"); int maxPossibleScore = totalOfApplicableElements * 2; Decimal overallCompliancePercentage = 0; if (maxPossibleScore != 0) { overallCompliancePercentage = (Decimal)((Decimal)workOrderSumOfJudgment * 100 / (Decimal)maxPossibleScore); } else { overallCompliancePercentage = 0; } //define the weighted score. Decimal workOrderWeightedScore = 0; //define the weight. int workOrderSumOfWeight = 0; if (elements != null) { string elementsID = ""; Decimal RiskLevelPercentage = 0; foreach (Entity element in elements.Entities) { elementsID = (elementsID + "<value>" + element.Id + "</value>"); int elementJudgment = element.GetAttributeValue <int>("net_inspectionjudgement"); //get the weight. int weight = element.GetAttributeValue <int>("net_weight"); //add the weight to the sumofweight. workOrderSumOfWeight = workOrderSumOfWeight + weight; workOrderWeightedScore = workOrderWeightedScore + (elementJudgment * weight); } if (workOrderSumOfWeight != 0) { workOrderWeightedScore = workOrderWeightedScore / workOrderSumOfWeight; } else { workOrderWeightedScore = 0; } //retrieve the number of critical element definition. //EntityCollection criticalElementDefinition = getCriticalElementsDefinitionByElementInstance(service, elementsID); //int numberOfCriticalElementsDefinition = criticalElementDefinition.Entities.Count; string fetch = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'> <entity name='net_element'> <attribute name='net_elementid' /> <attribute name='net_name' /> <attribute name='createdon' /> <order attribute='net_name' descending='false' /> <filter type='and'> <condition attribute='net_critical' operator='eq' value='1' /> </filter> <link-entity name='msdyn_workorderservicetask' from='net_element' to='net_elementid' alias='ab'> <filter type='and'> <condition attribute='msdyn_workorderservicetaskid' operator='in'>" + elementsID + "</condition>" + "</filter>" + "</link-entity>" + "</entity>" + "</fetch>"; EntityCollection criticalElementsDefinition = service.RetrieveMultiple(new FetchExpression(fetch)); int numberOfCriticalElementsDefinition = criticalElementsDefinition.Entities.Count; //Retrieve the number of critical elements. int numberOfCriticalElements = getWorkOrderCriticalElements(service, workOrder.Id).Entities.Count; if (numberOfCriticalElementsDefinition == 0) { RiskLevelPercentage = 0; } else { RiskLevelPercentage = (Decimal)numberOfCriticalElements * (Decimal)100 / (Decimal)numberOfCriticalElementsDefinition; } //update the work order. updatedWorkOrder["net_overallcompliance"] = overallCompliancePercentage; updatedWorkOrder["net_weightedscore"] = workOrderWeightedScore; updatedWorkOrder["net_numberofcriticalinspectionelements"] = numberOfCriticalElements; updatedWorkOrder["net_numberofcriticalelementdefinition"] = numberOfCriticalElementsDefinition; updatedWorkOrder["net_riskslevelpercentage"] = RiskLevelPercentage; service.Update(updatedWorkOrder); } #endregion } }
//Created By : Jerome Anthony Gerero, Created On : 8/25/2016 //Modified By : Jessica Casupanan, Modified On : 01/09/2017 /*Purpose: Create new allocated vehicle record * Registration Details: * Event/Message: * Pre/Create: * Post/Update: Inventory Id to Allocate = gsc_inventoryidtoallocate * Post/Create: * Primary Entity: Vehicle Adjustment/Variance Entry */ public Entity CreateVehicleAdjustmentVarianceEntryDetailRecord(Entity vehicleAdjustmentVarianceEntryEntity) { _tracingService.Trace("Started CreateVehicleAdjustmentVarianceEntryDetailRecord Method..."); //Return if Inventory ID to Allocate is null if (vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") == null) { _tracingService.Trace("Inventory ID to Allocate is null.. exiting."); return(null); } Guid inventoryId = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate") != null ? new Guid(vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <String>("gsc_inventoryidtoallocate")) : Guid.Empty; EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_color", "gsc_csno", "gsc_engineno", "gsc_modelcode", "gsc_modelyear", "gsc_optioncode", "gsc_productionno", "gsc_vin", "gsc_productquantityid", "gsc_siteid", "gsc_productid", "gsc_basemodelid" }); if (inventoryRecords != null && inventoryRecords.Entities.Count > 0) { Entity inventory = inventoryRecords.Entities[0]; if (!inventory.FormattedValues["gsc_status"].Equals("Available")) { throw new InvalidPluginExecutionException("The inventory for entered vehicle is not available."); } Entity vehicleAdjustmentVarianceEntryDetail = new Entity("gsc_sls_adjustmentvariancedetail"); vehicleAdjustmentVarianceEntryDetail["gsc_vehicleadjustmentvarianceentryid"] = new EntityReference(vehicleAdjustmentVarianceEntryEntity.LogicalName, vehicleAdjustmentVarianceEntryEntity.Id); vehicleAdjustmentVarianceEntryDetail["gsc_inventoryid"] = new EntityReference(inventory.LogicalName, inventory.Id); vehicleAdjustmentVarianceEntryDetail["gsc_modelcode"] = inventory.Contains("gsc_modelcode") ? inventory.GetAttributeValue <String>("gsc_modelcode") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_modelyear"] = inventory.Contains("gsc_modelyear") ? inventory.GetAttributeValue <String>("gsc_modelyear") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_optioncode"] = inventory.Contains("gsc_optioncode") ? inventory.GetAttributeValue <String>("gsc_optioncode") : String.Empty; String color = inventory.Contains("gsc_color") ? inventory.GetAttributeValue <String>("gsc_color") : String.Empty; //Retrieve Vehicle Color EntityCollection vehicleColorRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_cmn_vehiclecolor", "gsc_vehiclecolorpn", color, _organizationService, null, OrderType.Ascending, new[] { "gsc_cmn_vehiclecolorid" }); if (vehicleColorRecords != null && vehicleColorRecords.Entities.Count > 0) { Entity vehicleColor = vehicleColorRecords.Entities[0]; vehicleAdjustmentVarianceEntryDetail["gsc_vehiclecolorid"] = new EntityReference(vehicleColor.LogicalName, vehicleColor.Id); } vehicleAdjustmentVarianceEntryDetail["gsc_csno"] = inventory.Contains("gsc_csno") ? inventory.GetAttributeValue <String>("gsc_csno") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_vin"] = inventory.Contains("gsc_vin") ? inventory.GetAttributeValue <String>("gsc_vin") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_productionno"] = inventory.Contains("gsc_productionno") ? inventory.GetAttributeValue <String>("gsc_productionno") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_engineno"] = inventory.Contains("gsc_engineno") ? inventory.GetAttributeValue <String>("gsc_engineno") : String.Empty; vehicleAdjustmentVarianceEntryDetail["gsc_quantity"] = -1; vehicleAdjustmentVarianceEntryDetail["gsc_operation"] = new OptionSetValue(100000001); vehicleAdjustmentVarianceEntryDetail["gsc_recordownerid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid") != null ? new EntityReference("contact", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_recordownerid").Id) : null; vehicleAdjustmentVarianceEntryDetail["gsc_dealerid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid") != null ? new EntityReference("account", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_dealerid").Id) : null; vehicleAdjustmentVarianceEntryDetail["gsc_branchid"] = vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid") != null ? new EntityReference("account", vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <EntityReference>("gsc_branchid").Id) : null; Guid productQuantityId = inventory.Contains("gsc_productquantityid") ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id : Guid.Empty; //Retrieve Product Quantity record for additional fields EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending, new[] { "gsc_siteid", "gsc_productid", "gsc_vehiclemodelid", "gsc_allocated", "gsc_available", "gsc_vehiclemodelid" }); Entity productQuantity = new Entity("gsc_iv_productquantity"); if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0) { productQuantity = productQuantityRecords.Entities[0]; vehicleAdjustmentVarianceEntryDetail["gsc_vehiclebasemodelid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_vehiclemodelid") != null ? new EntityReference("gsc_iv_vehiclebasemodel", productQuantity.GetAttributeValue <EntityReference>("gsc_vehiclemodelid").Id) : null; vehicleAdjustmentVarianceEntryDetail["gsc_productid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_productid") != null ? new EntityReference("product", productQuantity.GetAttributeValue <EntityReference>("gsc_productid").Id) : null; vehicleAdjustmentVarianceEntryDetail["gsc_siteid"] = productQuantity.GetAttributeValue <EntityReference>("gsc_siteid") != null ? new EntityReference("gsc_iv_site", productQuantity.GetAttributeValue <EntityReference>("gsc_siteid").Id) : null; Int32 allocatedCount = productQuantity.Contains("gsc_allocated") ? productQuantity.GetAttributeValue <Int32>("gsc_allocated") : 0; Int32 availableCount = productQuantity.Contains("gsc_available") ? productQuantity.GetAttributeValue <Int32>("gsc_available") : 1; productQuantity["gsc_allocated"] = allocatedCount + 1; if (availableCount != 0) { productQuantity["gsc_available"] = availableCount - 1; } // throw new InvalidPluginExecutionException("test" + (allocatedCount + 1).ToString() + " " + (availableCount - 1).ToString()); _organizationService.Update(productQuantity); } _organizationService.Create(vehicleAdjustmentVarianceEntryDetail); //Set Inventory status to 'Allocated' inventory["gsc_status"] = new OptionSetValue(100000001); _organizationService.Update(inventory); InventoryMovementHandler inventoryMovement = new InventoryMovementHandler(_organizationService, _tracingService); inventoryMovement.CreateInventoryQuantityAllocated(vehicleAdjustmentVarianceEntryEntity, inventory, productQuantity, vehicleAdjustmentVarianceEntryEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"), DateTime.UtcNow, vehicleAdjustmentVarianceEntryEntity.FormattedValues["gsc_adjustmentvariancestatus"], Guid.Empty, 100000001); } //Clear Inventory ID to Allocate field vehicleAdjustmentVarianceEntryEntity["gsc_inventoryidtoallocate"] = String.Empty; _organizationService.Update(vehicleAdjustmentVarianceEntryEntity); _tracingService.Trace("Ended CreateVehicleAdjustmentVarianceEntryDetailRecord Method..."); return(vehicleAdjustmentVarianceEntryEntity); }
/// <summary> /// Executes the plug-in. /// </summary> /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the /// <see cref="IPluginExecutionContext"/>, /// <see cref="IOrganizationService"/> /// and <see cref="ITracingService"/> /// </param> /// <remarks> /// For improved performance, Microsoft Dynamics CRM caches plug-in instances. /// The plug-in's Execute method should be written to be stateless as the constructor /// is not called for every invocation of the plug-in. Also, multiple system threads /// could execute the plug-in at the same time. All per invocation state information /// is stored in the context. This means that you should not use global variables in plug-ins. /// </remarks> protected void ExecutePostProspectInquiryUpdate(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } IPluginExecutionContext context = localContext.PluginExecutionContext; IOrganizationService service = localContext.OrganizationService; ITracingService trace = localContext.TracingService; Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)) { return; } if (postImageEntity.LogicalName != "lead") { return; } string message = context.MessageName; if (context.Mode == 0) //synchronous plugin { try { ProspectInquiryHandler prospectInquiryHandler = new ProspectInquiryHandler(service, trace); var preImageBaseModelId = preImageEntity.Contains("gsc_vehiclebasemodelid") ? preImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id : Guid.Empty; var preImageDisqualified = preImageEntity.GetAttributeValue <Boolean>("gsc_disqualified"); var preImageDisqualifiedStatusReason = preImageEntity.Contains("gsc_disqualifiedstatusreason") ? preImageEntity.GetAttributeValue <Int32>("gsc_disqualifiedstatusreason") : 0; var preImageQualified = preImageEntity.GetAttributeValue <Boolean>("gsc_qualified"); var preImageCityName = preImageEntity.Contains("gsc_cityname") ? preImageEntity.GetAttributeValue <string>("gsc_cityname") : String.Empty; var preImageCityIdName = preImageEntity.Contains("gsc_cityid") ? preImageEntity.GetAttributeValue <EntityReference>("gsc_cityid").Name : String.Empty; var postImageBaseModelId = postImageEntity.Contains("gsc_vehiclebasemodelid") ? postImageEntity.GetAttributeValue <EntityReference>("gsc_vehiclebasemodelid").Id : Guid.Empty; var postImageDisqualified = postImageEntity.GetAttributeValue <Boolean>("gsc_disqualified"); var postImageDisqualifiedStatusReason = postImageEntity.Contains("gsc_disqualifiedstatusreason") ? postImageEntity.GetAttributeValue <Int32>("gsc_disqualifiedstatusreason") : 0; var postImageQualified = postImageEntity.GetAttributeValue <Boolean>("gsc_qualified"); var postImageCityName = postImageEntity.Contains("gsc_cityname") ? postImageEntity.GetAttributeValue <string>("gsc_cityname") : String.Empty; var postImageCityIdName = postImageEntity.Contains("gsc_cityid") ? postImageEntity.GetAttributeValue <EntityReference>("gsc_cityid").Name : String.Empty; //execute the method when Base Model Id was changed if (preImageBaseModelId != postImageBaseModelId) { prospectInquiryHandler.ConcatenateVehicleInfo(postImageEntity, message); } //Call DisqualifyProspectInquiry method on Disqualified and Disqualified Status Reason change if (preImageDisqualified != postImageDisqualified && preImageDisqualifiedStatusReason != postImageDisqualifiedStatusReason) { prospectInquiryHandler.DisqualifyProspectInquiry(postImageEntity); } //Call QualifyProsctInquiry if (preImageQualified != postImageQualified) { prospectInquiryHandler.CreateCustomer(postImageEntity); prospectInquiryHandler.CreateOpportunity(postImageEntity); prospectInquiryHandler.QualifyProspectInquiry(postImageEntity); } if (postImageCityName != postImageCityIdName && postImageCityName != String.Empty && preImageCityIdName == postImageCityIdName) { prospectInquiryHandler.SetCity(postImageEntity); } } catch (Exception ex) { throw new InvalidPluginExecutionException(String.Concat(ex.Message)); } } }
public WebResource(Entity webResource, string filePath) { FilePath = filePath; WebResourceEntity = webResource; InitialBase64 = webResource.GetAttributeValue<string>("content"); }
public override void Execute(ILocalPluginContext localContext) { // Depth check to prevent infinite loop if (localContext.PluginExecutionContext.Depth > 1) { return; } // The InputParameters collection contains all the data passed in the message request. if (localContext.PluginExecutionContext.InputParameters.Contains(Target) && localContext.PluginExecutionContext.InputParameters[Target] is Entity) { // Obtain the target entity from the input parameters. Entity target = (Entity)localContext.PluginExecutionContext.InputParameters[Target]; try { // Check for update event if (localContext.PluginExecutionContext.MessageName.Equals("update", StringComparison.InvariantCultureIgnoreCase)) { localContext.Trace("Entered {0}.Execute()", nameof(OnUpdateAccountEmail_CreateEmailChangeRequestCase)); localContext.ClearPluginTraceLog(nameof(OnUpdateAccountEmail_CreateEmailChangeRequestCase)); localContext.Trace($"Attempting to retrieve account email..."); //Obtain the pre image and post image entities Entity preImageEntity = (localContext.PluginExecutionContext.PreEntityImages != null && localContext.PluginExecutionContext.PreEntityImages.Contains(PreImageAlias)) ? localContext.PluginExecutionContext.PreEntityImages[PreImageAlias] : null; Entity postImageEntity = (localContext.PluginExecutionContext.PostEntityImages != null && localContext.PluginExecutionContext.PostEntityImages.Contains(PostImageAlias)) ? localContext.PluginExecutionContext.PostEntityImages[PostImageAlias] : null; string previousEmail = preImageEntity?.GetAttributeValue <string>(Email); string newEmail = postImageEntity?.GetAttributeValue <string>(Email); if (previousEmail == newEmail) { localContext.Trace($"Newly entered Email is the same as the old one. Aborting plugin execution."); return; } // Create new instance of account for update var retrievedAccount = new Entity(PluginXrm.Account.EntityLogicalName, target.Id); var account = new Entity(PluginXrm.Account.EntityLogicalName) { Id = retrievedAccount.Id, [Email] = previousEmail }; localContext.OrganizationService.Update(account); localContext.Trace($"Email field value set to the previous one: {previousEmail}"); // Create case Incident caseRecord = CreateCase(localContext, previousEmail, newEmail, account.Id); var caseId = localContext.OrganizationService.Create(caseRecord); localContext.Trace($"Case with id {caseId} created"); } } catch (Exception ex) { localContext.Trace($"An error occurred in {nameof(OnUpdateAccountEmail_CreateEmailChangeRequestCase)}. " + $"Exception details: {ex.Message}"); throw new InvalidPluginExecutionException(ex.Message); } finally { localContext.Trace("Exiting {0}.Execute()", nameof(OnUpdateAccountEmail_CreateEmailChangeRequestCase)); } } }
public static TEnum?GetOptionSetValueAsEnum <TEnum>(this Entity target, string attributeName) where TEnum : struct { return(target?.GetAttributeValue <OptionSetValue>(attributeName).ToEnum <TEnum>()); }
//Handles logic for removing vehicle adjustment details private Entity UnallocateVehicleAdjustment(Entity adjustedVehcileDetailsEntity, Entity vehicleAdjustmentEntity, string caller) { var inventoryId = adjustedVehcileDetailsEntity.Contains("gsc_inventoryid") ? adjustedVehcileDetailsEntity.GetAttributeValue <EntityReference>("gsc_inventoryid").Id : Guid.Empty; if (inventoryId != Guid.Empty) { var quantity = adjustedVehcileDetailsEntity.Contains("gsc_quantity") ? adjustedVehcileDetailsEntity.GetAttributeValue <Int32>("gsc_quantity") : 0; EntityCollection inventoryCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending, new[] { "gsc_status", "gsc_productquantityid", "gsc_basemodelid", "gsc_productid", "gsc_modelcode", "gsc_optioncode", "gsc_modelyear", "gsc_siteid", "gsc_vin", "gsc_csno", "gsc_productionno", "gsc_engineno", }); _tracingService.Trace("Inventory records retrieved: " + inventoryCollection.Entities.Count); if (inventoryCollection.Entities.Count > 0) { _organizationService.Delete(adjustedVehcileDetailsEntity.LogicalName, adjustedVehcileDetailsEntity.Id); _tracingService.Trace("Deleted inventory record..."); //negative adjustment logic if (quantity < 0) { Entity inventoryEntity = inventoryCollection.Entities[0]; InventoryMovementHandler inventoryMovementHandler = new InventoryMovementHandler(_organizationService, _tracingService); inventoryMovementHandler.UpdateInventoryStatus(inventoryEntity, 100000000); Entity productQuantityEntity = inventoryMovementHandler.UpdateProductQuantity(inventoryEntity, 0, 1, -1, 0, 0, 0, 0, 0); #region Inventory History Log Creation InventoryMovementHandler inventoryMovement = new InventoryMovementHandler(_organizationService, _tracingService); if (caller == "Cancel") { inventoryMovement.CreateInventoryQuantityAllocated(vehicleAdjustmentEntity, inventoryEntity, productQuantityEntity, vehicleAdjustmentEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"), DateTime.UtcNow, "Cancel", Guid.Empty, 100000004); } else { inventoryMovement.CreateInventoryQuantityAllocated(vehicleAdjustmentEntity, inventoryEntity, productQuantityEntity, vehicleAdjustmentEntity.GetAttributeValue <string>("gsc_vehicleadjustmentvarianceentrypn"), DateTime.UtcNow, "Open", Guid.Empty, 100000003); } #endregion } } } else { _organizationService.Delete(adjustedVehcileDetailsEntity.LogicalName, adjustedVehcileDetailsEntity.Id); } return(adjustedVehcileDetailsEntity); }
public static Entity GetCaseAccessByContact(this OrganizationServiceContext context, Entity contact) { contact.AssertEntityName("contact"); if (contact == null) { return(null); } var parentCustomerAccount = contact.GetRelatedEntity(context, "contact_customer_accounts"); IEnumerable <Entity> findCaseAccess; if (parentCustomerAccount == null) //contact is not associated with a parent account record { findCaseAccess = from aa in context.CreateQuery("adx_caseaccess").ToList() let c = aa.GetRelatedEntity(context, "adx_contact_caseaccess") where c != null && c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid") select aa; } else { findCaseAccess = from ca in context.CreateQuery("adx_caseaccess").ToList() let c = ca.GetRelatedEntity(context, "adx_contact_caseaccess") let a = ca.GetRelatedEntity(context, "adx_account_caseaccess") where c != null && c.GetAttributeValue <Guid>("contactid") == contact.GetAttributeValue <Guid>("contactid") && a != null && a.GetAttributeValue <Guid>("accountid") == parentCustomerAccount.GetAttributeValue <Guid>("accountid") select ca; } return(findCaseAccess.FirstOrDefault()); }
private static void CleanOtherAttributesValue(Entity inputData, Entity preImage = null) { var type = inputData.Contains("mctools_valuetype") ? inputData.GetAttributeValue <OptionSetValue>("mctools_valuetype").Value : preImage?.GetAttributeValue <OptionSetValue>("mctools_valuetype")?.Value ?? -1; switch (type) { case 1: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; break; case 2: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_textvalue"] = null; break; case 3: inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; case 4: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; case 5: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; case 6: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; case 7: inputData["mctools_boolvalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; case 8: inputData["mctools_boolvalue"] = null; inputData["mctools_datevalue"] = null; inputData["mctools_decimalvalue"] = null; inputData["mctools_floatvalue"] = null; inputData["mctools_integervalue"] = null; inputData["mctools_memovalue"] = null; inputData["mctools_textvalue"] = null; break; } }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); OrganizationServiceContext ctx = new OrganizationServiceContext(service); FaultException ex1 = new FaultException(); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { Entity entity = (Entity)context.InputParameters["Target"]; var entityName = entity.LogicalName; QueryExpression qe = new QueryExpression("fp_preventduplicatefield"); qe.Criteria.AddCondition("fp_name", ConditionOperator.Equal, entityName); qe.ColumnSet = new ColumnSet("fp_fieldnames"); var fieldNames = service.RetrieveMultiple(qe).Entities.First().GetAttributeValue <string>("fp_fieldnames"); char[] comma = { ',' }; var fieldNameArr = fieldNames.Split(comma).ToList(); //var publisherPrefix = entityName.Split('_')[0] + "_"; QueryExpression qe1 = new QueryExpression(); qe1.EntityName = entityName; qe1.ColumnSet = new ColumnSet(); foreach (string fieldName in fieldNameArr) { string fn = fieldName.Trim(); qe1.ColumnSet.AddColumn(fn); //MUST ADD IMAGE AT SOME POINT if (context.MessageName.ToUpper() == "UPDATE") { var thisEntity = service.Retrieve(entityName, entity.Id, new ColumnSet(fn)); // throw new InvalidPluginExecutionException(thisEntity.Attributes[fn].ToString(), ex1); if (thisEntity.Attributes[fn] is EntityReference) { qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, thisEntity.GetAttributeValue <EntityReference>(fn).Id); } if (thisEntity.Attributes[fn] is string) { qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, thisEntity.GetAttributeValue <string>(fn)); } } else { if (entity.Attributes[fn] is EntityReference) { qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, entity.GetAttributeValue <EntityReference>(fn).Id); } if (entity.Attributes[fn] is string) { qe1.Criteria.AddCondition(fn, ConditionOperator.Equal, entity.GetAttributeValue <string>(fn)); } } } if (service.RetrieveMultiple(qe1).Entities.Count() > 1) { throw new InvalidPluginExecutionException("You cannot add a duplicate record", ex1); } } }
public void Execute(IServiceProvider serviceProvider) { var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.Depth >= 2) { tracingService.Trace($"Depth of plug in {CURRENT_PLUGIN_NAME} more than 1 return. Current depth: {context.Depth}"); return; } if (context.MessageName.ToLower() != "update") { tracingService.Trace($"Context message was different than Update. It was: {context.MessageName}"); return; } try { // Delete All traces for thise plugin DeleteAllTracesForThisPlugIn(service); tracingService.Trace($"Start of plug in {CURRENT_PLUGIN_NAME}"); Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null; Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null; var preImageEmailChangeStatus = preImageEntity?.GetAttributeValue <OptionSetValue>(NEW_CHANGE_EMAIL_STATUS)?.Value; var postImageEmailChangeStatus = postImageEntity?.GetAttributeValue <OptionSetValue>(NEW_CHANGE_EMAIL_STATUS)?.Value; //CHECK if status was changed from InProcess to Confirm or RETURN if (preImageEmailChangeStatus == null || postImageEmailChangeStatus == null || preImageEmailChangeStatus != 100000001 || //InProcess postImageEmailChangeStatus != 100000002) //Confirmed { tracingService.Trace("Transiotion from InProcess to Confirmed not observed or null - return!"); return; } Entity target = null; if (context.InputParameters.Contains(TARGET_ENTITY) && context.InputParameters[TARGET_ENTITY] is Entity) { target = context.InputParameters[TARGET_ENTITY] as Entity; } var incidentId = target.Attributes[INCIDENT_ID].ToString(); // ACCOUNT OR CONTACT CHECK var incident = service.Retrieve(INCIDENT, Guid.Parse(incidentId), new ColumnSet(CUSTOMER_ID)); var customerRef = (EntityReference)incident.Attributes[CUSTOMER_ID]; Entity customer = service.Retrieve(ACCOUNT, customerRef.Id, new ColumnSet(EMAIL_ATTRIBUTE)); bool isContactInCustomer = false; // IF NULL customer try if customerid is CONTACT not ACCOUNT if (customer == null) { customer = service.Retrieve(CONTACT, customerRef.Id, new ColumnSet(EMAIL_ATTRIBUTE)); if (customer == null) { tracingService.Trace($"Customer was not retrieved from customerid: {customerRef.Id}"); return; } isContactInCustomer = true; } QueryExpression query = CreateQuery(customerRef); var entityCollection = service.RetrieveMultiple(query); var cases = new List <Entity>(); cases.AddRange(entityCollection.Entities.ToList()); tracingService.Trace($"Cases retreived: {cases.Count}"); //Create new object with the same GUID and update only fields that are needed !!! NEW OBJECT ALWAYS var caseToSolve = new Entity(INCIDENT); caseToSolve.Id = cases[0].Id; caseToSolve[NEW_CHANGE_EMAIL_STATUS] = new OptionSetValue(100000004); //Approved status of ChangeEmailStatus field caseToSolve[NEW_CHANGE_EMAIL_STATUS_REASON] = new OptionSetValue(100000002); //Approved - valid request service.Update(caseToSolve); string newMail = cases[0][NEW_TO_CHANGE_EMAIL].ToString(); //Resolve last case Entity caseResolution = new Entity(INCIDENT_RESOLUTION); caseResolution.Attributes.Add(INCIDENT_ID, new EntityReference(INCIDENT, caseToSolve.Id)); caseResolution.Attributes.Add(SUBJECT, "Parent Case has been resolved"); CloseIncidentRequest closeReq = new CloseIncidentRequest { IncidentResolution = caseResolution, RequestName = "CloseIncident", Status = new OptionSetValue(5) }; service.Execute(closeReq); tracingService.Trace($"Case Id: {caseToSolve.Id} resolved"); for (int i = 1; i < cases.Count; i++) { //Cancel all other cases var currentCase = new Entity(INCIDENT); currentCase.Id = cases[i].Id; currentCase[NEW_CHANGE_EMAIL_STATUS] = new OptionSetValue(100000003); //Declined status of ChangeEmailStatus field currentCase[NEW_CHANGE_EMAIL_STATUS_REASON] = new OptionSetValue(100000001); //Cancelled-Duplicated record service.Update(currentCase); SetStateRequest request = new SetStateRequest() { EntityMoniker = new EntityReference(INCIDENT, currentCase.Id), State = new OptionSetValue(2), Status = new OptionSetValue(6) }; service.Execute(request); tracingService.Trace($"Case Id: {currentCase.Id} closed!"); #region not Working Approach for closing casese //caseResolution = new Entity(INCIDENT_RESOLUTION); //caseResolution.Attributes.Add(INCIDENT_ID, new EntityReference(INCIDENT,currentCase.Id)); //caseResolution.Attributes.Add(SUBJECT, "Parent Case has been cancelled"); //closeReq = new CloseIncidentRequest //{ // IncidentResolution = caseResolution, // RequestName = "CancellIncident", // //Cancelled VALUE // Status = new OptionSetValue(6) //}; //This approach THROWS: //$exception { "CancellIncident#2011/Organization.svc"} //System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> //service.Execute(closeReq); #endregion } //var accountToChangeEmail = service.Retrieve("account", customer.Id, new ColumnSet(EMAIL_ATTRIBUTE)); //NEW OBJECT WITH this GUID if (isContactInCustomer) { var contact = new Entity(CONTACT); contact.Id = customer.Id; contact.Attributes[EMAIL_ATTRIBUTE] = newMail; service.Update(contact); tracingService.Trace($"Email of contact {customer.Id} was changed to {newMail}"); } else { var account = new Entity(ACCOUNT); account.Id = customer.Id; account.Attributes[EMAIL_ATTRIBUTE] = newMail; service.Update(account); tracingService.Trace($"Email of account {customer.Id} was changed to {newMail}"); } } catch (InvalidPluginExecutionException ex) { tracingService.Trace($"Exception: {ex.Message}"); throw new InvalidPluginExecutionException(ex.Message); } }
public void Execute(IServiceProvider serviceProvider) { int step = 0; IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); Entity leadEntity = (Entity)context.InputParameters["Target"]; if (leadEntity.LogicalName != "lead") { return; } try { IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId); //convert field type to bool & check bool isprimarylead = leadEntity.GetAttributeValue <bool>("fdx_primarylead"); EntityCollection contextLeadCollection; if (isprimarylead == true) { step = 0; //fetch groupid of context lead QueryExpression contextLeadQuery = new QueryExpression(); contextLeadQuery.EntityName = "lead"; contextLeadQuery.ColumnSet = new ColumnSet("fdx_groupid"); contextLeadQuery.Criteria.AddCondition("leadid", ConditionOperator.Equal, leadEntity.Id); contextLeadCollection = service.RetrieveMultiple(contextLeadQuery); step = 1; if (contextLeadCollection.Entities.Count > 0) { Entity contextLead = contextLeadCollection[0]; //fetch all leads with similar group id QueryExpression connectedLeadsQuery = new QueryExpression(); connectedLeadsQuery.EntityName = "lead"; connectedLeadsQuery.ColumnSet = new ColumnSet("fdx_groupid", "fdx_primarylead");//add the group ID attribute*** connectedLeadsQuery.Criteria.AddFilter(LogicalOperator.And); connectedLeadsQuery.Criteria.AddCondition("fdx_groupid", ConditionOperator.Equal, contextLead.Attributes["fdx_groupid"]); connectedLeadsQuery.Criteria.AddCondition("leadid", ConditionOperator.NotEqual, contextLead.Id); EntityCollection connectedLeadsCollection = service.RetrieveMultiple(connectedLeadsQuery); step = 2; if (connectedLeadsCollection.Entities.Count > 0) { //Loop through connected Leads //for (int i = 0; i < connectedLeadsCollection.Entities.Count; i++) foreach (Entity connectedLead in connectedLeadsCollection.Entities) { //Entity connectedLead = connectedLeadsCollection[i]; if (connectedLead.Attributes.Contains("fdx_primarylead") && (bool)connectedLead.Attributes["fdx_primarylead"] == true) { connectedLead.Attributes["fdx_primarylead"] = false; service.Update(connectedLead); } else if (!connectedLead.Attributes.Contains("fdx_primarylead")) { connectedLead.Attributes["fdx_primarylead"] = false; service.Update(connectedLead); } } } } } } catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException("An error occurred while setting primary lead. " + ex.Message); } catch (Exception ex) { tracingService.Trace("Lead_update: {0}", ex.ToString()); throw; } } }