public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.MessageName.ToLower() != "create" || context.PrimaryEntityName != SalesOrder.EntityLogicalName) return; using (var orgContext = new OrganizationServiceContext(service)) { var order = (Entity)context.InputParameters["Target"]; var neworder = order.ToEntity<SalesOrder>(); var constanta = (from i in orgContext.CreateQuery<new_constant>() select i).FirstOrDefault(); var user = (from i in orgContext.CreateQuery<SystemUser>() where i.Id == order.GetAttributeValue<EntityReference>("ownerid").Id select i).FirstOrDefault(); StringBuilder nomer = new StringBuilder(); nomer.Append(string.Format("{0}-{1}/СЛГУ-{2}", constanta.new_salesordernumber, DateTime.Now.Year.ToString(), user.new_abbreviation)); //var updateOrder = new SalesOrder(){ // Id = order.Id, // OrderNumber = //} neworder.new_ordernumber = nomer.ToString(); var updateConstanta = new new_constant() { Id = constanta.Id, new_salesordernumber = (Convert.ToInt32(constanta.new_salesordernumber) + 1).ToString() }; service.Update(updateConstanta); orgContext.SaveChanges(); } } catch (Exception) { throw; } }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); OrganizationServiceContext orgContext = new OrganizationServiceContext(service); if (context.MessageName.ToLower() == "create") { try { Entity entity = null; entity = (Entity)context.InputParameters["Target"]; //Entity preMessageImage = (Entity)context.PreEntityImages["Target"]; if (entity.GetAttributeValue<EntityReference>("productid") == null) return; var productId = entity.GetAttributeValue<EntityReference>("productid").Id; var productPrice = (from p in orgContext.CreateQuery("product") where p.GetAttributeValue<Guid>("productid") == productId select new Proxy { Price = p.GetAttributeValue<Money>("standardcost"), Currency = p.GetAttributeValue<EntityReference>("transactioncurrencyid") } ).FirstOrDefault(); if (productPrice == null) { return; } var currencyUSD = (from i in orgContext.CreateQuery("sl_exchangerate") where i.GetAttributeValue<EntityReference>("sl_transactioncurrencyid").Id == productPrice.Currency.Id && i.GetAttributeValue<OptionSetValue>("statecode") == new OptionSetValue(0) select i.GetAttributeValue<decimal>("sl_exchangerate")).FirstOrDefault(); decimal currentPrice = (productPrice.Price.Value * currencyUSD) + (productPrice.Price.Value * currencyUSD) * (decimal)0.03; Entity UpdateEntity = new Entity(entity.LogicalName); UpdateEntity.Id = entity.Id; UpdateEntity.Attributes.Add("new_usdprice", currentPrice); service.Update(UpdateEntity); } catch(Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.MessageName.ToLower() != "create" || context.PrimaryEntityName != Invoice.EntityLogicalName) return; using (var orgContext = new OrganizationServiceContext(service)) { var invoice = (Entity)context.InputParameters["Target"]; var newinvoice = invoice.ToEntity<Invoice>(); if (newinvoice.Name != null && !newinvoice.Name.Contains("СЛГУ")) { return; } var constanta = (from i in orgContext.CreateQuery<new_constant>() select i).FirstOrDefault(); var userAbbreviation = (from i in orgContext.CreateQuery<SystemUser>() where i.Id == newinvoice.OwnerId.Id select i.new_abbreviation).FirstOrDefault(); StringBuilder nomer = new StringBuilder(); nomer.Append(string.Format("{0}{1}-1", userAbbreviation, constanta.new_invoicenumder)); newinvoice.Name = nomer.ToString(); var updateConstanta = new new_constant() { Id = constanta.Id, new_invoicenumder = (Convert.ToInt32(constanta.new_invoicenumder) + 1).ToString() }; service.Update(updateConstanta); orgContext.SaveChanges(); } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); OrganizationServiceContext orgContext = new OrganizationServiceContext(service); ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); if (context.MessageName.ToLower() == "create") { Entity entity = null; entity = (Entity)context.InputParameters["Target"]; var constanta = (from p in orgContext.CreateQuery("new_constant") select p).FirstOrDefault(); string current_number = String.Format("SL-P-{0}", constanta.GetAttributeValue<String>("new_dogovor").ToString()); entity.Attributes.Add("new_agreem_number", current_number); service.Update(entity); Entity con = new Entity("new_constant"); con.Id = constanta.Id; con.Attributes.Add("new_dogovor", (Convert.ToInt32(constanta.GetAttributeValue<String>("new_dogovor").ToString()) + 1).ToString()); service.Update(con); } }
private void PurchaseDealUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service) { List<new_purchase_deal> _cdealListForUpdate = (from i in orgContext.CreateQuery<new_purchase_deal>() where i.new_cropid.Id == _proxyentity.new_cropid.Id && (i.new_purchase_deal_stage == new OptionSetValue(100000000) || i.new_purchase_deal_stage == new OptionSetValue(100000002) || i.new_purchase_deal_stage == new OptionSetValue(100000001)) && i.new_opportunity_status == new OptionSetValue(100000000) select i).ToList(); foreach ( var item in _cdealListForUpdate ) { new_purchase_deal _updateDeal = new new_purchase_deal(); _updateDeal.Id = item.Id; if ( item.new_ship_portid == null ) continue; if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Одеса" ) { _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_odessa; } else if ( _portList.Where(x => x.Id == item.new_ship_portid.Id)?.FirstOrDefault()?.new_name == "Миколаїв" ) { _updateDeal.new_recommended_price = _proxyentity.new_recom_purchase_price_nikolaev; } service.Update(_updateDeal); } }
public void CheckSalesOrderToday() { using (var orgContext = new OrganizationServiceContext(service)) { var correntSales = (from c in orgContext.CreateQuery<SalesOrder>() where c.new_Termagreement >= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 00:00:00")).ToUniversalTime() && c.new_Termagreement <= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 23:59:59")).ToUniversalTime() && (c.new_articipationof == new OptionSetValue(100000000) || c.new_participationlaw == new OptionSetValue(100000000) || c.new_participationlo == new OptionSetValue(100000000) || c.new_participationob == new OptionSetValue(100000000) || c.new_participationsp == new OptionSetValue(100000000)) select new ProxyToSendEmailExtended { recordId = c.Id, Name = c.Name, agreementLaw = (c.new_agreedlaw == false && Equals(c.new_participationlaw, new OptionSetValue(100000000))) ? c.new_lawdepartment : null, agreementLog = (c.new_agreedlog == false && Equals(c.new_participationlo, new OptionSetValue(100000000))) ? c.new_logistics : null, agreementFin = (c.new_agreed == false && Equals(c.new_articipationof, new OptionSetValue(100000000))) ? c.new_financedepartment : null, agreementAc = (c.new_agreed_ac == false && Equals(c.new_participationob, new OptionSetValue(100000000))) ? c.new_accountant : null, agreementSd = (c.new_agreed_sd == false && Equals(c.new_participationsp, new OptionSetValue(100000000))) ? c.new_salesdepartment : null }).ToList(); SendEmail(correntSales, service, 1); } }
public List<Entity> GetRoles() { OrganizationServiceContext org = new OrganizationServiceContext(service); return (from role in org.CreateQuery("role") select new Entity("role") { Id = role.Id }).ToList(); }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.PrimaryEntityName != new_paymentprovider.EntityLogicalName || context.MessageName.ToLower() != "create") return; using (var orgContext = new OrganizationServiceContext(service)) { var PaymentProvaider = (Entity)context.InputParameters["Target"]; var PaymentProvaiderCurrent = PaymentProvaider.ToEntity<new_paymentprovider>(); //new_paymentsprovider if (PaymentProvaiderCurrent.new_invoice == null || PaymentProvaiderCurrent.new_provider == null) return; var listProductInvoice = (from i in orgContext.CreateQuery<InvoiceDetail>() where i.InvoiceId.Id == PaymentProvaiderCurrent.new_invoice.Id && i.new_provider.Id == PaymentProvaiderCurrent.new_provider.Id select i).ToList(); if (listProductInvoice == null) return; foreach (var item in listProductInvoice) { service.Create(new new_paymentsprovider() { new_isproductoverridden = item.IsProductOverridden, new_productid = item.ProductId, new_productdescription = item.ProductDescription, new_numberorderatthesupplier = item.new_Numberorderatthesupplier, new_manufacturer = item.new_manufacturer, TransactionCurrencyId = item.TransactionCurrencyId, new_purchaseprice = item.new_purchaseprice, new_amountpurchase = item.new_amountpurchase, new_pricepurchaseusd = item.new_pricepurchaseusd, new_totalpurchaseusd = item.new_totalpurchaseusd, new_quantity = item.Quantity, new_paymentprovider = PaymentProvaiderCurrent.ToEntityReference(), new_provider = item.new_provider, new_nds = item.new_nds }); } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
public void Execute(IServiceProvider serviceProvider) { var context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); var factory = (IOrganizationServiceFactory) serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = factory.CreateOrganizationService(context.UserId); Entity _correntEntity; using ( var orgContext = new OrganizationServiceContext(service) ) { if ( context.MessageName.ToLower() == "create" ) { _correntEntity = (Entity) context.InputParameters["Target"]; } else if ( context.MessageName.ToLower() == "update" ) { _correntEntity = context.PostEntityImages["Post"]; } else { return; } new_aprove_price _proxyentity = _correntEntity.ToEntity<new_aprove_price>(); if ( _proxyentity.new_cropid == null || _proxyentity.new_approve == false ) { return; } if ( _proxyentity.new_recom_purchase_price_nikolaev == null && _proxyentity.new_recom_purchase_price_odessa == null ) { return; } List<new_port> _portList = (from port in orgContext.CreateQuery<new_port>() where port.new_name == "Одеса" || port.new_name == "Миколаїв" select port).ToList(); PurchaseOrderUpdateMethod(_proxyentity, _portList, orgContext, service); PurchaseTaskUpdateMethod(_proxyentity, _portList, orgContext, service); PurchaseCropUpdateMethod(_proxyentity, _portList, orgContext, service); PurchaseDealUpdateMethod(_proxyentity, _portList, orgContext, service); } }
private void PurchaseCropUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service) { List<Guid> _cropListForUpdate = (from i in orgContext.CreateQuery<new_purchase_crop>() where i.new_crop.Id == _proxyentity.new_cropid.Id && i.new_offer_status == new OptionSetValue(100000000) select i.Id).ToList(); foreach ( var item in _cropListForUpdate ) { new_purchase_crop _updateCrop = new new_purchase_crop(); _updateCrop.Id = item; _updateCrop.new_recom_price_mykolaiv = _proxyentity.new_recom_purchase_price_nikolaev; _updateCrop.new_recom_price_odesa = _proxyentity.new_recom_purchase_price_odessa; service.Update(_updateCrop); } }
public bool CreateInvoiceDetail(ExcelProxyInvoiceDetail invoicedetail, EntityReference product) { using (var orgContext = new OrganizationServiceContext(service)) { var newinvoiceeDetail = new InvoiceDetail() { ProductId = product, IsPriceOverridden = true, Quantity = Convert.ToInt32(invoicedetail.Count), PricePerUnit = new Money(Convert.ToDecimal(invoicedetail.Priceperunit)), new_purchaseprice = new Money(Convert.ToDecimal(invoicedetail.Purchaseprice)), new_amountpurchase = new Money(Convert.ToDecimal(invoicedetail.Amountpurchase)), new_pricepurchaseusd = Convert.ToDouble(invoicedetail.Pricepurchaseusd), InvoiceId = mainEntityId, new_kursspeka = Convert.ToDouble(invoicedetail.Exchangerates), new_viborkurs = new OptionSetValue(100000003), new_totalpurchaseusd = Convert.ToDouble(invoicedetail.totalUSD), UoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault() }; try { service.Create(newinvoiceeDetail); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } return true; }
public void CheckInvoiceToday() { using (var orgContext = new OrganizationServiceContext(service)) { var correntInvoice = (from c in orgContext.CreateQuery<Invoice>() where (c.PaymentTermsCode.Value == 34 || c.PaymentTermsCode.Value == 35) && c.DueDate >= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 00:00:00")).ToUniversalTime() && c.DueDate <= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yyyy 23:59:59")).ToUniversalTime() && (c.new_agreedlogistician == false || c.new_agreedCFO == false || c.new_agreedlawyer == false) select new ProxyToSendEmail { recordId = c.Id, Name = c.Name, agreementLaw = c.new_agreedlawyer == false ? c.new_lawyer : null, agreementLog = c.new_agreedlogistician == false ? c.new_Logist : null, agreementFin = c.new_agreedCFO == false ? c.new_CSO : null }).ToList(); SendEmail(correntInvoice, service, 1); } }
public void Monitoring() { try { using (var orgContext = new OrganizationServiceContext(service)) { List<MonitoringColection> listRecords; List<Product> CultivationColection = GetProductFromCRM(orgContext); List<TopCollection> TopSelected; listRecords = (from i in orgContext.CreateQuery<new_monitoring>() where i.statecode == new_monitoringState.Active select new MonitoringColection { MonitoringRecordId = i.Id, PriceOfNikolaev = i.new_purchase_price_nikolaev, PriceOfOdessa = i.new_purchase_price_odessa, Cultivation = i.new_cropid }).ToList(); if (listRecords.Count == 0 || CultivationColection.Count == 0) return; foreach (var item in CultivationColection) { } // TopPriceOddesa = new TopCollection { TopPrice = listRecords.Max(x => x.PriceOfOdessa), MonitoringRecordId = listRecords.Max(x => x.MonitoringRecordId) }; //TopPriceNIkolaev = new TopCollection { TopPrice = listRecords.Max(x => x.PriceOfNikolaev), MonitoringRecordId = listRecords.Max(x => x.MonitoringRecordId) }; } } catch (InvalidPluginExecutionException ex) { throw new InvalidPluginExecutionException(ex.Message); } }
private Guid CreateNextOpportunityStageForOpportunity(Entity opportunityRecord, LocalPluginContext localContext, OrganizationServiceContext orgSvcContext, IOrganizationService service) { localContext.TracingService.Trace("---------Entering CreateNextOpportunityStageForOpportunity()---------"); if (opportunityRecord == null) { localContext.TracingService.Trace("The variable opportunityRecord is null. Cannot create opportunity stage without an associated opportunity. Exiting Plugin."); throw new ArgumentNullException("opportunityRecord"); } Entity entity = new Entity("msnfp_opportunitystage"); Entity latestOpportunityStageForThisOpportunity = GetLatestOpportunityStageForThisOpportunity(opportunityRecord.Id, localContext, orgSvcContext); if (latestOpportunityStageForThisOpportunity == null) { localContext.TracingService.Trace("Error: There is no last opportunity stage but one was attempted to be retrieved. Exiting plugin."); throw new ArgumentNullException("lastOpportunityStage"); } localContext.TracingService.Trace("Updating opportunity stage name: " + (string)latestOpportunityStageForThisOpportunity["msnfp_stagename"]); string[] array = ((string)opportunityRecord["stepname"]).Split('-'); string text = ""; text = ((array.Length > 1) ? array[1] : ((string)opportunityRecord["stepname"])); localContext.TracingService.Trace("Pipeline Step Name: " + text); if (text == (string)latestOpportunityStageForThisOpportunity["msnfp_stagename"]) { localContext.TracingService.Trace("Stage names are both: " + text); } localContext.TracingService.Trace("Getting Appointments"); DateTime started = (latestOpportunityStageForThisOpportunity.Attributes.ContainsKey("msnfp_startedon") ? latestOpportunityStageForThisOpportunity.GetAttributeValue <DateTime>("msnfp_startedon") : DateTime.Now); List <Guid> list = (from s in orgSvcContext.CreateQuery("appointment") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Appointments: " + list.Count); localContext.TracingService.Trace("Getting Emails"); List <Guid> list2 = (from s in orgSvcContext.CreateQuery("email") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Emails: " + list2.Count); localContext.TracingService.Trace("Getting Letters"); List <Guid> list3 = (from s in orgSvcContext.CreateQuery("letter") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Letters: " + list3.Count); localContext.TracingService.Trace("Getting Phonecalls"); List <Guid> list4 = (from s in orgSvcContext.CreateQuery("phonecall") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Phonecalls: " + list4.Count); localContext.TracingService.Trace("Getting Tasks"); List <Guid> list5 = (from s in orgSvcContext.CreateQuery("task") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Tasks: " + list5.Count); latestOpportunityStageForThisOpportunity["msnfp_finishedon"] = DateTime.UtcNow; if (latestOpportunityStageForThisOpportunity.Attributes.ContainsKey("msnfp_startedon")) { localContext.TracingService.Trace("Days in stage: " + Math.Round((DateTime.Now - (DateTime)latestOpportunityStageForThisOpportunity["msnfp_startedon"]).TotalDays, MidpointRounding.AwayFromZero)); latestOpportunityStageForThisOpportunity["msnfp_daysinstage"] = (int)Math.Round((DateTime.Now - (DateTime)latestOpportunityStageForThisOpportunity["msnfp_startedon"]).TotalDays, MidpointRounding.AwayFromZero); } latestOpportunityStageForThisOpportunity["msnfp_appointments"] = list.Count; latestOpportunityStageForThisOpportunity["msnfp_emails"] = list2.Count; latestOpportunityStageForThisOpportunity["msnfp_letters"] = list3.Count; latestOpportunityStageForThisOpportunity["msnfp_phonecalls"] = list4.Count; latestOpportunityStageForThisOpportunity["msnfp_tasks"] = list5.Count; latestOpportunityStageForThisOpportunity["msnfp_totalactivities"] = list.Count + list2.Count + list3.Count + list4.Count + list5.Count; localContext.TracingService.Trace("Saving changes to previous stage: " + (string)latestOpportunityStageForThisOpportunity["msnfp_stagename"]); orgSvcContext.UpdateObject(latestOpportunityStageForThisOpportunity); orgSvcContext.SaveChanges(); localContext.TracingService.Trace("Update complete. Previous Stage End Date: " + DateTime.Now.ToString()); localContext.TracingService.Trace("Creating New Opportunity Stage with name: " + text); entity["msnfp_stagename"] = text; entity["msnfp_identifier"] = text + " - " + DateTime.Now.ToShortDateString(); entity["msnfp_startedon"] = DateTime.Now; entity["msnfp_appointments"] = 0; entity["msnfp_emails"] = 0; entity["msnfp_letters"] = 0; entity["msnfp_phonecalls"] = 0; entity["msnfp_tasks"] = 0; entity["msnfp_totalactivities"] = 0; entity["msnfp_opportunityid"] = new EntityReference("opportunity", opportunityRecord.Id); Guid result = service.Create(entity); localContext.TracingService.Trace("Opportunity Stage created with Id: " + result.ToString()); localContext.TracingService.Trace("---------Exiting CreateNextOpportunityStageForOpportunity()---------"); return(result); }
/// <summary> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered UpdateFXs.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace("UpdateFXs.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); string serviceBaseCurrency = "RUB"; using (var ctx = new OrganizationServiceContext(service)) { try { // Get exchange rates DailyInfo client = new DailyInfo(); tracingService.Trace("Getting Most recent date available"); DateTime lastestDate = client.GetLatestDateTime(); tracingService.Trace("Getting FX Rates"); var exchangeRates = client.GetCursOnDateXML(lastestDate); string baseCurrencyISO = string.Empty; Guid empty = Guid.Empty; var baseCurrency = (from c in ctx.CreateQuery <TransactionCurrency>() join o in ctx.CreateQuery <Organization>() on c.TransactionCurrencyId equals o.BaseCurrencyId.Id select new TransactionCurrency { TransactionCurrencyId = c.TransactionCurrencyId, ISOCurrencyCode = c.ISOCurrencyCode, }).FirstOrDefault(); if (baseCurrency != null) { baseCurrencyISO = baseCurrency.ISOCurrencyCode.ToUpper(); // Get the rate from service base rate to crm base currency var serviceRateToCrmBase = GetExchangeRate(baseCurrencyISO, exchangeRates); if (serviceRateToCrmBase == null) { throw new Exception(String.Format("Cannot find rate for base rate '{0}'", baseCurrencyISO)); } // Get the currencies that are not the base currency // Only update active currencies var currencies = (from c in ctx.CreateQuery <TransactionCurrency>() where c.TransactionCurrencyId != baseCurrency.TransactionCurrencyId && c.StateCode == TransactionCurrencyState.Active select new TransactionCurrency { TransactionCurrencyId = c.TransactionCurrencyId, ISOCurrencyCode = c.ISOCurrencyCode, }); foreach (TransactionCurrency currency in currencies) { string isoCode = currency.ISOCurrencyCode.ToUpper(); decimal?latestRate = null; // Get rate from service base currency to this currency decimal?serviceRate = 1; if (isoCode != serviceBaseCurrency) { serviceRate = GetExchangeRate(isoCode, exchangeRates); } if (serviceRate != null) { // Get the rate from crm base rate latestRate = serviceRateToCrmBase / serviceRate; } else { // The webserviceX currency service is no longer working - investigating alternatives // latestRate = GetStandardRate(baseCurrencyISO, isoCode); } if (latestRate != null) { // We have a new rate so update it (even if it is the same!) TransactionCurrency update = new TransactionCurrency(); update.TransactionCurrencyId = currency.TransactionCurrencyId; update.ExchangeRate = latestRate; service.Update(update); } } } } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } catch (Exception ex) { tracingService.Trace("Exception (will retry): {0}", ex.ToString()); // All exceptions must be retried since this workflow must call it's self to run on a daily basis OrganizationServiceFault fault = new OrganizationServiceFault(); fault.ErrorCode = -2147204346; // This will cause the Async Server to retry up to 10 times before failing fault.Message = ex.ToString(); var networkException = new FaultException <OrganizationServiceFault>(fault); throw networkException; } } tracingService.Trace("Exiting UpdateFXs.Execute(), Correlation Id: {0}", context.CorrelationId); }
private void UpdateExistingOpportunityStage(Entity opportunityRecord, LocalPluginContext localContext, OrganizationServiceContext orgSvcContext) { localContext.TracingService.Trace("---------Entering UpdateExistingOpportunityStage()---------"); if (opportunityRecord == null) { localContext.TracingService.Trace("The variable opportunityRecord is null. Cannot update opportunity stage without an associated opportunity. Exiting Plugin."); throw new ArgumentNullException("opportunityRecord"); } Entity latestOpportunityStageForThisOpportunity = GetLatestOpportunityStageForThisOpportunity(opportunityRecord.Id, localContext, orgSvcContext); if (latestOpportunityStageForThisOpportunity == null) { localContext.TracingService.Trace("The variable opportunityStage is null. Cannot update the opportunity stage as it is not found. Exiting Plugin."); throw new ArgumentNullException("opportunityStage"); } DateTime started = (latestOpportunityStageForThisOpportunity.Attributes.ContainsKey("msnfp_startedon") ? latestOpportunityStageForThisOpportunity.GetAttributeValue <DateTime>("msnfp_startedon") : DateTime.Now); List <Guid> list = (from s in orgSvcContext.CreateQuery("appointment") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Appointments: " + list.Count); localContext.TracingService.Trace("Getting Emails"); List <Guid> list2 = (from s in orgSvcContext.CreateQuery("email") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Emails: " + list2.Count); localContext.TracingService.Trace("Getting Letters"); List <Guid> list3 = (from s in orgSvcContext.CreateQuery("letter") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Letters: " + list3.Count); localContext.TracingService.Trace("Getting Phonecalls"); List <Guid> list4 = (from s in orgSvcContext.CreateQuery("phonecall") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Phonecalls: " + list4.Count); localContext.TracingService.Trace("Getting Tasks"); List <Guid> list5 = (from s in orgSvcContext.CreateQuery("task") where ((EntityReference)s["regardingobjectid"]).Id == opportunityRecord.Id && (DateTime)s["createdon"] >= started select s.Id).ToList(); localContext.TracingService.Trace("Got Tasks: " + list5.Count); if (latestOpportunityStageForThisOpportunity.Attributes.ContainsKey("msnfp_startedon")) { localContext.TracingService.Trace("Days in stage: " + Math.Round((DateTime.Now - (DateTime)latestOpportunityStageForThisOpportunity["msnfp_startedon"]).TotalDays, MidpointRounding.AwayFromZero)); latestOpportunityStageForThisOpportunity["msnfp_daysinstage"] = (int)Math.Round((DateTime.Now - (DateTime)latestOpportunityStageForThisOpportunity["msnfp_startedon"]).TotalDays, MidpointRounding.AwayFromZero); } latestOpportunityStageForThisOpportunity["msnfp_appointments"] = list.Count; latestOpportunityStageForThisOpportunity["msnfp_emails"] = list2.Count; latestOpportunityStageForThisOpportunity["msnfp_letters"] = list3.Count; latestOpportunityStageForThisOpportunity["msnfp_phonecalls"] = list4.Count; latestOpportunityStageForThisOpportunity["msnfp_tasks"] = list5.Count; latestOpportunityStageForThisOpportunity["msnfp_totalactivities"] = list.Count + list2.Count + list3.Count + list4.Count + list5.Count; localContext.TracingService.Trace("Opportunity statecode: " + ((OptionSetValue)opportunityRecord["statecode"]).Value); if (((OptionSetValue)opportunityRecord["statecode"]).Value != 0) { localContext.TracingService.Trace("Setting finish date to now as the opportunity status is inactive."); latestOpportunityStageForThisOpportunity["msnfp_finishedon"] = DateTime.UtcNow; } localContext.TracingService.Trace("Updating Opportunity Stage."); orgSvcContext.UpdateObject(latestOpportunityStageForThisOpportunity); orgSvcContext.SaveChanges(); localContext.TracingService.Trace("Updated Opportunity Stage."); localContext.TracingService.Trace("---------Exiting UpdateExistingOpportunityStage()---------"); }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// activity party records are created and associated with an activity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetWorkingWithActivityParties1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); // Retrieve the Contact records that we created previously. List <Contact> contacts = (from c in orgContext.CreateQuery <Contact>() where c.Address1_City == "Sammamish" select new Contact { ContactId = c.ContactId, FirstName = c.FirstName, LastName = c.LastName }).ToList <Contact>(); Console.Write("Contacts retrieved, "); // Create an Activity Party record for each Contact. var activityParty1 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[0].ContactId.Value), }; var activityParty2 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[1].ContactId.Value), }; var activityParty3 = new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contacts[2].ContactId.Value), }; Console.Write("ActivityParty instances created, "); // Create Letter Activity and set From and To fields to the // respective Activity Party entities. var letter = new Letter { RegardingObjectId = new EntityReference(Contact.EntityLogicalName, contacts[2].ContactId.Value), Subject = "Sample Letter Activity", ScheduledEnd = DateTime.Now + TimeSpan.FromDays(5), Description = @"Greetings, Mr. Andreshak, This is a sample letter activity as part of the Microsoft Dynamics CRM SDK. Sincerely, Mary Kay Andersen cc: Denise Smith", From = new ActivityParty[] { activityParty1 }, To = new ActivityParty[] { activityParty3, activityParty2 } }; orgContext.AddObject(letter); orgContext.SaveChanges(); Console.WriteLine("and Letter Activity created."); DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithActivityParties1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void PurchaseOrderUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service) { List<new_purchase_order> _orderListForUpdate = (from i in orgContext.CreateQuery<new_purchase_order>() where i.new_cropid.Id == _proxyentity.new_cropid.Id && (i.new_status == new OptionSetValue(100000000) || i.new_status == new OptionSetValue(100000001)) select i).ToList(); if ( _orderListForUpdate != null ) { foreach ( var item in _orderListForUpdate ) { new_purchase_order_change _newChangeOrder = new new_purchase_order_change(); _newChangeOrder.new_cropid = item.new_cropid; _newChangeOrder.new_purchase_price = item.new_purchase_price; _newChangeOrder.new_purchase_order = new EntityReference() { Id = item.Id, LogicalName = item.LogicalName }; service.Create(_newChangeOrder); new_purchase_order _updateOrder = new new_purchase_order(); _updateOrder.Id = item.Id; if ( item.new_portid == null ) continue; if ( _portList.Where(x => x.Id == item.new_portid.Id).FirstOrDefault().new_name == "Одеса" ) { _updateOrder.new_purchase_price = _proxyentity.new_recom_purchase_price_odessa; } else if ( _portList.Where(x => x.Id == item.new_portid.Id).FirstOrDefault().new_name == "Миколаїв" ) { _updateOrder.new_purchase_price = _proxyentity.new_recom_purchase_price_nikolaev; } service.Update(_updateOrder); } } }
protected static IQueryable <Entity> SelectActiveCartsInWebsite(OrganizationServiceContext serviceContext, EntityReference website) { return(serviceContext.CreateQuery("adx_shoppingcart") .Where(e => e.GetAttributeValue <EntityReference>("adx_websiteid") == website) .Where(e => e.GetAttributeValue <OptionSetValue>("statecode") != null && e.GetAttributeValue <OptionSetValue>("statecode").Value == 0)); }
protected override bool TryCreateHandler(OrganizationServiceContext context, string logicalName, Guid id, out IHttpHandler handler) { if (string.Equals(logicalName, "annotation", StringComparison.InvariantCulture)) { var annotation = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>("annotationid") == id); if (annotation != null) { var regarding = annotation.GetAttributeValue <EntityReference>("objectid"); if (regarding != null && string.Equals(regarding.LogicalName, "knowledgearticle", StringComparison.InvariantCulture)) { // Access to a note associated to a knowledge article requires the CMS Security to grant read of the annotation and the related knowledge article. // Additionally, if CAL or Product filtering is enabled and the CAL and/or Product providers reject access to the knowledge article // then access to the note is denied. If CAL and Product filtering are NOT enabled or CAL and/or Product Provider assertion passed, // we must continue to check the Entity Permissions. If the Entity Permission Provider grants read to the knowledge article then the // note can be accessed, otherwise access will be denied. // Assert CMS Security on the annotation and knowledge article. if (TryAssertByCrmEntitySecurityProvider(context, annotation.ToEntityReference()) && TryAssertByCrmEntitySecurityProvider(context, regarding)) { // Assert CAL and/or Product Filtering if enabled. var contentAccessLevelProvider = new ContentAccessLevelProvider(); var productAccessProvider = new ProductAccessProvider(); if (contentAccessLevelProvider.IsEnabled() || productAccessProvider.IsEnabled()) { if (!AssertKnowledgeArticleCalAndProductFiltering(annotation, context, contentAccessLevelProvider, productAccessProvider)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}"); handler = null; return(false); } } // Assert Entity Permissions on the knowledge article. if (TryAssertByCrmEntityPermissionProvider(context, regarding)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was granted. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}"); handler = CreateAnnotationHandler(annotation); return(true); } } ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}"); handler = null; return(false); } // Assert CMS security on the regarding entity or assert entity permission on the annotation and the regarding entity. if (TryAssertByCrmEntitySecurityProvider(context, regarding) || TryAssertByCrmEntityPermissionProvider(context, annotation, regarding)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was granted. Id={id} RegardingId={regarding?.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding?.LogicalName)}"); handler = CreateAnnotationHandler(annotation); return(true); } } } if (string.Equals(logicalName, "salesliteratureitem", StringComparison.InvariantCulture)) { var salesliteratureitem = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>("salesliteratureitemid") == id); if (salesliteratureitem != null) { //Currently salesliteratureitem.iscustomerviewable is not exposed to CRM UI, therefore get the parent and check visibility. //var isCustomerViewable = salesliteratureitem.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault(); var salesliterature = context.CreateQuery("salesliterature") .FirstOrDefault( e => e.GetAttributeValue <Guid>("salesliteratureid") == salesliteratureitem.GetAttributeValue <EntityReference>("salesliteratureid").Id); if (salesliterature != null) { var isCustomerViewable = salesliterature.GetAttributeValue <bool?>("iscustomerviewable").GetValueOrDefault(); if (isCustomerViewable) { handler = CreateSalesAttachmentHandler(salesliteratureitem); return(true); } } } } if (string.Equals(logicalName, "sharepointdocumentlocation", StringComparison.InvariantCulture)) { var location = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>("sharepointdocumentlocationid") == id); if (location != null) { var httpContext = HttpContext.Current; var regardingId = location.GetAttributeValue <EntityReference>("regardingobjectid"); // assert CMS access to the regarding entity or assert entity permission on the entity if (TryAssertByCrmEntitySecurityProvider(context, regardingId) || TryAssertByCrmEntityPermissionProvider(context, location, location.GetAttributeValue <EntityReference>("regardingobjectid"))) { var locationUrl = context.GetDocumentLocationUrl(location); var fileName = httpContext.Request["file"]; // Ensure safe file URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | } fileName = Regex.Replace(fileName, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)", string.Empty); // also removes solidus var folderPath = httpContext.Request["folderPath"]; Uri sharePointFileUrl; if (!string.IsNullOrWhiteSpace(folderPath)) { // Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | } folderPath = Regex.Replace(folderPath, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty).Trim('/'); sharePointFileUrl = new Uri("{0}/{1}/{2}".FormatWith(locationUrl.OriginalString, folderPath, fileName)); } else { sharePointFileUrl = new Uri("{0}/{1}".FormatWith(locationUrl.OriginalString, fileName)); } handler = CreateSharePointFileHandler(sharePointFileUrl, fileName); return(true); } if (!httpContext.Request.IsAuthenticated) { httpContext.Response.ForbiddenAndEndResponse(); } else { // Sending Forbidden gets caught by the Application_EndRequest and throws an error trying to redirect to the Access Denied page. // Send a 404 instead with plain text indicating Access Denied. httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; httpContext.Response.ContentType = "text/plain"; httpContext.Response.Write("Access Denied"); httpContext.Response.End(); } } } if (string.Equals(logicalName, "activitymimeattachment", StringComparison.InvariantCulture)) { var attachment = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue <Guid>("attachmentid") == id); if (attachment != null) { // retrieve the parent object for the annoation var objectId = attachment.GetAttributeValue <EntityReference>("objectid"); // assert CMS access to the regarding entity or assert entity permission on the entity if (TryAssertByCrmEntitySecurityProvider(context, objectId) || TryAssertByCrmEntityPermissionProvider(context, attachment, attachment.GetAttributeValue <EntityReference>("objectid"))) { handler = CreateActivityMimeAttachmentHandler(attachment); return(true); } } } handler = null; return(false); }
private static IQueryable <Entity> CreateProductEntityQuery(EntityReference subject, OrganizationServiceContext serviceContext) { return(serviceContext.CreateQuery("product") .Where(product => product.GetAttributeValue <EntityReference>("subjectid") == subject) .Where(product => product.GetAttributeValue <OptionSetValue>("statecode") != null && product.GetAttributeValue <OptionSetValue>("statecode").Value == (int)ProductState.Active)); }
public EntityReference ProductFromSpec(ExcelProxyProduct product) { using (var orgContext = new OrganizationServiceContext(service)) { var finder = (from c in orgContext.CreateQuery<Product>() where c.ProductNumber == product.SKU select c).FirstOrDefault(); if (finder != null) { var entityProduct = new Product() { Id = finder.Id, ProductNumber = product.SKU, Name = product.Product, Price = new Money(Convert.ToDecimal(product.recomendetPriceUSD)), DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>() where i.Name == "Единица измерения по умолчанию" // where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF")//Единица измерения по умолчанию name select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") //Базовая единица select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturer = findVendor(product.Vendor) }; try { service.Update(entityProduct); return new EntityReference { Id = entityProduct.Id, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }; } catch { return null; } } else { return CreateProduct(product); } } }
protected virtual IQueryable <Entity> GetSavedQueries(OrganizationServiceContext dataContext) { return(dataContext.CreateQuery("savedquery") .Where(e => e.GetAttributeValue <string>("name") == SavedQueryName && e.GetAttributeValue <int?>("statecode") == 0)); }
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)); }
/// <summary> /// Persists the Session History /// </summary> /// <param name="context">Context used to save the session history</param> /// <param name="sessionHistory">Session History object</param> public Guid PersistSessionHistory(OrganizationServiceContext context, SessionHistory sessionHistory) { if (sessionHistory == null) { return(Guid.Empty); } var webFormSession = sessionHistory.Id != Guid.Empty ? context.CreateQuery("adx_webformsession").FirstOrDefault(s => s.GetAttributeValue <OptionSetValue>("statecode") != null && s.GetAttributeValue <OptionSetValue>("statecode").Value == 0 && s.GetAttributeValue <Guid>("adx_webformsessionid") == sessionHistory.Id) : null; var addNew = webFormSession == null; if (addNew) { webFormSession = new Entity("adx_webformsession"); if (sessionHistory.WebFormId != Guid.Empty) { webFormSession.Attributes["adx_webform"] = new EntityReference("adx_webform", sessionHistory.WebFormId); } } if (sessionHistory.PrimaryRecord != null && sessionHistory.PrimaryRecord.ID != Guid.Empty) { webFormSession.Attributes["adx_primaryrecordid"] = sessionHistory.PrimaryRecord.ID.ToString(); } if (sessionHistory.CurrentStepId != Guid.Empty) { webFormSession.Attributes["adx_currentwebformstep"] = new EntityReference("adx_webformstep", sessionHistory.CurrentStepId); } if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.LogicalName)) { webFormSession.Attributes["adx_primaryrecordentitylogicalname"] = sessionHistory.PrimaryRecord.LogicalName; } if (sessionHistory.PrimaryRecord != null && !string.IsNullOrWhiteSpace(sessionHistory.PrimaryRecord.PrimaryKeyLogicalName)) { webFormSession.Attributes["adx_primaryrecordentitykeyname"] = sessionHistory.PrimaryRecord.PrimaryKeyLogicalName; } webFormSession.Attributes["adx_currentstepindex"] = sessionHistory.CurrentStepIndex; if (sessionHistory.ContactId != Guid.Empty) { webFormSession.Attributes["adx_contact"] = new EntityReference("contact", sessionHistory.ContactId); } if (sessionHistory.QuoteId != Guid.Empty) { webFormSession.Attributes["adx_quoteid"] = new EntityReference("quote", sessionHistory.QuoteId); } if (sessionHistory.SystemUserId != Guid.Empty) { webFormSession.Attributes["adx_systemuser"] = new EntityReference("systemuser", sessionHistory.SystemUserId); } if (!string.IsNullOrWhiteSpace(sessionHistory.AnonymousIdentification)) { webFormSession.Attributes["adx_anonymousidentification"] = sessionHistory.AnonymousIdentification; } webFormSession.Attributes["adx_stephistory"] = ConvertListToJsonString(sessionHistory.StepHistory); if (!string.IsNullOrWhiteSpace(sessionHistory.UserHostAddress)) { webFormSession.Attributes["adx_userhostaddress"] = sessionHistory.UserHostAddress; } if (!string.IsNullOrWhiteSpace(sessionHistory.UserIdentityName)) { webFormSession.Attributes["adx_useridentityname"] = sessionHistory.UserIdentityName; } if (addNew) { context.AddObject(webFormSession); } else { context.UpdateObject(webFormSession); } context.SaveChanges(); return(webFormSession.Id); }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate // Retrieve the system user ID of the user to impersonate. var orgContext = new OrganizationServiceContext(service); _userId = (from user in orgContext.CreateQuery <SystemUser>() where user.FullName == "Kevin Cook" select user.SystemUserId.Value).FirstOrDefault(); // To impersonate another user, set the OrganizationServiceProxy.CallerId // property to the ID of the other user. service.CallerId = _userId; // Instantiate an account object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account account = new Account { Name = "Fourth Coffee" }; // Create an account record named Fourth Coffee. _accountId = service.Create(account); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); //</snippetImpersonateWithOnBehalfOfPrivilege2> // Retrieve the account containing several of its attributes. // CreatedBy should reference the impersonated SystemUser. // CreatedOnBehalfBy should reference the running SystemUser. ColumnSet cols = new ColumnSet( "name", "createdby", "createdonbehalfby", "address1_postalcode", "lastusedincampaign"); Account retrievedAccount = (Account)service.Retrieve(Account.EntityLogicalName, _accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. service.Update(retrievedAccount); Console.Write("updated, "); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public List <MeteringPoint> GetMeteringPoints(OrganizationServiceContext serviceContext) { IQueryable <Entity> zahplunkts = serviceContext.CreateQuery(EntityNames.D_Zählpunkt); return(this.GetMeteringPointsFromEntityCollection(serviceContext, zahplunkts)); }
public static DiscountCodeValidationResult ValidateDiscountCode(OrganizationServiceContext context, Guid quoteId, string code) { var errorCode = DiscountErrorCode.Unknown; var isValid = false; var discountableQuoteProductIds = new List <Guid>(); if (string.IsNullOrWhiteSpace(code)) { var result = new DiscountCodeValidationResult { ErrorCode = DiscountErrorCode.CodeNotSpecified }; return(result); } var quote = context.CreateQuery("quote").FirstOrDefault(q => q.GetAttributeValue <Guid>("quoteid") == quoteId); if (quote == null) { var result = new DiscountCodeValidationResult { ErrorCode = DiscountErrorCode.QuoteNotFound, }; return(result); } var existingDiscountCodes = quote.GetAttributeValue <string>("adx_discountcodes") ?? string.Empty; if (existingDiscountCodes.Contains(code)) { var result = new DiscountCodeValidationResult { ErrorCode = DiscountErrorCode.AlreadyApplied, }; return(result); } var prefreightAmount = GetDecimalFromMoney(quote, "totalamountlessfreight"); if (prefreightAmount <= 0) { var result = new DiscountCodeValidationResult { ErrorCode = DiscountErrorCode.ZeroAmount, }; return(result); } var discountErrors = new List <DiscountError>(); var orderScopedDiscounts = context.CreateQuery("adx_discount") .Where( d => d.GetAttributeValue <OptionSetValue>("statecode").Value == 0 && (d.GetAttributeValue <OptionSetValue>("adx_scope") != null && d.GetAttributeValue <OptionSetValue>("adx_scope").Value == (int)DiscountScope.Order) && ((d.GetAttributeValue <DateTime?>("adx_startdate") == null || d.GetAttributeValue <DateTime?>("adx_startdate") <= DateTime.UtcNow) && (d.GetAttributeValue <DateTime?>("adx_enddate") == null || d.GetAttributeValue <DateTime?>("adx_enddate") >= DateTime.UtcNow)) && d.GetAttributeValue <string>("adx_code") == code) .ToList(); if (orderScopedDiscounts.Any()) { var discountPercentage = quote.GetAttributeValue <decimal?>("discountpercentage") ?? 0; var discountAmount = GetDecimalFromMoney(quote, "discountamount"); var newDiscountPercentage = discountPercentage; var newDiscountAmount = discountAmount; var appliedDiscounts = (from d in context.CreateQuery("adx_discount") join dq in context.CreateQuery("adx_discount_quote") on d.GetAttributeValue <Guid>("adx_discountid") equals dq.GetAttributeValue <Guid>("adx_discountid") where dq.GetAttributeValue <Guid>("quoteid") == quote.Id select d).ToList(); var newDiscounts = new List <Entity>(); foreach (var discount in orderScopedDiscounts) { var applied = appliedDiscounts.Any(d => d.GetAttributeValue <Guid>("adx_discountid") == discount.Id); if (applied) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied }); continue; } var minimumPurchaseAmount = GetDecimalFromMoney(discount, "adx_minimumpurchaseamount"); var maximumRedemptions = discount.GetAttributeValue <int?>("adx_maximumredemptions").GetValueOrDefault(0); var redemptions = discount.GetAttributeValue <int?>("adx_redemptions").GetValueOrDefault(0); var typeOption = discount.GetAttributeValue <OptionSetValue>("adx_type"); decimal percentage = 0; decimal amount = 0; if (typeOption == null) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration }); continue; } switch (typeOption.Value) { case (int)DiscountType.Percentage: percentage = discount.GetAttributeValue <decimal?>("adx_percentage") ?? 0; break; case (int)DiscountType.Amount: amount = GetDecimalFromMoney(discount, "adx_amount"); break; default: discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration }); continue; } if (minimumPurchaseAmount > 0 && prefreightAmount < minimumPurchaseAmount) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MinimumAmountNotMet }); } else if (maximumRedemptions > 0 && redemptions >= maximumRedemptions) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions }); } else { newDiscountPercentage += percentage; newDiscountAmount += amount; appliedDiscounts.Add(discount); newDiscounts.Add(discount); } } if (newDiscountPercentage != discountPercentage || newDiscountAmount != discountAmount) { isValid = true; } } if (!isValid) { // Check for valid quotedetail items var quoteDetails = context.CreateQuery("quotedetail") .Where(q => q.GetAttributeValue <EntityReference>("quoteid").Equals(quote.ToEntityReference())) .ToList(); if (quoteDetails.Any()) { var priceList = quote.GetAttributeValue <EntityReference>("pricelevelid"); var productScopeDiscounts = context.CreateQuery("adx_discount") .Where( d => d.GetAttributeValue <OptionSetValue>("statecode").Value == 0 && (d.GetAttributeValue <OptionSetValue>("adx_scope") != null && d.GetAttributeValue <OptionSetValue>("adx_scope").Value == (int)DiscountScope.Product) && ((d.GetAttributeValue <DateTime?>("adx_startdate") == null || d.GetAttributeValue <DateTime?>("adx_startdate") <= DateTime.UtcNow) && (d.GetAttributeValue <DateTime?>("adx_enddate") == null || d.GetAttributeValue <DateTime?>("adx_enddate") >= DateTime.UtcNow)) && d.GetAttributeValue <string>("adx_code") == code) .ToList(); if (!productScopeDiscounts.Any()) { var result = new DiscountCodeValidationResult { ErrorCode = DiscountErrorCode.DoesNotExist, DiscountErrors = discountErrors }; return(result); } foreach (var quotedetail in quoteDetails) { var baseAmount = GetDecimalFromMoney(quotedetail, "baseamount"); if (baseAmount <= 0) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.ZeroAmount }); continue; } var appliedDiscounts = (from d in context.CreateQuery("adx_discount") join i in context.CreateQuery("adx_discount_quotedetail") on d.GetAttributeValue <Guid>("adx_discountid") equals i.GetAttributeValue <Guid>("adx_discountid") where i.GetAttributeValue <Guid>("quotedetailid") == quotedetail.Id select d).ToList(); var newDiscounts = new List <Entity>(); var discountAmount = GetDecimalFromMoney(quotedetail, "manualdiscountamount"); var newDiscountAmount = discountAmount; foreach (var discount in productScopeDiscounts) { var applied = appliedDiscounts.Any(d => d.GetAttributeValue <Guid>("adx_discountid") == discount.Id); if (applied) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied }); continue; } var discountProductPriceLevel = (from pl in context.CreateQuery("productpricelevel") join dp in context.CreateQuery("adx_discount_productpricelevel") on pl.GetAttributeValue <Guid>("productpricelevelid") equals dp.GetAttributeValue <Guid>("productpricelevelid") where dp.GetAttributeValue <Guid>("adx_discountid") == discount.Id where pl.GetAttributeValue <EntityReference>("pricelevelid").Equals(priceList) select pl).ToList(); if (!discountProductPriceLevel.Any()) { continue; } var quotedetailid = quotedetail.Id; var quoteProductDiscounts = (from d in discountProductPriceLevel join q in context.CreateQuery("quotedetail") .Where(q => q.GetAttributeValue <Guid>("quotedetailid") == quotedetailid) on new { productid = d.GetAttributeValue <EntityReference>("productid"), uomid = d.GetAttributeValue <EntityReference>("uomid") } equals new { productid = q.GetAttributeValue <EntityReference>("productid"), uomid = q.GetAttributeValue <EntityReference>("uomid") } select q).ToList(); if (!quoteProductDiscounts.Any()) { continue; } var maximumRedemptions = discount.GetAttributeValue <int?>("adx_maximumredemptions").GetValueOrDefault(0); var redemptions = discount.GetAttributeValue <int?>("adx_redemptions").GetValueOrDefault(0); var typeOption = discount.GetAttributeValue <OptionSetValue>("adx_type"); decimal amount = 0; if (typeOption == null) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration }); continue; } switch (typeOption.Value) { case (int)DiscountType.Percentage: var percentage = discount.GetAttributeValue <decimal?>("adx_percentage") ?? 0; if (percentage > 0 && baseAmount > 0) { amount = baseAmount * percentage / 100; } break; case (int)DiscountType.Amount: amount = GetDecimalFromMoney(discount, "adx_amount"); break; default: discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration }); continue; } if (maximumRedemptions > 0 && redemptions >= maximumRedemptions) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions }); continue; } newDiscountAmount += amount; appliedDiscounts.Add(discount); newDiscounts.Add(discount); discountableQuoteProductIds.Add(quotedetail.Id); } if (newDiscountAmount == discountAmount) { continue; } isValid = true; break; } } } if (!isValid && !discountErrors.Any()) { discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.NotApplicable }); errorCode = DiscountErrorCode.NotApplicable; } return(new DiscountCodeValidationResult(isValid) { ErrorCode = errorCode, ExistingDiscountCodes = existingDiscountCodes, DiscountableQuoteProductIds = discountableQuoteProductIds.Distinct(), DiscountErrors = discountErrors }); }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = factory.CreateOrganizationService(context.UserId); if (context.MessageName == "Create") { object blok = new object(); int? number; new_constant counter = new new_constant(); Entity entity = (Entity)context.InputParameters["Target"]; string correntYear = DateTime.Now.ToString("yy"); lock (blok) { using (var orgContext = new OrganizationServiceContext(service)) { var getCounterValue = (from c in orgContext.CreateQuery <new_constant>() select c).FirstOrDefault(); switch (entity.LogicalName) { case new_purchase_order.EntityLogicalName: number = getCounterValue.new_purchase_order; counter.new_purchase_order = ++number; if (entity.Attributes.Contains("new_name") == true) { entity["new_name"] = $"{number}/{correntYear}"; } else { entity.Attributes.Add("new_name", $"{number}/{correntYear}"); } break; case new_purchase_order_change.EntityLogicalName: number = getCounterValue.new_purchase_order_change; counter.new_purchase_order_change = ++number;; if (entity.Attributes.Contains("new_name") == true) { entity["new_name"] = $"{number}/{correntYear}"; } else { entity.Attributes.Add("new_name", $"{number}/{correntYear}"); } break; case new_purchase_deal.EntityLogicalName: number = getCounterValue.new_purchase_deal; counter.new_purchase_deal = ++number; if (entity.Attributes.Contains("new_name") == true) { entity["new_name"] = $"{number}/{correntYear}"; } else { entity.Attributes.Add("new_name", $"{number}/{correntYear}"); } break; case new_purchase_task.EntityLogicalName: number = getCounterValue.new_purchase_deal; counter.new_purchase_task = ++number; if (entity.Attributes.Contains("new_name") == true) { entity["new_name"] = $"{number}/{correntYear}"; } else { entity.Attributes.Add("new_name", $"{number}/{correntYear}"); } break; default: return; } counter.Id = getCounterValue.Id; service.Update(counter); } } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
/// <summary> /// This method first connects to the Organization service and service context. /// Afterwards, several LINQ query techniques are demonstrated. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUseLinqWithDotNetDataServicesDE1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); // Retrieve records with Skip/Take record paging. Setting a page size // can help you manage your Skip and Take calls, since Skip must be // passed a multiple of Take's parameter value. //<snippetUseLinqWithDotNetDataServicesDE2> int pageSize = 5; var accountsByPage = from a in orgContext.CreateQuery("account") select a["name"]; System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts"); System.Console.WriteLine("======================================"); foreach (var name in accountsByPage.Skip(2 * pageSize).Take(pageSize)) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE2> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Skip 10 accounts, then Take 5 accounts //====================================== //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Fourth Coffee 10 //<End of Listing> // Use orderBy to order items retrieved. //<snippetUseLinqWithDotNetDataServicesDE3> var orderedAccounts = from a in orgContext.CreateQuery("account") orderby a["name"] select a["name"]; System.Console.WriteLine("Display accounts ordered by name"); System.Console.WriteLine("================================"); foreach (var name in orderedAccounts) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE3> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Display accounts ordered by name //================================ //A. Datum Corporation //Adventure Works //Coho Vineyard //Fabrikam //Fourth Coffee 1 //Fourth Coffee 10 //Fourth Coffee 2 //Fourth Coffee 3 //Fourth Coffee 4 //Fourth Coffee 5 //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Humongous Insurance //<End of Listing> // Filter multiple entities using LINQ. //<snippetUseLinqWithDotNetDataServicesDE4> var query = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] } }; Console.WriteLine("Join account and contact"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in query) { Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE4> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account and contact //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Contact Name: Ben Andrews //Account Phone: (206)555-5555 //Contact Name: Ben Andrews //Account Phone: (425)555-5555 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> // Build a complex query with LINQ. This query includes multiple // JOINs and a complex WHERE statement. //<snippetUseLinqWithDotNetDataServicesDE5> var complexQuery = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] join l in orgContext.CreateQuery("lead") on a["originatingleadid"] equals l["leadid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] }, Lead = new { LeadId = l["leadid"] } }; Console.WriteLine("Join account, contact and lead"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in complexQuery) { Console.WriteLine("Lead ID: {0}", record.Lead.LeadId); Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE5> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account, contact and lead //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> DeleteRequiredRecords(promptforDelete); } //</snippetUseLinqWithDotNetDataServicesDE1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private static IEnumerable <FilterOption> ToFilterOptions(OrganizationServiceContext context, IPortalContext portalContext, Link link, string[] selected, int languageCode) { // check for N:N relationship if (link.Intersect.GetValueOrDefault()) { var next = link.Links.FirstOrDefault(); if (next != null) { return(ToFilterOptions(context, portalContext, next, selected, languageCode)); } } // this is a 1:N relationship var filter = link.Filters.FirstOrDefault(); if (filter != null && filter.Conditions != null && filter.Conditions.Any()) { var condition = filter.Conditions.First(); if (condition.Extensions.GetExtensionValue("uiinputtype") == "dynamic") { var view = condition.Extensions.GetExtensionValue("view") ?? string.Empty; view = view.Replace("{", string.Empty).Replace("}", string.Empty); Guid id; if (Guid.TryParse(view, out id)) { var labelColumn = condition.Extensions.GetExtensionValue("labelcolumn"); var sq = context.CreateQuery("savedquery").FirstOrDefault(q => q.GetAttributeValue <Guid>("savedqueryid") == id); if (sq != null) { var fetch = Fetch.Parse(sq.GetAttributeValue <string>("fetchxml")); if (!AddPermissionFilterToFetch(fetch, context, CrmEntityPermissionRight.Read)) { return(new FilterOption[] { }); } var user = portalContext.User; var filterRelationshipName = condition.Extensions.GetExtensionValue("filterrelationship"); var filterEntityName = condition.Extensions.GetExtensionValue("filterentity"); if (user != null || string.IsNullOrEmpty(filterEntityName)) { if (!string.IsNullOrEmpty(filterEntityName) && user != null && filterEntityName == user.LogicalName) { AddRelatedRecordFilterToFetch(context, fetch, filterRelationshipName, filterEntityName, user.Id); } else if (!string.IsNullOrEmpty(filterEntityName) && !string.IsNullOrEmpty(filterRelationshipName)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Could not filter option list: user is not of type {filterEntityName}"); } var response = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest()); return(response.EntityCollection.Entities.Select( r => ToFilterOption(context.GetEntityMetadata(link.Name), r, labelColumn, selected))); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format( "Could not add filter condition: dynamic filter condition is not valid", filterEntityName)); } } return(new FilterOption[] { }); } return(filter.Conditions.Select(c => ToFilterOption(null, c, selected, languageCode))); } return(new FilterOption[] { }); }
/// <summary> /// This method first connects to the Organization service. Afterwards a dynamic /// list is created and associated to the campaign and the campaign's activity. /// Then the dynamic list is copied to a static list and associated with the same /// campaign and campaign activity. Finally the sample distributes the campaign /// to both the dynamic and static lists. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetMarketingAutomation1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Create Dynamic List // Create FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; //<snippetAddItemCampaign> // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = _serviceProxy.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. Campaign campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = _serviceProxy.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. AddItemCampaignRequest addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); //</snippetAddItemCampaign> //<snippetAddItemCampaignActivity> // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = _serviceProxy.Create(campaignActivity); // Add dynamic list to campaign activity. AddItemCampaignActivityRequest addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); //</snippetAddItemCampaignActivity> #endregion #region Associate static list to campaign //<snippetCopyDynamicListToStatic> // Copy the dynamic list to a static list. CopyDynamicListToStaticRequest copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; CopyDynamicListToStaticResponse copyResponse = (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); //</snippetCopyDynamicListToStatic> // Add the static list to the campaign. AddItemCampaignRequest addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. Fax fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list //<snippetDistributeCampaignActivity> // Distribute the campaign activity to the marketing lists. DistributeCampaignActivityRequest distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; _serviceProxy.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); //</snippetDistributeCampaignActivity> #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); var member = (from mb in orgContext.CreateQuery <List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; RetrieveMultipleRequest memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; RetrieveMultipleResponse memberResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #endregion Retrieve collection of entities from marketing list DeleteRequiredRecords(promptforDelete); } //</snippetMarketingAutomation1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void PurchaseTaskUpdateMethod(new_aprove_price _proxyentity, List<new_port> _portList, OrganizationServiceContext orgContext, IOrganizationService service) { List<new_purchase_task> _taskListForUpdate = (from i in orgContext.CreateQuery<new_purchase_task>() where i.new_product.Id == _proxyentity.new_cropid.Id && i.new_status == new OptionSetValue(100000000) select i).ToList(); foreach ( var item in _taskListForUpdate ) { new_purchase_task _updateTask = new new_purchase_task(); _updateTask.Id = item.Id; if ( item.new_port == null ) continue; if ( _portList.Where(x => x.Id == item.new_port.Id).FirstOrDefault().new_name == "Одеса" ) { _updateTask.new_aprove_purchase_price = _proxyentity.new_recom_purchase_price_odessa; } else if ( _portList.Where(x => x.Id == item.new_port.Id).FirstOrDefault().new_name == "Миколаїв" ) { _updateTask.new_aprove_purchase_price = _proxyentity.new_recom_purchase_price_nikolaev; } service.Update(_updateTask); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, /// records are retrieved from the systemuserroles intersect table via three /// methods: Query Expression, Fetch, and LINQ. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Retrieve records from an intersect table via QueryExpression //Create Query Expression. QueryExpression query = new QueryExpression() { EntityName = "role", ColumnSet = new ColumnSet("name"), LinkEntities = { new LinkEntity { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "systemuserid", Operator = ConditionOperator.Equal, Values = { _userId } } } } } } }; // Obtain results from the query expression. EntityCollection ec = _serviceProxy.RetrieveMultiple(query); // Display results. for (int i = 0; i < ec.Entities.Count; i++) { Console.WriteLine("Query Expression Retrieved: {0}", ((Role)ec.Entities[i]).Name); } #endregion #region Retrieve records from an intersect table via Fetch // Setup Fetch XML. StringBuilder linkFetch = new StringBuilder(); linkFetch.Append("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">"); linkFetch.Append("<entity name=\"role\">"); linkFetch.Append("<attribute name=\"name\"/>"); linkFetch.Append("<link-entity name=\"systemuserroles\" from=\"roleid\" to=\"roleid\" visible=\"false\" intersect=\"true\">"); linkFetch.Append("<filter type=\"and\">"); linkFetch.Append("<condition attribute=\"systemuserid\" operator=\"eq\" value=\"" + _userId + "\"/>"); linkFetch.Append("</filter>"); linkFetch.Append("</link-entity>"); linkFetch.Append("</entity>"); linkFetch.Append("</fetch>"); // Build fetch request and obtain results. RetrieveMultipleRequest efr = new RetrieveMultipleRequest() { Query = new FetchExpression(linkFetch.ToString()) }; EntityCollection entityResults = ((RetrieveMultipleResponse)_serviceProxy.Execute(efr)).EntityCollection; // Display results. foreach (var e in entityResults.Entities) { Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]); } #endregion #region Retrieve records from an intersect table via LINQ // Obtain the Organization Context. OrganizationServiceContext context = new OrganizationServiceContext(_serviceProxy); // Create Linq Query. var roles = (from r in context.CreateQuery <Role>() join s in context.CreateQuery <SystemUserRoles>() on r.RoleId equals s.RoleId where s.SystemUserId == _userId orderby r.RoleId select r.Name); // Display results. foreach (var role in roles) { Console.WriteLine("Linq Retrieved: {0}", role); } #endregion DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
protected override void Execute(CodeActivityContext executionContext) { if (executionContext == null) { throw new ArgumentNullException("localContext"); } ITracingService extension = executionContext.GetExtension <ITracingService>(); IWorkflowContext extension2 = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory extension3 = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService organizationService = extension3.CreateOrganizationService(null); try { OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(organizationService); Guid primaryEntityId = extension2.PrimaryEntityId; Entity gift = organizationService.Retrieve(extension2.PrimaryEntityName, extension2.PrimaryEntityId, new ColumnSet("msnfp_transactionid", "msnfp_taxreceiptid", "msnfp_customerid", "statuscode", "msnfp_bookdate", "msnfp_configurationid", "msnfp_amount_receipted", "msnfp_amount", "msnfp_amount_membership", "msnfp_amount_nonreceiptable", "msnfp_thirdpartyreceipt", "transactioncurrencyid", "ownerid", "msnfp_receiptpreferencecode")); decimal num = default(decimal); decimal num2 = default(decimal); decimal num3 = default(decimal); extension.Trace("Entering CreateReceiptOnTransactionCreate.cs"); if (IsTraced) { extension.Trace("Transaction Id : " + primaryEntityId.ToString()); } if (gift.Contains("msnfp_thirdpartyreceipt")) { if (IsTraced) { extension.Trace("Transaction contains msnfp_thirdpartyreceipt"); } Entity entity = new Entity("msnfp_receipt"); entity["msnfp_receipt"] = (string)gift["msnfp_thirdpartyreceipt"]; entity["msnfp_title"] = (string)gift["msnfp_thirdpartyreceipt"]; entity["msnfp_receiptgeneration"] = new OptionSetValue(844060002); num = (gift.Contains("msnfp_amount_receipted") ? ((Money)gift["msnfp_amount_receipted"]).Value : 0m); num2 = (gift.Contains("msnfp_amount_membership") ? ((Money)gift["msnfp_amount_membership"]).Value : 0m); num3 = (gift.Contains("msnfp_amount_nonreceiptable") ? ((Money)gift["msnfp_amount_nonreceiptable"]).Value : 0m); if (IsTraced) { extension.Trace("got membership amount and non-receiptable amount."); } if (IsTraced) { extension.Trace("amount " + num + " Membership Amount: " + num2 + " Non-receiptable : " + num3); } entity["msnfp_amount_receipted"] = gift["msnfp_amount_receipted"]; entity["msnfp_amount_nonreceiptable"] = new Money(num2 + num3); string logicalName = ((EntityReference)gift["ownerid"]).LogicalName; Guid id = ((EntityReference)gift["ownerid"]).Id; entity["ownerid"] = new EntityReference(logicalName, id); entity["statuscode"] = new OptionSetValue(1); Guid id2 = organizationService.Create(entity); if (IsTraced) { extension.Trace("receipt created based on third party receipt number."); } gift["msnfp_taxreceiptid"] = new EntityReference("msnfp_receipt", id2); gift["msnfp_previousreceiptid"] = new EntityReference("msnfp_receipt", id2); organizationService.Update(gift); if (IsTraced) { extension.Trace("Transaction updated with the receipt created wtih third party receipt number"); } } else if (gift.Contains("msnfp_receiptpreferencecode") && gift["msnfp_receiptpreferencecode"] != null) { if (IsTraced) { extension.Trace("Transaction contains receipt preference"); } int value = ((OptionSetValue)gift["msnfp_receiptpreferencecode"]).Value; if (value != 844060000) { if (IsTraced) { extension.Trace("Transaction receipt preference is NOT 'DO NOT RECEIPT', value: " + value); } if (gift.Contains("msnfp_taxreceiptid")) { if (IsTraced) { extension.Trace("Transaction contains receipt"); } Guid id3 = ((EntityReference)gift["msnfp_taxreceiptid"]).Id; Entity entity2 = organizationService.Retrieve("msnfp_receipt", id3, new ColumnSet("msnfp_generatedorprinted", "statuscode")); if (entity2 != null) { if (IsTraced) { extension.Trace("receipt retrieve"); } double num4 = (entity2.Contains("msnfp_generatedorprinted") ? ((double)entity2["msnfp_generatedorprinted"]) : 0.0); entity2["msnfp_generatedorprinted"] = num4 + 1.0; if (gift.Contains("statuscode") && ((OptionSetValue)gift["statuscode"]).Value != 844060000 && ((OptionSetValue)entity2["statuscode"]).Value == 1) { entity2["statuscode"] = new OptionSetValue(844060002); } organizationService.Update(entity2); SetReceiptIdentifier(entity2.Id, extension, organizationService); if (IsTraced) { extension.Trace("receipt updated"); } } } else { if (IsTraced) { extension.Trace("Transaction does not contains receipt"); } if (((OptionSetValue)gift["statuscode"]).Value == 844060000) { if (IsTraced) { extension.Trace("Transaction is completed"); } Entity entity3 = new Entity("msnfp_receipt"); int num5 = (gift.Contains("msnfp_bookdate") ? ((DateTime)gift["msnfp_bookdate"]).Year : 0); if (IsTraced) { extension.Trace("Gift Year : " + num5); } if (num5 != 0) { int receiptYearValue2 = Utilities.GetOptionsSetValueForLabel(organizationService, "msnfp_receiptstack", "msnfp_receiptyear", num5.ToString()); if (IsTraced) { extension.Trace("receipt year value: " + receiptYearValue2); } Entity entity4 = (from a in organizationServiceContext.CreateQuery("msnfp_receiptstack") where ((EntityReference)a["msnfp_configurationid"]).Id == ((EntityReference)gift["msnfp_configurationid"]).Id && a["msnfp_receiptyear"] == new OptionSetValue(receiptYearValue2) select a).FirstOrDefault(); if (entity4 != null) { if (IsTraced) { extension.Trace("receipt stake available."); } entity3["msnfp_receiptstackid"] = new EntityReference("msnfp_receiptstack", entity4.Id); num = (gift.Contains("msnfp_amount_receipted") ? ((Money)gift["msnfp_amount_receipted"]).Value : 0m); num2 = (gift.Contains("msnfp_amount_membership") ? ((Money)gift["msnfp_amount_membership"]).Value : 0m); num3 = (gift.Contains("msnfp_amount_nonreceiptable") ? ((Money)gift["msnfp_amount_nonreceiptable"]).Value : 0m); if (IsTraced) { extension.Trace("got membership amount and non-receiptable amount."); } if (IsTraced) { extension.Trace("amount " + num + " Membership Amount: " + num2 + " Non-receiptable : " + num3); } entity3["msnfp_amount_receipted"] = gift["msnfp_amount_receipted"]; entity3["msnfp_amount_nonreceiptable"] = new Money(num2 + num3); entity3["msnfp_generatedorprinted"] = Convert.ToDouble(1); entity3["msnfp_receiptgeneration"] = new OptionSetValue(844060000); entity3["msnfp_receiptissuedate"] = DateTime.Now; entity3["msnfp_transactioncount"] = 1; entity3["msnfp_amount"] = gift["msnfp_amount"]; if (gift.Contains("transactioncurrencyid")) { entity3["transactioncurrencyid"] = new EntityReference("transactioncurrency", ((EntityReference)gift["transactioncurrencyid"]).Id); } if (gift.Contains("msnfp_customerid")) { string logicalName2 = ((EntityReference)gift["msnfp_customerid"]).LogicalName; Guid id4 = ((EntityReference)gift["msnfp_customerid"]).Id; entity3["msnfp_customerid"] = new EntityReference(logicalName2, id4); } string logicalName3 = ((EntityReference)gift["ownerid"]).LogicalName; Guid id5 = ((EntityReference)gift["ownerid"]).Id; entity3["ownerid"] = new EntityReference(logicalName3, id5); entity3["statuscode"] = new OptionSetValue(1); Guid guid = organizationService.Create(entity3); bool flag = true; SetReceiptIdentifier(guid, extension, organizationService); if (IsTraced) { extension.Trace("receipt created"); } gift["msnfp_taxreceiptid"] = new EntityReference("msnfp_receipt", guid); gift["msnfp_previousreceiptid"] = new EntityReference("msnfp_receipt", guid); organizationService.Update(gift); if (IsTraced) { extension.Trace("Transaction Updated"); } } } } } } } else { if (IsTraced) { extension.Trace("Transaction does not contains receipt preference"); } if (!gift.Contains("msnfp_taxreceiptid")) { if (IsTraced) { extension.Trace("Transaction does not contains receipt"); } if (((OptionSetValue)gift["statuscode"]).Value == 844060000) { if (IsTraced) { extension.Trace("Transaction is completed"); } Entity entity5 = new Entity("msnfp_receipt"); int num6 = (gift.Contains("msnfp_bookdate") ? ((DateTime)gift["msnfp_bookdate"]).Year : 0); if (IsTraced) { extension.Trace("Gift Year : " + num6); } if (num6 != 0) { int receiptYearValue = Utilities.GetOptionsSetValueForLabel(organizationService, "msnfp_receiptstack", "msnfp_receiptyear", num6.ToString()); if (IsTraced) { extension.Trace("receipt year value: " + receiptYearValue); } Entity entity6 = (from a in organizationServiceContext.CreateQuery("msnfp_receiptstack") where ((EntityReference)a["msnfp_configurationid"]).Id == ((EntityReference)gift["msnfp_configurationid"]).Id && a["msnfp_receiptyear"] == new OptionSetValue(receiptYearValue) select a).FirstOrDefault(); if (entity6 != null) { if (IsTraced) { extension.Trace("receipt stake available."); } entity5["msnfp_receiptstackid"] = new EntityReference("msnfp_receiptstack", entity6.Id); num = (gift.Contains("msnfp_amount_receipted") ? ((Money)gift["msnfp_amount_receipted"]).Value : 0m); num2 = (gift.Contains("msnfp_amount_membership") ? ((Money)gift["msnfp_amount_membership"]).Value : 0m); num3 = (gift.Contains("msnfp_amount_nonreceiptable") ? ((Money)gift["msnfp_amount_nonreceiptable"]).Value : 0m); if (IsTraced) { extension.Trace("got membership amount and non-receiptable amount."); } if (IsTraced) { extension.Trace("amount " + num + " Membership Amount: " + num2 + " Non-receiptable : " + num3); } entity5["msnfp_amount_receipted"] = gift["msnfp_amount_receipted"]; entity5["msnfp_amount_nonreceiptable"] = new Money(num2 + num3); entity5["msnfp_generatedorprinted"] = Convert.ToDouble(1); entity5["msnfp_receiptgeneration"] = new OptionSetValue(844060000); entity5["msnfp_receiptissuedate"] = DateTime.Now; entity5["msnfp_transactioncount"] = 1; entity5["msnfp_amount"] = gift["msnfp_amount"]; if (gift.Contains("transactioncurrencyid")) { entity5["transactioncurrencyid"] = new EntityReference("transactioncurrency", ((EntityReference)gift["transactioncurrencyid"]).Id); } if (gift.Contains("msnfp_customerid")) { string logicalName4 = ((EntityReference)gift["msnfp_customerid"]).LogicalName; Guid id6 = ((EntityReference)gift["msnfp_customerid"]).Id; entity5["msnfp_customerid"] = new EntityReference(logicalName4, id6); } string logicalName5 = ((EntityReference)gift["ownerid"]).LogicalName; Guid id7 = ((EntityReference)gift["ownerid"]).Id; entity5["ownerid"] = new EntityReference(logicalName5, id7); entity5["statuscode"] = new OptionSetValue(1); Guid guid2 = organizationService.Create(entity5); bool flag2 = true; SetReceiptIdentifier(guid2, extension, organizationService); if (IsTraced) { extension.Trace("receipt created"); } gift["msnfp_taxreceiptid"] = new EntityReference("msnfp_receipt", guid2); gift["msnfp_previousreceiptid"] = new EntityReference("msnfp_receipt", guid2); organizationService.Update(gift); if (IsTraced) { extension.Trace("Transaction Updated"); } } } } } } } catch (FaultException <OrganizationServiceFault> ex) { if (IsTraced) { extension.Trace("Workflow Exception: {0}", ex.ToString()); } throw; } if (IsTraced) { throw new Exception("Tracing enabled. Set it to false to remove this message."); } }
public void Run() { tracingService.Trace("Beginning PostPublishAll"); // Create Defaults if (!dataContext.CreateQuery("dd_chartmapentity").Select(c => c.GetAttributeValue <Guid>("dd_chartmapentityid")).ToList().Any()) { tracingService.Trace("Creating predefined maps for Account,Contact,Lead and Opportunity entities"); CreateChartConfig("account", "Account Locations", "name", "Displays Account locations on a Bing Map.", "address1_city", "address1_line1", "address1_postalcode", "address1_stateorprovince", "address1_country", "address1_latitude", "address1_longitude", "Multiple Accounts"); CreateChartConfig("contact", "Contact Locations", "fullname", "Displays Contact locations on a Bing Map", "address1_city", "address1_line1", "address1_postalcode", "address1_stateorprovince", "address1_country", "address1_latitude", "address1_longitude", "Multiple Contacts"); CreateChartConfig("lead", "Lead Locations", "fullname", "Displays Lead locations on a Bing Map.", "address1_city", "address1_line1", "address1_postalcode", "address1_stateorprovince", "address1_country", "address1_latitude", "address1_longitude", "Multiple Leads"); CreateHeatMap("opportunity", "Estimated Value Heat Map", "name", "Displays heat map of Estimated Value by Parent Account address", "parentaccountid.address1_city", "parentaccountid.address1_line1", "parentaccountid.address1_postalcode", "parentaccountid.address1_stateorprovince", "parentaccountid.address1_country", "parentaccountid.address1_latitude", "parentaccountid.address1_longitude", 2, "estimatedvalue", 1000000, 0.5m, 50, false, 1128000128, 1000000255, 1000128000, 1255255000, 1255000000); tracingService.Trace("Predefined maps created sucessfully"); } else { #region Convert Existing Charts to new format #region Legacy Conversion // this bit can be removed in the future, once there are no legacy instances // find all records, and fill in config values if blank tracingService.Trace("Try to find ChartMapConfig.js"); ChartMapConfig configSettings = new ChartMapConfig(); Entity chartMapConfigRecord = dataContext.CreateQuery("webresource").Where(r => r.GetAttributeValue <string>("name") == "dd_chartmapconfig.js").SingleOrDefault(); if (chartMapConfigRecord == default(Entity)) { tracingService.Trace("Config file not found, using defaults"); configSettings = ChartMapConfig.defaultConfig(); } else { tracingService.Trace("Config file exists"); configSettings = ChartMapConfig.getConfig(chartMapConfigRecord); SetBingKey(configSettings.BingKey); } var allConfigRecords = dataContext.CreateQuery("dd_chartmapentity") .Select(c => new { Id = c.GetAttributeValue <Guid>("dd_chartmapentityid"), HasZoom = c.Contains("dd_zoom"), HasLatitude = c.Contains("dd_latitude"), HasLongitude = c.Contains("dd_longitude"), HasLanguage = c.Contains("dd_language"), HasEnableCaching = c.Contains("dd_enablecaching"), HasShowAllRecords = c.Contains("dd_showallrecords") }); foreach (var chartMapConfig in allConfigRecords) { Entity updatedConfig = new Entity("dd_chartmapentity"); updatedConfig.Id = chartMapConfig.Id; bool updateNeeded = false; if (!chartMapConfig.HasZoom) { updatedConfig["dd_zoom"] = configSettings.Zoom; updateNeeded = true; } if (!chartMapConfig.HasLatitude) { updatedConfig["dd_latitude"] = configSettings.CenterLat; updateNeeded = true; } if (!chartMapConfig.HasLongitude) { updatedConfig["dd_longitude"] = configSettings.CenterLong; updateNeeded = true; } if (!chartMapConfig.HasLanguage) { updatedConfig["dd_language"] = new OptionSetValue(DataDescription.LangCodes.Single(l => l.Value == configSettings.Lang).Key); updateNeeded = true; } if (!chartMapConfig.HasEnableCaching) { updatedConfig["dd_enablecaching"] = false; updateNeeded = true; } if (!chartMapConfig.HasShowAllRecords) { updatedConfig["dd_showallrecords"] = false; updateNeeded = true; } #endregion if (updateNeeded) { Service.Update(updatedConfig); } else { // Force update chart to latest version updatedConfig["dd_fetchattributes"] = ""; // This is just an old field, not used anymore. Being used here to force the update. Service.Update(updatedConfig); } } #endregion } // Remove this plugin step after the first time it runs successfully deletePluginStep("CrmChartMap.PostPublishAll"); }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); // Service implements IOrganizationService interface if (service.IsReady) { #region Sample Code ///////////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate //Create Query Expression. var query = new QueryExpression() { EntityName = "role", ColumnSet = new ColumnSet("name"), LinkEntities = { new LinkEntity { LinkFromEntityName = Role.EntityLogicalName, LinkFromAttributeName = "roleid", LinkToEntityName = SystemUserRoles.EntityLogicalName, LinkToAttributeName = "roleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression { AttributeName = "systemuserid", Operator = ConditionOperator.Equal, Values = { userId } } } } } } }; // Obtain results from the query expression. EntityCollection ec = service.RetrieveMultiple(query); // Display results. for (int i = 0; i < ec.Entities.Count; i++) { Console.WriteLine("Query Expression Retrieved: {0}", ((Role)ec.Entities[i]).Name); } #endregion #region Retrieve records from an intersect table via Fetch // Setup Fetch XML. StringBuilder linkFetch = new StringBuilder(); linkFetch.Append("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">"); linkFetch.Append("<entity name=\"role\">"); linkFetch.Append("<attribute name=\"name\"/>"); linkFetch.Append("<link-entity name=\"systemuserroles\" from=\"roleid\" to=\"roleid\" visible=\"false\" intersect=\"true\">"); linkFetch.Append("<filter type=\"and\">"); linkFetch.Append("<condition attribute=\"systemuserid\" operator=\"eq\" value=\"" + userId + "\"/>"); linkFetch.Append("</filter>"); linkFetch.Append("</link-entity>"); linkFetch.Append("</entity>"); linkFetch.Append("</fetch>"); // Build fetch request and obtain results. var efr = new RetrieveMultipleRequest() { Query = new FetchExpression(linkFetch.ToString()) }; EntityCollection entityResults = ((RetrieveMultipleResponse)service.Execute(efr)).EntityCollection; // Display results. foreach (var e in entityResults.Entities) { Console.WriteLine("Fetch Retrieved: {0}", e.Attributes["name"]); } #endregion #region Retrieve records from an intersect table via LINQ // Obtain the Organization Context. OrganizationServiceContext context = new OrganizationServiceContext(service); // Create Linq Query. var roles = (from r in context.CreateQuery <Role>() join s in context.CreateQuery <SystemUserRoles>() on r.RoleId equals s.RoleId where s.SystemUserId == userId orderby r.RoleId select r.Name); // Display results. foreach (var role in roles) { Console.WriteLine("Linq Retrieved: {0}", role); } #endregion Demonstrate #region Clean up // Provides option to delete the ChangeTracking solution CleanUpSample(service); #endregion Clean up ////////////////////////////////////////////// #endregion Sample Code } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// This method first connects to the Organization service and service context. /// Afterwards, several LINQ query techniques are demonstrated. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetUseLinqWithDotNetDataServicesDE1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); // Retrieve records with Skip/Take record paging. Setting a page size // can help you manage your Skip and Take calls, since Skip must be // passed a multiple of Take's parameter value. //<snippetUseLinqWithDotNetDataServicesDE2> int pageSize = 5; var accountsByPage = from a in orgContext.CreateQuery("account") select a["name"]; System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts"); System.Console.WriteLine("======================================"); foreach (var name in accountsByPage.Skip(2 * pageSize).Take(pageSize)) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE2> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Skip 10 accounts, then Take 5 accounts //====================================== //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Fourth Coffee 10 //<End of Listing> // Use orderBy to order items retrieved. //<snippetUseLinqWithDotNetDataServicesDE3> var orderedAccounts = from a in orgContext.CreateQuery("account") orderby a["name"] select a["name"]; System.Console.WriteLine("Display accounts ordered by name"); System.Console.WriteLine("================================"); foreach (var name in orderedAccounts) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE3> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Display accounts ordered by name //================================ //A. Datum Corporation //Adventure Works //Coho Vineyard //Fabrikam //Fourth Coffee 1 //Fourth Coffee 10 //Fourth Coffee 2 //Fourth Coffee 3 //Fourth Coffee 4 //Fourth Coffee 5 //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Humongous Insurance //<End of Listing> // Filter multiple entities using LINQ. //<snippetUseLinqWithDotNetDataServicesDE4> var query = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] } }; Console.WriteLine("Join account and contact"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in query) { Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE4> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account and contact //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Contact Name: Ben Andrews //Account Phone: (206)555-5555 //Contact Name: Ben Andrews //Account Phone: (425)555-5555 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> // Build a complex query with LINQ. This query includes multiple // JOINs and a complex WHERE statement. //<snippetUseLinqWithDotNetDataServicesDE5> var complexQuery = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] join l in orgContext.CreateQuery("lead") on a["originatingleadid"] equals l["leadid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] }, Lead = new { LeadId = l["leadid"] } }; Console.WriteLine("Join account, contact and lead"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in complexQuery) { Console.WriteLine("Lead ID: {0}", record.Lead.LeadId); Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE5> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account, contact and lead //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> DeleteRequiredRecords(promptforDelete); } //</snippetUseLinqWithDotNetDataServicesDE1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
private List<EntityReference> getAgreements() { using (var orgContext = new OrganizationServiceContext(service)) { List<EntityReference> ownerUsers = (from i in orgContext.CreateQuery<new_constant>() select new List<EntityReference>{ new EntityReference { Id = i.new_lawyer.Id, LogicalName = i.new_lawyer.LogicalName, Name = i.new_lawyer.Name, }, new EntityReference { Id = i.new_Logist.Id, LogicalName = i.new_Logist.LogicalName, Name = i.new_Logist.Name, }, new EntityReference { Id = i.new_financier.Id, LogicalName = i.new_financier.LogicalName, Name = i.new_financier.Name, }, new EntityReference { Id = i.new_accountant.Id, LogicalName = i.new_accountant.LogicalName, Name = i.new_accountant.Name, }, new EntityReference { Id = i.new_salesdepartment.Id, LogicalName = i.new_salesdepartment.LogicalName, Name = i.new_salesdepartment.Name, } }).FirstOrDefault(); return ownerUsers; } }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" objCommon = new Common(executionContext); objCommon.tracingService.Trace("CreateContact activity:Load CRM Service from context --- OK"); #endregion #region "Read Parameters" string jsonPayload = Payload.Get(executionContext); DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Contact)); //Contact contactPayload = JsonConvert.DeserializeObject<Contact>(jsonPayload); //EntityReference _Contact; Boolean _IsRecordCreated = false; Int64 ErrorCode = 400; //Bad Request String _ErrorMessage = string.Empty; String _ErrorMessageDetail = string.Empty; Guid ContactId = Guid.Empty; #endregion #region "Create Execution" try { using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonPayload))) { Contact contactPayload = (Contact)deserializer.ReadObject(ms); Entity contact = new Entity("contact");//,"defra_upn", _UPN); if (string.IsNullOrEmpty(contactPayload.b2cobjectid) || string.IsNullOrWhiteSpace(contactPayload.b2cobjectid)) { _ErrorMessage = "B2C Object Id can not be empty"; } if (string.IsNullOrEmpty(contactPayload.firstname) || string.IsNullOrWhiteSpace(contactPayload.firstname)) { _ErrorMessage = "First Name can not empty"; } if (string.IsNullOrEmpty(contactPayload.lastname) || string.IsNullOrWhiteSpace(contactPayload.lastname)) { _ErrorMessage = "Last Name can not empty"; } if (!string.IsNullOrEmpty(contactPayload.b2cobjectid) && !string.IsNullOrWhiteSpace(contactPayload.b2cobjectid) && contactPayload.b2cobjectid.Length > 50) { _ErrorMessage = "B2C Object Id is invalid/exceed the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.firstname) && contactPayload.firstname.Length > 50) { _ErrorMessage = "Firstname exceeded the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.lastname) && contactPayload.lastname.Length > 50) { _ErrorMessage = "Lastname exceeded the max length(50)"; } if (!string.IsNullOrEmpty(contactPayload.lastname) && contactPayload.lastname.Length > 100) { _ErrorMessage = "Email exceeded the max length(100)"; } if (_ErrorMessage == string.Empty) { //search contact record based on UPN OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(objCommon.service); var ContactWithUPN = from c in orgSvcContext.CreateQuery("contact") where ((string)c["defra_b2cobjectid"]).Equals((contactPayload.b2cobjectid.Trim())) select new { ContactId = c.Id, UniqueReference = c["defra_uniquereference"] }; var contactRecordWithUPN = ContactWithUPN.FirstOrDefault() == null ? null : ContactWithUPN.FirstOrDefault(); Guid ContactRecordGuidWithUPN = contactRecordWithUPN == null ? Guid.Empty : contactRecordWithUPN.ContactId; if (ContactRecordGuidWithUPN == Guid.Empty) { objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithUPN is empty started, Creating Contact.."); ErrorCode = 200;//Success if (contactPayload.title != null) { contact["defra_title"] = contactPayload.title; } contact["firstname"] = contactPayload.firstname; contact["lastname"] = contactPayload.lastname; if (contactPayload.middlename != null) { contact["middlename"] = contactPayload.middlename; } if (contactPayload.middlename != null) { contact["emailaddress1"] = contactPayload.email; } if (contactPayload.b2cobjectid != null) { contact["defra_b2cobjectid"] = contactPayload.b2cobjectid; } if (contactPayload.tacsacceptedversion != null) { contact["defra_tacsacceptedversion"] = contactPayload.tacsacceptedversion; } if (contact["telephone1"] != null) { contact["telephone1"] = contactPayload.telephone; } objCommon.tracingService.Trace("setting contact date params:started.."); if (!string.IsNullOrEmpty(contactPayload.tacsacceptedon) && !string.IsNullOrWhiteSpace(contactPayload.tacsacceptedon)) { DateTime resultDate; if (DateTime.TryParse(contactPayload.tacsacceptedon, out resultDate)) { contact["defra_tandcagreedon"] = resultDate; } } //set birthdate if (!string.IsNullOrEmpty(contactPayload.dob) && !string.IsNullOrWhiteSpace(contactPayload.dob)) { DateTime resultDob; if (DateTime.TryParse(contactPayload.dob, out resultDob)) { contact["birthdate"] = resultDob; } } if (!string.IsNullOrEmpty(contactPayload.gender) && !string.IsNullOrWhiteSpace(contactPayload.gender)) { int genderCode; if (int.TryParse(contactPayload.gender, out genderCode)) { contact["gendercode"] = new OptionSetValue(genderCode); } } objCommon.tracingService.Trace("CreateContact activity:started.."); ContactId = objCommon.service.Create(contact); objCommon.tracingService.Trace("CreateContact activity:ended. " + ContactId); //var CreatedContacts = from c in orgSvcContext.CreateQuery("contact") // where ((Guid)c["contactid"]).Equals((ContactId)) // select new { ContactUID = c["defra_uniquereference"] }; //var CreatedContact = CreatedContacts.FirstOrDefault() == null ? null : CreatedContacts.FirstOrDefault(); //if (CreatedContact != null) // UID.Set(executionContext, CreatedContact.ContactUID); this.CrmGuid.Set(executionContext, ContactId.ToString()); // Entity ContactRecord = objCommon.service.Retrieve("contact", ContactId, new Microsoft.Xrm.Sdk.Query.ColumnSet("defra_uniquereference")); // this.UniqueReference.Set(executionContext, ContactRecord["defra_uniquereference"]); // _Contact = new EntityReference("contact", ContactId); // this.Individual.Set(executionContext, _Contact); _IsRecordCreated = true; if (contactPayload.address != null) { //CreateAddress(contactPayload.address, ContactId); objCommon.CreateAddress(contactPayload.address, new EntityReference("contact", ContactId)); } } else { this.CrmGuid.Set(executionContext, ContactRecordGuidWithUPN.ToString()); objCommon.tracingService.Trace("CreateContact activity:ContactRecordGuidWithUPN is found/duplicate started.."); ErrorCode = 412;//Duplicate UPN _ErrorMessage = "Duplicate Record"; } } objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. started"); this.IsRecordCreated.Set(executionContext, _IsRecordCreated); this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); objCommon.tracingService.Trace("CreateContact activity:setting output params like error code etc.. ended"); } } catch (FaultException <OrganizationServiceFault> ex) { ErrorCode = 500;//Internal Error _ErrorMessage = "Error occured while processing request"; _ErrorMessageDetail = ex.Message; //throw ex; this.Code.Set(executionContext, ErrorCode.ToString()); this.Message.Set(executionContext, _ErrorMessage); this.MessageDetail.Set(executionContext, _ErrorMessageDetail); } #endregion }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.PrimaryEntityName != new_payment.EntityLogicalName) { return; } using (var orgContext = new OrganizationServiceContext(service)) { var payment = (Entity)context.InputParameters["Target"]; var paymentCorrent = payment.ToEntity <new_payment>(); EntityReference correntInvoice = null; correntInvoice = (from c in orgContext.CreateQuery <new_payment>() where c.Id == payment.Id select c.new_expense).FirstOrDefault() ?? payment.GetAttributeValue <EntityReference>("new_expense"); if (correntInvoice == null) { return; } if (context.MessageName.ToLower() != "delete") { var objPayment = (from i in orgContext.CreateQuery <new_payment>() where i.new_expense.Id == correntInvoice.Id select new { new_amountsreceived = i.new_amountsreceived ?? new Money(0), new_percentagepayment = i.new_percentagepayment ?? 0, new_postsummausd = i.new_postsummausd ?? 0 }).ToList(); objPayment.Add(new { new_amountsreceived = paymentCorrent.new_amountsreceived ?? new Money(0), new_percentagepayment = paymentCorrent.new_percentagepayment ?? 0, new_postsummausd = paymentCorrent.new_postsummausd ?? 0 }); var amount = objPayment.Sum(item => item.new_amountsreceived.Value); var precent = objPayment.Sum(item => item.new_percentagepayment); var amountUSD = objPayment.Sum(item => item.new_postsummausd); Invoice updateEntity = new Invoice() { Id = correntInvoice.Id, new_amountsreceived = new Money(amount), new_percentage_amount = Convert.ToDouble(precent), new_amountsreceived_usd = amountUSD }; service.Update(updateEntity); } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
public bool CreateQuoteDetail(ExcelProxyQuotedetail quotedetail, EntityReference product) { using (var orgContext = new OrganizationServiceContext(service)) { var newquoteDetail = new QuoteDetail() { ProductId = product, new_SKU = quotedetail.SKU, new_manufacturingname = findVendor(quotedetail.Vendor), IsPriceOverridden = true, Quantity = Convert.ToInt32(quotedetail.quantity), PricePerUnit = new Money(Convert.ToDecimal(quotedetail.priceperunit)), new_usdprice = Convert.ToDecimal(quotedetail.new_usdprice), new_totalpurchaseusd = Convert.ToDouble(quotedetail.new_totalpurchaseusd), new_koef = Convert.ToDecimal(quotedetail.new_koef), QuoteId = mainEntityId, new_sellingusd = Convert.ToDouble(quotedetail.new_sellingusd), new_generalsellingusd = Convert.ToDouble(quotedetail.new_generalsellingusd), new_exchangerate = Convert.ToDouble(quotedetail.exchangeRates), UoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault() }; try { service.Create(newquoteDetail); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } return true; }
private PluginAssembly RegisterAssembly(FileInfo assemblyFilePath, Assembly assembly, IEnumerable <Type> pluginTypes, bool isWorkflowActivity = false) { // Get the isolation mode of the first attribute var firstType = Reflection.GetAttributes(pluginTypes, typeof(CrmPluginRegistrationAttribute).Name).FirstOrDefault(); if (firstType == null) { return(null); } var firstTypeAttribute = firstType.CreateFromData() as CrmPluginRegistrationAttribute; // Is there any steps to register? if (firstTypeAttribute == null) { return(null); } var assemblyProperties = assembly.GetName().FullName.Split(",= ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var assemblyName = assembly.GetName().Name; // If found then register or update it var plugin = (from p in _ctx.CreateQuery <PluginAssembly>() where p.Name == assemblyName select new PluginAssembly { Id = p.Id, Name = p.Name }).FirstOrDefault(); string assemblyBase64 = Convert.ToBase64String(File.ReadAllBytes(assemblyFilePath.FullName)); if (plugin == null) { plugin = new PluginAssembly(); } // update plugin.Content = assemblyBase64; plugin.Name = assemblyProperties[0]; plugin.Culture = assemblyProperties[4]; plugin.Version = assemblyProperties[2]; plugin.PublicKeyToken = assemblyProperties[6]; plugin.SourceType = pluginassembly_sourcetype.Database; // database plugin.IsolationMode = firstTypeAttribute.IsolationMode == IsolationModeEnum.Sandbox ? pluginassembly_isolationmode.Sandbox : pluginassembly_isolationmode.None; // 1= none, 2 = sandbox if (plugin.Id == Guid.Empty) { _trace.WriteLine("Registering Plugin '{0}' from '{1}'", plugin.Name, assemblyFilePath.FullName); // Create plugin.Id = _service.Create(plugin); } else { UnregisterRemovedPluginTypes(pluginTypes, plugin, isWorkflowActivity); _trace.WriteLine("Updating Plugin '{0}' from '{1}'", plugin.Name, assemblyFilePath.FullName); // Update _service.Update(plugin); } // Add to solution if (SolutionUniqueName != null) { _trace.WriteLine("Adding Plugin '{0}' to solution '{1}'", plugin.Name, SolutionUniqueName); AddAssemblyToSolution(SolutionUniqueName, plugin); } return(plugin); }
private EntityReference findVendor(string name) { using (var orgContext = new OrganizationServiceContext(service)) { EntityReference vendor = (from q in orgContext.CreateQuery<new_manufacturer>() where q.new_name == name select new EntityReference { Id = q.Id, Name = q.new_name, LogicalName = q.LogicalName }).FirstOrDefault(); if (vendor == null) { // Create vendor var newid = service.Create(new new_manufacturer { new_name = name }); return new EntityReference { Id = newid, Name = name, LogicalName = new_manufacturer.EntityLogicalName }; } else { return vendor; } } }
private List <MeteringPoint> GetMeteringPointsFromEntityCollection(OrganizationServiceContext serviceContext, IQueryable <Entity> zahplunkts) { List <MeteringPoint> meteringPoints = new List <MeteringPoint>(); foreach (Entity zahplunkt in zahplunkts) { MeteringPoint meteringPoint = new MeteringPoint(); if (zahplunkt.Contains(MetadataDZählpunkt.METERING_POINT_ID)) { meteringPoint.Id = zahplunkt.GetAttributeValue <Guid>(MetadataDZählpunkt.METERING_POINT_ID); } if (zahplunkt.Contains(MetadataDZählpunkt.NAME)) { meteringPoint.Name = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.NAME); } if (zahplunkt.Contains(MetadataDZählpunkt.ACCOUNT)) { EntityReference linkedAccount = zahplunkt.GetAttributeValue <EntityReference>(MetadataDZählpunkt.ACCOUNT); meteringPoint.CrmAccountId = linkedAccount.Id; meteringPoint.CrmAccountName = linkedAccount.Name; //GetBeitreibersByAccountId(linkedAccount.Id); } if (zahplunkt.Contains(MetadataDZählpunkt.ZAHLPUNKTBEZEICHNER)) { meteringPoint.Zählpunktbezeichner = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ZAHLPUNKTBEZEICHNER); } if (zahplunkt.Contains(MetadataDZählpunkt.KURZEEZEICHNUNG)) { meteringPoint.Kurzbezeichnung = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.KURZEEZEICHNUNG); } if (zahplunkt.Contains(MetadataDZählpunkt.ANLAGENTYP)) { meteringPoint.Anlagentyp = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ANLAGENTYP); } if (zahplunkt.Contains(MetadataDZählpunkt.PLZ)) { meteringPoint.PLZ = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.PLZ); } if (zahplunkt.Contains(MetadataDZählpunkt.STRASSE)) { meteringPoint.Strasse = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.STRASSE); } if (zahplunkt.Contains(MetadataDZählpunkt.ORT)) { meteringPoint.Ort = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ORT); } if (zahplunkt.Contains(MetadataDZählpunkt.DATENVERSANDAKTIV)) { meteringPoint.DatenversandAktiv = zahplunkt.GetAttributeValue <bool>(MetadataDZählpunkt.DATENVERSANDAKTIV) ? "Yes" : "No"; } if (zahplunkt.Contains(MetadataDZählpunkt.ZAHLVERFAHREN)) { string value = String.Empty; int code = -1; switch (zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.ZAHLVERFAHREN).Value) { case (int)MetadataDZählpunkt.OpSetZählverfahren.RLM: code = (int)MetadataDZählpunkt.OpSetZählverfahren.RLM; value = MetadataDZählpunkt.OpSetZählverfahren.RLM.ToString(); break; case (int)MetadataDZählpunkt.OpSetZählverfahren.SLP: code = (int)MetadataDZählpunkt.OpSetZählverfahren.SLP; value = MetadataDZählpunkt.OpSetZählverfahren.SLP.ToString(); break; } meteringPoint.ZählverfahrenCode = code; meteringPoint.ZählverfahrenValue = value; } if (zahplunkt.Contains(MetadataDZählpunkt.UMESSUNG)) { int code; string value; this.SetSetSpannungsebene(zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.UMESSUNG).Value, out code, out value); meteringPoint.UMessungCode = code; meteringPoint.UMessungValue = value; } if (zahplunkt.Contains(MetadataDZählpunkt.UENTNAHME)) { int code; string value; this.SetSetSpannungsebene(zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.UENTNAHME).Value, out code, out value); meteringPoint.UEntnahmeCode = code; meteringPoint.UEntnahmeValue = value; } if (zahplunkt.Contains(MetadataDZählpunkt.KUNDENRUCKMELDUNG)) { meteringPoint.Kundenrückmeldung = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.KUNDENRUCKMELDUNG); } if (zahplunkt.Contains(MetadataDZählpunkt.VNB)) { EntityReference linkedVnb = zahplunkt.GetAttributeValue <EntityReference>(MetadataDZählpunkt.VNB); meteringPoint.VNBId = linkedVnb.Id; meteringPoint.VNBName = linkedVnb.Name; } if (zahplunkt.Contains(MetadataDZählpunkt.CODE)) { meteringPoint.Code = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.CODE); } #region "Threshold Values" //Get the threshold for this metering point IQueryable <Entity> grenzwerts = serviceContext.CreateQuery(EntityNames.Grenzwert).Where(g => g.GetAttributeValue <EntityReference>(MetadataGrenzwert.GrenzwerteZPID).Id == zahplunkt.Id); List <MeteringPointThreshold> meteringPointThresholds = new List <MeteringPointThreshold>(); meteringPoint.MeteringCodeThresholds = new List <MeteringPointThreshold>(); if (grenzwerts != null) { Entity grenzwert = grenzwerts.ToList().FirstOrDefault(); if (grenzwert != null) { #region "System Threshold Values" MeteringPointThreshold meteringPointThreshlodSystem = new MeteringPointThreshold { Type = MeteringPointThresholdType.System }; if (grenzwert.Contains(MetadataGrenzwert.Grenze)) { meteringPointThreshlodSystem.GrenzwertBezeichner = String.Format("{0:F2}", grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.Grenze)); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwerteId)) { meteringPointThreshlodSystem.Id = grenzwert.GetAttributeValue <Guid>(MetadataGrenzwert.GrenzwerteId); } if (grenzwert.Contains(MetadataGrenzwert.GültigAb)) { meteringPointThreshlodSystem.GultingAb = grenzwert.GetAttributeValue <DateTime>(MetadataGrenzwert.GültigAb); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMaxSystem)) { meteringPointThreshlodSystem.MaximaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMaxSystem)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMinSystem)) { meteringPointThreshlodSystem.MinimaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMinSystem)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMaxSystem)) { meteringPointThreshlodSystem.MaximaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMaxSystem)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMinSystem)) { meteringPointThreshlodSystem.MinimaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMinSystem)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMaxSystem)) { meteringPointThreshlodSystem.MaximaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMaxSystem)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMinSystem)) { meteringPointThreshlodSystem.MinimaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMinSystem)).ToString(); } meteringPointThresholds.Add(meteringPointThreshlodSystem); #endregion "System Threshold Values" #region "User Threshold Values" MeteringPointThreshold meteringPointThreshlodUser = new MeteringPointThreshold { Type = MeteringPointThresholdType.User }; if (grenzwert.Contains(MetadataGrenzwert.GrenzwerteId)) { meteringPointThreshlodUser.Id = grenzwert.GetAttributeValue <Guid>(MetadataGrenzwert.GrenzwerteId); } if (grenzwert.Contains(MetadataGrenzwert.Grenze)) { meteringPointThreshlodUser.GrenzwertBezeichner = String.Format("{0:F2}", grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.Grenze)); } if (grenzwert.Contains(MetadataGrenzwert.GültigAb)) { meteringPointThreshlodUser.GultingAb = grenzwert.GetAttributeValue <DateTime>(MetadataGrenzwert.GültigAb); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMaxUser)) { meteringPointThreshlodUser.MaximaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMaxUser)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMinUser)) { meteringPointThreshlodUser.MinimaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMinUser)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMaxUser)) { meteringPointThreshlodUser.MaximaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMaxUser)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMinUser)) { meteringPointThreshlodUser.MinimaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMinUser)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMaxUser)) { meteringPointThreshlodUser.MaximaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMaxUser)).ToString(); } if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMinUser)) { meteringPointThreshlodUser.MinimaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMinUser)).ToString(); } meteringPointThresholds.Add(meteringPointThreshlodUser); #endregion "User Threshold Values" meteringPoint.MeteringCodeThresholds = meteringPointThresholds; } #endregion "Threshold Values" } meteringPoints.Add(meteringPoint); } return(meteringPoints); }
private void createCampaignActivityEM(Entity entity, string authentication, IOrganizationService service) { Guid campaignActivityId = entity.Id; EmEmailCampaign eCampaign; OrganizationServiceContext orgcontext = new OrganizationServiceContext(service); int sendingType = 1; try { if (entity.Contains("new_sendingtype")) { sendingType = ((OptionSetValue)entity["new_sendingtype"]).Value; } var query = (from r in orgcontext.CreateQuery("campaignactivity") where (Guid)r["activityid"] == campaignActivityId select new { campaign = r.Attributes.Contains("regardingobjectid") ? r["regardingobjectid"] : new EntityReference("campaign", Guid.Empty), CampaignSubject = r.Attributes.Contains("subject") ? r["subject"] : string.Empty }).FirstOrDefault(); if (query != null) { eCampaign = new EmEmailCampaign(); // Periyodik if (sendingType == 2) { eCampaign.CampaignType = EmEmailCampaignType.SingleShot; eCampaign.HtmlMessage = GetHtmlAttachment(Globals.BirthdayCampaignId, service); } else // Standart { eCampaign.CampaignType = EmEmailCampaignType.Template; eCampaign.HtmlMessage = "<html><head></head><body></body></html>"; } eCampaign.CampaignID = campaignActivityId.ToString().Replace("{", "").Replace("}", "").Replace("-", "").ToUpper(); eCampaign.ClickThroughFlag = true; eCampaign.FromAddress = Globals.EuromsgFromAddressLive; eCampaign.FromName = Globals.EuromsgFromNameLive; eCampaign.GoogleAnalytics = false; eCampaign.GoogleUtmCampaign = ""; eCampaign.GoogleUtmContent = ""; eCampaign.GoogleUtmMedium = ""; eCampaign.GoogleUtmSource = ""; eCampaign.GoogleUtmTerm = ""; eCampaign.Locked = false; eCampaign.Name = ((EntityReference)query.campaign).Name; eCampaign.OmnitureFlag = false; eCampaign.RateFlag = false; eCampaign.ReadFlag = true; eCampaign.ReplyAddress = Globals.EuromsgReplyAddressLive; eCampaign.Speed = 1; eCampaign.Subject = new string[1]; eCampaign.Subject[0] = query.CampaignSubject.ToString(); eCampaign.UniqueEmailFlag = false; eCampaign.ShareThisFlag = false; EmCampaignFuncRes emResult = campaign.CreateEmailCampaign(authentication, ref eCampaign); if (emResult.Code != "00") // Başarısız ise { if (emResult.Message == "Email message has a high spam score. This e-mail campaign can't be created." || emResult.Message == "Not a valid from name!") { throw new InvalidPluginExecutionException(emResult.Message); } else { throw new InvalidPluginExecutionException(emResult.Message + "\n" + emResult.DetailedMessage); } } LogoutEM(authentication); } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.ToString()); } }
private List<EmailProxy> TakeDataList() { using (var orgContext = new OrganizationServiceContext(this.service)) { var PrelistData = (from i in orgContext.CreateQuery<InvoiceDetail>() where i.new_Data_razmescheniya != null && i.ActualDeliveryOn != null && i.new_Fact_date_otgryzki == null && i.InvoiceId != null && i.new_shipping == false && i.ActualDeliveryOn <= DateTime.Now.ToUniversalTime() && i.CreatedOn > DateTime.Parse("10-03-2015").ToUniversalTime() select i).ToList(); if (PrelistData == null) return null; return (from c in PrelistData select new EmailProxy { EntityOwner = c.OwnerId, InvoiceDetail = new EntityReference { Id = c.Id, LogicalName = c.LogicalName }, InvoiceAccount = c.new_sopplierid, NumberInvoice = (from p in orgContext.CreateQuery<Invoice>() where p.Id == c.InvoiceId.Id select p.new_invoice_number).FirstOrDefault(), Number = c.new__number_invoice_supplier, Product = c.ProductId.Name, InvoiceId = c.InvoiceId.Id }).ToList(); } }
private bool FindAndDeactivateEntity(DateTime date) { using (var orgContext = new OrganizationServiceContext(this.service)) { var currencyFromCrm = (from i in orgContext.CreateQuery<sl_ExchangeRate>() where i.sl_RelevanceDate < date.ToUniversalTime().AddHours(_ToCrmUTCDate) && i.statecode == sl_ExchangeRateState.Active select i).ToList(); if (currencyFromCrm.Count == 0) { return true; } // деактивация устаревших курсов State = Close foreach (var item in currencyFromCrm) { SetStateRequest deactivateRequest = new SetStateRequest() { EntityMoniker = new EntityReference(sl_ExchangeRate.EntityLogicalName, item.Id), State = new OptionSetValue(1), Status = new OptionSetValue(-1) }; orgContext.Execute(deactivateRequest); } return true; } }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = factory.CreateOrganizationService(context.UserId); if (context.MessageName == "Create") { object blok = new object(); int? number; new_constant counter = new new_constant(); Entity entity = (Entity)context.InputParameters["Target"]; string correntYear = DateTime.Now.ToString("yy"); lock (blok) { using (var orgContext = new OrganizationServiceContext(service)) { var getCounterValue = (from c in orgContext.CreateQuery<new_constant>() select c).FirstOrDefault(); switch (entity.LogicalName) { case new_purchase_order.EntityLogicalName: number = getCounterValue.new_purchase_order; counter.new_purchase_order = ++number; if (entity.Attributes.Contains("new_name") == true) entity["new_name"] = $"{number}/{correntYear}"; else entity.Attributes.Add("new_name", $"{number}/{correntYear}"); break; case new_purchase_order_change.EntityLogicalName: number = getCounterValue.new_purchase_order_change; counter.new_purchase_order_change = ++number;; if (entity.Attributes.Contains("new_name") == true) entity["new_name"] = $"{number}/{correntYear}"; else entity.Attributes.Add("new_name", $"{number}/{correntYear}"); break; case new_purchase_deal.EntityLogicalName: number = getCounterValue.new_purchase_deal; counter.new_purchase_deal = ++number; if (entity.Attributes.Contains("new_name") == true) entity["new_name"] = $"{number}/{correntYear}"; else entity.Attributes.Add("new_name", $"{number}/{correntYear}"); break; case new_purchase_task.EntityLogicalName: number = getCounterValue.new_purchase_deal; counter.new_purchase_task = ++number; if (entity.Attributes.Contains("new_name") == true) entity["new_name"] = $"{number}/{correntYear}"; else entity.Attributes.Add("new_name", $"{number}/{correntYear}"); break; default: return; } counter.Id = getCounterValue.Id; service.Update(counter); } } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
public IQueryable <Entity> CreateQuery(string entityName, OrganizationServiceContext context) { return(context.CreateQuery(entityName)); }
private List<Product> GetProductFromCRM(OrganizationServiceContext orgContext) { return (from c in orgContext.CreateQuery<Product>() select c).ToList(); }
public EntityReference CreateProduct(ExcelProxyProduct product) { using (var orgContext = new OrganizationServiceContext(service)) { Product entityProduct = new Product() { Id = Guid.NewGuid(), ProductNumber = product.SKU, Name = product.Product, Price = new Money(Convert.ToDecimal(product.recomendetPriceUSD)), DefaultUoMScheduleId = (from i in orgContext.CreateQuery <UoMSchedule>() where i.Name == "Единица измерения по умолчанию" //where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery <UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturer = findVendor(product.Vendor) }; try { /////////////////////////////////////// Guid idNewProduct = service.Create(entityProduct); var productPriceLevel = new ProductPriceLevel() { PriceLevelId = (from i in orgContext.CreateQuery <PriceLevel>() where i.Name == "Default UAH Pricelist" //Default USD Pricelist select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault(), UoMId = (from i in orgContext.CreateQuery <UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), Amount = new Money(Convert.ToDecimal(product.recomendetPriceUSD)), ProductId = new EntityReference { Id = idNewProduct, LogicalName = Product.EntityLogicalName, Name = product.Product } }; var idProductPriceLevel = service.Create(productPriceLevel); var updateNewProduct = new Product() { Id = idNewProduct, PriceLevelId = (from i in orgContext.CreateQuery <PriceLevel>() where i.Name == "Default USD Pricelist" select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault() }; service.Update(updateNewProduct); return(new EntityReference { Id = idNewProduct, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }); /////////////////////////////////////// } catch { return(null); } } }
private EntityReference ToTransactionCurrency(string p, decimal? value) { using (var orgContext = new OrganizationServiceContext(this.service)) { if (p == "USD") { return (from i in orgContext.CreateQuery<TransactionCurrency>() where i.ISOCurrencyCode == p select i).FirstOrDefault().ToEntityReference(); } var TransactionCurrencyId = (from i in orgContext.CreateQuery<TransactionCurrency>() where i.ISOCurrencyCode == p select i.Id).FirstOrDefault(); TransactionCurrency entityForUpdate = new TransactionCurrency() { Id = TransactionCurrencyId, LogicalName = TransactionCurrency.EntityLogicalName, ExchangeRate = value }; service.Update(entityForUpdate); return entityForUpdate.ToEntityReference(); } }
public void Execute(IServiceProvider serviceProvider) { try { var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); var service = serviceFactory.CreateOrganizationService(context.UserId); if (context.MessageName.ToLower() != "create" || context.PrimaryEntityName != new_oplata.EntityLogicalName) return; var oplata = (Entity)context.InputParameters["Target"]; if (oplata.GetAttributeValue<EntityReference>("new_sdelkaid") == null) return; new_oplata newoplata = oplata.ToEntity<new_oplata>(); var sdelka = oplata.GetAttributeValue<EntityReference>("new_sdelkaid"); var dogovor = oplata.GetAttributeValue<EntityReference>("new_dogovorid"); using (var orgContext = new OrganizationServiceContext(service)) { var sumEntity = (from i in orgContext.CreateQuery<new_oplata>() where i.new_dogovorid.Id == dogovor.Id select i).ToList(); var sumProc = (from d in sumEntity select d.new_discount_predoplatu).ToArray().Sum(); var sumSumma = (from p in sumEntity select p.new_summa.Value).ToArray().Sum(); var sumSummaUsd = (from p in sumEntity select p.new_summausd).ToArray().Sum(); if (sumProc < 100) { var dogovorUpdate = new SalesOrder() { Id = dogovor.Id, new_Receivedamount = new Money(sumSumma), new_amount = sumProc, new_summa = sumSummaUsd }; service.Update(dogovorUpdate); } else if (sumProc == 100) { //int newStatus = (int)SalesOrderState.Fulfilled; //var request = new FulfillSalesOrderRequest //{ // OrderClose = new OrderClose // { // SalesOrderId = new EntityReference { LogicalName = SalesOrder.EntityLogicalName, Id = dogovor.Id } // }, // Status = new OptionSetValue(100001) //}; //service.Execute(request); var dogovorUpdate = new SalesOrder() { Id = dogovor.Id, new_Receivedamount = new Money(sumSumma), new_amount = sumProc, StatusCode = new OptionSetValue(100000000) //100 001 }; service.Update(dogovorUpdate); } else if (sumProc > 100) { //var dogovorUpdate = new SalesOrder() //{ // Id = dogovor.Id, // new_Receivedamount = new Money(sumSumma), // new_amount = sumProc //}; //service.Update(dogovorUpdate); throw new InvalidPluginExecutionException("Поступившая сумма не соответствует Общей сумме сделки. Проверьте введенные данные."); } orgContext.SaveChanges(); } } catch (Exception) { throw; } }
public void When_Creating_Using_Organization_Context_Without_Saving_Changes_Record_Should_Not_Be_Created() { var context = new XrmFakedContext(); context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account)); var account = new Account() { Id = Guid.NewGuid(), Name = "Super Great Customer", AccountNumber = "69" }; var service = context.GetFakedOrganizationService(); using (var ctx = new OrganizationServiceContext(service)) { ctx.AddObject(account); var retrievedAccount = ctx.CreateQuery<Account>().SingleOrDefault(acc => acc.Id == account.Id); Assert.Null(retrievedAccount); } }
public void Processes(Annotation annotation, IOrganizationService service) { using (var orgContext = new OrganizationServiceContext(service)) { var invoiceMain = (from y in orgContext.CreateQuery<Invoice>() where y.Id == annotation.ObjectId.Id select y).FirstOrDefault(); var exel = new ExcelReader().ExcelOpenSpreadsheets(annotation.DocumentBody.ToString(), annotation.FileName.ToString()); if (exel == null) return; if (exel.Tables[0].Rows[1][0].ToString() != "SKU") return; var data = new CreateNewProduct(); List<ExcelProxyInvoice> invoice = new List<ExcelProxyInvoice>(); data.service = service; data.mainEntityId = annotation.ObjectId; for (int i = 2; i < exel.Tables[0].Rows.Count; i++) { var product = new ExcelProxyProduct(); var invoicedetail = new ExcelProxyInvoiceDetail(); if (exel.Tables[0].Rows[i][0].ToString() != string.Empty && exel.Tables[0].Rows[i][0].ToString() != "Итого:") { product.SKU = exel.Tables[0].Rows[i][0].ToString(); product.Vendor = exel.Tables[0].Rows[i][1].ToString(); //product.recomendetPriceUSD = exel.Tables[0].Rows[i][10].ToString(); product.Product = exel.Tables[0].Rows[i][2].ToString(); invoicedetail.Product = exel.Tables[0].Rows[i][2].ToString(); invoicedetail.Count = exel.Tables[0].Rows[i][3].ToString(); invoicedetail.Priceperunit = exel.Tables[0].Rows[i][4].ToString(); invoicedetail.Baseamount = exel.Tables[0].Rows[i][5].ToString(); invoicedetail.Purchaseprice = exel.Tables[0].Rows[i][6].ToString(); invoicedetail.Amountpurchase = exel.Tables[0].Rows[i][7].ToString(); invoicedetail.Pricepurchaseusd = exel.Tables[0].Rows[i][11].ToString(); invoicedetail.Exchangerates = exel.Tables[0].Rows[i][13].ToString(); invoicedetail.totalUSD = exel.Tables[0].Rows[i][12].ToString(); invoice.Add(new ExcelProxyInvoice { Marza = exel.Tables[0].Rows[i][8].ToString(), MarzaPersent = exel.Tables[0].Rows[i][9].ToString(), totalUSD = exel.Tables[0].Rows[i][12].ToString(), exchangeRates = exel.Tables[0].Rows[i][13].ToString() }); EntityReference idProduct = data.ProductFromSpec(product, invoiceMain.PriceLevelId); if (idProduct == null) { throw new InvalidPluginExecutionException("Product not found"); } if (data.CreateInvoiceDetail(invoicedetail, idProduct) == false) { throw new InvalidPluginExecutionException("InvoiceDetail don`t create"); } } else { break; } } decimal sum = (from i in invoice select Convert.ToDecimal(i.Marza)).Sum(); decimal percent = (from i in invoice select Convert.ToDecimal(i.MarzaPersent)).Average(); decimal totalUSD = (from i in invoice select Convert.ToDecimal(i.totalUSD)).Sum(); double rates = (from i in invoice select Convert.ToDouble(i.exchangeRates)).Average(); var updateInvoice = new Invoice() { Id = annotation.ObjectId.Id, //new_marginUSD = invoiceMain.new_marginUSD + (double)sum, //new_morginpercentage = percent == 0 ? 0 : (invoiceMain.new_morginpercentage ?? 0 + percent), //new_USD = invoiceMain.new_USD + (double)totalUSD, //new_exchangerate = invoiceMain.new_exchangerate ?? 0 + rates }; service.Update(updateInvoice); } }
public EntityReference ProductFromSpec(ExcelProxyProduct product, EntityReference priceName) { using (var orgContext = new OrganizationServiceContext(service)) { var finder = (from c in orgContext.CreateQuery<Product>() where c.ProductNumber == product.SKU select c).FirstOrDefault(); if (finder != null) { var entityProduct = new Product() { Id = finder.Id, ProductNumber = product.SKU, Name = product.Product, DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>() where i.Name == "Единица измерения по умолчанию" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturingname = findVendor(product.Vendor) }; try { service.Update(entityProduct); return new EntityReference { Id = entityProduct.Id, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }; } catch { return null; } } else { return CreateProduct(product, priceName); } } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate OrganizationServiceContext orgContext = new OrganizationServiceContext(service); // Retrieve records with Skip/Take record paging. Setting a page size // can help you manage your Skip and Take calls, since Skip must be // passed a multiple of Take's parameter value. //<snippetUseLinqWithDotNetDataServicesDE2> int pageSize = 5; var accountsByPage = from a in orgContext.CreateQuery("account") select a["name"]; System.Console.WriteLine("Skip 10 accounts, then Take 5 accounts"); System.Console.WriteLine("======================================"); foreach (var name in accountsByPage.Skip(2 * pageSize).Take(pageSize)) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE2> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Skip 10 accounts, then Take 5 accounts //====================================== //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Fourth Coffee 10 //<End of Listing> // Use orderBy to order items retrieved. //<snippetUseLinqWithDotNetDataServicesDE3> var orderedAccounts = from a in orgContext.CreateQuery("account") orderby a["name"] select a["name"]; System.Console.WriteLine("Display accounts ordered by name"); System.Console.WriteLine("================================"); foreach (var name in orderedAccounts) { System.Console.WriteLine(name); } //</snippetUseLinqWithDotNetDataServicesDE3> System.Console.WriteLine(); System.Console.WriteLine("<End of Listing>"); System.Console.WriteLine(); //OUTPUT: //Display accounts ordered by name //================================ //A. Datum Corporation //Adventure Works //Coho Vineyard //Fabrikam //Fourth Coffee 1 //Fourth Coffee 10 //Fourth Coffee 2 //Fourth Coffee 3 //Fourth Coffee 4 //Fourth Coffee 5 //Fourth Coffee 6 //Fourth Coffee 7 //Fourth Coffee 8 //Fourth Coffee 9 //Humongous Insurance //<End of Listing> // Filter multiple entities using LINQ. //<snippetUseLinqWithDotNetDataServicesDE4> var query = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] } }; Console.WriteLine("Join account and contact"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in query) { Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE4> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account and contact //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Contact Name: Ben Andrews //Account Phone: (206)555-5555 //Contact Name: Ben Andrews //Account Phone: (425)555-5555 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> // Build a complex query with LINQ. This query includes multiple // JOINs and a complex WHERE statement. //<snippetUseLinqWithDotNetDataServicesDE5> var complexQuery = from c in orgContext.CreateQuery("contact") join a in orgContext.CreateQuery("account") on c["contactid"] equals a["primarycontactid"] join l in orgContext.CreateQuery("lead") on a["originatingleadid"] equals l["leadid"] where (String)c["lastname"] == "Wilcox" || (String)c["lastname"] == "Andrews" where ((String)a["address1_telephone1"]).Contains("(206)") || ((String)a["address1_telephone1"]).Contains("(425)") select new { Contact = new { FirstName = c["firstname"], LastName = c["lastname"] }, Account = new { Address1_Telephone1 = a["address1_telephone1"] }, Lead = new { LeadId = l["leadid"] } }; Console.WriteLine("Join account, contact and lead"); Console.WriteLine("List all records matching specified parameters"); Console.WriteLine("Contact name: Wilcox or Andrews"); Console.WriteLine("Account area code: 206 or 425"); Console.WriteLine("=============================================="); foreach (var record in complexQuery) { Console.WriteLine("Lead ID: {0}", record.Lead.LeadId); Console.WriteLine("Contact Name: {0} {1}", record.Contact.FirstName, record.Contact.LastName); Console.WriteLine("Account Phone: {0}", record.Account.Address1_Telephone1); } //</snippetUseLinqWithDotNetDataServicesDE5> Console.WriteLine("<End of Listing>"); Console.WriteLine(); //OUTPUT: //Join account, contact and lead //List all records matching specified parameters //Contact name: Wilcox or Andrews //Account area code: 206 or 425 //============================================== //Lead ID: 78d5df14-64a3-e011-aea3-00155dba3818 //Contact Name: Colin Wilcox //Account Phone: (425)555-5555 //<End of Listing> #endregion Demonstrate DeleteRequiredRecords(service, true); } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public EntityReference CreateProduct(ExcelProxyProduct product, EntityReference priceName) { using (var orgContext = new OrganizationServiceContext(service)) { Product entityProduct = new Product() { Id = Guid.NewGuid(), ProductNumber = product.SKU, Name = product.Product, DefaultUoMScheduleId = (from i in orgContext.CreateQuery<UoMSchedule>() where i.Name == "Единица измерения по умолчанию" //where i.Id == new Guid("AFB0C13B-11DA-49D0-8767-A71F1AA593BF") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), DefaultUoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" //where i.Id == new Guid("28FD5C9C-22F7-419C-BBBC-720523DD3666") select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), new_manufacturingname = findVendor(product.Vendor) }; try { /////////////////////////////////////// Guid idNewProduct = service.Create(entityProduct); var productPriceLevel = new ProductPriceLevel() { PriceLevelId = priceName /*(from i in orgContext.CreateQuery<PriceLevel>() where i.Name == "Default Sales USD" //Default Sales USD select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault()*/, UoMId = (from i in orgContext.CreateQuery<UoM>() where i.Name == "Базовая единица" select new EntityReference { Id = i.Id, LogicalName = i.LogicalName, Name = i.Name }).FirstOrDefault(), ProductId = new EntityReference { Id = idNewProduct, LogicalName = Product.EntityLogicalName, Name = product.Product } }; var idProductPriceLevel = service.Create(productPriceLevel); var updateNewProduct = new Product() { Id = idNewProduct, PriceLevelId = priceName/*(from i in orgContext.CreateQuery<PriceLevel>() where i.Name == "Default Sales USD " select new EntityReference { LogicalName = PriceLevel.EntityLogicalName, Id = i.Id, Name = i.Name }).FirstOrDefault()*/ }; service.Update(updateNewProduct); return new EntityReference { Id = idNewProduct, Name = entityProduct.Name, LogicalName = entityProduct.LogicalName }; /////////////////////////////////////// } catch { return null; } } }
protected virtual IPurchasable SelectFromLineItemEntities(OrganizationServiceContext serviceContext, Entity purchaseEntity, string lineItemRelationship, Entity purchaseMetadata, IEnumerable <IPurchasableItemOptions> options) { TraceMethodInfo("Start: purchaseEntity={0}:{1}, lineItemRelationship={2}", purchaseEntity.LogicalName, purchaseEntity.Id, lineItemRelationship); var productAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemProduct); if (string.IsNullOrEmpty(productAttribute)) { TraceMethodError("Unable to retrieve products from line item entities. {0} not defined in web form step metadata. Returning null.", PurchaseMetadataAttributes.LineItemProduct); return(null); } var descriptionAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemDescription); var instructionsAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemInstructions); var orderAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemOrder); var requiredAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemRequired); var quantityAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemQuantity); var uomAttribute = purchaseMetadata.GetAttributeValue <string>(PurchaseMetadataAttributes.LineItemUom); var entities = purchaseEntity.GetRelatedEntities(serviceContext, lineItemRelationship).ToArray(); if (!entities.Any()) { TraceMethodError("Unable to retrieve any line item entities. Returning null."); return(null); } var productIds = entities .Select(e => e.GetAttributeValue <EntityReference>(productAttribute)) .Where(product => product != null) .Select(product => product.Id) .ToArray(); if (!productIds.Any()) { TraceMethodError("Unable to retrieve any products from line item entities. Returning null."); return(null); } var products = serviceContext.CreateQuery("product") .WhereIn(e => e.GetAttributeValue <Guid>("productid"), productIds) .ToDictionary(e => e.Id, e => e); var lineItems = entities .Select(e => LineItem.GetLineItemFromLineItemEntity(e, productAttribute, descriptionAttribute, instructionsAttribute, orderAttribute, requiredAttribute, quantityAttribute, uomAttribute, products)) .Where(lineItem => lineItem != null); var quote = QuoteFunctions.CreateQuote(lineItems, purchaseEntity.ToEntityReference(), serviceContext, Dependencies.GetServiceContextForWrite(), Dependencies.GetPortalUser(), Dependencies.GetPriceList(), WebFormSession.AnonymousIdentification, Target, purchaseMetadata); var purchasable = quote == null ? null : SelectFromQuote(quote, purchaseMetadata, options); TraceMethodInfo("End"); return(purchasable); }