public static Delivery MapToDelivery(this IGrouping<int, Message> groupedMessages) { var delivery = new Delivery(); if(!groupedMessages.Any()) return delivery; delivery.PositionHistory = new List<Zuehlke.Camp2013.ConnectedVehicles.Position>(); delivery.StatusHistory = new List<DeliveryStatus>(); delivery.Vehicle = new Vehicle { VehicleId = groupedMessages.First().VehicleId, SensorHistory = new List<SensorData>() }; foreach(var message in groupedMessages) { delivery.PositionHistory.Add(message.MapToPosition()); if(message.Type == MessageType.STATUS) delivery.StatusHistory.Add(message.MapToDeliveryStatus()); if (message.Type == MessageType.SENSOR) delivery.Vehicle.SensorHistory.Add(message.MapToSensorData()); } return delivery; }
public void Deliveries_With_Different_Ids_Should_Not_Be_Equal() { var delivery1 = new Delivery(Guid.NewGuid(), Guid.NewGuid()); var delivery2 = new Delivery(Guid.NewGuid(), Guid.NewGuid()); delivery1.ShouldNotBe(delivery2); }
public override void Map(string inputLine, MapperContext context) { var delivery = new Delivery(); double result = 0.0; context.Log("MAPPER:::START"); context.Log(inputLine); context.Log("UTF-8: " + Encoding.UTF8.GetBytes(inputLine).Length); context.Log("ASCII: " + Encoding.ASCII.GetBytes(inputLine).Length); // Read the incoming string as a Thrift Binary serialized object var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(inputLine)); using (var transport = new TStreamTransport(inputStream, null)) { delivery.Read(new TBinaryProtocol(transport)); context.Log("MAPPER:::AFTER_READ"); // Get the driven kilometers from the vehicle's odometer sensor var sensorData = delivery.Vehicle.SensorHistory; var minOdo = sensorData.Min(d => d.OdoMeter); var maxOdo = sensorData.Max(d => d.OdoMeter); result = maxOdo - minOdo; context.Log("MAPPER:::BEFORE_STREAM_CLOSE"); } context.Log("MAPPER:::AFTER_STREAM_CLOSE"); // Emit the vehicle id, and the driven kilometers. if (result > 0.1) { context.EmitKeyValue(delivery.Vehicle.VehicleId, result.ToString(CultureInfo.InvariantCulture)); } context.Log("MAPPER:::END"); }
public void OnDelivery(AmqpLink link, Delivery delivery) { var message = AnnotatedMessage.Decode(delivery.PayloadBuffer); var queue = linkNameToQueue[link.Name]; queue.Enqueue(message); link.SetDeliveryTerminalState(delivery, new Accepted()); }
public Order(Guid _UserId, Dictionary<Guid, int> _Items, Delivery _Delivery) : base(_UserId) { PayMethod = 0; Delivery = _Delivery; Status = 0; SetTime = DateTime.Now; Items = _Items; }
protected void setUp() { routeSpecification = new RouteSpecification(L.HANGZOU, L.STOCKHOLM, DateTime.Parse("2008-11-03")); itinerary = new Itinerary( Leg.DeriveLeg(V.HONGKONG_TO_NEW_YORK, L.HANGZOU, L.NEWYORK), Leg.DeriveLeg(V.NEW_YORK_TO_DALLAS, L.NEWYORK, L.DALLAS), Leg.DeriveLeg(V.DALLAS_TO_HELSINKI, L.DALLAS, L.STOCKHOLM)); delivery = Delivery.BeforeHandling(); Thread.Sleep(1); }
public void StateEngineTest() { { var orderState = new StateDefinition<Order, OrderState>( x => x.State, new StateTransitionDefinition<Order, OrderState>(OrderState.Init, OrderState.Confirmed), new StateTransitionDefinition<Order, OrderState>(OrderState.Confirmed, OrderState.Processing), new StateTransitionDefinition<Order, OrderState>(OrderState.Processing, OrderState.Done) { Expect = (entity, o) => entity.Delivery.State == DeliveryState.Done } ); var deliveryState = new StateDefinition<Delivery, DeliveryState>( x => x.State, new StateTransitionDefinition<Delivery, DeliveryState>(DeliveryState.Init, DeliveryState.Prepare) { Expect = (entity, o) => entity.Order.State == OrderState.Processing }, new StateTransitionDefinition<Delivery, DeliveryState>(DeliveryState.Prepare, DeliveryState.Sent) { Expect = (entity, o) => entity.Order.State == OrderState.Processing }, new StateTransitionDefinition<Delivery, DeliveryState>(DeliveryState.Sent, DeliveryState.Done) { PostAction = (container, entity, arg3) => container.StateEngine.Execute(entity.Order, OrderState.Done) } ); StateEngine.Add(orderState); StateEngine.Add(deliveryState); } { var order = new Order(); var delivery = new Delivery {Order = order}; order.Delivery = delivery; using (var uow = new DummyUnitOfWorkContainer()) { Assert.Throws<StateTransitionNotAllowedException>(() => uow.StateEngine.Execute(delivery, DeliveryState.Prepare)); uow.StateEngine.Execute(order, OrderState.Confirmed); Assert.Throws<StateTransitionNotAllowedException>(() => uow.StateEngine.Execute(delivery, DeliveryState.Prepare)); uow.StateEngine.Execute(order, OrderState.Processing); Assert.Throws<StateTransitionNotAllowedException>(() => uow.StateEngine.Execute(order, OrderState.Done)); uow.StateEngine.Execute(delivery, DeliveryState.Prepare); Assert.Throws<StateTransitionNotAllowedException>(() => uow.StateEngine.Execute(order, OrderState.Done)); uow.StateEngine.Execute(delivery, DeliveryState.Sent); Assert.Throws<StateTransitionNotAllowedException>(() => uow.StateEngine.Execute(order, OrderState.Done)); uow.StateEngine.Execute(delivery, DeliveryState.Done); Assert.Equal(OrderState.Done, order.State); } } }
public void Deliveries_With_Same_Ids_Should_Be_Equal() { var delivery1DistributableId = Guid.NewGuid(); var delivery1EndpointId = Guid.NewGuid(); var delivery1 = new Delivery(delivery1DistributableId, delivery1EndpointId); var delivery2DistributableId = new Guid(delivery1DistributableId.ToString()); //Clone var delivery2EndpointId = new Guid(delivery1EndpointId.ToString()); //Clone var delivery2 = new Delivery(delivery2DistributableId, delivery2EndpointId); delivery1.ShouldBe(delivery2); }
protected Transmittal(object key, object projectKey) : base(key) { this.projectKey = projectKey; this.transmittalDate = DateTime.Now; this.totalPages = 1; this.deliveryMethod = Delivery.None; this.otherDeliveryMethod = string.Empty; this.phaseNumber = string.Empty; this.reimbursable = false; this.final = false; this.copyToList = new List<CopyTo>(); this.transmittalRemarks = string.Empty; }
protected void InsertDelivery() { #region Delivery Delivery _Delivery = new Delivery(); _Delivery.LotID = int.Parse(ddlLot1.SelectedValue); _Delivery.Pcs = int.Parse(txtPcs.Text); _Delivery.Sqft = float.Parse(txtSqFt.Text); _Delivery.Date = Convert.ToDateTime(txtDate.Text); _Delivery.Description = txtDescription.Text; _Delivery.IsDeleted = false; #endregion lblMessage.Text = Delivery_DA.InsertDelivery(_Delivery); lblMessage.ForeColor = System.Drawing.Color.Green; Response.Write("<script>alert('Inserted Successfully'); document.location='/forms/formDelivery';</script>"); }
public void testOnHandling() { Delivery delivery = Delivery.BeforeHandling(); HandlingActivity load = HandlingActivity.LoadOnto(V.HONGKONG_TO_NEW_YORK).In(L.HONGKONG); delivery = delivery.OnHandling(load); Assert.That(delivery.MostRecentHandlingActivity, Is.EqualTo(load)); Assert.That(delivery.MostRecentPhysicalHandlingActivity, Is.EqualTo(load)); HandlingActivity customs = HandlingActivity.CustomsIn(L.NEWYORK); delivery = delivery.OnHandling(customs); Assert.That(delivery.MostRecentHandlingActivity, Is.EqualTo(customs)); Assert.That(delivery.MostRecentPhysicalHandlingActivity, Is.EqualTo(load)); HandlingActivity loadAgain = HandlingActivity.LoadOnto(V.NEW_YORK_TO_DALLAS).In(L.NEWYORK); delivery = delivery.OnHandling(loadAgain); Assert.That(delivery.MostRecentHandlingActivity, Is.EqualTo(loadAgain)); Assert.That(delivery.MostRecentPhysicalHandlingActivity, Is.EqualTo(loadAgain)); }
public ActionResult AvailableNewsPaper(NewsPaperModel model) { Delivery deliver = new Delivery(); if(!string.IsNullOrEmpty(model.Address) && !string.IsNullOrEmpty(model.phoneNumber)) { deliver.Address = model.Address; deliver.PhoneNumber = model.phoneNumber; deliver.DateOrdered = DateTime.Now; context.Deliveries.Add(deliver); context.SaveChanges(); TempData["success"] = "Your NewsPaper will be delivered to the given address in three days you can now proceed to payment"; } List<NewsPapersPrice> newspapers = new List<NewsPapersPrice>(); newspapers = context.NewsPapersPrices.ToList(); model.PriceList = new MultiSelectList(newspapers, "Id", "Price", newspapers.Select(x => x.Id)); model.NewsPapers = new MultiSelectList(newspapers, "Price", "NewsPaper", newspapers.Select(x => x.Price)); ViewBag.delievery = "Do you want it delivered to your address"; model.phoneNumber = string.Empty; model.Address = string.Empty; return View(model); }
public void ChooseDeliveryOption(Delivery delivery) { UIUtil.DefaultProvider.WaitForElementDisplay(StringEnum.GetStringValue(Delivery.SendNow), LocateBy.Id); UIUtil.DefaultProvider.WaitForDisplayAndClick(StringEnum.GetStringValue(delivery), LocateBy.Id); UIUtil.DefaultProvider.WaitForAJAXRequest(); }
// Precondition: pLength > 0, pWidth > 0, pHeight > 0, // pWeight > 0 // Postcondition: The two day air package is created with the specified values for // origin address, destination address, length, width, // height, weight, and delivery type public TwoDayAirPackage(Address originAddress, Address destAddress, double pLength, double pWidth, double pHeight, double pWeight, Delivery delType) : base(originAddress, destAddress, pLength, pWidth, pHeight, pWeight) { DeliveryType = delType; }
//public Delivery Find(int Id) //{ // foreach (Delivery d in context.Deliveries) // { // if (d.Id == Id) // return d; // } // return null; //} public void Delete(Delivery d) { context.Deliveries.Remove(d); }
public override void AddDelivery(Delivery delivery) { deliveries.Add(delivery); }
private async Task OnNewJob(Job job, Delivery delivery) { bool updateStatus = true; var cancel = new CancellationTokenSource( _workerConfiguration.MaximumAllowedExecutionTime) .Token; try { if (job.Input is null) { throw new ArgumentNullException(nameof(job.Input)); } using var scope = _scopeFactory.CreateScope(job); var worker = scope.GetWorker <TWorker>(); var input = _inputSerializer.Deserialize(job.Input); job.Start(worker.EstimateExecutionTime(input)); await _jobRepository.UpdateAsync(job, cancel); var result = await worker.ExecuteAsync(input, cancel); if (result.IsCancelled) { job.Cancel(); delivery.Acknowledge = true; return; } if (result.IsFinished) { if (result.Output is null) { throw new InvalidOperationException("Job finished without output"); } string output = _outputSerializer.Serialize(result.Output); job.Finish(output); delivery.Acknowledge = true; return; } if (result.IsError) { if (delivery.SupportsRepeat) { updateStatus = false; } else { delivery.Acknowledge = true; if (result.Error is not null) { job.Error(result.Error); } else { var genericError = JobError.FromMessage("Job execution failed"); job.Error(genericError); } } } } catch (OperationCanceledException e) { if (delivery.SupportsRepeat) { updateStatus = false; } else { delivery.Acknowledge = true; job.Error(e); } } catch (Exception e) { delivery.Acknowledge = true; job.Error(e); } finally { if (updateStatus) { await _jobRepository.UpdateAsync(job, CancellationToken.None); } } }
private void AddRecordToProjectCharacterVerseData(Block block, Character character, Delivery delivery) { var cv = new CharacterVerse( new BCVRef(GetBlockVerseRef(block, ScrVers.English).BBBCCCVVV), character.IsNarrator ? CharacterVerseData.GetStandardCharacterId(CurrentBookId, CharacterVerseData.StandardCharacter.Narrator) : character.CharacterId, delivery.IsNormal ? null : delivery.Text, character.Alias, character.ProjectSpecific || delivery.ProjectSpecific); m_projectCharacterVerseData.Add(cv); m_project.SaveProjectCharacterVerseData(); }
public ActionResult SaveDelivery(Delivery delivery) { if (delivery.DeliveryId != 0) this.DataService.Update(delivery); else this.DataService.Insert(delivery); return this.Json(new { result = "success" , Delivery = delivery}); }
private void SetCharacterAndDelivery(Block block, Character selectedCharacter, Delivery selectedDelivery) { if (CharacterVerseData.IsCharacterUnclear(selectedCharacter.CharacterId)) { throw new ArgumentException("Character cannot be confirmed as ambigous or unknown.", "selectedCharacter"); } // If the user sets a non-narrator to a block we marked as narrator, we want to track it if (!selectedCharacter.IsNarrator && !block.IsQuote) { Analytics.Track("NarratorToQuote", new Dictionary <string, string> { { "book", CurrentBookId }, { "chapter", block.ChapterNumber.ToString(CultureInfo.InvariantCulture) }, { "initialStartVerse", block.InitialStartVerseNumber.ToString(CultureInfo.InvariantCulture) }, { "lastVerse", block.LastVerseNum.ToString(CultureInfo.InvariantCulture) }, { "character", selectedCharacter.CharacterId } }); } if (selectedCharacter.ProjectSpecific || selectedDelivery.ProjectSpecific) { AddRecordToProjectCharacterVerseData(block, selectedCharacter, selectedDelivery); } SetCharacter(block, selectedCharacter); block.Delivery = selectedDelivery.IsNormal ? null : selectedDelivery.Text; block.UserConfirmed = true; }
public void SetReferenceTextMatchupDelivery(int blockIndex, Delivery selectedDelivery) { CurrentReferenceTextMatchup.CorrelatedBlocks[blockIndex].Delivery = selectedDelivery.IsNormal ? null : selectedDelivery.Text; }
public void changeButtonClick(Storage storage, Delivery delivery) { new AddDeliveryForm(storage, delivery).ShowDialog(); }
public string Update(Delivery delivery) { DeliveryUnitTests.OutputHelper.WriteLine("Deliviring the package."); delivery.UpdatePackageState(new DeliviredPackage()); return("Deliviring the package"); }
public DeliveryViewModel() { delivery = new Delivery(); DataService = new DeliveryService(); AcceptCommand = new RelayCommand(AcceptExecute); }
public void SendTransfer(byte[] deliveryTag, ByteBuffer payloadBuffer) { var delivery = new Delivery(); delivery.Link = this; delivery.DeliveryTag = deliveryTag; delivery.Settled = senderSettlementMode == LinkSenderSettlementModeEnum.Settled; delivery.State = null; delivery.PayloadBuffer = payloadBuffer; delivery.ReceiverSettlementMode = receiverSettlementMode; LinkCredit--; DeliveryCount++; Session.SendTransfer(delivery); }
public void SetUiStrings(string narrator, string bookChapterCharacter, string introCharacter, string extraCharacter, string normalDelivery) { Character.SetUiStrings(narrator, bookChapterCharacter, introCharacter, extraCharacter, () => CurrentBookId, GetCurrentRelevantAlias); Delivery.SetNormalDelivery(normalDelivery); }
internal void NotifyOfDisposition(Delivery delivery, Disposition disposition) { try { // TODO: notify application of change in application state } catch (AmqpException amqpException) { trace.Error(amqpException); DetachLink(amqpException.Error, destoryLink: true); } catch (Exception fatalException) { trace.Fatal(fatalException, "Ending Session due to fatal exception."); var error = new Error() { Condition = ErrorCode.InternalError, Description = "Ending Session due to fatal exception: " + fatalException.Message, }; DetachLink(error, destoryLink: true); } }
public static void SetNormalDelivery(string normalDelivery) { s_normalDelivery = new Delivery(normalDelivery, false); }
/// <summary> /// Sends a message with an optional buffer as the message payload. /// </summary> /// <param name="message">The message to be sent.</param> /// <param name="buffer">The serialized buffer of the message. It is null, the message is serialized.</param> public void SendMessage(Message message, ByteBuffer buffer) { if (this.role) { throw new AmqpException(ErrorCode.NotAllowed, "Cannot send a message over a receiving link."); } Delivery delivery = new Delivery() { Handle = this.Handle, Message = message, Buffer = buffer ?? message.Encode(), Link = this, Settled = this.SettleOnSend, Tag = Delivery.GetDeliveryTag(this.deliveryCount) }; this.Session.SendDelivery(delivery); this.deliveryCount++; }
protected bool Equals(Delivery other) { return(String.Equals(Text, other.Text)); }
private Delivery GetNextDelivery(Product curProduct) { IProductRepository productRep = RepositoryFactory.GetInstance().GetRepository<IProductRepository, IProduct>(); IDeliveryRepository deliveryRep = RepositoryFactory.GetInstance().GetRepository<IDeliveryRepository, Delivery>(); IModelRepository modelRep = RepositoryFactory.GetInstance().GetRepository<IModelRepository, Model>(); IMORepository moRep = RepositoryFactory.GetInstance().GetRepository<IMORepository>(); Delivery assignDelivery = new Delivery(); CurrentSession.AddValue("HasDN", "N"); //CDSI 机器Assign Delivery的特殊要求 //IList<IMES.FisObject.Common.Model.ModelInfo> GetModelInfoByModelAndName(string model, string name); IList<IMES.FisObject.Common.Model.ModelInfo> infoList = modelRep.GetModelInfoByModelAndName(curProduct.Model, "PO"); Model model = modelRep.Find(curProduct.Model); string cdsi = ""; cdsi = model.GetAttribute("PO"); if (cdsi != "Y") { cdsi = ""; cdsi = model.GetAttribute("ATSNAV"); if (!string.IsNullOrEmpty(cdsi)) { cdsi = "cdsi"; } } else { cdsi = "cdsi"; } CurrentSession.AddValue("CDSI", cdsi); if (cdsi == "cdsi") { if (!string.IsNullOrEmpty(curProduct.DeliveryNo)) { assignDelivery = deliveryRep.Find(curProduct.DeliveryNo); CurrentSession.AddValue(Session.SessionKeys.Delivery, assignDelivery); return assignDelivery; } string factoryPo = ""; //获取Product 结合的Factory Po,对于CDSI 机器如果获取不到结合的Factory Po, //需要报告错误:“CDSI AST MISSING DATA!” //SELECT @FactoryPo = Sno FROM CDSIAST NOLOCK WHERE SnoId = @ProductId AND Tp = 'FactoryPO' CdsiastInfo conf = new CdsiastInfo(); conf.snoId = curProduct.ProId; conf.tp = "FactoryPO"; IList<CdsiastInfo> cdsiList = productRep.GetCdsiastInfoList(conf); /*if (cdsiList.Count == 0) { errpara.Add(this.Key); throw new FisException("PAK140", errpara);//“CDSI AST MISSING DATA!” }*/ factoryPo = cdsiList[0].sno; IList<Delivery> dnList = deliveryRep.GetDeliveryListByModelPrefix(factoryPo, "PC", 12, "00"); //IF @Delivery = '' SELECT 'CDSI 机器,无此PoNo: ' + @FactoryPo + ' 的Delivery!' if (dnList.Count == 0) { return null; } assignDelivery = dnList[0]; } else if (curProduct.IsBindedPo) { if (!string.IsNullOrEmpty(curProduct.DeliveryNo)) { assignDelivery = deliveryRep.Find(curProduct.DeliveryNo); CurrentSession.AddValue(Session.SessionKeys.Delivery, assignDelivery); return assignDelivery; } string factoryPo = curProduct.BindPoNo; IList<Delivery> dnList = deliveryRep.GetDeliveryListByModelPrefix(factoryPo, "PC", 12, "00"); if (dnList.Count == 0) { return null; } assignDelivery = dnList[0]; } else if (!curProduct.IsBT) { //a)选择的DN需要满足如下要求: //Delivery.ShipDate 大于3天前 (例如:当天为2011/9/13,那么获取的DN 的ShipDate 要大于2011/9/10) – 即ShipDate>=convert(char(10),getdate()-3,111) //Note: //ShipDate 需要转换为YYYY/MM/DD 格式显示 //Sample: 2009/05/11 //Delivery.Status = ‘00’ //Delivery.Model 长度为12 位 //Delivery.Model 前两码为’PC’ //系统自动分配另外一个DN(列表中满足条件的Delivery按照ShipDate,Qty,DeliveryNo 排序取第一个), DNQueryCondition condition = new DNQueryCondition(); DateTime temp = DateTime.Now; temp = temp.AddDays(-3); condition.ShipDateFrom = new DateTime(temp.Year, temp.Month, temp.Day, 0, 0, 0, 0); condition.Model = curProduct.Model; IList<DNForUI> dnList = deliveryRep.GetDNListByConditionWithSorting(condition); //Vincent 2015-02-27 過濾綁訂PoDN if (dnList != null && dnList.Count > 0) { IList<string> bindPoNoList = moRep.GetBindPoNoByModel(curProduct.Model); if (bindPoNoList != null && bindPoNoList.Count > 0) { dnList = dnList.Where(x => !bindPoNoList.Contains(x.PoNo)).ToList(); } } foreach (DNForUI tmp in dnList) { if (tmp.Status != "00") { continue; } if (!(tmp.ModelName.Length == 12 && tmp.ModelName.Substring(0, 2) == "PC")) { continue; } int qty = 0; int packedQty = 0; qty = tmp.Qty; IList<IProduct> productList = new List<IProduct>(); productList = productRep.GetProductListByDeliveryNo(tmp.DeliveryNo); packedQty = productList.Count; if (packedQty + 1 > qty) { continue; } assignDelivery = deliveryRep.Find(tmp.DeliveryNo); break; } if (assignDelivery == null) { return null; } } return assignDelivery; }
private Delivery _deliveryType; // TDAP's delivery type (Early or Saver) // Precondition: pLength > 0, pWidth > 0, pHeight > 0, // pWeight > 0 // Postcondition: The two day air package is created with the specified values for // origin address, destination address, length, width, // height, weight, and delivery type public TwoDayAirPackage(Address originAddress, Address destAddress, double pLength, double pWidth, double pHeight, double pWeight, Delivery delType) : base(originAddress, destAddress, pLength, pWidth, pHeight, pWeight) { DeliveryType = delType; }
internal override void OnTransfer(Delivery delivery, Transfer transfer, ByteBuffer buffer) { if (delivery != null) { buffer.AddReference(); delivery.Buffer = buffer; this.deliveryCount++; } else { delivery = this.deliveryCurrent; AmqpBitConverter.WriteBytes(delivery.Buffer, buffer.Buffer, buffer.Offset, buffer.Length); } if (!transfer.More) { this.DeliverMessage(delivery); } else { this.deliveryCurrent = delivery; } }
public AdDataImportSession(Delivery delivery) : base(delivery) { _bufferSize = int.Parse(AppSettings.Get(this, "BufferSize")); }
public ActionResult EditBook(EditBookModel model, bool deliveryBool1, bool deliveryBool2, bool deliveryBool3, bool deliveryBool4) { int counter = 0; if (!ModelState.IsValid) { List <string> errors = new List <string>(); foreach (var modelStateVal in ViewData.ModelState.Values) { foreach (var error in modelStateVal.Errors) { var errorMessage = error.ErrorMessage; var exception = error.Exception; errors.Add(errorMessage); } } foreach (string error in errors) { ModelState.AddModelError("", error); } return(View()); } var context = new AppDbContext(); var book = context.Books.Find(model.Id); if (model.Price == null) { model.Price = 0; } book.Author = model.Author; book.Title = model.Title; book.Genre = model.Genre; book.Description = model.Description; book.AddDate = DateTime.Now; book.Price = model.Price; book.Publisher = model.Publisher; book.Changeable = model.Changeable; book.PublicationDate = model.PublicationDate; book.SellerId = System.Web.HttpContext.Current.User.Identity.GetUserId(); book.Seller = context.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()); bool bookIsAdded = false; bool checkDelivery = false; if (deliveryBool1 == true) { counter++; if (!bookIsAdded) { context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Odbiór osobisty"); if (oneDelivery != null) { oneDelivery.Price = model.DeliveryDict["Odbiór osobisty"]; oneDelivery.DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId; oneDelivery.DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(); context.SaveChanges(); } else { var del = new Delivery { Name = "Odbiór osobisty", Price = model.DeliveryDict["Odbiór osobisty"], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(del); context.SaveChanges(); } } else { var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Odbiór osobisty"); if (oneDelivery != null) { context.DeliveryOptions.Remove(oneDelivery); } } if (deliveryBool2 == true) { counter++; if (!bookIsAdded) { context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka pocztowa - priorytetowa"); if (oneDelivery != null) { oneDelivery.Price = model.DeliveryDict["Przesyłka pocztowa - priorytetowa"]; oneDelivery.DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId; oneDelivery.DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(); context.SaveChanges(); } else { var del = new Delivery { Name = "Przesyłka pocztowa - priorytetowa", Price = model.DeliveryDict["Przesyłka pocztowa - priorytetowa"], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(del); context.SaveChanges(); } } else { var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka pocztowa - priorytetowa"); if (oneDelivery != null) { context.DeliveryOptions.Remove(oneDelivery); } } if (deliveryBool3 == true) { counter++; if (!bookIsAdded) { context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka pocztowa - ekonomiczna"); if (oneDelivery != null) { oneDelivery.Price = model.DeliveryDict["Przesyłka pocztowa - ekonomiczna"]; oneDelivery.DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId; oneDelivery.DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(); context.SaveChanges(); } else { var del = new Delivery { Name = "Przesyłka pocztowa - ekonomiczna", Price = model.DeliveryDict["Przesyłka pocztowa - ekonomiczna"], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(del); context.SaveChanges(); } } else { var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka pocztowa - ekonomiczna"); if (oneDelivery != null) { context.DeliveryOptions.Remove(oneDelivery); } } if (deliveryBool4 == true) { counter++; if (!bookIsAdded) { context.Books.Attach(book); context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); Debug.WriteLine(delivery.Count() + " " + counter); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka kurierska"); if (oneDelivery != null) { oneDelivery.Price = model.DeliveryDict["Przesyłka kurierska"]; oneDelivery.DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId; oneDelivery.DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(); context.SaveChanges(); } else { var del = new Delivery { Name = "Przesyłka kurierska", Price = model.DeliveryDict["Przesyłka kurierska"], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(del); context.SaveChanges(); } } else { var delivery = context.DeliveryOptions.Where(m => m.DeliveryPriceId == model.Id); var oneDelivery = delivery.SingleOrDefault(m => m.Name == "Przesyłka kurierska"); if (oneDelivery != null) { context.DeliveryOptions.Remove(oneDelivery); } } if (!checkDelivery) { ModelState.AddModelError("", "Proszę wybrać opcję dostawy"); return(View()); } byte[] uploadedFile = null; if (Request.Files != null && Request.Files.Count > 0) { int i = 0; foreach (string image in Request.Files) { HttpPostedFileBase hpf2 = Request.Files.Get(i); if (hpf2.InputStream.Length > 0) { Debug.WriteLine(image); uploadedFile = new byte[hpf2.InputStream.Length]; hpf2.InputStream.Read(uploadedFile, 0, uploadedFile.Length); var img = context.BookImages.Where(m => m.BookImgId == model.Id); BookImage[] imgTab = img.ToArray(); if (imgTab.Count() == 0) { var newImage = new BookImage { Image = uploadedFile, BookImg = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(), BookImgId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId }; context.BookImages.Add(newImage); context.SaveChanges(); } else { string nameImputImage = "BookImage" + i; Debug.WriteLine("Przy edytowaniu książki: nameImputImage = ", nameImputImage, "image = ", image); if (nameImputImage == image) { int imageId = imgTab[i].ImageId; Debug.WriteLine("imageID = ", imageId); img.Single(m => m.ImageId == imageId).Image = uploadedFile; img.Single(m => m.ImageId == imageId).BookImgId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId; img.Single(m => m.ImageId == imageId).BookImg = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault(); context.SaveChanges(); } } } } i++; } LuceneSearchIndexer.UpdateBooksIndex(); return(RedirectToAction("index", "home")); }
public ActionResult Delivery(FormCollection collection) { try { var transport = collection["ownTransport"]; bool isOwnTransport = transport != null; int deliverebyUserId = ((ViewUser)Session["user"]).UserId; int replaceId = Convert.ToInt32(collection["ReplaceId"]); var replace = _iProductReplaceManager.GetReplaceById(replaceId); IEnumerable <ViewReplaceDetailsModel> details = _iProductReplaceManager.GetReplaceProductListById(replaceId); var deliveredQty = _iProductReplaceManager.GetDeliveredProductsByReplaceRef(replace.ReplaceRef).Count; var remainingToDeliverQty = replace.Quantity - deliveredQty; var filePath = GetTempReplaceProductXmlFilePath(replaceId); //if the file is exists read the file var barcodeList = _iProductManager.GetScannedProductListFromTextFile(filePath).ToList(); int replaceStatus = 1; if (remainingToDeliverQty == barcodeList.Count) { replaceStatus = 2; } List <ViewReplaceDetailsModel> deliveredProductList = new List <ViewReplaceDetailsModel>(); foreach (ScannedProduct product in barcodeList.DistinctBy(n => n.ProductId)) { var model = details.ToList().Find(n => n.ProductId.Equals(product.ProductId)); var qty = barcodeList.ToList().FindAll(n => n.ProductId == product.ProductId).Count; model.Quantity = qty; deliveredProductList.Add(model); } var aDelivery = new Delivery { IsOwnTransport = isOwnTransport, TransactionRef = replace.ReplaceRef, InvoiceRef = replace.ReplaceRef, DeliveredByUserId = deliverebyUserId, Transportation = collection["Transportation"], DriverName = collection["DriverName"], DriverPhone = collection["DriverPhone"], TransportationCost = Convert.ToDecimal(collection["TransportationCost"]), VehicleNo = collection["VehicleNo"], DeliveryDate = Convert.ToDateTime(collection["DeliveryDate"]).Date, CompanyId = replace.CompanyId, ToBranchId = replace.BranchId, InvoiceId = replaceId, FromBranchId = replace.BranchId }; string result = _iInventoryManager.SaveReplaceDeliveryInfo(barcodeList, aDelivery, replaceStatus, replace); if (result.StartsWith("S")) { System.IO.File.Create(filePath).Close(); return(RedirectToAction("ViewAll")); } return(View()); } catch (Exception exception) { TempData["Error"] = exception.Message; Log.WriteErrorLog(exception); return(PartialView("_ErrorPartial", exception)); } }
static void Main(string[] args) { //LOAD THE FILE var fileContents = File.ReadAllLines(@"c:\projects\planet_express_logs.csv"); var numOfLines = fileContents.Count(); //CREATE AN ARRAY OF DELIVERIES TO PUSH THAT STUFF INTO Delivery[] deliveries = new Delivery[numOfLines - 1]; //loop through each line in the file //creating a delivery as I do. for (int i = 0; i < numOfLines - 1; i++) { var line = fileContents[i + 1]; var columns = line.Split(new[] { ',' }); deliveries[i] = new Delivery(); deliveries[i].Destination = columns[0]; deliveries[i].MoneyMade = int.Parse(columns[3]); } foreach (var d in deliveries) { Console.WriteLine($"Dest: {d.Destination}. Amount = {d.MoneyMade}"); } //how much money total did we make? int totalMoneyMade = 0; //One possible way //for (int i = 0; i < deliveries.Length; i++) //{ // totalMoneyMade = totalMoneyMade + deliveries[i].MoneyMade; //} //second possible way foreach (Delivery d in deliveries) { totalMoneyMade += d.MoneyMade; } Console.WriteLine($"We made {totalMoneyMade} last week."); //who piloted each delivery? foreach (Delivery d in deliveries) { string pilot = d.WhoIsThePilot(); Console.WriteLine($"This was delivered by {pilot} to Planet {d.Destination}"); } //figure out each pilot's bonus double FrysBonus = 0; double AmysBonus = 0; double BendersBonus = 0; foreach (var d in deliveries) { var bonus = (d.MoneyMade * .10); switch (d.WhoIsThePilot()) { case "Fry": FrysBonus += bonus; break; case "Amy": AmysBonus += bonus; break; case "Bender": BendersBonus += bonus; break; } } Console.WriteLine($"Fry's Bonus is {FrysBonus}"); Console.WriteLine($"Amy's Bonus is {AmysBonus}"); Console.WriteLine($"Bender's Bonus is {BendersBonus}"); Console.ReadLine(); }
public decimal GetFedExRate(Rates objRates, CurrentUserInfo uinfo, Delivery delivery, string strShippingOptionName) { decimal decRate = 0; try { // Cache the data for 10 minutes with a key using (CachedSection <Rates> cs = new CachedSection <Rates>(ref objRates, 60, true, null, "FexExRates-" + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, ""))) { if (cs.LoadData) { //Get real-time shipping rates from FedEx using dotNETShip Ship objShip = new Ship(); objShip.FedExLogin = strFedExLogin; // "Account number, meter number, key, password" objShip.FedExURLTest = SettingsKeyInfoProvider.GetBoolValue("MultiCarrierTestMode"); objShip.OrigZipPostal = SettingsKeyInfoProvider.GetValue("SourceZip", "90001"); string[] strCountryState = SettingsKeyInfoProvider.GetValue("SourceCountryState", "US").Split(';'); CountryInfo ci = CountryInfoProvider.GetCountryInfo(ValidationHelper.GetString(strCountryState[0], "USA")); objShip.OrigCountry = ci.CountryTwoLetterCode; StateInfo si = StateInfoProvider.GetStateInfo(ValidationHelper.GetString(strCountryState[1], "California")); objShip.OrigStateProvince = si.StateCode; objShip.DestZipPostal = delivery.DeliveryAddress.AddressZip; objShip.DestCountry = delivery.DeliveryAddress.GetCountryTwoLetterCode(); objShip.DestStateProvince = delivery.DeliveryAddress.GetStateCode(); objShip.Weight = (float)delivery.Weight; objShip.Rate("FedEx"); cs.Data = objShip.Rates; } objRates = cs.Data; } if (objRates.Count > 0) { foreach (Rate rate in objRates) { if (rate.Name.ToLower() == strShippingOptionName.ToLower()) { decRate = ValidationHelper.GetDecimal(rate.Charge, 0) * 1.08m; break; } } } else { CacheHelper.ClearCache("FexExRates-" + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, "")); } } catch (Exception ex) { //Log the error EventLogProvider.LogException("MultiCarrier - GetFedExRate", "EXCEPTION", ex); //Set some base rate for the shipping decRate = 10; } return(decRate); }
private static DeliveryContract ToDeliveryMethodContract(Delivery delivery) { return (DeliveryContract)Enum.Parse(typeof(DeliveryContract), delivery.ToString()); }
public bool CanDeliver(Delivery delivery) { return(true); }
public unsafe static Delivery CreateDelivery() { Delivery d = new Delivery(); Vector3 me = Game.Player.Character.Position; int k = 0; while (k < 100) { Vector3 end = randomOnRoad(me, 500); d.end = end; int junk, street; Function.Call(Hash.GET_STREET_NAME_AT_COORD, d.end.X, d.end.Y, d.end.Z, &street, &junk); d.end_text = Function.Call<string>(Hash.GET_STREET_NAME_FROM_HASH_KEY, street); if (end != new Vector3(0, 0, 0) && isPassedStreetFilter(d.end_text)) break; k += 1; } k = 0; while (k < 100) { Vector3 start = randomOnRoad(me, 500); d.start = start; int junk, street; Function.Call(Hash.GET_STREET_NAME_AT_COORD, d.start.X, d.start.Y, d.start.Z, &street, &junk); d.start_text = Function.Call<string>(Hash.GET_STREET_NAME_FROM_HASH_KEY, street); if (start != new Vector3(0, 0, 0) && isPassedStreetFilter(d.start_text)) break; k += 1; } if (k == 100) { return null; UI.Notify("OHFUK"); } else { unsafe { } return d; } }
public decimal GetPrice(Delivery delivery, string currencyCode) { decimal decRate = 0; try { ShipmentCarrier scCarrier = new ShipmentCarrier(); string strShippingOptionName = ""; switch (delivery.ShippingOption.ShippingOptionName) { case "Multi-FedExPriorityOvernight": strShippingOptionName = "Priority Overnight"; scCarrier = ShipmentCarrier.FedEx; break; case "Multi-FedExStandardOvernight": strShippingOptionName = "Standard Overnight"; scCarrier = ShipmentCarrier.FedEx; break; case "Multi-UPSNextDayAirSaver": strShippingOptionName = "UPS Next Day Air Saver®"; scCarrier = ShipmentCarrier.UPS; break; case "Multi-UPSNextDayAir": strShippingOptionName = "UPS Next Day Air®"; scCarrier = ShipmentCarrier.UPS; break; case "Multi-USPSFirstClassMail": strShippingOptionName = "First-Class Mail"; scCarrier = ShipmentCarrier.USPS; break; case "Multi-USPSPriorityMail2-Day": strShippingOptionName = "Priority Mail 2-Day"; scCarrier = ShipmentCarrier.USPS; break; case "Multi-USPSPriorityMailExpress1-Day": strShippingOptionName = "Priority Mail Express 1-Day"; scCarrier = ShipmentCarrier.USPS; break; } Rates objRates = new Rates(); CurrentUserInfo uinfo = MembershipContext.AuthenticatedUser; switch (scCarrier) { case ShipmentCarrier.FedEx: decRate = GetFedExRate(objRates, uinfo, delivery, strShippingOptionName); break; case ShipmentCarrier.UPS: decRate = GetUPSRate(objRates, uinfo, delivery, strShippingOptionName); break; case ShipmentCarrier.USPS: decRate = GetUSPSRate(objRates, uinfo, delivery, strShippingOptionName); break; default: decRate = 10; //Set a default shipping rate in case there is an issue. break; } } catch (Exception ex) { //Log the error EventLogProvider.LogException("MultiCarrier - GetPrice", "EXCEPTION", ex); //Set some base rate for the shipping decRate = 10; } return(decRate); }
public void SetDeliveryTerminalState(Delivery delivery, DeliveryState state) { delivery.State = state; delivery.Settled = delivery.ReceiverSettlementMode == LinkReceiverSettlementModeEnum.First; if (delivery.Settled) { if (IsReceiverLink) { LinkCredit++; if (DeliveryCount % ReflowModulus == 0) SendFlow(drain: false, echo: false); } } Session.SendDeliveryDisposition(this.IsReceiverLink, delivery, state, delivery.Settled); }
public ActionResult Delivery(FormCollection collection) { try { int branchId = Convert.ToInt32(Session["BranchId"]); var transport = collection["ownTransport"]; bool isOwnTransport = transport != null; int deliverebyUserId = ((ViewUser)Session["user"]).UserId; int invoiceId = Convert.ToInt32(collection["InvoiceId"]); var invoice = _iInvoiceManager.GetInvoicedOrderByInvoiceId(invoiceId); IEnumerable <InvoiceDetails> details = _iInvoiceManager.GetInvoicedOrderDetailsByInvoiceId(invoiceId); var client = _iClientManager.GetById(invoice.ClientId); var deliveredQty = _iInvoiceManager.GetDeliveredProductsByInvoiceRef(invoice.InvoiceRef).Count; var remainingToDeliverQty = invoice.Quantity - deliveredQty; string fileName = "Scanned_Ordered_Product_List_For_" + invoiceId; var filePath = Server.MapPath("~/Files/" + fileName); //if the file is exists read the file var barcodeList = _iProductManager.GetScannedProductListFromTextFile(filePath).ToList(); int invoiceStatus = Convert.ToInt32(InvoiceStatus.PartiallyDelivered); int orderStatus = Convert.ToInt32(OrderStatus.PartiallyDelivered); if (remainingToDeliverQty == barcodeList.Count) { invoiceStatus = Convert.ToInt32(InvoiceStatus.Delivered); orderStatus = Convert.ToInt32(OrderStatus.Delivered); } List <InvoiceDetails> deliveredProductList = new List <InvoiceDetails>(); foreach (ScannedProduct product in barcodeList.DistinctBy(n => n.ProductId)) { var invoiceDetails = details.ToList().Find(n => n.ProductId.Equals(product.ProductId)); var qty = barcodeList.ToList().FindAll(n => n.ProductId == product.ProductId).Count; invoiceDetails.Quantity = qty; deliveredProductList.Add(invoiceDetails); } //-----------------Credit sale account code =1001021 --------------- //financialModel.InvoiceDiscountCode = "2102011"; //financialModel.InvoiceDiscountAmount = (invoice.SpecialDiscount/invoice.Quantity)*barcodeList.Count; //-----------------Credit vat account code =2102013 --------------- //-----------------Credit invoice discount account code =2102012 --------------- //var up= deliveredProductList.Sum(n => n.UnitPrice); // var discount = deliveredProductList.Sum(n => n.Discount); var grossAmount = deliveredProductList.Sum(n => (n.UnitPrice + n.Vat) * n.Quantity); var tradeDiscount = deliveredProductList.Sum(n => n.Discount * n.Quantity); var invoiceDiscount = (invoice.SpecialDiscount / invoice.Quantity) * barcodeList.Count; var grossDiscount = tradeDiscount + invoiceDiscount; var vat = deliveredProductList.Sum(n => n.Vat * n.Quantity); var financialModel = new FinancialTransactionModel { //--------Dr ------------------- ClientCode = client.SubSubSubAccountCode, ClientDrAmount = grossAmount - grossDiscount, GrossDiscountAmount = grossDiscount, GrossDiscountCode = "2102018", //--------Cr ------------------- //SalesRevenueCode = "1001021" old, SalesRevenueCode = "1001011", SalesRevenueAmount = grossAmount - vat, //VatCode = "2102013 test", VatCode = "3108011", VatAmount = vat, TradeDiscountCode = "2102012", TradeDiscountAmount = tradeDiscount, InvoiceDiscountAmount = invoiceDiscount, InvoiceDiscountCode = "2102011" }; var aDelivery = new Delivery { IsOwnTransport = isOwnTransport, TransactionRef = invoice.TransactionRef, InvoiceRef = invoice.InvoiceRef, DeliveredByUserId = deliverebyUserId, Transportation = collection["Transportation"], DriverName = collection["DriverName"], DriverPhone = collection["DriverPhone"], TransportationCost = Convert.ToDecimal(collection["TransportationCost"]), VehicleNo = collection["VehicleNo"], DeliveryDate = Convert.ToDateTime(collection["DeliveryDate"]).Date, CompanyId = invoice.CompanyId, ToBranchId = invoice.BranchId, DistributionPointId = branchId, InvoiceId = invoiceId, FromBranchId = invoice.BranchId, FinancialTransactionModel = financialModel, SpecialDiscount = invoiceDiscount }; //----------SMS Buildder Model----------- var aModel = new MessageModel { PhoneNumber = client.Phone.Replace("-", "").Trim(), CustomerName = client.ClientName, TotalQuantity = deliveredProductList.Sum(n => n.Quantity), Amount = financialModel.ClientDrAmount, TransactionDate = DateTime.Now, }; aDelivery.MessageModel = aModel; if (client.IsConsiderCreditLimit == 1) { var netAmount = grossAmount - grossDiscount; if (netAmount + client.Outstanding <= client.CreditLimit) { string result = _iInventoryManager.SaveDeliveredOrder(barcodeList, aDelivery, invoiceStatus, orderStatus); aModel.MessageBody = aModel.GetMessageForDistribution(); if (result.StartsWith("S")) { System.IO.File.Create(filePath).Close(); //-----------Send SMS after successfull delivery inf save------------ var res = _iCommonManager.SendSms(aModel); return(RedirectToAction("LatestOrderList")); } } else { TempData["CreditLimit"] = "Credit Limit exceed!!"; return(RedirectToAction("Delivery", new { id = invoice.InvoiceId })); } } else { string result = _iInventoryManager.SaveDeliveredOrder(barcodeList, aDelivery, invoiceStatus, orderStatus); aModel.MessageBody = aModel.GetMessageForDistribution(); if (result.StartsWith("S")) { System.IO.File.Create(filePath).Close(); //-----------Send SMS after successfull delivery inf save------------ var res = _iCommonManager.SendSms(aModel); return(RedirectToAction("LatestOrderList")); } return(View()); } return(View()); } catch (Exception exception) { TempData["Error"] = exception.Message; //return View("Delivery"); throw new Exception(); } }
private void HandleTransferFrame(Transfer transfer, ByteBuffer buffer) { if (State != LinkStateEnum.ATTACHED) throw new AmqpException(ErrorCode.IllegalState, $"Received Transfer frame but link state is {State.ToString()}."); if (LinkCredit <= 0) throw new AmqpException(ErrorCode.TransferLimitExceeded, "The link credit has dropped to 0. Wait for messages to finishing processing."); if (!IsReceiverLink) throw new AmqpException(ErrorCode.NotAllowed, "A Sender Link cannot receive Transfers."); Delivery delivery; if (continuationDelivery == null) { // new transfer delivery = new Delivery(); delivery.Link = this; delivery.DeliveryId = transfer.DeliveryId.Value; delivery.DeliveryTag = transfer.DeliveryTag; delivery.Settled = transfer.Settled.IsTrue(); delivery.State = transfer.State; delivery.PayloadBuffer = new ByteBuffer(buffer.LengthAvailableToRead, true); delivery.ReceiverSettlementMode = receiverSettlementMode; if (transfer.ReceiverSettlementMode.HasValue) { delivery.ReceiverSettlementMode = (LinkReceiverSettlementModeEnum)transfer.ReceiverSettlementMode.Value; if (receiverSettlementMode == LinkReceiverSettlementModeEnum.First && delivery.ReceiverSettlementMode == LinkReceiverSettlementModeEnum.Second) throw new AmqpException(ErrorCode.InvalidField, "rcv-settle-mode: If the negotiated link value is first, then it is illegal to set this field to second."); } } else { // continuation if (transfer.DeliveryId.HasValue && transfer.DeliveryId.Value != continuationDelivery.DeliveryId) throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer."); if (transfer.DeliveryTag != null && !transfer.DeliveryTag.SequenceEqual(continuationDelivery.DeliveryTag)) throw new AmqpException(ErrorCode.NotAllowed, "Expecting Continuation Transfer but got a new Transfer."); delivery = continuationDelivery; } if (transfer.Aborted.IsTrue()) { continuationDelivery = null; return; // ignore message } // copy and append the buffer (message payload) to the cached PayloadBuffer AmqpBitConverter.WriteBytes(delivery.PayloadBuffer, buffer.Buffer, buffer.ReadOffset, buffer.LengthAvailableToRead); if (transfer.More.IsTrue()) { continuationDelivery = delivery; return; // expecting more payload } // assume transferred complete payload at this point continuationDelivery = null; if (!delivery.Settled) { Session.NotifyUnsettledIncomingDelivery(this, delivery); } LinkCredit--; DeliveryCount++; Session.Connection.Container.OnDelivery(this, delivery); }
private Delivery _delivery; // temporarily holds delivery type // Precondition: originAddress and destAddress must be valid address objects // 0 < length // 0 < width // 0 < height // 0 < weight // Postcondition: The orignation and destination addresses are created and // passed to the base class with the size parameters to be set to the specified // values. The delivery type is set to the specified value public TwoDayAirPackage(Address originAddress, Address destAddress, double length, double width, double height, double weight, Delivery delivery) : base(originAddress, destAddress, length, width, height, weight) { DeliveryType = delivery; }
public void Add(Delivery D) { context.Deliveries.Add(D); context.SaveChanges(); }
private async void PickUpBarButtonItem_Clicked(object sender, EventArgs e) { await Delivery.MarkAsPickerUp(delivery, userId); }
public void Add_Delivery(Delivery delivery) { new BL_IMP().Add_Delivery(delivery); }
void DeliverMessage(Delivery delivery) { var container = ((ListenerConnection)this.Session.Connection).Listener.Container; delivery.Message = container.CreateMessage(delivery.Buffer); if (this.onMessage != null) { this.onMessage(this, delivery.Message, delivery.State, this.state); } else if (this.linkEndpoint != null) { this.linkEndpoint.OnMessage(new MessageContext(this, delivery.Message)); } }
public void UpdateHistory(HandlingActivity nextExpectedActivity, HandlingActivity lastKnownActivity, RoutingStatus routingStatus, TransportStatus transportStatus, DateTime? estimatedTimeOfArrival, bool isUnloadedAtDestination, bool isMisdirected, DateTime calculatedAt) { var delivery = new Delivery(nextExpectedActivity, lastKnownActivity, routingStatus, transportStatus, estimatedTimeOfArrival, isUnloadedAtDestination, isMisdirected, calculatedAt); History.Add(delivery); CurrentInformation = delivery; }
public ActionResult Delivery() { var model = new Delivery(base.BasketCount); return(View(model)); }
static public List<Delivery> GetAvailableDeliveryByCustPo(SqlConnection connect, Log log, ProductInfo prodInfo, int shipDateoffset) { List<Delivery> ret = new List<Delivery>(); DateTime now = DateTime.Now; DateTime shipDate = new DateTime(now.Year, now.Month, now.Day); //now.AddDays(shipDateoffset); DateTime shipDateEnd = shipDate.AddDays(shipDateoffset); SqlCommand dbCmd = connect.CreateCommand(); dbCmd.CommandType = CommandType.Text; // dbCmd.CommandText = @"select DeliveryNo, PoNo,Qty from Delivery // where Model=@model and // ShipDate between @ShipDate and @ShipDateEnd and // Qty> 0 and // Status ='00' // order by ShipDate"; dbCmd.CommandText = @"select a.DeliveryNo, b.FactoryPO, a.Qty , a.PoNo from Delivery a, DeliveryInfo c, SpecialOrder b where a.DeliveryNo =c.DeliveryNo and c.InfoType='CustPo' and c.InfoValue= b.FactoryPO and b.Status in ('Created','Active') and a.Model=@model and a.ShipDate between @ShipDate and @ShipDateEnd and a.Qty> 0 and a.Status ='00' order by ShipDate"; SQLHelper.createInputSqlParameter(dbCmd, "@model", 15, prodInfo.Model); SQLHelper.createInputSqlParameter(dbCmd, "@ShipDate", shipDate); SQLHelper.createInputSqlParameter(dbCmd, "@ShipDateEnd", shipDateEnd); log.write(LogType.Info, 0, "SQL", "GetAvailableDelivery", dbCmd.CommandText); log.write(LogType.Info, 0, "SQL", "@model", prodInfo.Model); log.write(LogType.Info, 0, "SQL", "@ShipDate", shipDate.ToString()); log.write(LogType.Info, 0, "SQL", "@ShipDateEnd", shipDateEnd.ToString()); SqlDataReader sdr = dbCmd.ExecuteReader(); while (sdr.Read()) { Delivery delivery = new Delivery(); delivery.DeliveryNo = sdr.GetString(0).Trim(); delivery.PO = sdr.GetString(1).Trim(); delivery.Qty = sdr.GetInt32(2); delivery.CustPo = delivery.PO; delivery.HpPo = sdr.GetString(3).Trim(); delivery.isCustPo = true; ret.Add(delivery); } sdr.Close(); return ret; }
public ActionResult AddBook(SellBookModel model, bool deliveryBool1, bool deliveryBool2, bool deliveryBool3, bool deliveryBool4, IEnumerable <HttpPostedFileBase> files) { List <bool> CheckList = new List <bool> { deliveryBool1, deliveryBool2, deliveryBool3, deliveryBool4 }; if (!ModelState.IsValid) { List <string> errors = new List <string>(); foreach (var modelStateVal in ViewData.ModelState.Values) { foreach (var error in modelStateVal.Errors) { var errorMessage = error.ErrorMessage; var exception = error.Exception; errors.Add(errorMessage); } } foreach (string error in errors) { ModelState.AddModelError("", error); } return(View()); } var context = new AppDbContext(); Debug.WriteLine(context.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()).BankNumber + model.Price + deliveryBool1); if (context.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()).BankNumber == "Nie podano" && model.Price != 0 && deliveryBool1 == false) { ModelState.AddModelError("", "W ustawieniach użytkownika nie podano numeru konta potrzebnego do ewentualnej finalizacji tranzakcji. Aby wystawić książkę na sprzedaż należy uzupełnić te dane."); return(View()); } { } if (model.Price == null) { model.Price = 0; } var book = new Book { Author = model.Author, Title = model.Title, Genre = model.Genre, Description = model.Description, AddDate = DateTime.Now, isChanged = false, isSold = false, Price = model.Price, Publisher = model.Publisher, Changeable = model.Changeable, PublicationDate = model.PublicationDate, SellerId = System.Web.HttpContext.Current.User.Identity.GetUserId(), Seller = context.Users.Find(System.Web.HttpContext.Current.User.Identity.GetUserId()), }; bool bookIsAdded = false; bool checkDelivery = false; if (deliveryBool1 == true) { if (!bookIsAdded) { context.Books.Add(book); context.SaveChanges(); bookIsAdded = true; } bookIsAdded = true; checkDelivery = true; var delivery = new Delivery { Name = "Odbiór osobisty", Price = model.DeliveryPrice[0], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(delivery); context.SaveChanges(); } if (deliveryBool2 == true) { if (!bookIsAdded) { context.Books.Add(book); context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = new Delivery { Name = "Przesyłka pocztowa - priorytetowa", Price = model.DeliveryPrice[1], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(delivery); context.SaveChanges(); } if (deliveryBool3 == true) { if (!bookIsAdded) { context.Books.Add(book); context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = new Delivery { Name = "Przesyłka pocztowa - ekonomiczna", Price = model.DeliveryPrice[2], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(delivery); context.SaveChanges(); } if (deliveryBool4 == true) { if (!bookIsAdded) { context.Books.Add(book); context.SaveChanges(); bookIsAdded = true; } checkDelivery = true; var delivery = new Delivery { Name = "Przesyłka kurierska", Price = model.DeliveryPrice[3], DeliveryPriceId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, DeliveryPrices = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.DeliveryOptions.Add(delivery); context.SaveChanges(); } if (!checkDelivery) { ModelState.AddModelError("", "Proszę wybrać opcję dostawy"); return(View()); } byte[] uploadedFile = null; BookImage bookImage = null; if (Request.Files != null) { int i = 0; foreach (string image in Request.Files) { HttpPostedFileBase hpf = Request.Files[image] as HttpPostedFileBase; if (image != "files") { if (hpf.InputStream.Length > 0) { uploadedFile = new byte[hpf.InputStream.Length]; Debug.WriteLine(uploadedFile.Length); hpf.InputStream.Read(uploadedFile, 0, uploadedFile.Length); bookImage = new BookImage { Image = uploadedFile, BookImgId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, BookImg = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.BookImages.Add(bookImage); context.SaveChanges(); } } else { HttpPostedFileBase hpf2 = Request.Files.Get(i); if (hpf2.InputStream.Length > 0) { uploadedFile = new byte[hpf2.InputStream.Length]; Debug.WriteLine(uploadedFile.Length); hpf2.InputStream.Read(uploadedFile, 0, uploadedFile.Length); bookImage = new BookImage { Image = uploadedFile, BookImgId = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault().BookId, BookImg = context.Books.OrderByDescending(o => o.BookId).FirstOrDefault() }; context.BookImages.Add(bookImage); context.SaveChanges(); } } i++; } //próba skalowania obrazu //Image image = Image.FromStream(new MemoryStream(uploadedFile)); //Image newImage; //newImage = ScaleImage(image, 300, 150); //var ms = new MemoryStream(); //newImage.Save(ms, ImageFormat.Gif); //ms.ToArray(); //uploadedFile = ms.ToArray(); //model.BookImage.InputStream.Read(uploadedFile, 0, uploadedFile.Length); } LuceneSearchIndexer.UpdateBooksIndex(); return(RedirectToAction("index", "home")); }
internal override void OnDeliveryStateChanged(Delivery delivery) { if (this.onDispose != null) { this.onDispose(delivery.Message, delivery.State, delivery.Settled, this.state); } else if (this.linkEndpoint != null) { this.linkEndpoint.OnDisposition(new DispositionContext(this, delivery.Message, delivery.State, delivery.Settled)); } }
protected override void OnCommit(int pass) { DeliveryHistoryEntry processedEntry = this.CurrentDelivery.History.Last(entry => entry.Operation == DeliveryOperation.Imported); if (processedEntry == null) { throw new Exception("This delivery has not been imported yet (could not find an 'Imported' history entry)."); } DeliveryHistoryEntry preparedEntry = this.CurrentDelivery.History.Last(entry => entry.Operation == DeliveryOperation.Prepared); if (preparedEntry == null) { throw new Exception("This delivery has not been prepared yet (could not find an 'Prepared' history entry)."); } // get this from last 'Processed' history entry string measuresFieldNamesSQL = processedEntry.Parameters[Consts.DeliveryHistoryParameters.MeasureOltpFieldsSql].ToString(); string measuresNamesSQL = processedEntry.Parameters[Consts.DeliveryHistoryParameters.MeasureNamesSql].ToString(); string tablePerfix = processedEntry.Parameters[Consts.DeliveryHistoryParameters.TablePerfix].ToString(); string deliveryId = this.CurrentDelivery.DeliveryID.ToString("N"); // ........................... // COMMIT data to OLTP _commitCommand = _commitCommand ?? DataManager.CreateCommand(this.Options.SqlCommitCommand, CommandType.StoredProcedure); _commitCommand.Connection = _sqlConnection; _commitCommand.Transaction = _commitTransaction; _commitCommand.Parameters["@DeliveryFileName"].Size = 4000; _commitCommand.Parameters["@DeliveryFileName"].Value = tablePerfix; _commitCommand.Parameters["@CommitTableName"].Size = 4000; _commitCommand.Parameters["@CommitTableName"].Value = preparedEntry.Parameters["CommitTableName"]; _commitCommand.Parameters["@MeasuresNamesSQL"].Size = 4000; _commitCommand.Parameters["@MeasuresNamesSQL"].Value = measuresNamesSQL; _commitCommand.Parameters["@MeasuresFieldNamesSQL"].Size = 4000; _commitCommand.Parameters["@MeasuresFieldNamesSQL"].Value = measuresFieldNamesSQL; _commitCommand.Parameters["@Signature"].Size = 4000; _commitCommand.Parameters["@Signature"].Value = this.CurrentDelivery.Signature;; _commitCommand.Parameters["@DeliveryIDsPerSignature"].Size = 4000; _commitCommand.Parameters["@DeliveryIDsPerSignature"].Direction = ParameterDirection.Output; _commitCommand.Parameters["@DeliveryID"].Size = 4000; _commitCommand.Parameters["@DeliveryID"].Value = deliveryId; try { _commitCommand.ExecuteNonQuery(); // _commitTransaction.Commit(); string deliveryIDsPerSignature = _commitCommand.Parameters["@DeliveryIDsPerSignature"].Value.ToString(); string[] existDeliveries; if ((!string.IsNullOrEmpty(deliveryIDsPerSignature) && deliveryIDsPerSignature != "0")) { _commitTransaction.Rollback(); existDeliveries = deliveryIDsPerSignature.Split(','); List <Delivery> deliveries = new List <Delivery>(); foreach (string existDelivery in existDeliveries) { deliveries.Add(Delivery.Get(Guid.Parse(existDelivery))); } throw new DeliveryConflictException(string.Format("Deliveries with the same signature are already committed in the database\n Deliveries:\n {0}:", deliveryIDsPerSignature)) { ConflictingDeliveries = deliveries.ToArray() }; } else { //already updated by sp, this is so we don't override it this.CurrentDelivery.IsCommited = true; } } finally { this.State = DeliveryImportManagerState.Idle; } }
internal uint SendMessageInternal(Message message, ByteBuffer buffer, object userToken) { if (this.role) { throw new AmqpException(ErrorCode.NotAllowed, "Cannot send a message over a receiving link."); } this.ThrowIfDetaching("Send"); uint tag; uint remainingCredit; lock (this.ThisLock) { tag = this.deliveryCount++; remainingCredit = --this.credit; } try { Delivery delivery = new Delivery() { Handle = this.Handle, Message = message, Buffer = buffer ?? message.Encode(), Link = this, Settled = this.SettleOnSend, Tag = Delivery.GetDeliveryTag(tag), UserToken = userToken }; this.Session.SendDelivery(delivery); return remainingCredit; } catch { lock (this.ThisLock) { this.credit++; this.deliveryCount--; } throw; } }
public override void RemoveDelivery(Delivery delivery) { deliveries.Remove(delivery); }
public IActionResult Post([FromForm] string senderfname, [FromForm] string sendersname, [FromForm] string senderemail, [FromForm] string senderphone, [FromForm] string senderstreet, [FromForm] string senderbuilding, [FromForm] string senderlocal, [FromForm] string sendercity, [FromForm] string senderzip, [FromForm] string senderstate, [FromForm] string sendercountry, [FromForm] string receiverfname, [FromForm] string receiversname, [FromForm] string receiveremail, [FromForm] string receiverphone, [FromForm] string receiverstreet, [FromForm] string receiverbuilding, [FromForm] string receiverlocal, [FromForm] string receivercity, [FromForm] string receiverzip, [FromForm] string receiverstate, [FromForm] string receivercountry, [FromForm] string parceltype, [FromForm] int width, [FromForm] int height, [FromForm] int length, [FromForm] int weight, [FromForm] string comments, [FromForm] DateTime pickupdate, [FromForm] DateTime pickuptime, [FromForm] string sendercoordinate, [FromForm] string receivercoordinate) { System.Console.WriteLine(parceltype); Delivery d = new Delivery { ID = GeneratedID++, sender = new Person { name = senderfname, surname = sendersname, email = senderemail, phonenumber = senderphone, address = new Address { Street = senderstreet, Building = senderbuilding, Local = senderlocal, City = sendercity, State = senderstate, Country = sendercountry, ZipCode = senderzip, Coordinate = sendercoordinate } }, receiver = new Person { name = receiverfname, surname = receiversname, email = receiveremail, phonenumber = receiverphone, address = new Address { Street = receiverstreet, Building = receiverbuilding, Local = receiverlocal, City = receivercity, State = receiverstate, Country = receivercountry, ZipCode = receiverzip, Coordinate = receivercoordinate } }, package = new Package { parceltype = parceltype, width = width, height = height, length = length, weight = weight, Date = pickupdate, Time = pickuptime, comments = comments } }; lock (locker) { DeliveryData.deliveries.Add(d); } return(NoContent()); }
public void AddShip(Delivery delivery) { }