/// <summary> /// This method first connects to the Organization service. Afterwards, a /// quote is created. This quote is then converted to an order, and the pricing /// is unlocked and relocked. This is followed by the order being converted /// to an invoice, and the pricing is locked then unlocked. /// </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 { //<snippetProcessingQuotesAndSalesOrders1> // 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 Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity<Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity<Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdateRequest> // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // 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 void Page_Load(object sender, EventArgs e) { if (!int.TryParse(Request.QueryString["id"], out id)) { Response.Write("<script language='javascript'>alert('参数错误!');location.href='Quote.aspx?id=" + id + "';</script>"); } qd = QuoteOperation.GetQuoteDetailById(id); if (!IsPostBack) { FormDataBind(); txtDiscount.Value = StringHelper.CurtNumber(qd.Discount.ToString()); } }
public void CreateQuoteDetail(QuoteDetail qd) { SqlParameter[] param = new SqlParameter[] { SqlUtilities.GenerateInputNVarcharParameter("@quote_id", 50, qd.QuoteId), SqlUtilities.GenerateInputIntParameter("@carrier_id", qd.Carrier.Id), SqlUtilities.GenerateInputIntParameter("@carrier_area_id", qd.CarrierArea.Id), SqlUtilities.GenerateInputIntParameter("@client_id", qd.ClientId), SqlUtilities.GenerateInputParameter("@status", SqlDbType.Bit, qd.Status), SqlUtilities.GenerateInputParameter("@discount", SqlDbType.Decimal, qd.Discount), SqlUtilities.GenerateInputIntParameter("@user_id", qd.UserId), SqlUtilities.GenerateInputDateTimeParameter("@create_time", qd.CreateTime), SqlUtilities.GenerateInputParameter("@preferential_gram", SqlDbType.Decimal, qd.PreferentialGram), SqlUtilities.GenerateInputParameter("@is_register_abate", SqlDbType.Bit, qd.IsRegisterAbate), SqlUtilities.GenerateInputParameter("@register_costs", SqlDbType.Decimal, qd.RegisterCosts) }; string sql = "INSERT INTO quote_details(quote_id, carrier_id, carrier_area_id, client_id, status, discount, user_id, create_time, preferential_gram, is_register_abate, register_costs) VALUES(@quote_id, @carrier_id, @carrier_area_id, @client_id, @status, @discount, @user_id, @create_time, @preferential_gram, @is_register_abate, @register_costs)"; SqlHelper.ExecuteNonQuery(CommandType.Text, sql, param); }
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); }
public bool CreateQuoteDetail(ExcelProxyQuotedetail quotedetail, EntityReference product) { using (var orgContext = new OrganizationServiceContext(service)) { var newquoteDetail = new QuoteDetail() { ProductId = product, IsPriceOverridden = true, Quantity = Convert.ToInt32(quotedetail.Count), PricePerUnit = new Money(Convert.ToDecimal(quotedetail.priceForOneHRN)), new_priceprocurementUAH = new Money(Convert.ToDecimal(quotedetail.buyPriceHRN)), new_totalpurchaseUAH = new Money(Convert.ToDecimal(quotedetail.buyPriceAllHRN)), new_pricepurchaseusd = Convert.ToDouble(quotedetail.buyPriceAllUSD), QuoteId = mainEntityId, new_kursspeka = Convert.ToDouble(quotedetail.exchangeRates), new_viborkurs = new OptionSetValue(100000003), new_totalpurchaseusd = Convert.ToDouble(quotedetail.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(newquoteDetail); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } return(true); }
public object Post(QuoteDetail model) { object json; try { model = repository.Add(model); if (model != null) { json = new { total = 1, data = model, success = true }; } else { json = new { success = false }; }; } catch (Exception ex) { LogManager.Write("ERROR:" + Environment.NewLine + "\tMETHOD = " + this.GetType().FullName + "." + MethodBase.GetCurrentMethod().Name + Environment.NewLine + "\tMESSAGE = " + ex.Message); json = new { message = ex.Message, success = false }; }; return(json); }
public void Execute(IServiceProvider serviceProvider) { ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); CrmServiceContext xrm = new CrmServiceContext(service); try { if (context.PostEntityImages.Contains("PostQuoteProduct") && context.PostEntityImages["PostQuoteProduct"] is Entity) { QuoteDetail QuoteProduct = context.PostEntityImages["PostQuoteProduct"].ToEntity <QuoteDetail>(); Quote quote = xrm.QuoteSet.Where(p => p.Id == QuoteProduct.QuoteId.Id).FirstOrDefault(); OpportunityProduct oppProd; //Looking for opportunity product in related opportunity if (!(bool)QuoteProduct.IsProductOverridden)//if QuoteProduct is existing product { oppProd = xrm.OpportunityProductSet.Where(p => p.ProductId == QuoteProduct.ProductId && p.OpportunityId == quote.OpportunityId && p.SequenceNumber == QuoteProduct.SequenceNumber).FirstOrDefault(); } else//if QuoteProduct is write-in product { oppProd = xrm.OpportunityProductSet.Where(p => p.OpportunityId == quote.OpportunityId && p.ProductDescription == QuoteProduct.ProductDescription && p.SequenceNumber == QuoteProduct.SequenceNumber).FirstOrDefault(); } //Updating custom fields if (oppProd != null) { QuoteProduct.new_Comment = oppProd.new_Comment; QuoteProduct.new_Country = oppProd.new_Country; } service.Update(QuoteProduct); } } catch (Exception ex) { throw new InvalidPluginExecutionException($"An error occurred in QuoteProducts plug-in: {ex.Message}"); } }
public void SetIdManually() { int qdId; using (var db = new Context()) { var q = new Quote { QuoteDetails = new Collection <QuoteDetail>() }; var p = new Product(); var qd = new QuoteDetail { Name = "blah", Product = p }; db.Products.Add(p); db.QuoteDetails.Add(qd); db.Quotes.Add(q); db.SaveChanges(); qdId = qd.Id; } using (var db = new Context()) { var qd = db.QuoteDetails.Single(x => x.Id == qdId); qd.ParentId = 6; db.ChangeTracker.DetectChanges(); Assert.That(qd.Quote.Id == 6); } }
public List <string> UpdateQuantity(int currentQuoteId, int quantity, string itemID, string type = "") { ItemService itemsrvc = new ItemService(); itemsrvc.UserVM = UserVM; Quote currentQuote = itemsrvc.GetQuoteByLoggedIn(currentQuoteId, type); // Quote currentQuote = _Context.Quote.GetSingle(e => e.QuoteID == currentQuoteId); List <string> lstPriceQuantity = new List <string>(); List <QuoteDetail> lstQD = currentQuote.QuoteDetails.ToList(); decimal? totalPrice = 0; if (lstQD != null) { QuoteDetail iQD = lstQD.Where(e => e.ItemID == itemID).FirstOrDefault(); if (iQD != null) { iQD.Quantity = quantity; totalPrice = iQD.Item.Price * quantity; //Updating Penworthy Updated Date if (currentQuote != null) { ItemListViewService lstviewsvc = new ItemListViewService(); lstviewsvc.UserVM = UserVM; lstviewsvc.UpdatedDateTime(currentQuoteId); } _Context.QuoteDetail.SaveChanges(); } } if (UserVM != null) { UserVM.SCCount = currentQuote.QuoteDetails.Sum(e => e.Quantity); lstPriceQuantity.Add(UserVM.SCCount.ToString()); } lstPriceQuantity.Add(totalPrice.ToString()); lstPriceQuantity.Add(currentQuote.QuoteDetails.Sum(e => e.Item.Price * e.Quantity).ToString()); return(lstPriceQuantity); }
private void OnSelectedRowsChanged() { SelectedRange[] selectedContacts = Lines.GetSelectedRows(); if (selectedContacts.Length > 0) { ObservableQuoteDetail observableQuoteDetail = SelectedQuoteDetail.GetValue(); if (observableQuoteDetail.InnerQuoteDetail != null) { observableQuoteDetail.InnerQuoteDetail.PropertyChanged -= quote_PropertyChanged; } QuoteDetail selectedQuoteDetail = (QuoteDetail)Lines.GetItem(selectedContacts[0].FromRow.Value); if (selectedQuoteDetail != null) { selectedQuoteDetail.PropertyChanged += quote_PropertyChanged; } SelectedQuoteDetail.GetValue().SetValue(selectedQuoteDetail); } else { SelectedQuoteDetail.GetValue().SetValue(null); } }
public ItemDetailedViewModel GetItemByID(string itemID, string Quoteid, string type = "") { ItemDetailedViewModel kplVM = new ItemDetailedViewModel(); kplVM.LstItemParentVM = new List <ItemParentViewModel>(); int quoteid = UserVM != null ? UserVM.CurrentQuoteID : Convert.ToInt32(Quoteid); Item item = _Context.Item.GetSingle(e => e.ItemID == itemID); ItemListViewService itemListViewSrv = new ItemListViewService(); int?seriesID = item.Series; int?originalSetID = null; originalSetID = item != null ? item.SetID : (int?)null; QuoteViewService QuoteViewService = new QuoteViewService(); Item itVM = null; List <QuoteDetail> lstQuoteDetailsType = null; List <Item> itemList = new List <Item>(); Item setItemInfo = null; if (originalSetID != null) { string setID = Convert.ToString(originalSetID); setItemInfo = _Context.Item.GetSingle(e => e.ItemID == setID); itemList = itemListViewSrv.GetActiveItemList().Where(e => e.SetID == originalSetID).ToList(); } itemList = itemListViewSrv.SortingAlgorithim(itemList); itemList.Remove(item); itemList.Insert(0, item); kplVM.LstItemParentVM.Add(new ItemParentViewModel()); kplVM.LstItemParentVM.Add(new ItemParentViewModel()); Quote currentQuote = new Quote(); string quotetypetext = ""; Quote scQuote = GetQuoteByLoggedIn(quoteid, type); if (quoteid != 0) { currentQuote = _Context.Quote.GetSingle(e => e.QuoteID == quoteid); //GetQuoteByLoggedIn(quoteid, type); lstQuoteDetailsType = scQuote.QuoteDetails.ToList(); quotetypetext = currentQuote.QuoteType.QuoteTypeText; } kplVM.QuoteTypeText = quotetypetext; ItemContainerService itemContainerService = new ItemContainerService(); itemContainerService.UserVM = UserVM; List <string> lstTitlesBroughtBeforeItemIDs = itemContainerService.GetTitlesBroughtBeforeItemIDs(); List <string> lstCharacterBroughtBeforeItemIDs = new List <string>(); List <string> lstSeriesBroughtBeforeItemIDs = new List <string>(); if (UserVM != null && UserVM.CRMModelProperties != null) { lstSeriesBroughtBeforeItemIDs = itemContainerService.GetListSeriesCharacterbyCustomerID(UserVM.CRMModelProperties.CustAutoID, "SE"); lstCharacterBroughtBeforeItemIDs = itemContainerService.GetListSeriesCharacterbyCustomerID(UserVM.CRMModelProperties.CustAutoID, "PC"); } kplVM.LstItemParentVM[0].ListItemVM = itemList.Select(e => new ItemViewModel { ItemID = e.ItemID, Title = e.Title, IPrice = (double)e.Price, ISBN = e.ISBN, Description = e.Description, Lexile = e.Lexile, ARLevel = e.ARLevel, Author = e.Author != null ? e.Author.AuthorName : string.Empty, IsInCustomerTitles = lstTitlesBroughtBeforeItemIDs.Contains(e.ItemID) ? true : false, SeriesBroughtBefore = lstSeriesBroughtBeforeItemIDs.Contains(e.ItemID) ? true : false, CharecterBroughtBefore = lstCharacterBroughtBeforeItemIDs.Contains(e.ItemID) ? true : false, //ProductLine =e.ProductLine }).ToList(); if (quoteid != 0) { kplVM.LstItemParentVM[0].ListItemVM = UpdateIsScDWQuoteStatus(currentQuote.QuoteTypeID, lstQuoteDetailsType, kplVM.LstItemParentVM[0].ListItemVM); kplVM.LstItemParentVM[0].ListItemVM.ToList().ForEach(e => e.QuoteTypeText = quotetypetext); kplVM.LstItemParentVM[0].ListItemVM.ToList().ForEach(e => e.QuoteFlag = type); if (currentQuote.QuoteTypeID == (int)QuoteTypeEnum.Preview) { List <string> lstPreviewableItemIds = itemContainerService.GetPreviewableItemIDs(); kplVM.LstItemParentVM[0].ListItemVM.Where(e => lstPreviewableItemIds.Contains(e.ItemID)).ToList().ForEach(e => e.IsPreviewItem = true); } } if (kplVM.LstItemParentVM[0].ListItemVM.Count > 0) { kplVM.LstItemParentVM[0].ListItemVM.Where(e => e.ItemID == itemID).FirstOrDefault().IsSelected = true; } kplVM.SetItemsTotalPrice = Convert.ToDouble(kplVM.LstItemParentVM[0].ListItemVM.Sum(e => e.IPrice)); itVM = item; string strempty = string.Empty; kplVM.Binding = "Penworthy " + itVM.Type == null ? strempty : itVM.Type + " Book"; kplVM.InterestGrade = itVM.InterestGrade == null ? strempty : itVM.InterestGrade == ((int)InterestGradeEnums.Grade2to3).ToString() ? QuoteValidationConstants.Grade2to3 : itVM.InterestGrade == ((int)InterestGradeEnums.Grade4Above).ToString() ? QuoteValidationConstants.Grade4Above : itVM.InterestGrade == QuoteValidationConstants.Preschooltograde1Text ? QuoteValidationConstants.Preschooltograde1 : string.Empty; kplVM.ItemID = itVM.ItemID; kplVM.ISBN = itVM.ISBN == null ? string.Empty : itVM.ISBN; kplVM.ReviewSource = (itVM.SLJ == "Y" ? QuoteValidationConstants.SLJ + "," : string.Empty) + (itVM.PW == "Y" ? QuoteValidationConstants.PW + "," : string.Empty) + (itVM.Horn == "Y" ? QuoteValidationConstants.HORN + "," : string.Empty) + (itVM.Kirkus == "Y" ? QuoteValidationConstants.KIRKUS + "," : string.Empty) + (itVM.LJ == "Y" ? QuoteValidationConstants.LJ : string.Empty); kplVM.Subject = itVM.Subject == null ? strempty : itVM.Subject; kplVM.Primarycharacter = itVM.SeriesAndCharacter == null ? strempty : itVM.SeriesAndCharacter.SCText; kplVM.SecondCharacter = itVM.SecondaryCharacter == null ? strempty : itVM.SecondaryCharacter; kplVM.Format = itVM.Format == null ? strempty : itVM.Format; kplVM.Series = itVM.SeriesAndCharacter1 == null ? strempty : itVM.SeriesAndCharacter1.SCText; //kplVM.Quantity = itVM.QuoteDetails.FirstOrDefault().Quantity == null ? 1 : itVM.QuoteDetails.FirstOrDefault().Quantity; QuoteDetail quote = lstQuoteDetailsType != null?lstQuoteDetailsType.Where(e => e.ItemID == itVM.ItemID).FirstOrDefault() : null; if (quote != null) { kplVM.Quantity = quote.Quantity; } else { kplVM.Quantity = 1; } kplVM.Size = itVM.Size == null ? strempty : itVM.Size; kplVM.Fiction = ClassificationEnums.Fiction.ToString(); kplVM.Dewey = itVM.Dewery == null ? strempty : itVM.Dewery; kplVM.ARLevel = itVM.ARLevel == null ? strempty : itVM.ARLevel; kplVM.ARQuiz = itVM.ARQuiz; kplVM.Barcode = itVM.Barcode == null ? strempty : itVM.Barcode; kplVM.Classification = itVM.Classification == null ? strempty : itVM.Classification; kplVM.CopyRight = itVM.Copyright == null ? 0 : Convert.ToInt32(itVM.Copyright); kplVM.Description = itVM.Description == null ? strempty : itVM.Description; kplVM.Illustrator = itVM.Illustrator == null ? strempty : itVM.Illustrator; kplVM.ISBN = itVM.ISBN == null ? strempty : itVM.ISBN; kplVM.Lexile = itVM.Lexile == null ? strempty : itVM.Lexile; kplVM.OnListDate = itVM.OnListDate == null ? strempty : string.Format("{0:d}", itVM.OnListDate); kplVM.Pages = itVM.Pages; kplVM.Price = itVM.Price; kplVM.RCLevel = itVM.RCLevel == null ? strempty : itVM.RCLevel; kplVM.RCQuiz = itVM.RCQuiz; kplVM.Title = itVM.Title == null ? string.Empty : itVM.Title; kplVM.SetTitle = setItemInfo != null ? setItemInfo.Title == null ? string.Empty : setItemInfo.Title : string.Empty; kplVM.SetDescription = setItemInfo != null ? setItemInfo.Description == null ? string.Empty : setItemInfo.Description : string.Empty; kplVM.Type = itVM.ProductLine == null ? string.Empty : itVM.ProductLine.Trim().ToString(); kplVM.Publisher = itVM.PublisherID == null ? strempty : _Context.Publisher.GetSingle(e => e.PublisherID == itVM.PublisherID).PublisherName; kplVM.Author = itVM.AuthorID == null ? strempty : _Context.Author.GetSingle(e => e.AuthorID == itVM.AuthorID).AuthorName; kplVM.ProductLine = itVM.ProductLine == "" ? strempty : itVM.ProductLine; kplVM.QuoteFlag = type; QuoteDetail quoteDetails = null; quoteDetails = _Context.QuoteDetail.GetSingle(e => e.QuoteID == quoteid && e.ItemID == itemID); if (quoteid != 0 && originalSetID != null) { kplVM.QuoteID = Convert.ToInt32(quoteid); kplVM.QuoteTypeID = (Int32)_Context.Quote.GetSingle(e => e.QuoteID == quoteid).QuoteTypeID; if (quoteDetails != null && lstQuoteDetailsType != null) { kplVM.IsInSCDWQuote = kplVM.LstItemParentVM[0].ListItemVM.Where(e => e.ItemID == itemID).FirstOrDefault().IsInSCDWQuote; kplVM.DWSelectionStatus = _Context.QuoteDetail.GetSingle(e => e.QuoteID == quoteid && e.ItemID == itemID) != null?_Context.QuoteDetail.GetSingle(e => e.QuoteID == quoteid && e.ItemID == itemID).DWSelectionID.ToString() : ""; } else { kplVM.IsInSCDWQuote = kplVM.LstItemParentVM[0].ListItemVM.Where(e => e.ItemID == itemID).FirstOrDefault().IsInSCDWQuote; kplVM.DWSelectionStatus = kplVM.IsInSCDWQuote ? "1" : "5"; } } if (Quoteid != "0" && originalSetID == null) { // QuoteDetail quoteDetails = quoteDetails// _Context.QuoteDetail.GetSingle(e => e.QuoteID == quoteid && e.ItemID == itemID); if (quoteDetails != null) { kplVM.IsInSCDWQuote = kplVM.LstItemParentVM[0].ListItemVM.Where(e => e.ItemID == itemID).FirstOrDefault().IsInSCDWQuote; kplVM.DWSelectionStatus = Convert.ToString(quoteDetails.DWSelectionID); } } kplVM.UserVM = UserVM; return(kplVM); }
public void UpdateQutoeDetail(QuoteDetail qd) { SqlParameter[] param = new SqlParameter[] { SqlUtilities.GenerateInputIntParameter("@id", qd.Id), SqlUtilities.GenerateInputIntParameter("@carrier_id", qd.Carrier.Id), SqlUtilities.GenerateInputIntParameter("@carrier_area_id", qd.CarrierArea.Id), SqlUtilities.GenerateInputParameter("@discount", SqlDbType.Decimal, qd.Discount), SqlUtilities.GenerateInputIntParameter("@user_id", qd.UserId), SqlUtilities.GenerateInputParameter("@preferential_gram", SqlDbType.Decimal, qd.PreferentialGram), SqlUtilities.GenerateInputParameter("@is_register_abate", SqlDbType.Bit, qd.IsRegisterAbate), SqlUtilities.GenerateInputParameter("@register_costs", SqlDbType.Decimal, qd.RegisterCosts) }; string sql = "UPDATE quote_details SET carrier_id = @carrier_id, carrier_area_id = @carrier_area_id, discount = @discount, user_id = @user_id, preferential_gram = @preferential_gram, is_register_abate = @is_register_abate, register_costs = @register_costs WHERE id = @id"; SqlHelper.ExecuteNonQuery(CommandType.Text, sql, param); }
//Update the DWStatus in SingleItemDetailedView public SingleItemDetailedModel UpdateDWSingleItemDetails(KPLBasedCommonViewModel itemViewModel) { #region Private Variables int currentDWStatus = Convert.ToInt32(itemViewModel.DWSelectionStatus); int DWYes = (int)DecisionWhizardStatusEnum.Yes; int DWNo = (int)DecisionWhizardStatusEnum.No; int DWMayBe = (int)DecisionWhizardStatusEnum.MayBe; #endregion QuoteDetail dwquoteDetail = new QuoteDetail(); Quote scQuote = _Context.Quote.GetSingle(e => e.QuoteTypeID == (int)QuoteTypeEnum.ShoppingCart && e.UserID == UserVM.CRMModelProperties.LoggedINCustomerUserID); Quote DWQuote = _Context.Quote.GetSingle(e => e.QuoteTypeID == (int)QuoteTypeEnum.DecisionWhizard && e.UserID == UserVM.CRMModelProperties.LoggedINCustomerUserID); List <QuoteDetail> lstSCQuoteDetails = scQuote.QuoteDetails.ToList(); if (lstSCQuoteDetails != null)//item is in shoppingcart { QuoteDetail scQuoteDetail = lstSCQuoteDetails.Where(e => e.ItemID == itemViewModel.ItemID).FirstOrDefault(); dwquoteDetail = _Context.QuoteDetail.GetSingle(e => e.QuoteID == itemViewModel.QuoteID && e.ItemID == itemViewModel.ItemID); if (scQuoteDetail != null) { if (currentDWStatus == DWNo || currentDWStatus == DWMayBe) { //delete from sc _Context.QuoteDetail.Delete(scQuoteDetail); } } else { if (currentDWStatus == DWYes) { //Insert In to Sc _Context.QuoteDetail.Add(new QuoteDetail { ItemID = itemViewModel.ItemID, Quantity = 1, CreatedDate = DateTime.Now, QuoteID = scQuote.QuoteID, DWSelectionID = (int)DecisionWhizardStatusEnum.Yes, UpdateDate = DateTime.Now }); //Insert In to DW if (dwquoteDetail == null) { _Context.QuoteDetail.Add(new QuoteDetail { ItemID = itemViewModel.ItemID, Quantity = 1, CreatedDate = DateTime.Now, QuoteID = DWQuote.QuoteID, DWSelectionID = (int)DecisionWhizardStatusEnum.Yes, UpdateDate = DateTime.Now }); } } } if (dwquoteDetail != null) { dwquoteDetail.DWSelectionID = Convert.ToInt32(itemViewModel.DWSelectionStatus); } } _Context.QuoteDetail.SaveChanges(); //To get next element in list when we select either of yes no may be in singleItemDetailedview List <QuoteDetail> quoteDetailList = new List <QuoteDetail>(); ItemListViewModel _itemList = new ItemListViewModel(); _itemList.KPLItemListVM = new List <KPLBasedCommonViewModel>(); quoteDetailList = _Context.QuoteDetail.GetAll(e => e.QuoteID == itemViewModel.QuoteID).ToList(); List <Item> lstItem = quoteDetailList.Select(e => e.Item).ToList(); _itemList.KPLItemListVM = AutoMapper.Mapper.Map <IList <Item>, IList <KPLBasedCommonViewModel> >(lstItem).ToList(); int index = _itemList.KPLItemListVM.FindIndex(e => e.ItemID == itemViewModel.ItemID); if (index < _itemList.KPLItemListVM.Count() - 1) { itemViewModel.ItemID = _itemList.KPLItemListVM[index + 1].ItemID; } SingleItemDetailedModel singleItemDetailes = GetSingleItemDetailsWithSets(itemViewModel.ItemID.ToString(), itemViewModel.QuoteID.ToString()); return(singleItemDetailes); }
public List<QuoteDetail> GetQuoteDetailByQuoteId(int id) { List<QuoteDetail> result = new List<QuoteDetail>(); SqlParameter[] param = new SqlParameter[] { SqlUtilities.GenerateInputIntParameter("@quote_id", id) }; string sql = "SELECT id, quote_id, carrier_id, carrier_area_id, discount, preferential_gram, is_register_abate, register_costs FROM quote_details WHERE quote_id = @quote_id AND is_delete = 0"; using (SqlDataReader dr = SqlHelper.ExecuteReader(CommandType.Text, sql, param)) { while (dr.Read()) { QuoteDetail qd = new QuoteDetail(); qd.Id = dr.GetInt32(0); qd.QuoteId = dr.GetInt32(1); Carrier carrier = new CarrierDAL().GetCarrierById(dr.GetInt32(2)); qd.Carrier = carrier; CarrierArea ca = new CarrierAreaDAL().GetCarrierAreaById(dr.GetInt32(3)); qd.CarrierArea = ca; qd.Discount = dr.GetDecimal(4); qd.PreferentialGram = dr.GetDecimal(5); qd.IsRegisterAbate = dr.GetBoolean(6); qd.RegisterCosts = dr.GetDecimal(7); result.Add(qd); } } return result; }
public static void UpdateQutoeDetail(QuoteDetail qd) { dal.UpdateQutoeDetail(qd); }
[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 // TODO Add demonstration code here #region Opportunity with negative estimated value // Create a new opportunity with user-specified negative // estimated value. Opportunity opportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(-400.00m), FreightAmount = new Money(10.00m), ActualValue = new Money(-390.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityId = _serviceProxy.Create(opportunity); opportunity.Id = _opportunityId; // Create a catalog product for the opportunity. OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = opportunity.ToEntityReference(), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created opportunity with negative estimated value."); #endregion #region Quote with negative quantity // Create the quote. Quote quote = new Quote() { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample Quote", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _quoteId = _serviceProxy.Create(quote); quote.Id = _quoteId; // Set the quote's product quantity to a negative value. QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = -4, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Created quote with negative quantity."); #endregion #region Sales Order with negative price // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(-40.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); Console.WriteLine("Created order with negative price per unit."); #endregion #endregion Demonstrate } 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(); } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </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 { //<snippetBasicContextExamples1> // 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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery<SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery<UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery<UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery<Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // 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; } }
public ActionResult Edit(int id) { QuoteDetail e = Repo.Get(id); return(View(e)); }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// opportunity is created to demonstrate a negative estimated value. This is /// followed by the creation of a quote with a negative product quantity. /// Finally, a sales order with a negative product price is shown. /// </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 { //<snippetWorkingWithNegativePrices1> // 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 Opportunity with negative estimated value // Create a new opportunity with user-specified negative // estimated value. Opportunity opportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(-400.00m), FreightAmount = new Money(10.00m), ActualValue = new Money(-390.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityId = _serviceProxy.Create(opportunity); opportunity.Id = _opportunityId; // Create a catalog product for the opportunity. OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = opportunity.ToEntityReference(), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created opportunity with negative estimated value."); #endregion #region Quote with negative quantity // Create the quote. Quote quote = new Quote() { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample Quote", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _quoteId = _serviceProxy.Create(quote); quote.Id = _quoteId; // Set the quote's product quantity to a negative value. QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = -4, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Created quote with negative quantity."); #endregion #region Sales Order with negative price // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(-40.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); Console.WriteLine("Created order with negative price per unit."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithNegativePrices1> } // 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; } }
public void InsertTonsOfData() { using (var db = new Context()) { db.Configuration.AutoDetectChangesEnabled = false; db.Configuration.ValidateOnSaveEnabled = false; var w = new Warehouse { Name = Guid.NewGuid().ToString() }; db.Warehouses.Add(w); var p = new Product { Name = Guid.NewGuid().ToString(), Warehouse = w }; db.Products.Add(p); db.SaveChanges(); var quotes = new List <Quote>(); var qds = new List <QuoteDetail>(); for (int i = 1; i <= TotalQuotes; i++) { var q = new Quote { Name = "Quote " + i, QuoteDetails = new Collection <QuoteDetail>() }; for (int j = 1; j <= NumOfLineItemsPerQuote; j++) { var qd = new QuoteDetail { Name = "Line Item " + j, Quality = j, Price = 10 * j, Cost = 20 * j, Product = p }; q.QuoteDetails.Add(qd); qds.Add(qd); qd.Quote = q; //db.QuoteDetails.Add(qd); } quotes.Add(q); if (i % 500 == 0) { db.Quotes.AddRange(quotes); //db.BulkInsert(quotes); //db.SaveChanges(); //db.BulkInsert(qds); db.SaveChanges(); quotes.Clear(); Console.WriteLine("Flushed"); //qds.Clear(); } //db.Quotes.Add(q); //Flush every 500 records //if (i%500 == 0) // db.SaveChanges(); } db.Quotes.AddRange(quotes); //db.BulkInsert(quotes); //db.SaveChanges(); //db.BulkInsert(qds); db.SaveChanges(); } }
private QuoteDetail GetClientQuoteDetailByParameters(int carrierAreaId, int clientId) { QuoteDetail qd = new QuoteDetail(); qd.Discount = 1; qd.PreferentialGram = 0; qd.RegisterCosts = 0; qd.IsRegisterAbate = true; SqlParameter[] param = new SqlParameter[] { SqlUtilities.GenerateInputIntParameter("@carrier_area_id", carrierAreaId), SqlUtilities.GenerateInputIntParameter("@client_id", clientId) }; string sql = "SELECT TOP 1 discount, preferential_gram, is_register_abate, register_costs FROM quote_details WHERE client_id = @client_id AND status = 1 AND is_delete = 0 AND carrier_area_id = @carrier_area_id ORDER BY create_time DESC"; using (SqlDataReader dr = SqlHelper.ExecuteReader(CommandType.Text, sql, param)) { while (dr.Read()) { qd.Discount = dr.GetDecimal(0); qd.PreferentialGram = dr.GetDecimal(1); qd.IsRegisterAbate = dr.GetBoolean(2); qd.RegisterCosts = dr.GetDecimal(3); } } return qd; }
public void SaveQuote() { try { using (ProxyBE p = new ProxyBE()) { #region 报价单 if (string.IsNullOrEmpty(Request["ReferenceID"])) { throw new Exception("ReferenceID:参数无效!"); } Solution solution = p.Client.GetSolutionByDesignerID(SenderUser, Guid.Parse(Request["ReferenceID"])); if (solution == null) { throw new Exception("对象无效!"); } if (string.IsNullOrEmpty(Request["TaskID"])) { throw new Exception("TaskID:参数无效!"); } QuoteMain quotemain = p.Client.GetQuoteMain(SenderUser, parm.QuoteID); if (quotemain == null) { quotemain = new QuoteMain(); quotemain.QuoteID = Guid.NewGuid(); quotemain.SolutionID = solution.SolutionID; quotemain.Status = "N"; //报价单状态,N:确认中,F:已确认,C:已取消 } quotemain.PartnerID = CurrentUser.PartnerID; quotemain.CustomerID = solution.CustomerID; quotemain.QuoteNo = GetNumber("YS"); quotemain.DiscountPercent = parm.DiscountPercent; quotemain.ExpiryDate = parm.ExpiryDate; quotemain.Status = "N"; quotemain.Remark = parm.Remark; SaveQuoteMainArgs args = new SaveQuoteMainArgs(); #endregion #region 报价单详情 List <QuoteDetail> QuoteDetails = new List <QuoteDetail>(); string details = Request["QuoteDetails"]; decimal DiscountPercent = 1; JsonData sj = JsonMapper.ToObject(details); decimal totalamount = 0; if (sj.Count > 0) { //遍历对象元素,保存 int i = 1; foreach (JsonData item in sj) { try { QuoteDetail detail = new QuoteDetail(); detail.DetailID = Guid.NewGuid(); detail.QuoteID = quotemain.QuoteID; detail.ItemGroup = item["ItemGroup"].ToString(); detail.ItemName = item["ItemName"].ToString(); detail.ItemStyle = item["ItemStyle"].ToString(); try { detail.Qty = Decimal.Parse(item["Qty"].ToString()); } catch { throw new PException("第{0}行的数量有误。", i); } try { detail.Price = Decimal.Parse(item["Price"].ToString()); } catch { throw new PException("第{0}行的价格有误。", i); } detail.ItemRemark = item["ItemRemark"].ToString(); QuoteDetails.Add(detail); totalamount += detail.Price * detail.Qty; i++; } catch { throw new PException("第{0}行的数据有误。", i); } } } quotemain.TotalAmount = totalamount; quotemain.DiscountAmount = (DiscountPercent - quotemain.DiscountPercent) * quotemain.TotalAmount; args.QuoteMain = quotemain; args.QuoteDetails = QuoteDetails; p.Client.SaveQuote(SenderUser, args); #endregion #region 修改方案状态 solution.Status = "F";//方案状态:N,待上传方案文件;P,待生成报价明细;Q,已报价;F,方案成交;C,已取消; SaveSolutionArgs arg = new SaveSolutionArgs(); arg.Solution = solution; p.Client.SaveSolution(SenderUser, arg); #endregion #region 任务流程 Database dbCheck = new Database("BE_PartnerTask_Proc", "UPSTEPNO4", 5, 0, Request["TaskID"], "待提交订单", "P"); int rst = dbCheck.ExecuteNoQuery(); if (rst == 0) { WriteError("失败!"); } //PartnerTask task = p.Client.GetPartnerTask(SenderUser, Guid.Parse(Request["TaskID"])); //if (task != null) //{ // SavePartnerTaskArgs taskArgs = new SavePartnerTaskArgs(); // taskArgs.PartnerTask = task; // taskArgs.NextStep = "待提交订单"; // taskArgs.Resource = "报价确认组";//当前处理组 // taskArgs.NextResource = "报价确认组";//下一个组 // taskArgs.ActionRemarksType = ""; // taskArgs.ActionRemarks = ""; // taskArgs.Action = "已出报价合同,待确认"; // p.Client.SavePartnerTask(SenderUser, taskArgs); //} #endregion } WriteSuccess(); } catch (Exception ex) { WriteError(ex.Message, ex); } }
public List <string> DeleteItem(int quoteid, string item, int QuoteTypeID) { Quote currentQuote = _Context.Quote.GetSingle(e => e.QuoteID == quoteid); List <QuoteDetail> quoteDetail = new List <QuoteDetail>(); if (QuoteTypeID == (int)QuoteTypeEnum.DecisionWhizard) { quoteDetail = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid).ToList(); } else { quoteDetail = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid && e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).ToList(); } int itemsCount = 0; decimal? itemsprice = 0; List <string> lstItemids = quoteDetail.Select(e => e.ItemID).ToList(); switch (item) { case "DeleteAll": { foreach (QuoteDetail qd in quoteDetail) { _Context.QuoteDetail.Delete(qd); _Context.Quote.SaveChanges(); } DWChangesStatusToNew(lstItemids); itemsCount = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid && e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).ToList().Sum(e => e.Quantity); itemsprice = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid && e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).ToList().Sum(e => e.Quantity * e.Item.Price); break; } case "IncreaseAll": { foreach (QuoteDetail qd in quoteDetail) { qd.Quantity = qd.Quantity + 1; _Context.Quote.SaveChanges(); } itemsCount = quoteDetail.Sum(e => e.Quantity); itemsprice = quoteDetail.Sum(e => e.Quantity * e.Item.Price); break; } case "DecreaseAll": { foreach (QuoteDetail qd in quoteDetail) { qd.Quantity = qd.Quantity - 1; _Context.Quote.SaveChanges(); } itemsCount = quoteDetail.Sum(e => e.Quantity); itemsprice = quoteDetail.Sum(e => e.Quantity * e.Item.Price); break; } case "Sumbit": { Quote quote = _Context.Quote.GetSingle(e => e.QuoteID == quoteid); if (quote != null) { if (ValidateQuoteID(quoteid)) { itemsCount = SetStateForQuote(quote, (int)QuoteStatusEnum.Transferred); } else { if (quote.StatusID == (int)QuoteStatusEnum.Open) { itemsCount = SetStateForQuote(quote, (int)QuoteStatusEnum.HoldRepresentative); } } } break; } default: { if (!String.IsNullOrEmpty(item)) { // int itemid = Convert.ToInt32(item); QuoteDetail qd = _Context.QuoteDetail.GetSingle(e => e.QuoteID == quoteid && e.ItemID == item); _Context.QuoteDetail.Delete(qd); _Context.Quote.SaveChanges(); lstItemids.Clear(); lstItemids.Add(item); DWChangesStatusToNew(lstItemids); } itemsCount = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid && e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).ToList().Sum(e => e.Quantity); itemsprice = _Context.QuoteDetail.GetAll(e => e.QuoteID == quoteid && e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).ToList().Sum(e => e.Quantity * e.Item.Price); break; } } List <string> lstScountPrice = new List <string>(); lstScountPrice.Add(itemsCount.ToString()); lstScountPrice.Add(itemsprice.ToString()); ItemListViewService lstviewsvc = new ItemListViewService(); if (currentQuote != null) { lstviewsvc.UserVM = UserVM; lstviewsvc.UpdatedDateTime(quoteid); } return(lstScountPrice); }
/// <summary> /// This method first connects to the Organization service. Afterwards, a /// quote is created. This quote is then converted to an order, and the pricing /// is unlocked and relocked. This is followed by the order being converted /// to an invoice, and the pricing is locked then unlocked. /// </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 { //<snippetProcessingQuotesAndSalesOrders1> // 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 Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won), }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdateRequest> // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // 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; } }
public bool CreateQuoteDetail(ExcelProxyQuotedetail quotedetail, EntityReference product) { using (var orgContext = new OrganizationServiceContext(service)) { var newquoteDetail = new QuoteDetail() { ProductId = product, IsPriceOverridden = true, Quantity = Convert.ToInt32(quotedetail.Count), PricePerUnit = new Money(Convert.ToDecimal(quotedetail.priceForOneHRN)), new_priceprocurementUAH = new Money(Convert.ToDecimal(quotedetail.buyPriceHRN)), new_totalpurchaseUAH = new Money(Convert.ToDecimal(quotedetail.buyPriceAllHRN)), new_pricepurchaseusd = Convert.ToDouble(quotedetail.buyPriceAllUSD), QuoteId = mainEntityId, new_kursspeka = Convert.ToDouble(quotedetail.exchangeRates), new_viborkurs = new OptionSetValue(100000003), new_totalpurchaseusd = Convert.ToDouble(quotedetail.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(newquoteDetail); } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } return true; }
[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 // TODO Add demonstration code here #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); #endregion #region Lose Opportunity var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); #endregion #region Convert Opportunity to a Quote // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); #endregion #region Close Quote // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); #endregion #region Convert Quote to SalesOrder // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); Console.WriteLine("Order pricing relocked."); #endregion #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); #endregion #endregion Demonstrate } 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(); } }
//addToCart,YesNoMayBE,AddToSet public ItemListViewModel selectedOptions(string lstiID, string quoteID, int userID, string type = "", int quantity = 0) { string[] itemList = lstiID.Split(','); int quoteid = Convert.ToInt32(quoteID); int currentquote = Convert.ToInt32(quoteID); Quote CurrentQuote = null; Quote quoteToUpdate = _Context.Quote.GetSingle(e => e.QuoteID == quoteid); User loggedInUser = _Context.User.GetSingle(e => e.UserId == userID); int rollID = loggedInUser.webpages_Roles.FirstOrDefault().RoleId; if ((rollID == (int)UserRolesEnum.Repo || rollID == (int)UserRolesEnum.AdminRep) && CurrentQuote == null) { CurrentQuote = type == "Preview" ? _Context.Quote.GetSingle(e => e.QuoteTypeID == (int)QuoteTypeEnum.ShoppingCart && e.UserID == UserVM.CRMModelProperties.LoggedINCustomerUserID) : _Context.Quote.GetSingle(e => e.QuoteID == quoteid); } else if ((rollID == (int)UserRolesEnum.CustomerShipTo) && CurrentQuote == null) { CurrentQuote = _Context.Quote.GetSingle(e => e.QuoteTypeID == (int)QuoteTypeEnum.ShoppingCart && e.UserID == UserVM.CRMModelProperties.LoggedINCustomerUserID); } int dwselectionID = CurrentQuote.QuoteType.QuoteTypeID == (int)QuoteTypeEnum.ShoppingCart ? (int)DecisionWhizardStatusEnum.Yes : (int)DecisionWhizardStatusEnum.New; List <KPLBasedCommonViewModel> lstKplViewModel = new List <KPLBasedCommonViewModel>(); List <string> lstitemIdsToUI = new List <string>(); _Context.Quote.SetAutoDetectChangesEnabled(false); foreach (string Itemid in itemList) { if (Itemid != "") { KPLBasedCommonViewModel tempKplViewModel = new KPLBasedCommonViewModel(); // int itemNum = Convert.ToInt32(Itemid); QuoteDetail quoteDetail = CurrentQuote.QuoteDetails.Where(e => e.ItemID == Itemid).FirstOrDefault(); QuoteDetail quoteDetailToUpdate = null; if (quoteid != 0) { quoteDetailToUpdate = quoteToUpdate.QuoteDetails.SingleOrDefault(e => e.ItemID == Itemid); } if (quoteDetail == null || (quoteDetail.DWSelectionID != (int)DecisionWhizardStatusEnum.Yes) && (quoteDetail.DWSelectionID != (int)DecisionWhizardStatusEnum.New)) { lstitemIdsToUI.Add(Itemid); } if (quoteDetail == null) { _Context.QuoteDetail.Add(new QuoteDetail { ItemID = Itemid, QuoteID = CurrentQuote.QuoteID, DWSelectionID = dwselectionID, Quantity = quantity == 0 ? 1 : quantity, CreatedDate = System.DateTime.Now, UpdateDate = System.DateTime.Now }); } //Updating Penworthy Updated Date if (quoteDetailToUpdate != null) { quoteDetailToUpdate.DWSelectionID = dwselectionID; quoteDetailToUpdate.UpdateDate = System.DateTime.Now; } if (quoteDetail != null) { quoteDetail.DWSelectionID = dwselectionID; quoteDetail.UpdateDate = System.DateTime.Now; // quoteDetail.Quantity = 1; } if (rollID == (int)UserRolesEnum.Repo || rollID == (int)UserRolesEnum.AdminRep) { CurrentQuote.PenworthyUpdatedDate = System.DateTime.UtcNow; } else if (rollID == (int)UserRolesEnum.CustomerShipTo) { CurrentQuote.CustomerUpdatedDate = System.DateTime.UtcNow; } CurrentQuote.UpdateDate = System.DateTime.UtcNow; } } _Context.Quote.SetAutoDetectChangesEnabled(true); _Context.Quote.SaveChanges(); lstKplViewModel.AddRange(_Context.Item.GetAll(e => lstitemIdsToUI.Contains(e.ItemID)).Select(item => new KPLBasedCommonViewModel() { ItemID = item.ItemID, ISBN = item.ISBN, Price = item.Price, Series = item.SeriesAndCharacter1 == null ? string.Empty : item.SeriesAndCharacter1.SCText, Title = item.Title, Author = item.Author == null ? string.Empty : item.Author.AuthorName, Lexile = item.Lexile, ARLevel = item.ARLevel, RCLevel = item.RCLevel, ProductLine = item.ProductLine.Trim(), DWDate = string.Format("{0:MM/dd/yy}", System.DateTime.UtcNow) }).ToList()); ItemListViewModel itemListVm = new ItemListViewModel(); itemListVm.KPLItemListVM = lstKplViewModel; if (quoteToUpdate != null) { itemListVm.noOfYesCount = quoteToUpdate.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes) .Sum(e => e.Quantity); itemListVm.noOfNoCount = quoteToUpdate.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.No) .Sum(e => e.Quantity); itemListVm.noOfMaybeCount = quoteToUpdate.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.MayBe) .Sum(e => e.Quantity); itemListVm.noOfNewCount = quoteToUpdate.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.New) .Sum(e => e.Quantity); itemListVm.YesTotalPrice = (decimal)quoteToUpdate.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).Sum(e => e.Item.Price); } itemListVm.SelectionCount = itemListVm.noOfYesCount + itemListVm.noOfNoCount + itemListVm.noOfMaybeCount + itemListVm.noOfNewCount; itemListVm.SCItemsCount = CurrentQuote.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).Sum(e => e.Quantity); string taxschuduleID = CurrentQuote.User.Customer != null ? CurrentQuote.User.Customer.TaxScheduleID : null; decimal SalesTax = 0; if (string.IsNullOrEmpty(taxschuduleID) || taxschuduleID == "NONTAX") { SalesTax = 0; } else { SalesTax = Convert.ToDecimal(_Context.TaxSchedule.GetSingle(e => e.TaxScheduleID == taxschuduleID).TaxRate); } decimal?price = CurrentQuote.QuoteDetails.Where(e => e.DWSelectionID == (int)DecisionWhizardStatusEnum.Yes).Sum(e => e.Quantity * e.Item.Price); itemListVm.SCItemsPrice = price + (price * SalesTax); itemListVm.ItemIDS = lstiID; UserVM.SCCount = itemListVm.SCItemsCount; UserVM.SCPrice = itemListVm.SCItemsPrice; return(itemListVm); }
public async Task <IHttpActionResult> CheckSubscriptionStatus(int cabOfficeId, string cabOfficeEmail) { SubscriptionStatusDto subscriptionStatusDto = new SubscriptionStatusDto(); QuoteDetail quoteDetail = new QuoteDetail(); SubscriptionMonthly subscriptionMonthly = new SubscriptionMonthly(); SubscriptionPayAsYouGo subscriptionPayAsYouGo = new SubscriptionPayAsYouGo(); try { Account account = accountService.getCabOfficeByEmailAndCabOfficeId(cabOfficeEmail, cabOfficeId); if (account == null) { subscriptionStatusDto.QuoteDetailResponse = null; subscriptionStatusDto.isAllow = false; subscriptionStatusDto.IsSuccess = true; subscriptionStatusDto.Error = Constant.APIError.AccountNotFound.ToString(); subscriptionStatusDto.ErrorCode = (int)Constant.APIError.AccountNotFound; return(Ok(subscriptionStatusDto)); } Subscription subscription = subscriptionService.GetSubscriptionBySubscriptionId(Convert.ToInt32(account.CurrentSubscriptionId)); if (subscription == null) { subscriptionStatusDto.QuoteDetailResponse = null; subscriptionStatusDto.isAllow = false; subscriptionStatusDto.IsSuccess = true; subscriptionStatusDto.Error = Constant.APIError.NoSubscriptionFound.ToString(); subscriptionStatusDto.ErrorCode = (int)Constant.APIError.NoSubscriptionFound; return(Ok(subscriptionStatusDto)); } int subscriptionType = subscription.SubscriptionTypeId; quoteDetail.SubscriptionTypeId = subscriptionType; if (subscriptionType == (int)Constant.SubscriptionType.Monthly) { quoteDetail.SubscriptionType = Constant.SubscriptionType.Monthly.ToString(); if (subscription.EndDate < DateTime.Now) { subscriptionStatusDto.QuoteDetailResponse = null; subscriptionStatusDto.isAllow = false; subscriptionStatusDto.IsSuccess = true; subscriptionStatusDto.Error = Constant.APIError.SubscriptionExpired.ToString(); subscriptionStatusDto.ErrorCode = (int)Constant.APIError.SubscriptionExpired; return(Ok(subscriptionStatusDto)); } else { subscriptionMonthly.RemainingNoOfAgent = Convert.ToInt32(subscription.RemainingNoOfAgents); subscriptionMonthly.RemainingNoOfDriver = Convert.ToInt32(subscription.RemainingNoOfDrivers); subscriptionMonthly.RemainingNoOfVehicle = Convert.ToInt32(subscription.RemainingNoOfVehicles); quoteDetail.subscriptionMonthly = subscriptionMonthly; quoteDetail.subscriptionPayAsYouGo = null; } } else if (subscriptionType == (int)Constant.SubscriptionType.PayAsYouGo) { quoteDetail.SubscriptionType = Constant.SubscriptionType.PayAsYouGo.ToString(); if (subscription.RemainingCredit <= 0) { subscriptionStatusDto.QuoteDetailResponse = null; subscriptionStatusDto.isAllow = false; subscriptionStatusDto.IsSuccess = true; subscriptionStatusDto.Error = Constant.APIError.NotEnoughCredit.ToString(); subscriptionStatusDto.ErrorCode = (int)Constant.APIError.NotEnoughCredit; return(Ok(subscriptionStatusDto)); } else { subscriptionPayAsYouGo.TotalCredit = subscription.TotalCredit; subscriptionPayAsYouGo.RemainingCredit = subscription.RemainingCredit; quoteDetail.subscriptionPayAsYouGo = subscriptionPayAsYouGo; quoteDetail.subscriptionMonthly = null; } } subscriptionStatusDto.QuoteDetailResponse = quoteDetail; subscriptionStatusDto.isAllow = true; subscriptionStatusDto.IsSuccess = true; subscriptionStatusDto.Error = ""; subscriptionStatusDto.ErrorCode = 0; return(Ok(subscriptionStatusDto)); } catch (Exception ex) { subscriptionStatusDto.QuoteDetailResponse = null; subscriptionStatusDto.isAllow = false; subscriptionStatusDto.IsSuccess = false; subscriptionStatusDto.Error = ex.ToString(); subscriptionStatusDto.ErrorCode = (int)Constant.APIError.Exception; return(Ok(subscriptionStatusDto)); } }
protected void btnCreate_Click(object sender, EventArgs e) { AdminCookie cookie = (AdminCookie)RuleAuthorizationManager.GetCurrentSessionObject(Context, true); User user = UserOperation.GetUserByUsername(cookie.Username); string strDiscount = Request.Form[txtDiscount.ID].Trim(); string strPreferentialGram = Request.Form[txtPreferentialGram.ID].Trim(); string strRegisterCosts = Request.Form[txtSetRegisterCosts.ID].Trim(); decimal discount = 1; decimal preferentialGram = 0; decimal registerCosts = 0; if (string.IsNullOrEmpty(strDiscount) || !decimal.TryParse(strDiscount, out discount)) { lblMsg.Text = "折扣不能为空,且只能为数字!"; return; } if (discount <= 0 || discount > 2) { lblMsg.Text = "折扣率数字只能在0和2之间!"; return; } if (string.IsNullOrEmpty(strPreferentialGram) || !decimal.TryParse(strPreferentialGram, out preferentialGram)) { lblMsg.Text = "让利克数不能为空,且只能为不小于0的数字!"; return; } if (preferentialGram < 0) { lblMsg.Text = "让利克数只能为不小于0的数字!"; return; } if (!string.IsNullOrEmpty(strRegisterCosts) && !decimal.TryParse(strRegisterCosts, out registerCosts)) { lblMsg.Text = "挂号费只能为数字!"; return; } Carrier carrier = CarrierOperation.GetCarrierById(int.Parse(ddlCarrier.SelectedItem.Value)); Quote quote = QuoteOperation.GetQuoteById(id); if (ddlCarrierArea.SelectedValue != "0") { QuoteDetail qd = new QuoteDetail(); qd.QuoteId = id; qd.Carrier = carrier; CarrierArea ca = CarrierAreaOperation.GetCarrierAreaById(int.Parse(ddlCarrierArea.SelectedItem.Value)); qd.CarrierArea = ca; qd.ClientId = quote.Client.Id; qd.Status = false; qd.CreateTime = DateTime.Now; qd.UserId = user.Id; qd.Discount = discount; qd.PreferentialGram = preferentialGram; qd.IsRegisterAbate = chkIsRegisterAbate.Checked; qd.RegisterCosts = registerCosts; QuoteOperation.CreateQuoteDetail(qd); } else { List<CarrierArea> result = CarrierAreaOperation.GetCarrierAreaByCarrierId(carrier.Id); foreach (CarrierArea ca in result) { QuoteDetail qd = new QuoteDetail(); qd.QuoteId = id; qd.Carrier = carrier; qd.CarrierArea = ca; qd.ClientId = quote.Client.Id; qd.Status = false; qd.CreateTime = DateTime.Now; qd.UserId = user.Id; qd.Discount = discount; qd.PreferentialGram = preferentialGram; qd.IsRegisterAbate = chkIsRegisterAbate.Checked; qd.RegisterCosts = registerCosts; QuoteOperation.CreateQuoteDetail(qd); } } Response.Write("<script language='javascript'>alert('添加成功!');location.href='Quote.aspx?id=" + id + "';</script>"); }
public static void CreateQuoteDetail(QuoteDetail qd) { dal.CreateQuoteDetail(qd); }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </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 { //<snippetBasicContextExamples1> // 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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery <SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery <UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery <UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery <Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // 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; } }
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 void FinishSaveRecord(List <QuoteDetail> dirtyCollection, List <string> errorMessages, Action callBack, QuoteDetail itemToSave) { dirtyCollection.Remove(itemToSave); if (dirtyCollection.Count == 0) { callBack(); } else { SaveNextRecord(dirtyCollection, errorMessages, callBack); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// opportunity is created to demonstrate a negative estimated value. This is /// followed by the creation of a quote with a negative product quantity. /// Finally, a sales order with a negative product price is shown. /// </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 { //<snippetWorkingWithNegativePrices1> // 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 Opportunity with negative estimated value // Create a new opportunity with user-specified negative // estimated value. Opportunity opportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(-400.00m), FreightAmount = new Money(10.00m), ActualValue = new Money(-390.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityId = _serviceProxy.Create(opportunity); opportunity.Id = _opportunityId; // Create a catalog product for the opportunity. OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = opportunity.ToEntityReference(), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created opportunity with negative estimated value."); #endregion #region Quote with negative quantity // Create the quote. Quote quote = new Quote() { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample Quote", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _quoteId = _serviceProxy.Create(quote); quote.Id = _quoteId; // Set the quote's product quantity to a negative value. QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = -4, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Created quote with negative quantity."); #endregion #region Sales Order with negative price // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(-40.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); Console.WriteLine("Created order with negative price per unit."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithNegativePrices1> } // 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; } }
public QuoteAddModel() { Quote = new Quote(); PrepopulateCustomers = new List<CustomerDdlModel>(); PrepopulateProductSamples = new List<ProductSampleDdlModel>(); QuoteDetail = new QuoteDetail(); }