public ActionResult Create(LineItem lineitem) { lineitem.CartId = ExtentionMethods.GetCartId(this); if (ModelState.IsValid) { var currentLineItem = db.LineItems.AsEnumerable().Where(l => l.Equals(lineitem)).SingleOrDefault(); if (currentLineItem != null) { currentLineItem.Quantity++; db.Entry(currentLineItem).State = EntityState.Modified; } else { lineitem.Quantity = 1; db.LineItems.Add(lineitem); currentLineItem = lineitem; } db.SaveChanges(); if (Request.IsAjaxRequest()) { var lineitems = db.LineItems.Include(l => l.Product).Where(l => l.CartId == lineitem.CartId); ViewBag.CurrentItem = currentLineItem; return PartialView("_Cart", lineitems); } else { return RedirectToAction("Index", "Home"); } } else { TempData["Notice"] = "Model state is invalid."; return RedirectToAction("Index", "Home"); } }
public void CanAddItemToOrderAndCalculate() { RequestContext c = new RequestContext(); MerchantTribeApplication app = MerchantTribeApplication.InstantiateForMemory(c); c.CurrentStore = new Accounts.Store(); c.CurrentStore.Id = 1; Order target = new Order(); LineItem li = new LineItem() { BasePricePerItem = 19.99m, ProductName = "Sample Product", ProductSku = "ABC123", Quantity = 2 }; target.Items.Add(li); app.CalculateOrder(target); Assert.AreEqual(39.98m, target.TotalOrderBeforeDiscounts, "SubTotal was Incorrect"); Assert.AreEqual(39.98m, target.TotalGrand, "Grand Total was incorrect"); bool upsertResult = app.OrderServices.Orders.Upsert(target); Assert.IsTrue(upsertResult, "Order Upsert Failed"); Assert.AreEqual(c.CurrentStore.Id, target.StoreId, "Order store ID was not set correctly"); Assert.AreNotEqual(string.Empty, target.bvin, "Order failed to get a bvin"); Assert.AreEqual(1, target.Items.Count, "Item count should be one"); Assert.AreEqual(target.bvin, target.Items[0].OrderBvin, "Line item didn't receive order bvin"); Assert.AreEqual(target.StoreId, target.Items[0].StoreId, "Line item didn't recieve storeid"); }
private void PopulateVariationInfo(CatalogEntryDto.CatalogEntryRow entryRow, LineItem lineItem) { CatalogEntryDto.VariationRow variationRow = entryRow.GetVariationRows().FirstOrDefault(); if (variationRow != null) { lineItem.MaxQuantity = variationRow.MaxQuantity; lineItem.MinQuantity = variationRow.MinQuantity; CustomerContact customerContact = CustomerContext.Current.GetContactById(lineItem.Parent.Parent.CustomerId); Money? newListPrice = GetItemPrice(entryRow, lineItem, customerContact); if (newListPrice.HasValue) { Money oldListPrice = new Money(Math.Round(lineItem.ListPrice, 2), lineItem.Parent.Parent.BillingCurrency); if (oldListPrice != newListPrice.Value) { AddWarningSafe(Warnings, "LineItemPriceChange-" + lineItem.Parent.LineItems.IndexOf(lineItem).ToString(), string.Format("Price for \"{0}\" has been changed from {1} to {2}.", lineItem.DisplayName, oldListPrice.ToString(), newListPrice.ToString())); // Set new price on line item. lineItem.ListPrice = newListPrice.Value.Amount; if (lineItem.Parent.Parent.ProviderId.ToLower().Equals("frontend")) { lineItem.PlacedPrice = newListPrice.Value.Amount; } } } } }
public virtual void PopulateFromApi(LineItem model) { string add1 = null; string add2 = null; string city = null; string state = null; string postalCode = null; var response = this.SearchProApi(model); if ((response != null) && (!response.IsFailure)) { var bestMatch = response.Results.FirstOrDefault(); if (bestMatch != null) { var bestLocation = bestMatch.BestLocation; if (bestLocation != null) { add1 = bestLocation.StandardAddressLine1; add2 = bestLocation.StandardAddressLine2; city = bestLocation.City; state = bestLocation.StateCode; postalCode = bestLocation.PostalCode; } } } model.StreetAddress1 = add1; model.StreetAddress2 = add2; model.City = city; model.State = state; model.PostalCode = postalCode; }
/// <summary> /// This should return a list of "LineItem" objects for every item in the cart, but I don't yet know how to add items /// to a cart after creating it, so this method currently will never return success. /// </summary> /// <param name="steamId"></param> /// <returns></returns> public async Task<List<LineItem>> GetCartContents(long steamId) { List<WebRequestParameter> requestParameters = new List<WebRequestParameter>(); WebRequestParameter steamIdParameter = new WebRequestParameter("steamid", steamId.ToString()); requestParameters.Add(steamIdParameter); // send the request and wait for the response JObject data = await PerformSteamRequestAsync("ISteamMicroTxn", "GetCartContents", 1, requestParameters); bool success = TypeHelper.CreateBoolean(data["result"]["success"]); if (!success) throw new Exception(E_HTTP_RESPONSE_RESULT_FAILED); try { List<LineItem> lineItems = new List<LineItem>(); foreach (JObject groupObject in data["result"]["lineitems"]) { LineItem lineItem = new LineItem(); lineItems.Add(lineItem); } return lineItems; } catch { throw new Exception(E_JSON_DESERIALIZATION_FAILED); } }
public void lineitem_null_description_fails() { Validator<LineItem> liValidator = new LineItemValidator(); LineItem li = new LineItem(); var results = liValidator.Validate(li); Assert.Greater(results.Count, 0); }
/// <summary> /// Get entry row from a line item /// </summary> /// <param name="lineItem">line item</param> protected static CatalogEntryDto.CatalogEntryRow GetEntryRowForLineItem(LineItem lineItem) { var responseGroup = new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Variations); CatalogEntryDto entryDto = CatalogContext.Current.GetCatalogEntryDto(lineItem.Code, responseGroup); return entryDto.CatalogEntry.FirstOrDefault(); }
/// <summary> /// CTR /// </summary> public CheckoutIndex() { LineItems = new LineItem[] { }; Countries = new Country[] { }; DeliveryAddress = new CreateOrderRequest.Address(); var url = new UrlHelper(HttpContext.Current.Request.RequestContext); CheckoutShippingCostsUrl = url.Action(MVC.Store.Checkout.VariableCosts()); }
private static void DeleteInvalidItem(OrderForm[] orderForms, LineItem lineItem) { foreach (var form in orderForms) { form.RemoveLineItemFromShipments(lineItem); } lineItem.Delete(); }
private void PopulateInventoryInfo(InventoryRecord inventoryRecord, LineItem lineItem) { lineItem.AllowBackordersAndPreorders = inventoryRecord.BackorderAvailableQuantity > 0 | inventoryRecord.PreorderAvailableUtc > SafeBeginningOfTime; lineItem.BackorderQuantity = inventoryRecord.BackorderAvailableQuantity; lineItem.InStockQuantity = inventoryRecord.PurchaseAvailableQuantity + inventoryRecord.AdditionalQuantity; lineItem.PreorderQuantity = inventoryRecord.PreorderAvailableQuantity; lineItem.InventoryStatus = inventoryRecord.IsTracked ? 1 : 0; }
public void Add(PropertyDescriptor property, PropertyMap map) { var index = GetIndex(property.NameId); var line = _lines[index]; if (line == null) _lines[index] = line = new LineItem(); line.Property = property; line.Map = map; }
public void TotalCostTest_promotionAvailable_returnsPromotionCostCalculation() { LineItem lineItem = new LineItem(new Item("Apple")); lineItem.PricePerUnit = 1.5; lineItem.Quantity = 2; Promotion promotion = new QuantityPricePromotion(new Item("Apple"), "[email protected]"); lineItem.Promotion = promotion; Assert.AreEqual(promotion.GetPromotionAdjustedTotalCost(lineItem), lineItem.TotalCost); }
private void DeleteLineItemFromShipment(Shipment shipment, LineItem lineItem) { var orderForm = OrderGroup.OrderForms.ToArray().Where(of => of.LineItems.ToArray().Contains(lineItem)).FirstOrDefault(); if (orderForm != null) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); decimal shipmentQty = Shipment.GetLineItemQuantity(shipment, lineItem.LineItemId); lineItem.Quantity -= shipmentQty; shipment.RemoveLineItemIndex(lineItemIndex); } }
public void CanGetLineTotalWithDiscounts() { LineItem target = new LineItem(); target.BasePricePerItem = 39.99m; target.DiscountDetails.Add(new Marketing.DiscountDetail(){ Amount = -20.01m}); target.DiscountDetails.Add(new Marketing.DiscountDetail() { Amount = -5m }); Decimal actual = target.LineTotal; Assert.AreEqual((39.99m - 20.01m - 5m), actual, "Total was not correct."); }
private decimal GetCustomLineItemDiscountAmount(LineItem lineItem) { decimal retVal = 0m; foreach (LineItemDiscount lineItemDiscount in lineItem.Discounts) { if (lineItemDiscount.DiscountName.StartsWith("@")) { retVal += lineItemDiscount.DiscountValue; } } return retVal; }
private void DeleteLineItemFromShipments(LineItem lineItem) { var orderForm = OrderGroup.OrderForms.ToArray().FirstOrDefault(); if (orderForm != null) { var lineItemIndex = orderForm.LineItems.IndexOf(lineItem); var allShipmentContainsLineItem = orderForm.Shipments.ToArray().Where(x => Shipment.GetShipmentLineItems(x).Contains(lineItem)); foreach (var shipment in allShipmentContainsLineItem) { shipment.RemoveLineItemIndex(lineItemIndex); } } }
public void When_constructed() { var productCatalog = new ProductCatalog(); productCatalog.AddProduct("apple", 0.75m); productCatalog.AddProduct("banana", 1.00m); var sut = new LineItem("apple", 2, productCatalog, new Promotions(new List<IPromotionalDiscountRule>())); Assert.That(sut.Barcode, Is.EqualTo("apple")); Assert.That(sut.Quantity, Is.EqualTo(2)); Assert.That(sut.PricePerUnit, Is.EqualTo(0.75m)); Assert.That(sut.SubTotal, Is.EqualTo(1.50m)); Assert.That(sut.DiscountNote, Is.EqualTo("")); }
public void It_will_not_report_diff_if_content_is_the_same() { var lineItem = new LineItem { Product = "Product A", Total = 2.00M }; var order = new Order() { Id = 1, LineItems = new[] { lineItem } }; var orderCopy = (Order)ObjectCloner.Clone(order); Cross.diff(order, orderCopy, (left, right) => { var report = Diff.ObjectValues(left, right); Assert.IsFalse(report.DiffFound); }); }
public void When_promotion_applies() { var productCatalog = new ProductCatalog(); productCatalog.AddAdditionalItemDiscount("apple", 1, 1, 100); productCatalog.AddProduct("apple", 0.75m); var sut = new AdditionalItemDiscountRule(productCatalog); var promotions = new Promotions(new List<IPromotionalDiscountRule>() { sut }); var lineItem = new LineItem("apple", 7, productCatalog, promotions); var actual = sut.PromotionApplies(lineItem); Assert.That(actual, Is.True); }
/// <summary> /// Determines whether [is gift line item] [the specified line item]. /// </summary> /// <param name="lineItem">The line item.</param> /// <returns> /// <c>true</c> if [is gift line item] [the specified line item]; otherwise, <c>false</c>. /// </returns> public bool IsGiftLineItem(LineItem lineItem) { bool retVal = false; foreach (LineItemDiscount discount in lineItem.Discounts) { if (discount.DiscountName.EndsWith(":Gift")) { retVal = true; break; } } return retVal; }
public void When_no_promotion_applies() { var rule = new Mock<IPromotionalDiscountRule>(); rule.Setup(p => p.PromotionApplies(It.IsAny<LineItem>())).Returns(false); var sut = new Promotions(new List<IPromotionalDiscountRule>() { rule.Object }); var productCatalog = new ProductCatalog(); productCatalog.AddProduct("apple", 0.75m); var lineItem = new LineItem("apple", 7, productCatalog, sut); var actual = sut.CalculatePromotionalCost(lineItem); Assert.That(actual.DiscountedSubTotal, Is.EqualTo(lineItem.SubTotal)); Assert.That(actual.DiscountNote, Is.EqualTo("")); }
public void When_calculating_rule() { var productCatalog = new ProductCatalog(); productCatalog.AddQuantityDiscount("apple", 3, 2); productCatalog.AddProduct("apple", 0.75m); var sut = new QuantityDiscountRule(productCatalog); var promotions = new Promotions(new List<IPromotionalDiscountRule>() { sut }); var lineItem = new LineItem("apple", 7, productCatalog, promotions); var actual = sut.Calculate(lineItem); Assert.That(actual.DiscountedSubTotal, Is.EqualTo(4.75m)); Assert.That(actual.DiscountNote, Is.EqualTo("***Discount on apple: Buy 3 apple for $2.00, New Price $4.75, Savings $0.50")); }
public void When_promotion_does_not_apply() { var productCatalog = new ProductCatalog(); productCatalog.AddQuantityDiscount("apple", 3, 2); productCatalog.AddProduct("apple", 0.75m); productCatalog.AddProduct("banana", 1m); var sut = new QuantityDiscountRule(productCatalog); var promotions = new Promotions(new List<IPromotionalDiscountRule>() { sut }); var lineItem = new LineItem("banana", 7, productCatalog, promotions); var actual = sut.PromotionApplies(lineItem); Assert.That(actual, Is.False); }
public static ILineItem GetLineItem(string name, decimal price, int quantity, ItemType itemType) { ILineItem item = new LineItem(name, price, quantity); foreach (int flag in Enum.GetValues(typeof(ItemType))) { if ((flag & (int)itemType) == flag) { item = (ILineItem)Activator.CreateInstance(typeof(LineItemTaxDecorator), new object[] { item, itemTaxLookup[(ItemType)flag] }); } } return item; }
public void When_calculating_rule() { var productCatalog = new ProductCatalog(); productCatalog.AddAdditionalItemDiscount("apple", 1, 1, 100); productCatalog.AddProduct("apple", 0.75m); var sut = new AdditionalItemDiscountRule(productCatalog); var promotions = new Promotions(new List<IPromotionalDiscountRule>() { sut }); var lineItem = new LineItem("apple", 7, productCatalog, promotions); var actual = sut.Calculate(lineItem); Assert.That(actual.DiscountedSubTotal, Is.EqualTo(3m)); Assert.That(actual.DiscountNote, Is.EqualTo("***Discount on apple: Buy 1 apple get 1 at $0.00, New Price $3.00, Savings $2.25")); }
public void When_constructed_with_quantity_discount() { var productCatalog = new ProductCatalog(); productCatalog.AddProduct("apple", 0.75m); productCatalog.AddProduct("banana", 1.00m); productCatalog.AddQuantityDiscount("apple", 3, 2.00m); var sut = new LineItem("apple", 7, productCatalog, new Promotions(new List<IPromotionalDiscountRule>() { new AdditionalItemDiscountRule(productCatalog), new QuantityDiscountRule(productCatalog) })); Assert.That(sut.Barcode, Is.EqualTo("apple")); Assert.That(sut.Quantity, Is.EqualTo(7)); Assert.That(sut.PricePerUnit, Is.EqualTo(0.75m)); Assert.That(sut.SubTotal, Is.EqualTo(5.25m)); Assert.That(sut.DiscountedSubTotal, Is.EqualTo(4.75m)); Assert.That(sut.DiscountNote, Is.EqualTo("***Discount on apple: Buy 3 apple for $2.00, New Price $4.75, Savings $0.50")); }
public void When_constructed_with_additional_item_discount() { var productCatalog = new ProductCatalog(); productCatalog.AddProduct("apple", 0.75m); productCatalog.AddProduct("banana", 1.00m); productCatalog.AddAdditionalItemDiscount("apple", 1, 1, 100); var sut = new LineItem("apple", 5, productCatalog, new Promotions(new List<IPromotionalDiscountRule>() { new AdditionalItemDiscountRule(productCatalog), new QuantityDiscountRule(productCatalog)})); Assert.That(sut.Barcode, Is.EqualTo("apple")); Assert.That(sut.Quantity, Is.EqualTo(5)); Assert.That(sut.PricePerUnit, Is.EqualTo(0.75m)); Assert.That(sut.SubTotal, Is.EqualTo(3.75m)); Assert.That(sut.DiscountedSubTotal, Is.EqualTo(2.25m)); Assert.That(sut.DiscountNote, Is.EqualTo("***Discount on apple: Buy 1 apple get 1 at $0.00, New Price $2.25, Savings $1.50")); }
public void It_will_report_diff_if_content_is_not_the_same() { var lineItem = new LineItem { Product = "Product A", Total = 2.00M }; var order = new Order() { Id = 1, LineItems = new[] { lineItem } }; var orderCopy = (Order)ObjectCloner.Clone(order); orderCopy.LineItems.ElementAt(0).Total *= 2; Cross.diff(order, orderCopy, (left, right) => { var report = Diff.ObjectValues(left, right); Assert.IsTrue(report.DiffFound); Assert.AreEqual("LineItems[0].Total", report.Table.Rows.ElementAt(0).MemberPath); }); }
public void addPoint(IntVector2 point) { LineItem lc = new LineItem (lineMeshType, lineMaterial); if (lineNumber == 0) { lc.setPoint (point); } else { if (point.equalsTo (previousPoint)) return; lc.setPoints (previousPoint, point); } line.Add(lc); previousPoint = point; pointQueue.Enqueue (point); lineNumber++; }
public PromotionalDiscount Calculate(LineItem lineItem) { var discount = GetCurrentDiscount(lineItem); var hasDiscount = PromotionApplies(lineItem); var discountedSubTotal = lineItem.SubTotal; var discountNote = ""; if (hasDiscount) { var applicableQuantity = lineItem.Quantity / discount.DiscountQuantity; discountedSubTotal = applicableQuantity * discount.DiscountPrice + (lineItem.Quantity - applicableQuantity * discount.DiscountQuantity) * lineItem.PricePerUnit; discountNote = $"***Discount on {lineItem.Barcode}: Buy {discount.DiscountQuantity} {lineItem.Barcode} for {discount.DiscountPrice:C2}, New Price {discountedSubTotal:C2}, Savings {(lineItem.SubTotal - discountedSubTotal):C2}"; } var promotionalDiscount = new PromotionalDiscount(discountedSubTotal, discountNote); return promotionalDiscount; }
// Vẽ đồ thị private void graphUpdate() { LineItem curve = zGrphPlotData.GraphPane.CurveList[0] as LineItem; //Khai báo đường cong từ danh sách đường cong đồ thị (kế thừa từ heap của dữ liệu ở Form_load) if (curve == null) { return; } LineItem curve2 = zGrphPlotData.GraphPane.CurveList[1] as LineItem; if (curve2 == null) { return; } IPointListEdit list = curve.Points as IPointListEdit; //Khai báo danh sách dữ liệu cho đường cong đồ thị if (list == null) { return; } IPointListEdit list2 = curve2.Points as IPointListEdit; if (list2 == null) { return; } list.Add(Realtime, Setpoint); // Thêm điểm trên đồ thị list2.Add(Realtime, Measure); // Thêm điểm trên đồ thị Scale xScale = zGrphPlotData.GraphPane.XAxis.Scale; //Giới hạn của đồ thị Scale yScale = zGrphPlotData.GraphPane.YAxis.Scale; if (enScroll == GraphScroll.Scroll) { // Tự động Scale theo trục x if (Realtime > xScale.Max - xScale.MajorStep) //Nếu realtime lớn hơn Max x trừ đi 1 MajorStep (2 vạch lớn) { xScale.Min = xScale.Min + Realtime - (xScale.Max - xScale.MajorStep); xScale.Max = Realtime + xScale.MajorStep; //Tự dời đồ thị qua 1 MajorStep //xScale.Min = xScale.Max - 6; } // Tự động Scale theo trục y if (Setpoint > yScale.Max - yScale.MajorStep) //Nếu datas vượt quá giới hạn trừ 1 MajorStep { yScale.Max = Setpoint + yScale.MajorStep; //Thì tăng giới hạn thêm 1 MajorStep } else if (Setpoint < yScale.Min + yScale.MajorStep) { yScale.Min = Setpoint - yScale.MajorStep; } } LineItem curvePara = zGraphParameters.GraphPane.CurveList[0] as LineItem; //Khai báo đường cong từ danh sách đường cong đồ thị (kế thừa từ heap của dữ liệu ở Form_load) if (curvePara == null) { return; } IPointListEdit listPara = curvePara.Points as IPointListEdit; //Khai báo danh sách dữ liệu cho đường cong đồ thị if (listPara == null) { return; } listPara.Add(Realtime, PWM); // Thêm điểm trên đồ thị Scale xScalePara = zGraphParameters.GraphPane.XAxis.Scale; //Giới hạn của đồ thị Scale yScalePara = zGraphParameters.GraphPane.YAxis.Scale; if (enScroll == GraphScroll.Scroll) { // Tự động Scale theo trục x if (Realtime > xScalePara.Max - xScalePara.MajorStep) //Nếu realtime lớn hơn Max x trừ đi 1 MajorStep (2 vạch lớn) { xScalePara.Min = xScalePara.Min + Realtime - (xScalePara.Max - xScalePara.MajorStep); xScalePara.Max = Realtime + xScalePara.MajorStep; //Tự dời đồ thị qua 1 MajorStep //xScale.Min = xScale.Max - 6; } // Tự động Scale theo trục y if (PWM > yScalePara.Max - yScalePara.MajorStep) //Nếu datas vượt quá giới hạn trừ 1 MajorStep { yScalePara.Max = PWM + yScalePara.MajorStep; //Thì tăng giới hạn thêm 1 MajorStep } else if (PWM < yScalePara.Min + yScalePara.MajorStep) { yScalePara.Min = PWM - yScalePara.MajorStep; } } //if (status == GraphStatus.GraphRun) //{ // zGrphPlotData.AxisChange(); //Thay đổi trục theo giá trị Scale // zGrphPlotData.Invalidate(); //Mở khoá để và vẽ lại // zGraphParameters.AxisChange(); //Thay đổi trục theo giá trị Scale // zGraphParameters.Invalidate(); //Mở khoá để và vẽ lại //} }
public void OneTimeSetUp() { _item = new Item("sku", "name", 1M); _lineItem = new LineItem(_item); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == LOAD_MASKED_WALLET_REQ_CODE) // Unique, identifying constant { if (resultCode == Result.Ok) { var maskedWallet = data.GetParcelableExtra(WalletConstants.ExtraMaskedWallet).JavaCast <MaskedWallet> (); var fullWalletRequest = FullWalletRequest.NewBuilder() .SetCart(Cart.NewBuilder() .SetCurrencyCode("USD") .SetTotalPrice("20.00") .AddLineItem(LineItem.NewBuilder() // Identify item being purchased .SetCurrencyCode("USD") .SetQuantity("1") .SetDescription("Premium Llama Food") .SetTotalPrice("20.00") .SetUnitPrice("20.00") .Build()) .Build()) .SetGoogleTransactionId(maskedWallet.GoogleTransactionId) .Build(); WalletClass.Payments.LoadFullWallet(googleApiClient, fullWalletRequest, LOAD_FULL_WALLET_REQ_CODE); } else { base.OnActivityResult(requestCode, resultCode, data); } } else if (requestCode == LOAD_FULL_WALLET_REQ_CODE) // Unique, identifying constant { if (resultCode == Result.Ok) { var fullWallet = data.GetParcelableExtra(WalletConstants.ExtraFullWallet).JavaCast <FullWallet> (); var tokenJson = fullWallet.PaymentMethodToken.Token; var stripeToken = Stripe.Token.FromJson(tokenJson); var msg = string.Empty; if (stripeToken != null) { //TODO: Send token to your server to process a payment with msg = string.Format("Good news! Stripe turned your credit card into a token: \n{0} \n\nYou can follow the instructions in the README to set up Parse as an example backend, or use this token to manually create charges at dashboard.stripe.com .", stripeToken.Id); } else { msg = "Failed to create Token"; } new Android.Support.V7.App.AlertDialog.Builder(this) .SetTitle("Stripe Response") .SetMessage(msg) .SetCancelable(true) .SetNegativeButton("OK", delegate { }) .Show(); } } else { base.OnActivityResult(requestCode, resultCode, data); } }
/// <summary> /// Handle the LTI POST request from the Authorization Server. /// </summary> /// <returns></returns> public async Task <IActionResult> OnPostAsync( string platformId, [FromForm(Name = "id_token")] string idToken, [FromForm(Name = "scope")] string scope = null, [FromForm(Name = "state")] string state = null, [FromForm(Name = "session_state")] string sessionState = null) { // Authenticate the request starting at step 5 in the OpenId Implicit Flow // See https://www.imsglobal.org/spec/security/v1p0/#platform-originating-messages // See https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowSteps // The Platform MUST send the id_token via the OAuth 2 Form Post // See https://www.imsglobal.org/spec/security/v1p0/#successful-authentication // See http://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html if (string.IsNullOrEmpty(idToken)) { Error = "id_token is missing or empty"; return(Page()); } var handler = new JwtSecurityTokenHandler(); if (!handler.CanReadToken(idToken)) { Error = "Cannot read id_token"; return(Page()); } var jwt = handler.ReadJwtToken(idToken); JwtHeader = jwt.Header; var messageType = jwt.Claims.SingleOrDefault(c => c.Type == Constants.LtiClaims.MessageType)?.Value; if (messageType.IsMissing()) { Error = $"{Constants.LtiClaims.MessageType} claim is missing."; return(Page()); } // Authentication Response Validation // See https://www.imsglobal.org/spec/security/v1p0/#authentication-response-validation // The ID Token MUST contain a nonce Claim. var nonce = jwt.Claims.SingleOrDefault(c => c.Type == "nonce")?.Value; if (string.IsNullOrEmpty(nonce)) { Error = "Nonce is missing from request."; return(Page()); } // If the launch was initiated with a 3rd party login, then there will be a state // entry for the nonce. var memorizedState = _stateContext.GetState(nonce); if (memorizedState == null) { Error = "Invalid nonce. Possible request replay."; return(Page()); } // The state should be echoed back by the AS without modification if (memorizedState.Value != state) { Error = "Invalid state."; return(Page()); } // Look for the platform with platformId in the redirect URI var platform = await _context.GetPlatformByPlatformId(platformId); if (platform == null) { Error = "Unknown platform."; return(Page()); } // Using the JwtSecurityTokenHandler.ValidateToken method, validate four things: // // 1. The Issuer Identifier for the Platform MUST exactly match the value of the iss // (Issuer) Claim (therefore the Tool MUST previously have been made aware of this // identifier. // 2. The Tool MUST Validate the signature of the ID Token according to JSON Web Signature // RFC 7515, Section 5; using the Public Key for the Platform which collected offline. // 3. The Tool MUST validate that the aud (audience) Claim contains its client_id value // registered as an audience with the Issuer identified by the iss (Issuer) Claim. The // aud (audience) Claim MAY contain an array with more than one element. The Tool MUST // reject the ID Token if it does not list the client_id as a valid audience, or if it // contains additional audiences not trusted by the Tool. // 4. The current time MUST be before the time represented by the exp Claim; RSAParameters rsaParameters; try { var httpClient = _httpClientFactory.CreateClient(); var keySetJson = await httpClient.GetStringAsync(platform.JwkSetUrl); var keySet = JsonConvert.DeserializeObject <JsonWebKeySet>(keySetJson); var key = keySet.Keys.SingleOrDefault(k => k.Kid == jwt.Header.Kid); if (key == null) { Error = "No matching key found."; return(Page()); } rsaParameters = new RSAParameters { Modulus = Base64UrlEncoder.DecodeBytes(key.N), Exponent = Base64UrlEncoder.DecodeBytes(key.E) }; } catch (Exception e) { Error = e.Message; return(Page()); } var validationParameters = new TokenValidationParameters { ValidateTokenReplay = true, ValidateAudience = true, ValidateIssuer = true, RequireSignedTokens = true, ValidateIssuerSigningKey = true, ValidAudience = platform.ClientId, ValidIssuer = platform.Issuer, IssuerSigningKey = new RsaSecurityKey(rsaParameters), ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5.0) }; try { handler.ValidateToken(idToken, validationParameters, out _); } catch (Exception e) { Error = e.Message; return(Page()); } if (messageType == Constants.Lti.LtiDeepLinkingRequestMessageType) { return(Post("/Catalog", new { idToken })); } IdToken = idToken; LtiRequest = new LtiResourceLinkRequest(jwt.Payload); var tokenResponse = await _accessTokenService.GetAccessTokenAsync( LtiRequest.Iss, Constants.LtiScopes.Ags.LineItem); var lineItemClient = _httpClientFactory.CreateClient(); lineItemClient.SetBearerToken(tokenResponse.AccessToken); lineItemClient.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue(Constants.MediaTypes.LineItem)); var resultsUrl = $"{LtiRequest.AssignmentGradeServices.LineItemUrl}/{Constants.ServiceEndpoints.Ags.ResultsService}"; var resultsResponse = await lineItemClient.GetAsync(resultsUrl); var resultsContent = await resultsResponse.Content.ReadAsStringAsync(); var results = JsonConvert.DeserializeObject <ResultContainer>(resultsContent); Results = results; var lineItemResponse = await lineItemClient.GetAsync(LtiRequest.AssignmentGradeServices.LineItemUrl); var lineItemContent = await lineItemResponse.Content.ReadAsStringAsync(); var lineItem = JsonConvert.DeserializeObject <LineItem>(lineItemContent); LineItem = lineItem; return(Page()); }
private void animateFor2() { int counter = 0; zgc22.GraphPane.CurveList.Clear(); zgc23.GraphPane.CurveList.Clear(); PointPairList tempList; PointPairList tempListForThird; LineItem tempC = null; LineItem tempCB = null; GraphPane myPane = zgc22.GraphPane; GraphPane myPane2 = zgc23.GraphPane; int step = -72; LineItem myCurve2 = myPane.AddCurve("", list2_1, Color.Transparent, SymbolType.None); myCurve2.Line.Fill = new Fill(Color.FromArgb(200, Color.White)); while (step < 33) { Thread.Sleep(speed_2); tempList = new PointPairList(); tempList.Add(step, 0); tempList.Add(step, 1); tempList.Add(step + 40, 0); tempListForThird = new PointPairList(); for (int i = 0; i < counter; i++) { double res = (double)data21[i] / 100; int x = i - 72; tempListForThird.Add(x, (double)res); } if (tempCB != null) { myPane2.CurveList.Remove(tempCB); } LineItem myCurve3 = myPane2.AddCurve("", tempListForThird, Color.Red, SymbolType.None); tempCB = myCurve3; myCurve3.Line.Width = 2.0F; //zmiana labeli if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { vallabel21.Text = step.ToString(); vallabel22.Text = step.ToString(); if (counter != -1 && counter < data21.Length) { vallabel23.Text = "0," + data21[counter].ToString(); } })); } if (counter != -1 && counter < data21.Length) { counter++; } //dodanie krzywej if (tempC != null) { myPane.CurveList.Remove(tempC); } LineItem myCurve = myPane.AddCurve("", tempList, Color.Red, SymbolType.None); myCurve.Line.Fill = new Fill(Color.Red); tempC = myCurve; myCurve.Line.Width = 2.0F; //odswiezenie grafow if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { zgc22.Refresh(); zgc23.Refresh(); })); } //pauza w srodku if (step == -11) { if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { pauza2.Text = "Kontynuuj"; pauza2.BackColor = Color.Gold; infolabel2.Visible = true; })); } animate2.Suspend(); } step++; } }
public virtual LineItem ToModel(LineItem lineItem) { if (lineItem == null) { throw new ArgumentNullException(nameof(lineItem)); } lineItem.Id = Id; lineItem.CreatedBy = CreatedBy; lineItem.CreatedDate = CreatedDate; lineItem.ModifiedBy = ModifiedBy; lineItem.ModifiedDate = ModifiedDate; lineItem.ListPrice = ListPrice; lineItem.ListPriceWithTax = ListPriceWithTax; lineItem.SalePrice = SalePrice; lineItem.SalePriceWithTax = SalePriceWithTax; lineItem.Fee = Fee; lineItem.FeeWithTax = FeeWithTax; lineItem.DiscountAmount = DiscountAmount; lineItem.DiscountAmountWithTax = DiscountAmountWithTax; lineItem.Quantity = Quantity; lineItem.TaxTotal = TaxTotal; lineItem.TaxPercentRate = TaxPercentRate; lineItem.Weight = Weight; lineItem.Height = Height; lineItem.Width = Width; lineItem.MeasureUnit = MeasureUnit; lineItem.WeightUnit = WeightUnit; lineItem.Length = Length; lineItem.TaxType = TaxType; lineItem.IsReadOnly = IsReadOnly; lineItem.ValidationType = ValidationType; lineItem.PriceId = PriceId; lineItem.LanguageCode = LanguageCode; lineItem.IsReccuring = IsReccuring; lineItem.IsGift = IsGift; lineItem.ImageUrl = ImageUrl; lineItem.ProductId = ProductId; lineItem.ProductType = ProductType; lineItem.ShipmentMethodCode = ShipmentMethodCode; lineItem.RequiredShipping = RequiredShipping; lineItem.ProductType = ProductType; lineItem.FulfillmentLocationCode = FulfillmentLocationCode; lineItem.Note = Comment; lineItem.CatalogId = CatalogId; lineItem.CategoryId = CategoryId; lineItem.Currency = Currency; lineItem.Name = Name; lineItem.Sku = Sku; if (!Discounts.IsNullOrEmpty()) { lineItem.Discounts = Discounts.Select(x => x.ToModel(AbstractTypeFactory <Discount> .TryCreateInstance())).ToList(); } if (!TaxDetails.IsNullOrEmpty()) { lineItem.TaxDetails = TaxDetails.Select(x => x.ToModel(AbstractTypeFactory <TaxDetail> .TryCreateInstance())).ToList(); } return(lineItem); }
/// <summary> /// Run the code examples. /// </summary> /// <param name="user">The DFP user object running the code examples.</param> public void Run(DfpUser user) { // Get the LineItemService. LineItemService lineItemService = (LineItemService)user.GetService(DfpService.v201605.LineItemService); // Set the order that all created line items will belong to and the // placement ID to target. long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE")); long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) }; // Create inventory targeting. InventoryTargeting inventoryTargeting = new InventoryTargeting(); inventoryTargeting.targetedPlacementIds = targetPlacementIds; // Create geographical targeting. GeoTargeting geoTargeting = new GeoTargeting(); // Include the US and Quebec, Canada. Location countryLocation = new Location(); countryLocation.id = 2840L; Location regionLocation = new Location(); regionLocation.id = 20123L; geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation }; Location postalCodeLocation = new Location(); postalCodeLocation.id = 9000093; // Exclude Chicago and the New York metro area. Location cityLocation = new Location(); cityLocation.id = 1016367L; Location metroLocation = new Location(); metroLocation.id = 200501L; geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation }; // Exclude domains that are not under the network's control. UserDomainTargeting userDomainTargeting = new UserDomainTargeting(); userDomainTargeting.domains = new String[] { "usa.gov" }; userDomainTargeting.targeted = false; // Create day-part targeting. DayPartTargeting dayPartTargeting = new DayPartTargeting(); dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER; // Target only the weekend in the browser's timezone. DayPart saturdayDayPart = new DayPart(); saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201605.DayOfWeek.SATURDAY; saturdayDayPart.startTime = new TimeOfDay(); saturdayDayPart.startTime.hour = 0; saturdayDayPart.startTime.minute = MinuteOfHour.ZERO; saturdayDayPart.endTime = new TimeOfDay(); saturdayDayPart.endTime.hour = 24; saturdayDayPart.endTime.minute = MinuteOfHour.ZERO; DayPart sundayDayPart = new DayPart(); sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201605.DayOfWeek.SUNDAY; sundayDayPart.startTime = new TimeOfDay(); sundayDayPart.startTime.hour = 0; sundayDayPart.startTime.minute = MinuteOfHour.ZERO; sundayDayPart.endTime = new TimeOfDay(); sundayDayPart.endTime.hour = 24; sundayDayPart.endTime.minute = MinuteOfHour.ZERO; dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart }; // Create technology targeting. TechnologyTargeting technologyTargeting = new TechnologyTargeting(); // Create browser targeting. BrowserTargeting browserTargeting = new BrowserTargeting(); browserTargeting.isTargeted = true; // Target just the Chrome browser. Technology browserTechnology = new Technology(); browserTechnology.id = 500072L; browserTargeting.browsers = new Technology[] { browserTechnology }; technologyTargeting.browserTargeting = browserTargeting; // Create an array to store local line item objects. LineItem[] lineItems = new LineItem[5]; for (int i = 0; i < 5; i++) { LineItem lineItem = new LineItem(); lineItem.name = "Line item #" + i; lineItem.orderId = orderId; lineItem.targeting = new Targeting(); lineItem.targeting.inventoryTargeting = inventoryTargeting; lineItem.targeting.geoTargeting = geoTargeting; lineItem.targeting.userDomainTargeting = userDomainTargeting; lineItem.targeting.dayPartTargeting = dayPartTargeting; lineItem.targeting.technologyTargeting = technologyTargeting; lineItem.lineItemType = LineItemType.STANDARD; lineItem.allowOverbook = true; // Set the creative rotation type to even. lineItem.creativeRotationType = CreativeRotationType.EVEN; // Set the size of creatives that can be associated with this line item. Size size = new Size(); size.width = 300; size.height = 250; size.isAspectRatio = false; // Create the creative placeholder. CreativePlaceholder creativePlaceholder = new CreativePlaceholder(); creativePlaceholder.size = size; lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder }; // Set the line item to run for one month. lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY; lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York"); // Set the cost per unit to $2. lineItem.costType = CostType.CPM; lineItem.costPerUnit = new Money(); lineItem.costPerUnit.currencyCode = "USD"; lineItem.costPerUnit.microAmount = 2000000L; // Set the number of units bought to 500,000 so that the budget is // $1,000. Goal goal = new Goal(); goal.goalType = GoalType.LIFETIME; goal.unitType = UnitType.IMPRESSIONS; goal.units = 500000L; lineItem.primaryGoal = goal; lineItems[i] = lineItem; } try { // Create the line items on the server. lineItems = lineItemService.createLineItems(lineItems); if (lineItems != null) { foreach (LineItem lineItem in lineItems) { Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and" + " named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name); } } else { Console.WriteLine("No line items created."); } } catch (Exception e) { Console.WriteLine("Failed to create line items. Exception says \"{0}\"", e.Message); } }
//控制水平仪,其中还有从接口获取数据代码段 private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { int count = serialPort1.BytesToRead; string str_receice_data; byte[] receivedData = new byte[count]; serialPort1.Read(receivedData, 0, receivedData.Length); serialPort1.DiscardInBuffer(); //x_value,y_value,z_value是从接口中得到的三个值 this.Invoke((EventHandler)(delegate { str_receice_data = Encoding.Default.GetString(receivedData); textBox1.Text += (str_receice_data + "\r\n"); float num = Convert.ToSingle(str_receice_data.Split(' ')[1]) / 10; count += 1; quickView1.number = num; //水平仪下方数据1 plist.Add(count, num); //将新的点加入列表 GraphPane mypane = zedGraphControl1.GraphPane; //创建图形对象 mypane.CurveList.Clear(); //清空图中原有的线 LineItem mycurve = mypane.AddCurve("11", plist, Color.Black, SymbolType.None); //绘制图形 zedGraphControl1.Invalidate(); /* * str_receice_data = Encoding.Default.GetString(receivedData); * x_value = Convert.ToSingle(str_receice_data.Split(',')[0]); * y_value = Convert.ToSingle(str_receice_data.Split(',')[1]); * z_value = Convert.ToSingle(str_receice_data.Split(',')[2]); * textBox1.Text = "x:" + x_value.ToString() + "y:" + y_value.ToString() + "z:" + z_value.ToString(); * userControl12.slider.Value = -x_value; * userControl12.slider_Copy.Value = z_value; * userControl12.slider_Copy1.Value = y_value; * * * pitchAndBank1.Bank = x_value; //控制水平仪方向 * pitchAndBank1.Pitch = y_value; //控制水平仪蓝色绿色占比 * * // quickview1 3 * // 2 4 * * //quickView1.number = 50; //水平仪下方数据1 * //quickView2.number = 50; * //quickView3.number = 50; * //quickView4.number = 50; * * //仪表盘 数值大小 * //aGauge3 4 1 2 * * aGauge1.Value0 = 10; * aGauge1.Value0 = 10; * aGauge1.Value0 = 10; * aGauge1.Value0 = 10; */ //指南针朝向 //hsi1.Heading= 40; })); } catch (System.Exception ex) { MessageBox.Show("Error:" + ex.Message, "Error"); } }
public OrderTablePage() { InitializeComponent(); Items = LineItem.GetSampleData(); BindingContext = viewModel = new LineItemsViewModel(); }
/// <summary> /// Adjusts the stock inventory quantities. Method assumes only inventory TRACKING is enabled. /// </summary> /// <param name="lineItem">Line item object in cart.</param> /// <param name="inventory">Inventory associated with the line item's catalog entry.</param> /// <param name="delta">The change in inventory.</param> private static void AdjustStockInventoryQuantity(LineItem lineItem, IWarehouseInventory inventory, decimal delta) { if (inventory == null) { if (delta != 0) { //throw new Exception("Inventory cannot be null with non-zero delta."); return; } return; } WarehouseInventory editedInventory = new WarehouseInventory(inventory); //arrival if (delta > 0) { // need distribute delta between InStock, Backorder, Preorder. if (lineItem.InStockQuantity > 0) { var backorderDelta = Math.Min(delta, lineItem.BackorderQuantity - inventory.BackorderQuantity); var preorderdelta = Math.Min(delta, lineItem.PreorderQuantity - inventory.PreorderQuantity); editedInventory.PreorderQuantity += preorderdelta; editedInventory.BackorderQuantity += backorderDelta; editedInventory.InStockQuantity += delta - backorderDelta - preorderdelta; } //need distribute delta between Preorder and Backorder else if (lineItem.InStockQuantity == 0) { if (lineItem.PreorderQuantity > 0) { editedInventory.PreorderQuantity += delta; } else if (lineItem.BackorderQuantity > 0) { editedInventory.BackorderQuantity += delta; } } } //consumption else { delta = Math.Abs(delta); bool inventoryEnabled = inventory.InventoryStatus == InventoryTrackingStatus.Enabled; if (inventory.InStockQuantity >= delta + inventory.ReservedQuantity) // Adjust the main inventory { //just simply subtract from Instock quantity editedInventory.InStockQuantity -= delta; } //Instock quantity is larger than delta but smaller than delta and reserved quantity else if (inventory.InStockQuantity >= inventory.ReservedQuantity) { if (inventoryEnabled) { editedInventory.BackorderQuantity -= delta - (editedInventory.InStockQuantity - inventory.ReservedQuantity); editedInventory.InStockQuantity = inventory.ReservedQuantity; } else { editedInventory.InStockQuantity -= delta; } } else if (inventory.InStockQuantity > 0) // there still exist items in stock { // Calculate difference between currently availbe and backorder var backorderDelta = delta - (inventory.InStockQuantity - (inventoryEnabled ? inventory.ReservedQuantity : 0)); // Update inventory if (inventoryEnabled) { editedInventory.InStockQuantity = inventory.ReservedQuantity; editedInventory.BackorderQuantity -= backorderDelta; } else { editedInventory.InStockQuantity -= delta; } } else if (inventory.InStockQuantity <= 0) { // Update inventory editedInventory.InStockQuantity = -delta; if (inventoryEnabled) { if (inventory.PreorderQuantity == 0) { editedInventory.BackorderQuantity -= delta; } else { editedInventory.PreorderQuantity -= delta; } } } } ServiceLocator.Current.GetInstance <IWarehouseInventoryService>().Save(editedInventory); }
public IActionResult CheckoutSuccesful(ShoppingCartCheckoutViewModel VM) { if (ModelState.IsValid) { if (retrieveCartFromSession().Count() > 0) { Guid orderId = new Guid(); Order currentOrder = new Order(); currentOrder.OrderId = orderId; List <ShoppingCartItem> shoppingCartItems = retrieveCartFromSession(); List <LineItem> orderItems = new List <LineItem>(); foreach (ShoppingCartItem item in shoppingCartItems) { LineItem orderItem = new LineItem { OrderId = orderId, HamperId = item.Hamper.HamperId, Quantity = item.Quantity }; orderItems.Add(orderItem); } // Add ListItems to order: currentOrder.ShoppingCartItems = orderItems; //Retrieve user's address from session (if logged in): if (User.Identity.IsAuthenticated) { // Add User ID: string UserName = User.Identity.Name; ApplicationUser user = _userManager.Users.FirstOrDefault(x => x.UserName == UserName); currentOrder.UserId = user.Id; // Retrieve address from session: var addressInSession = HttpContext.Session.GetString(userAddress); Address shippingAddress = JsonConvert.DeserializeObject <Address>(addressInSession); // Add address details to order: currentOrder.StreetAddress = shippingAddress.StreetAddress; currentOrder.Suburb = shippingAddress.Suburb; currentOrder.State = shippingAddress.State; currentOrder.Postcode = shippingAddress.Postcode; } else { // Add [No User] ID: currentOrder.UserId = null; // Add address details to order directly from VM: currentOrder.StreetAddress = VM.PreferredAddress.StreetAddress; currentOrder.Suburb = VM.PreferredAddress.Suburb; currentOrder.State = VM.PreferredAddress.State; currentOrder.Postcode = VM.PreferredAddress.Postcode; } // Update order price: currentOrder.Price = calculateTotalPrice(shoppingCartItems, 1, true); // Add current date: currentOrder.DateOrdered = DateTime.Now; // Update order in DB: _orderService.Create(currentOrder); // Update list items in DB: _lineItemService.UpdateMultiple(orderItems); // Clear session: HttpContext.Session.Clear(); return(RedirectToAction("OrderProcessedSuccessfully", "Order")); } else { return(RedirectToAction("ViewCart", "ShoppingCart")); } } return(View(VM)); }
/// <summary> /// Run the code example. /// </summary> public void Run(DfpUser user) { // Get the LineItemService. LineItemService lineItemService = (LineItemService)user.GetService( DfpService.v201705.LineItemService); long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE")); long[] customCriteriaIds1 = new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")), long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) }; long[] customCriteriaIds2 = new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")), long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) }; long[] customCriteriaIds3 = new long[] { long.Parse(_T("INSERT_CUSTOM_TARGETING_KEY_ID_HERE")), long.Parse(_T("INSERT_CUSTOM_TARGETING_VALUE_ID_HERE")) }; // Create custom criteria. CustomCriteria customCriteria1 = new CustomCriteria(); customCriteria1.keyId = customCriteriaIds1[0]; customCriteria1.valueIds = new long[] { customCriteriaIds1[1] }; customCriteria1.@operator = CustomCriteriaComparisonOperator.IS; CustomCriteria customCriteria2 = new CustomCriteria(); customCriteria2.keyId = customCriteriaIds2[0]; customCriteria2.valueIds = new long[] { customCriteriaIds2[1] }; customCriteria2.@operator = CustomCriteriaComparisonOperator.IS_NOT; CustomCriteria customCriteria3 = new CustomCriteria(); customCriteria3.keyId = customCriteriaIds3[0]; customCriteria3.valueIds = new long[] { customCriteriaIds3[1] }; customCriteria3.@operator = CustomCriteriaComparisonOperator.IS; // Create the custom criteria set that will resemble: // // (customCriteria1.key == customCriteria1.value OR // (customCriteria2.key != customCriteria2.value AND // customCriteria3.key == customCriteria3.value)) CustomCriteriaSet topCustomCriteriaSet = new CustomCriteriaSet(); topCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.OR; CustomCriteriaSet subCustomCriteriaSet = new CustomCriteriaSet(); subCustomCriteriaSet.logicalOperator = CustomCriteriaSetLogicalOperator.AND; subCustomCriteriaSet.children = new CustomCriteriaNode[] { customCriteria2, customCriteria3 }; topCustomCriteriaSet.children = new CustomCriteriaNode[] { customCriteria1, subCustomCriteriaSet }; try { StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", lineItemId); // Set the custom criteria targeting on the line item. LineItemPage page = lineItemService.getLineItemsByStatement(statementBuilder.ToStatement()); LineItem lineItem = page.results[0]; lineItem.targeting.customTargeting = topCustomCriteriaSet; // Update the line items on the server. LineItem[] updatedLineItems = lineItemService.updateLineItems(new LineItem[] { lineItem }); foreach (LineItem updatedLineItem in updatedLineItems) { // Display the updated line item. Console.WriteLine("Line item with ID {0} updated with custom criteria targeting \n{1}\n", updatedLineItem.id, getCustomCriteriaSetString(updatedLineItem.targeting.customTargeting, 0)); } } catch (Exception e) { Console.WriteLine("Failed to add custom target criteria. Exception says \"{0}\"", e.Message); } }
//double[] filtval = new double[RegistersCountMax - 257]; //double[] filtval1 = new double[RegistersCountMax - 257]; //double[] filtval2 = new double[RegistersCountMax - 257]; // int upshift = 0; internal void Dispdata(SIP.SipRegisters sel2) { GraphPane myPane = zedGraphControl1.GraphPane; PointPairList listPoints = new PointPairList(); PointPairList filtpoints = new PointPairList(); PointPairList filtpoints1 = new PointPairList(); PointPairList filtpoints2 = new PointPairList(); //filtval[0] = rdBuf[257]; //filtval2[0] = rdBuf[257]; if (axisflag == 1 & yscalectrl == 1) { myPane.YAxis.Max = 2500; myPane.YAxis.Min = -10; myPane.XAxis.Max = 20; myPane.XAxis.Min = 0; } myPane.CurveList.Clear(); //for(int yr =0; yr<rdBuf.Length; yr++) //{ // rdBuf[yr] /= 13; //} //for (int t = 1; t < RegistersCountMax-258; t++) //{ // filtval[t] =B * (t) + A * rdBuf[t + 257 - 1]; // filtpoints.Add((t)/51.2, filtval[t]/26.2); // filtval1[t] = (rdBuf[t + 257 - 1] + rdBuf[t + 257] + rdBuf[t + 257 + 1])/3; // filtpoints1.Add((t)/51.2, filtval1[t]/26.2); // filtval2[t] = (rdBuf[t+257-1] + rdBuf[t+257]) / 2; // filtpoints2.Add(t/51.2, filtval2[t]/26.2); //} ////double xfilt = 0; ////double yfilt = 0; ////for(int t =0; t < RegistersCountMax-257; t++) ////{ //// for(int j =0; j < t; j++) //// { //// yfilt = yfilt + rdBuf[j + 258-1]; //// xfilt += j; //// } //// xfilt -= t; //// filtpoints2.Add(t, B * xfilt - A * yfilt); ////} //LineItem FiltLine = myPane.AddCurve("Filtered data", filtpoints, Color.Black, SymbolType.None); //LineItem Filtline1 = myPane.AddCurve("Filtered data1", filtpoints1, Color.Blue, SymbolType.None); //LineItem Filtline2 = myPane.AddCurve("Filtered data2", filtpoints2, Color.Green, SymbolType.None); double[] apprBuf = new double[8]; for (int t = 257; t < RegistersCountMax; t++) { if (t < RegistersCountMax - 4 & t > 260) { for (int l = -3; l < 5; l++) { apprBuf[l + 3] = rdBuf[t + l]; } } filtpoints.Add((t - 257) / 51.2, apprBuf.Average() / 26.2); //SIP.SipRegisters trx = t; listPoints.Add((t - 257) / 51.2, rdBuf[t] / 26.2); // approxL[t - 257] = rdBuf[t]; } // bezcurv(approxL, RegistersCountMax - 257); //upshift++; //LineItem midline = myPane.AddCurve(null, cX, cY, Color.Blue, SymbolType.Star); LineItem Dataline = myPane.AddCurve("Data", listPoints, Color.Coral, SymbolType.None); LineItem Filtline = myPane.AddCurve("Averaged data", filtpoints, Color.Black, SymbolType.None); Dataline.Line.Width = 3; zedGraphControl1.Refresh(); zedGraphControl1.AxisChange(); //sleeptime = 1000; }
private void button1_Click_1(object sender, EventArgs e) { GraphPane myPane = zedGraphControl1.GraphPane; PointPairList listPointsTwo = new PointPairList(); string selected = comboBox1.Text; SIP.SipRegisters sel = EnumDescriptor.ToEnum <SIP.SipRegisters>(selected); if (selected == "Data1") { Dispdata(sel); //button6_Click(this, null); } if (selected != "Data1") { //if (axisflag == 1) //{ // myPane.YAxis.Max = 40; // myPane.YAxis.Min = 0; // myPane.XAxis.Min = 0; // myPane.XAxis.Max = 50; //} if (i * yscalectrl > myPane.XAxis.Max - 5) { myPane.XAxis.Max = (i + 10); axisflag = 0; } i++; Sipval[(i - 1)] = Data.GetVal(sel); zedGraphControl1.AxisChange(); zedGraphControl1.Refresh(); myPane.ScaledGap(1); Rangscale(sel); myPane.IsFontsScaled = true; PointPairList approx2 = new PointPairList(); if (i > 1) { a = (sumxy * (i - 1) - sumy * sumx) / (sumx2 * (i - 1) - Math.Pow(sumx, 2)); b = (sumy - a * sumx) / (i - 1); for (double x = i - 1; x <= i; x += 0.5) { approx2.Add(x, a1 * x + b1); } } sumx += i; sumy += Data.GetVal(sel); sumx2 += Math.Pow(i, 2); sumxy += i * Data.GetVal(sel); a = (sumxy * i - sumy * sumx) / (sumx2 * i - Math.Pow(sumx, 2)); b = (sumy - a * sumx) / i; PointPairList approx1 = new PointPairList(); approx1.Clear(); for (double x = 1; x <= i; x += 0.5) { approx1.Add(x, a * x + b); } /* * LineItem f1_curve = myPane.AddCurve(null, approx1, Color.Black, SymbolType.None); */ myPane.CurveList.Clear(); for (int u = 0; u < Sipval.Length; u++) { listPointsTwo.Add(u + 1, Sipval[u]); } LineItem myCurveTwo = myPane.AddCurve("real T", listPointsTwo, Color.Black, SymbolType.None); if (i > 2) { bezcurv(Sipval, i); } Array.Resize <double>(ref Sipval, Sipval.Length + 1); //byte[] temBuf = new byte[4]; //int index = 0; //private void COM3_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) //{ // ////byte[] tempval = new byte[3]; // //int[] tempval = new int[3];// tempval[3]; // //int j = 0; // int count = COM3.BytesToRead; // while (count > 0) // { // byte[] buf = new byte[count]; // COM3.Read(buf, 0, count); // int wrCount = ((temBuf.Length - index) < count) ? count : count; //(temBuf.Length - index); // Array.Copy(buf, 0, temBuf, index, wrCount); // index += wrCount; // if (index >= temBuf.Length) // { // index = 0; // float temp = 0; // try // { // temp = BitConverter.ToSingle(temBuf, 0); // } // catch {} // richTextBox1.Invoke(new Action(() => // { // richTextBox2.Text = string.Format("{0:F3}", temp); ; // })); // } // //tempval[j]= COM3.Read(buf, 0, count); // //richTextBox4.Text += tempval[j]; // //j++; // //if (j > 2) // //{ // // j = 0; // //}; // //string strB = ""; // //for (int i = 0; i < count; i++) // //{ // // strB += string.Format("{0:X2}", buf[i]); // // strB += "\t"; // //} // //richTextBox1.Invoke(new Action(() => // //{ // // richTextBox2.Text += strB; // //})); // count = COM3.BytesToRead; // } // } //private void COM3_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e) //{ //} // #endregion // Events //------------------------------------------------------------------------- //button1_Click_1(this, null); } }
public async Task AddShoppingCartItem(LineItem lineItem) { await _context.LineItems.AddAsync(lineItem); }
public LineItemsController() { OnDeleteLineItem = context => { if (string.IsNullOrEmpty(context.Id) || _lineItem == null || !_lineItem.Id.ToString().Equals(context.Id)) { context.StatusCode = HttpStatusCode.NotFound; } else { _lineItem = null; context.StatusCode = HttpStatusCode.OK; } return(Task.FromResult <object>(null)); }; OnGetLineItem = context => { if (string.IsNullOrEmpty(context.Id) || _lineItem == null || !_lineItem.Id.ToString().Equals(context.Id)) { context.StatusCode = HttpStatusCode.NotFound; } else { context.LineItem = _lineItem; context.StatusCode = HttpStatusCode.OK; } return(Task.FromResult <object>(null)); }; OnGetLineItems = context => { if (_lineItem == null || (!string.IsNullOrEmpty(context.ActivityId) && !context.ActivityId.Equals(_lineItem.AssignedActivity.ActivityId))) { context.StatusCode = HttpStatusCode.NotFound; } else { context.LineItemContainerPage = new LineItemContainerPage { ExternalContextId = LtiConstants.LineItemContainerContextId, Id = Request.RequestUri, LineItemContainer = new LineItemContainer { MembershipSubject = new LineItemMembershipSubject { ContextId = _lineItem.LineItemOf.ContextId, LineItems = new[] { _lineItem } } } }; context.StatusCode = HttpStatusCode.OK; } return(Task.FromResult <object>(null)); }; OnPostLineItem = context => { if (_lineItem != null) { context.StatusCode = HttpStatusCode.BadRequest; return(Task.FromResult <object>(null)); } context.LineItem.Id = new Uri(LineItemId, UriKind.Relative); context.LineItem.Results = new Uri(Request.RequestUri.AbsoluteUri + "/" + LineItemId + "/results"); _lineItem = context.LineItem; context.StatusCode = HttpStatusCode.Created; return(Task.FromResult <object>(null)); }; OnPutLineItem = context => { if (context.LineItem == null || _lineItem == null || !_lineItem.Id.Equals(context.LineItem.Id)) { context.StatusCode = HttpStatusCode.NotFound; } else { _lineItem = context.LineItem; context.StatusCode = HttpStatusCode.OK; } return(Task.FromResult <object>(null)); }; }
public virtual LineItemEntity FromModel(LineItem lineItem, PrimaryKeyResolvingMap pkMap) { if (lineItem == null) { throw new ArgumentNullException(nameof(lineItem)); } pkMap.AddPair(lineItem, this); Id = lineItem.Id; CreatedBy = lineItem.CreatedBy; CreatedDate = lineItem.CreatedDate; ModifiedBy = lineItem.ModifiedBy; ModifiedDate = lineItem.ModifiedDate; ListPrice = lineItem.ListPrice; ListPriceWithTax = lineItem.ListPriceWithTax; SalePrice = lineItem.SalePrice; SalePriceWithTax = lineItem.SalePriceWithTax; Fee = lineItem.Fee; FeeWithTax = lineItem.FeeWithTax; DiscountAmount = lineItem.DiscountAmount; DiscountAmountWithTax = lineItem.DiscountAmountWithTax; Quantity = lineItem.Quantity; TaxTotal = lineItem.TaxTotal; TaxPercentRate = lineItem.TaxPercentRate; Weight = lineItem.Weight; Height = lineItem.Height; Width = lineItem.Width; MeasureUnit = lineItem.MeasureUnit; WeightUnit = lineItem.WeightUnit; Length = lineItem.Length; TaxType = lineItem.TaxType; IsReadOnly = lineItem.IsReadOnly; ValidationType = lineItem.ValidationType; PriceId = lineItem.PriceId; LanguageCode = lineItem.LanguageCode; IsReccuring = lineItem.IsReccuring; IsGift = lineItem.IsGift; ImageUrl = lineItem.ImageUrl; ProductId = lineItem.ProductId; ProductType = lineItem.ProductType; ShipmentMethodCode = lineItem.ShipmentMethodCode; RequiredShipping = lineItem.RequiredShipping; ProductType = lineItem.ProductType; FulfillmentLocationCode = FulfillmentLocationCode; Comment = lineItem.Note; CatalogId = lineItem.CatalogId; CategoryId = lineItem.CategoryId; Currency = lineItem.Currency; Name = lineItem.Name; Sku = lineItem.Sku; //Preserve link of the original model LineItem for future references binding LineItems with ShipmentLineItems ModelLineItem = lineItem; if (lineItem.Discounts != null) { Discounts = new ObservableCollection <DiscountEntity>(lineItem.Discounts.Select(x => AbstractTypeFactory <DiscountEntity> .TryCreateInstance().FromModel(x))); } if (lineItem.TaxDetails != null) { TaxDetails = new ObservableCollection <TaxDetailEntity>(lineItem.TaxDetails.Select(x => AbstractTypeFactory <TaxDetailEntity> .TryCreateInstance().FromModel(x))); } return(this); }
private bool MeetLineItem(PromotionContext context, LineItem li) { return(GetProductIds().Contains(li.ProductId)); }
/// <summary> /// Initialize a new instance of the class. /// </summary> public PutLineItemDto(LineItem lineItem) { LineItem = lineItem; StatusCode = StatusCodes.Status200OK; }
//ploting data into graph. private void plotGraph() { GraphPane myPane = zedGraphControl1.GraphPane; // Set the Titles myPane.Title.Text = "Polar Cycle Computer"; myPane.XAxis.Title.Text = "Year"; myPane.YAxis.Title.Text = "Times"; myPane.Title.FontSpec.FontColor = Color.BlueViolet; PointPairList speed = new PointPairList(); PointPairList cadence = new PointPairList(); PointPairList altitude = new PointPairList(); PointPairList heart_rate = new PointPairList(); PointPairList power = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] hr = Dashbord.graphHeartRate; double[] sp = Dashbord.graphSpeed; double[] cd = Dashbord.graphCadence; double[] alt = Dashbord.graphAltitude; double[] pwr = Dashbord.graphPower; for (int i = 0; i < hr.Length; i++) { heart_rate.Add(i, hr[i]); speed.Add(i, sp[i]); cadence.Add(i, cd[i]); altitude.Add(i, alt[i]); power.Add(i, pwr[i]); } LineItem hrCurve = myPane.AddCurve("Heart Rate", heart_rate, Color.Black, SymbolType.None); hrCurve.Line.IsSmooth = true; hrCurve.Line.SmoothTension = 1f; LineItem spCurve = myPane.AddCurve("Speed", speed, Color.Pink, SymbolType.None); spCurve.Line.IsSmooth = true; spCurve.Line.SmoothTension = 1f; LineItem cdCurve = myPane.AddCurve("Cadence", cadence, Color.DarkBlue, SymbolType.None); cdCurve.Line.IsSmooth = true; cdCurve.Line.SmoothTension = 1f; LineItem altCurve = myPane.AddCurve("Altitude", altitude, Color.Yellow, SymbolType.Star); altCurve.Line.IsSmooth = true; altCurve.Line.SmoothTension = 1f; LineItem pwCurve = myPane.AddCurve("Power", power, Color.DarkOrchid, SymbolType.None); pwCurve.Line.IsSmooth = true; pwCurve.Line.SmoothTension = 1f; zedGraphControl1.AxisChange(); }
private void DrawGraph() { // Получим панель для рисования GraphPane pane = zedGraph.GraphPane; // Очистим список кривых на тот случай, если до этого сигналы уже были нарисованы pane.CurveList.Clear(); // Создадим список точек PointPairList list = new PointPairList(); // Интервал, в котором будут лежать точки int xmin = -100; int xmax = 100; int ymin = -100; int ymax = 100; int pointsCount = 50; Random rnd = new Random(); // Заполняем список точек for (int i = 0; i < pointsCount; i++) { // Случайным образом сгенерим точку int x = rnd.Next(xmin, xmax); int y = rnd.Next(ymin, ymax); list.Add(x, y); } // Создадим кривую с названием "Scatter". // Обводка ромбиков будут рисоваться голубым цветом (Color.Blue), // Опорные точки - ромбики (SymbolType.Diamond) LineItem myCurve = pane.AddCurve("Scatter", list, Color.Blue, SymbolType.Diamond); myCurve.Line.IsVisible = false; myCurve.Symbol.Fill.Color = Color.Blue; myCurve.Symbol.Fill.Type = FillType.Solid; myCurve.Symbol.Size = 7; // !!! // Горизонтальная линия на уровне y = 0 рисоваться не будет pane.YAxis.MajorGrid.IsZeroLine = false; // Устанавливаем интересующий нас интервал по оси X pane.XAxis.Scale.Min = xmin; pane.XAxis.Scale.Max = xmax; // Устанавливаем интересующий нас интервал по оси Y pane.YAxis.Scale.Min = ymin; pane.YAxis.Scale.Max = ymax; // Вызываем метод AxisChange (), чтобы обновить данные об осях. // В противном случае на рисунке будет показана только часть графика, // которая умещается в интервалы по осям, установленные по умолчанию zedGraph.AxisChange(); // Обновляем график zedGraph.Invalidate(); }
private void lblCombo_SelectedIndexChanged(object sender, EventArgs e) { GraphPane myPane = zedGraphControl1.GraphPane; // Set the Titles myPane.Title.Text = "Polar Cycle Computer"; myPane.XAxis.Title.Text = "Year"; myPane.YAxis.Title.Text = "Times"; myPane.Title.FontSpec.FontColor = Color.BlueViolet; if (lblCombo.SelectedItem.ToString() == "Speed") { zedGraphControl1.GraphPane.CurveList.Clear(); PointPairList speed = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] sp = Dashbord.graphSpeed; for (int i = 0; i < sp.Length; i++) { speed.Add(i, sp[i]); } LineItem spCurve = myPane.AddCurve("Speed", speed, Color.Crimson, SymbolType.None); zedGraphControl1.Refresh(); } else if (lblCombo.SelectedItem.ToString() == "Cadence") { zedGraphControl1.GraphPane.CurveList.Clear(); PointPairList cadence = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] cad = Dashbord.graphCadence; for (int i = 0; i < cad.Length; i++) { cadence.Add(i, cad[i]); } LineItem cdCurve = myPane.AddCurve("Cadence", cadence, Color.DarkBlue, SymbolType.None); zedGraphControl1.Refresh(); } else if (lblCombo.SelectedItem.ToString() == "Altitude") { zedGraphControl1.GraphPane.CurveList.Clear(); PointPairList altitude = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] alt = Dashbord.graphAltitude; for (int i = 0; i < alt.Length; i++) { altitude.Add(i, alt[i]); } LineItem altCurve = myPane.AddCurve("Altitude", altitude, Color.Yellow, SymbolType.Star); zedGraphControl1.Refresh(); } else if (lblCombo.SelectedItem.ToString() == "Heart Rate") { zedGraphControl1.GraphPane.CurveList.Clear(); PointPairList heart_rate = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] hr = Dashbord.graphHeartRate; for (int i = 0; i < hr.Length; i++) { heart_rate.Add(i, hr[i]); } LineItem hrCurve = myPane.AddCurve("Heart Rate", heart_rate, Color.Black, SymbolType.None); zedGraphControl1.Refresh(); } else if (lblCombo.SelectedItem.ToString() == "Power") { zedGraphControl1.GraphPane.CurveList.Clear(); PointPairList power = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] pwr = Dashbord.graphPower; for (int i = 0; i < pwr.Length; i++) { power.Add(i, pwr[i]); } LineItem pwCurve = myPane.AddCurve("Power", power, Color.DarkOrchid, SymbolType.None); zedGraphControl1.Refresh(); } else if (lblCombo.SelectedItem.ToString() == "None") { zedGraphControl1.GraphPane.CurveList.Clear(); myPane.Title.Text = "Polar Cycle Computer"; myPane.XAxis.Title.Text = "Year"; myPane.YAxis.Title.Text = "Times"; myPane.Title.FontSpec.FontColor = Color.BlueViolet; PointPairList speed = new PointPairList(); PointPairList cadence = new PointPairList(); PointPairList altitude = new PointPairList(); PointPairList heart_rate = new PointPairList(); PointPairList power = new PointPairList(); myPane.XAxis.Scale.Min = 1; myPane.XAxis.Scale.Max = 2000; myPane.YAxis.Scale.Min = 1; myPane.YAxis.Scale.Max = 650; double[] hr = Dashbord.graphHeartRate; double[] sp = Dashbord.graphSpeed; double[] cd = Dashbord.graphCadence; double[] alt = Dashbord.graphAltitude; double[] pwr = Dashbord.graphPower; for (int i = 0; i < hr.Length; i++) { heart_rate.Add(i, hr[i]); speed.Add(i, sp[i]); cadence.Add(i, cd[i]); altitude.Add(i, alt[i]); power.Add(i, pwr[i]); } LineItem hrCurve = myPane.AddCurve("Heart Rate", heart_rate, Color.Black, SymbolType.None); hrCurve.Line.IsSmooth = true; hrCurve.Line.SmoothTension = 1f; LineItem spCurve = myPane.AddCurve("Speed", speed, Color.Pink, SymbolType.None); spCurve.Line.IsSmooth = true; spCurve.Line.SmoothTension = 1f; LineItem cdCurve = myPane.AddCurve("Cadence", cadence, Color.DarkBlue, SymbolType.None); cdCurve.Line.IsSmooth = true; cdCurve.Line.SmoothTension = 1f; LineItem altCurve = myPane.AddCurve("Altitude", altitude, Color.Yellow, SymbolType.Star); altCurve.Line.IsSmooth = true; altCurve.Line.SmoothTension = 1f; LineItem pwCurve = myPane.AddCurve("Power", power, Color.DarkOrchid, SymbolType.None); pwCurve.Line.IsSmooth = true; pwCurve.Line.SmoothTension = 1f; zedGraphControl1.Refresh(); zedGraphControl1.AxisChange(); } else { MessageBox.Show("Please select the appropriate value."); } }
/// <summary> /// Handler for creating a line item. /// </summary> /// <returns>The result.</returns> public async Task <IActionResult> OnPostCreateLineItemAsync([FromForm(Name = "id_token")] string idToken, [FromForm(Name = "resource_link_id")] string resourceLinkId) { if (idToken.IsMissing()) { Error = $"{nameof(idToken)} is missing."; return(Page()); } var handler = new JwtSecurityTokenHandler(); var jwt = handler.ReadJwtToken(idToken); LtiRequest = new LtiResourceLinkRequest(jwt.Payload); var tokenResponse = await _accessTokenService.GetAccessTokenAsync( LtiRequest.Iss, Constants.LtiScopes.Ags.LineItem); // The IMS reference implementation returns "Created" with success. if (tokenResponse.IsError && tokenResponse.Error != "Created") { Error = tokenResponse.Error; return(Page()); } var httpClient = _httpClientFactory.CreateClient(); httpClient.SetBearerToken(tokenResponse.AccessToken); httpClient.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue(Constants.MediaTypes.LineItem)); try { var lineItem = new LineItem { EndDateTime = DateTime.UtcNow.AddMonths(3), Label = LtiRequest.ResourceLink.Title, ResourceLinkId = string.IsNullOrEmpty(resourceLinkId) ? LtiRequest.ResourceLink.Id : resourceLinkId, ScoreMaximum = 100, StartDateTime = DateTime.UtcNow }; using (var response = await httpClient.PostAsync( LtiRequest.AssignmentGradeServices.LineItemsUrl, new StringContent(JsonConvert.SerializeObject(lineItem), Encoding.UTF8, Constants.MediaTypes.LineItem))) { if (!response.IsSuccessStatusCode) { Error = response.ReasonPhrase; return(Page()); } } } catch (Exception e) { Error = e.Message; return(Page()); } return(Relaunch( LtiRequest.Iss, LtiRequest.UserId, LtiRequest.ResourceLink.Id, LtiRequest.Context.Id)); }
private void initGraph() { mGraph.GraphPane.Title.IsVisible = false; mGraph.GraphPane.XAxis.Title.IsVisible = false; mGraph.GraphPane.YAxis.Title.IsVisible = false; mGraph.IsEnableZoom = false; mGraph.MouseDownEvent += onGraphMouseDown; mGraph.MouseMoveEvent += onGraphMouseMove; mGraph.MouseUpEvent += onGraphMouseUp; // X axis mGraph.GraphPane.XAxis.Scale.MinorStep = 5; mGraph.GraphPane.XAxis.Scale.MajorStep = 10; mGraph.GraphPane.XAxis.Scale.Min = 0; mGraph.GraphPane.XAxis.Scale.Max = 100; mGraph.GraphPane.XAxis.MinorGrid.IsVisible = false; mGraph.GraphPane.XAxis.MajorGrid.IsVisible = true; mGraph.GraphPane.XAxis.Type = AxisType.Linear; mGraph.GraphPane.XAxis.ScaleFormatEvent += (pane, axis, val, index) => { var min = OptionManager.getInstance().IsFahrenheit == false ? 0 : 32; var majorStep = OptionManager.getInstance().IsFahrenheit == false ? 10 : 18; var temp = min + majorStep * index; return(temp + (OptionManager.getInstance().IsFahrenheit == false ? "°C" : "°F")); }; // Y axis mGraph.GraphPane.YAxis.Scale.MinorStep = 5; mGraph.GraphPane.YAxis.Scale.MajorStep = 10; mGraph.GraphPane.YAxis.Scale.Min = 0; mGraph.GraphPane.YAxis.Scale.Max = 100; mGraph.GraphPane.YAxis.Scale.Format = "0%"; mGraph.GraphPane.YAxis.MajorGrid.IsVisible = true; mGraph.GraphPane.YAxis.Type = AxisType.Linear; mGraph.GraphPane.CurveList.Clear(); mNowPoint = new PointPairList(); mNowPoint.Add(0, 0); mNowPointLineItem = mGraph.GraphPane.AddCurve("Now", mNowPoint, Color.Red, SymbolType.Circle); mNowPointLineItem.Line.Width = 1.0f; mNowPointLineItem.Symbol.Size = 10.0f; mNowPointLineItem.Symbol.Fill = new Fill(Color.Red); // line mPointList = new PointPairList(); for (int i = 0; i < FanData.MAX_FAN_VALUE_SIZE_5; i++) { mPointList.Add(5 * i, 50); } mLineItem = mGraph.GraphPane.AddCurve("Graph", mPointList, Color.Blue, SymbolType.Circle); mLineItem.Line.Width = 2.0f; mLineItem.Symbol.Size = 10.0f; mLineItem.Symbol.Fill = new Fill(Color.White); mUnitLabel.Visible = false; mUnitComboBox.Visible = false; mGraph.Visible = false; mStepCheckBox.Visible = false; mHysLabel.Visible = false; mHysNumericUpDown.Visible = false; }
private void animateFor1() { int counter = -1; zedGraphControl2.GraphPane.CurveList.Clear(); zedGraphControl3.GraphPane.CurveList.Clear(); PointPairList tempList; PointPairList tempListForThird; LineItem tempC = null; LineItem tempCB = null; GraphPane myPane = zedGraphControl2.GraphPane; GraphPane myPane2 = zedGraphControl3.GraphPane; int step = -72; LineItem myCurve2 = myPane.AddCurve("", list1_1, Color.Transparent, SymbolType.None); myCurve2.Line.Fill = new Fill(Color.FromArgb(200, Color.White)); while (step < 13) { Thread.Sleep(speed); tempList = new PointPairList(); tempList.Add(step, 0); tempList.Add(step, 1); tempList.Add(step + 40, 0); if (step == -47) { counter = 0; } //wykres calki if (counter > 0) { tempListForThird = new PointPairList(); for (int i = 0; i < counter; i++) { //String lol = "0," + data[i].ToString(); double res = (double)data[i] / 100; //Double.TryParse(lol, out res); int x = -47 + i; tempListForThird.Add(x, (double)res); } if (tempCB != null) { myPane2.CurveList.Remove(tempCB); } LineItem myCurve3 = myPane2.AddCurve("", tempListForThird, Color.Red, SymbolType.None); tempCB = myCurve3; myCurve3.Line.Width = 2.0F; } //zmiana labeli if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { label3.Text = step.ToString(); label5.Text = step.ToString(); if (counter != -1 && counter < data.Length) { label6.Text = "0," + data[counter].ToString(); } })); } if (counter != -1 && counter < data.Length) { counter++; } //dodanie krzywej if (tempC != null) { myPane.CurveList.Remove(tempC); } LineItem myCurve = myPane.AddCurve("", tempList, Color.Red, SymbolType.None); myCurve.Line.Fill = new Fill(Color.Red); tempC = myCurve; myCurve.Line.Width = 2.0F; //odswiezenie grafow if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { zedGraphControl2.Refresh(); zedGraphControl3.Refresh(); })); } //pauza w srodku if (step == -11) { if (this.InvokeRequired) { this.Invoke(new MethodInvoker( delegate { button9.Text = "Kontynuuj"; button9.BackColor = Color.Gold; label24.Visible = true; })); } animate.Suspend(); } step++; } }
private void btnExecutar_Click(object sender, EventArgs e) { btnCriarPop.Enabled = false; float taxaMutacao = float.Parse(txtTaxaMutacao.Text); float taxaCrossover = float.Parse(txtTaxaCrossover.Text); int torneio = int.Parse(txtQtdeTorneio.Text); evolucoes += int.Parse(txtEvolucao.Text); bestAux = double.PositiveInfinity; // Configurar AG ConfigurationGA.rateCrossover = taxaCrossover; ConfigurationGA.rateMutation = taxaMutacao; ConfigurationGA.numbOfCompetitors = torneio; ConfigurationGA.Mutation mutacao = ConfigurationGA.Mutation.NewIndividual; if (rbNovoIndividuo.Checked) { mutacao = ConfigurationGA.Mutation.NewIndividual; } else if (rbPopGeral.Checked) { mutacao = ConfigurationGA.Mutation.InPopulation; } else if (rbGenesPop.Checked) { mutacao = ConfigurationGA.Mutation.InGenesPopulation; } ConfigurationGA.mutationType = mutacao; if (chElitismo.Checked) { ConfigurationGA.elitism = true; ConfigurationGA.sizeElitism = int.Parse(txtQtdeElitismo.Text); } else { ConfigurationGA.elitism = false; //ConfigurationGA.sizeElitism = 0; } Console.Write("-----------------------------------------------------------------------------\n"); Console.Write("TIPO CROSSOVER: " + "PMX" + "\n"); Console.Write("TIPO MUTAÇÃO: " + ConfigurationGA.mutationType + "\n"); Console.Write("TIPO SELEÇÃO: " + "Torneio" + "\n"); Console.Write("ELITISMO: " + ConfigurationGA.elitism + " - QTDE: " + ConfigurationGA.sizeElitism + "\n"); Console.Write("TAXA MUTAÇÃO: " + ConfigurationGA.rateMutation + "\n"); Console.Write("TAXA CROSSOVER: " + ConfigurationGA.rateCrossover + "\n"); Console.Write("EVOLUÇÕES: " + evolucoes.ToString() + "\n"); Console.Write("-----------------------------------------------------------------------------\n"); GeneticAlgorithm ag = new GeneticAlgorithm(); for (int i = iTemp; i < evolucoes; i++) { iTemp++; lbEvolucoes.Text = i.ToString(); lbEvolucoes.Refresh(); // Execução do algoritmo genético pop = ag.executaGA(pop); // Limpar o gráfico zedMedia.GraphPane.CurveList.Clear(); zedMedia.GraphPane.GraphObjList.Clear(); double mediaPop = pop.getAveragePopulation(); mediaPopulacao.Add(i, mediaPop); // Busca o Fitness do melhor indivíduo double bestFitness = pop.getBest().getFitness(); lbMenorDistancia.Text = Math.Round(bestFitness, 0).ToString(); lbMenorDistancia.Refresh(); testaMaiorDistancia(bestFitness); lbMaiorDistancia.Text = Math.Round(maiorDistancia, 2).ToString(); lbMaiorDistancia.Refresh(); // Adiciona a média da população no gráfico LineItem media = paneMedia.AddCurve("Média", mediaPopulacao, Color.Red, SymbolType.None); // Print linhas a cada 6 evoluções if (i % 6 == 0 && bestFitness < bestAux) { bestAux = bestFitness; g.Clear(Color.White); plotLines(pop, Color.Blue); plotPoints(); } zedMedia.AxisChange(); zedMedia.Invalidate(); zedMedia.Refresh(); } g.Clear(Color.White); // Chama o método para melhorar a população pop.twoOptSwap(pop.getBest()); plotLines(pop, Color.Blue); plotPoints(); }
/// <summary> /// zedgragh作图 /// </summary> /// <param name="zg"></param> private void SetGragh(ZedGraph.ZedGraphControl zg) { GraphPane myPane = zg.GraphPane; myPane.CurveList.Clear(); myPane.GraphObjList.Clear(); //Set labels myPane.Title.Text = "煤气实绩"; // 表头 myPane.XAxis.Title.Text = "时间"; // 横坐标lable myPane.YAxis.Title.Text = "煤气量"; // 纵坐标label //Set list PointPairList list = new PointPairList(); DataView dvList = new DataView(dataset.Tables[0]); foreach (DataRowView dv in dvList) { //double x = Convert.ToDouble(dv["TIME"]); //double x = (double)new XDate(2013, 6, 11, i, 0, 0); DateTime xx = DateTime.Parse(dv["TIME"].ToString()); double x = (double)new XDate(xx); if (dv["FLOW"] is DBNull) { dv["FLOW"] = 500; } double y = Convert.ToDouble(dv["FLOW"]); list.Add(x, y); } /* * List<HRGasReal> tempList = vList.ToList(); * * for (int i = 0; i < 100; i++) * { * double C = tempList[i].Consumption; * DateTime T = tempList[i].Time; * * double x = Convert.ToDouble(i); * double y = Convert.ToDouble(C); * list.Add(x, y); * } */ /* * DateTime m = Convert.ToDateTime(DG1.Columns[1]); * Double n = Convert.ToDouble( DG1.Columns[2]); * list.Add(m, n); * for (int i = 0; i < 100; i++) * { * double x = (double)new XDate(2013, 6,11,i,0,0); * * double y = Math.Sin((double)i * Math.PI / 15.0); * * list.Add(x, y); * } */ // Generate a blue curve with circle symbols, and "My Curve 2" in the legend LineItem myCurve = myPane.AddCurve("煤气量", list, Color.Blue, SymbolType.Circle); // Fill the area under the curve with a white-red gradient at 45 degrees myCurve.Line.Fill = new Fill(Color.White, Color.Red, 45F); // Make the symbols opaque by filling them with white myCurve.Symbol.Fill = new Fill(Color.White); // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill(Color.White, Color.LightGoldenrodYellow, 45F); // Fill the pane background with a color gradient myPane.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F); //Calculate the Axis Scale Ranges myPane.XAxis.Type = AxisType.Date; myPane.AxisChange(); SetSize(); }
public void DeleteShoppingCartItem(LineItem lineItem) { _context.LineItems.Remove(lineItem); }
public void ShowSpectrum(string title, float[] channels, float maxCount, float minCount) { if (session == null) { return; } try { // Reset spectrum graphpane GraphPane pane = graphSession.GraphPane; pane.Chart.Fill = new Fill(SystemColors.ButtonFace); pane.Fill = new Fill(SystemColors.ButtonFace); pane.Title.Text = title; pane.XAxis.Title.Text = "Channel"; pane.YAxis.Title.Text = "Counts"; pane.XAxis.Scale.Min = 0; pane.XAxis.Scale.Max = maxCount; pane.YAxis.Scale.Min = minCount; pane.YAxis.Scale.Max = maxCount + (maxCount / 10.0); pane.CurveList.Clear(); // Update background graph if (session.Background != null && !menuItemSubtractBackground.Checked) { bkgGraphList.Clear(); for (int i = 0; i < session.Background.Length; i++) { bkgGraphList.Add((double)i, (double)session.Background[i] * bkgScale); } LineItem bkgCurve = pane.AddCurve("Background", bkgGraphList, Color.Blue, SymbolType.None); bkgCurve.Line.IsSmooth = true; bkgCurve.Line.SmoothTension = 0.5f; } // Update spectrum graph sessionGraphList.Clear(); for (int i = 0; i < channels.Length; i++) { double cnt = (double)channels[i]; if (session.Background != null && menuItemSubtractBackground.Checked) { cnt -= session.Background[i] * bkgScale; if (menuItemLockBackgroundToZero.Checked) { if (cnt < 0.0) { cnt = 0.0; } } } sessionGraphList.Add((double)i, cnt); } LineItem curve = pane.AddCurve("Spectrum", sessionGraphList, Color.Red, SymbolType.None); curve.Line.IsSmooth = true; curve.Line.SmoothTension = 0.5f; // Update state pane.Chart.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); pane.Legend.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); pane.Fill = new Fill(SystemColors.ButtonFace, SystemColors.ButtonFace); graphSession.RestoreScale(pane); graphSession.AxisChange(); graphSession.Refresh(); } catch (Exception ex) { log.Error(ex.Message, ex); } }
/// <summary> /// Run the code example. /// </summary> /// <param name="user">The DFP user object running the code example.</param> public override void Run(DfpUser user) { // Get the CustomFieldService. CustomFieldService customFieldService = (CustomFieldService)user.GetService( DfpService.v201511.CustomFieldService); // Get the LineItemService. LineItemService lineItemService = (LineItemService)user.GetService( DfpService.v201511.LineItemService); // Set the IDs of the custom fields, custom field option, and line item. long customFieldId = long.Parse(_T("INSERT_STRING_CUSTOM_FIELD_ID_HERE")); long customFieldOptionId = long.Parse(_T("INSERT_CUSTOM_FIELD_OPTION_ID_HERE")); long lineItemId = long.Parse(_T("INSERT_LINE_ITEM_ID_HERE")); try { // Get the drop-down custom field id. long dropDownCustomFieldId = customFieldService.getCustomFieldOption(customFieldOptionId).customFieldId; StatementBuilder statementBuilder = new StatementBuilder() .Where("id = :id") .OrderBy("id ASC") .Limit(1) .AddValue("id", lineItemId); // Get the line item. LineItemPage lineItemPage = lineItemService.getLineItemsByStatement( statementBuilder.ToStatement()); LineItem lineItem = lineItemPage.results[0]; // Create custom field values. List <BaseCustomFieldValue> customFieldValues = new List <BaseCustomFieldValue>(); TextValue textValue = new TextValue(); textValue.value = "Custom field value"; CustomFieldValue customFieldValue = new CustomFieldValue(); customFieldValue.customFieldId = customFieldId; customFieldValue.value = textValue; customFieldValues.Add(customFieldValue); DropDownCustomFieldValue dropDownCustomFieldValue = new DropDownCustomFieldValue(); dropDownCustomFieldValue.customFieldId = dropDownCustomFieldId; dropDownCustomFieldValue.customFieldOptionId = customFieldOptionId; customFieldValues.Add(dropDownCustomFieldValue); // Only add existing custom field values for different custom fields than // the ones you are setting. if (lineItem.customFieldValues != null) { foreach (BaseCustomFieldValue oldCustomFieldValue in lineItem.customFieldValues) { if (!(oldCustomFieldValue.customFieldId == customFieldId) && !(oldCustomFieldValue.customFieldId == dropDownCustomFieldId)) { customFieldValues.Add(oldCustomFieldValue); } } } lineItem.customFieldValues = customFieldValues.ToArray(); // Update the line item on the server. LineItem[] lineItems = lineItemService.updateLineItems(new LineItem[] { lineItem }); if (lineItems != null) { foreach (LineItem updatedLineItem in lineItems) { List <String> customFieldValueStrings = new List <String>(); foreach (BaseCustomFieldValue baseCustomFieldValue in lineItem.customFieldValues) { if (baseCustomFieldValue is CustomFieldValue && ((CustomFieldValue)baseCustomFieldValue).value is TextValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', value: '" + ((TextValue)((CustomFieldValue)baseCustomFieldValue).value).value + "'}"); } else if (baseCustomFieldValue is DropDownCustomFieldValue) { customFieldValueStrings.Add("{ID: '" + baseCustomFieldValue.customFieldId + "', custom field option ID: '" + ((DropDownCustomFieldValue)baseCustomFieldValue).customFieldOptionId + "'}"); } } Console.WriteLine("A line item with ID \"{0}\" set with custom field values \"{1}\".", updatedLineItem.id, string.Join(", ", customFieldValueStrings.ToArray())); } } else { Console.WriteLine("No line items were updated."); } } catch (Exception e) { Console.WriteLine("Failed to update line items. Exception says \"{0}\"", e.Message); } }