protected void OnItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e) { var opportunity = XrmContext.CreateQuery("opportunity").First(o => o.GetAttributeValue <Guid>("opportunityid") == e.EntityId); var opportunityProductsFromLead = opportunity.GetAttributeValue <string>("adx_opportunityproductsfromlead"); var productsList = new List <Entity>(); if (!string.IsNullOrEmpty(opportunityProductsFromLead)) { var products = XrmContext.CreateQuery("product"); var words = opportunityProductsFromLead.Split(','); foreach (var word in words) { foreach (var product in products) { if (product.GetAttributeValue <string>("name").Trim().ToUpper() == word.Trim().ToUpper()) { productsList.Add(product); } } } } foreach (var leadProduct in productsList) { if (!XrmContext.IsAttached(leadProduct)) { XrmContext.Attach(leadProduct); } XrmContext.AddLink(opportunity, new Relationship("adx_opportunity_product"), leadProduct); } opportunity.SetAttributeValue("adx_referencecode", GetOpportunityReferenceCode()); var salesStage = opportunity.GetAttributeValue <OptionSetValue>("salesstagecode") == null ? 0 : opportunity.GetAttributeValue <OptionSetValue>("salesstagecode").Value; var response = (RetrieveAttributeResponse)ServiceContext.Execute(new RetrieveAttributeRequest { EntityLogicalName = "opportunity", LogicalName = "salesstagecode" }); var picklist = response.AttributeMetadata as PicklistAttributeMetadata; if (picklist == null) { return; } foreach (var option in picklist.OptionSet.Options) { if (option != null && option.Value != null && option.Value.Value == salesStage) { opportunity.SetAttributeValue("stepname", option.Label.GetLocalizedLabelString()); } } var leadType = XrmContext.CreateQuery("adx_leadtype").FirstOrDefault(lt => lt.GetAttributeValue <string>("adx_name") == "Partner Created"); if (leadType != null) { opportunity.SetAttributeValue("adx_leadtypeid", leadType.ToEntityReference()); } XrmContext.UpdateObject(opportunity); XrmContext.SaveChanges(); var url = GetUrlForRequiredSiteMarker("Accepted Opportunities"); Response.Redirect(url); }