Example #1
0
        public override IResult Calculate(Request request)
        {
            IResult result = null;

            if (request.ResultLeft == false && request.ResultRight == true && request.Type != OperationTypes.Undo)
            {
                var operation = Calculator.OperationsCollection.GetOperation(request.Type);

                Calculator.ResultsCaretaker.ResultMemento = Calculator.Result.SaveResult();

                var res = operation.Calculate(request.X, Calculator.Result.Value);

                Calculator.Result.Value = res.Value;

                result = res;
            }
            else
            {
                result = Successor.Calculate(request);
            }

            return(result);
        }
Example #2
0
        public override List <RedirectItemValidationResult> HandleValidation(RedirectItem redirectItem, IEnumerable <RedirectItem> otherRedirectItems)
        {
            var response = new RedirectItemValidationResult();

            if (string.IsNullOrEmpty(redirectItem.LinkUrl))
            {
                response.Status       = ImportErrorLevel.Error;
                response.ErrorMessage = "No destination URL was provided or is in the wrong format";

                ErrorsResult.Add(response);

                return(ErrorsResult);
            }

            if (Successor != null)
            {
                return(Successor.HandleValidation(redirectItem, otherRedirectItems));
            }

            ErrorsResult.Add(response);

            return(ErrorsResult);
        }
Example #3
0
        /// <summary>
        /// Process register payment step
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="orderForm"></param>
        /// <param name="orderGroup"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup)
        {
            var paymentMethodDto = PaymentManager.GetPaymentMethod(payment.PaymentMethodId);

            if (payment.TransactionType == "Authorization")
            {
                var transactionId = "";
                try
                {
                    transactionId = this.Client.Register(CreatePaymentRequest(paymentMethodDto, payment, orderForm, orderGroup));
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.Message);
                    AddNoteAndSaveChanges(orderGroup, "Payment Registered - Error", "Payment Registered - Error: " + ex.Message);
                    return(Fail(ex.Message));
                }

                AddNoteAndSaveChanges(orderGroup, "Payment - Registered", $"Payment - Registered with transactionId {transactionId}");

                var url = new UriBuilder(GetTerminalUrl(paymentMethodDto));
                var nvc = new NameValueCollection
                {
                    { "merchantId", paymentMethodDto.GetParameter(NetaxeptConstants.MerchantIdField) },
                    { "transactionId", transactionId }
                };

                url.Query = string.Join("&", nvc.AllKeys.Select(key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
                return(Success(url.ToString()));
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup));
            }

            return(Fail(null));
        }
Example #4
0
        /// <summary>
        /// When an order needs to be captured the cartridge needs to make an API Call
        /// POST /ordermanagement/v1/orders/{order_id}/captures for the amount which needs to be captured.
        ///     If it's a partial capture the API call will be the same just for the
        /// amount that should be captured. Many captures can be made up to the whole amount authorized.
        /// The shipment information can be added in this call or amended afterwards using the method
        /// "Add shipping info to a capture".
        ///     The amount captured never can be greater than the authorized.
        /// When an order is Partially Captured the status of the order in Klarna is PART_CAPTURED
        /// </summary>
        public override async Task <PaymentStepResult> Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment)
        {
            var paymentStepResult = new PaymentStepResult();

            if (payment.TransactionType == TransactionType.Capture.ToString())
            {
                var amount  = AmountHelper.GetAmount(payment.Amount);
                var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString();
                if (!string.IsNullOrEmpty(orderId))
                {
                    try
                    {
                        var captureData = await KlarnaOrderService.CaptureOrder(orderId, amount, "Capture the payment", orderGroup, orderForm, payment, shipment).ConfigureAwait(false);

                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Captured {payment.Amount}, id {captureData.CaptureId}");
                        paymentStepResult.Status = true;
                    }
                    catch (Exception ex) when(ex is ApiException || ex is WebException || ex is AggregateException)
                    {
                        var exceptionMessage = GetExceptionMessage(ex);

                        payment.Status = PaymentStatus.Failed.ToString();

                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
                        Logger.Error(exceptionMessage, ex);

                        paymentStepResult.Message = exceptionMessage;
                    }
                }
            }
            else if (Successor != null)
            {
                return(await Successor.Process(payment, orderForm, orderGroup, shipment).ConfigureAwait(false));
            }

            return(paymentStepResult);
        }
        public override void HandleRequest(HttpContextBase context)
        {
            if (CanHandle(context))
            {
                var packageName = context.Request["name"];
                if (!string.IsNullOrWhiteSpace(packageName))
                {
                    var versionText = UpdatePackageVersionRetriver.GetUpdatePackageVersion(packageName);
                    TextResponse(versionText, HttpStatusCode.OK, context);
                    return;
                }

                try
                {
                    var installedPackage = _installationRecorder.GetLatestPackage();

                    if (installedPackage is InstalledPackageNotFound)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                    }
                    else
                    {
                        var json = Json.Encode(new { installedPackage });

                        JsonResponse(json, HttpStatusCode.OK, context);
                    }
                }
                catch (NotFoundException)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                }
            }
            else if (Successor != null)
            {
                Successor.HandleRequest(context);
            }
        }
Example #6
0
        public override ShapeEx Create(OpenXmlElement openXmlElement)
        {
            Check.NotNull(openXmlElement, nameof(openXmlElement));

            P.Picture sdkPicture;
            if (openXmlElement is P.Picture treePic)
            {
                sdkPicture = treePic;
            }
            else
            {
                var framePic = openXmlElement.Descendants <P.Picture>().FirstOrDefault();
                sdkPicture = framePic;
            }
            if (sdkPicture != null)
            {
                var pBlipFill    = sdkPicture.GetFirstChild <P.BlipFill>();
                var blipRelateId = pBlipFill?.Blip?.Embed?.Value;
                if (blipRelateId == null)
                {
                    return(null);
                }
                var pictureEx      = new PictureEx(_sdkSldPart, blipRelateId);
                var spContext      = new ShapeContext(_preSettings, _sldFontService, openXmlElement, _sdkSldPart);
                var innerTransform = _transformFactory.FromComposite(sdkPicture);
                var shape          = _shapeBuilder.WithPicture(innerTransform, spContext, pictureEx);

                return(shape);
            }

            if (Successor != null)
            {
                return(Successor.Create(openXmlElement));
            }

            return(null);
        }
        public override async Task <PaymentStepResult> Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment)
        {
            var paymentStepResult = new PaymentStepResult();

            if (payment.TransactionType == KlarnaAdditionalTransactionType.ReleaseRemainingAuthorization.ToString())
            {
                try
                {
                    var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString();
                    if (!string.IsNullOrEmpty(orderId))
                    {
                        await KlarnaOrderService.ReleaseRemainingAuthorization(orderId).ConfigureAwait(false);

                        payment.Status = PaymentStatus.Processed.ToString();

                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Released remaining authorization at Klarna");

                        paymentStepResult.Status = true;
                    }
                }
                catch (Exception ex) when(ex is ApiException || ex is WebException || ex is AggregateException)
                {
                    var exceptionMessage = GetExceptionMessage(ex);

                    payment.Status            = PaymentStatus.Failed.ToString();
                    paymentStepResult.Message = exceptionMessage;
                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
                    Logger.Error(exceptionMessage, ex);
                }
            }
            else if (Successor != null)
            {
                return(await Successor.Process(payment, orderForm, orderGroup, shipment).ConfigureAwait(false));
            }
            return(paymentStepResult);
        }
        public override IResult Calculate(Request request)
        {
            IResult result = null;

            if (request.Type == OperationTypes.Undo)
            {
                var memento = Calculator.ResultsCaretaker.ResultMemento;

                if (memento == null)
                {
                    throw new ArgumentException("No previous value available");
                }

                Calculator.Result.Value = memento.Value;

                result = Calculator.Result;
            }
            else
            {
                result = Successor.Calculate(request);
            }

            return(result);
        }
Example #9
0
        public override async Task Process(ResultSummary testResult)
        {
            if (!string.IsNullOrEmpty(Options.XmlTransformFile))
            {
                try
                {
                    var xpathDocument = new XPathDocument(Options.ResultFilePath);
                    var transform     = new XslCompiledTransform();
                    transform.Load(Options.XmlTransformFile);
                    var writer = new XmlTextWriter(Options.ResultFilePath, null);
                    transform.Transform(xpathDocument, null, writer);
                }
                catch (Exception ex)
                {
                    var message = $"Fatal error while trying to transform xml result: {ex.Message}";
                    MessagingCenter.Send(new ErrorMessage(message), ErrorMessage.Name);
                }
            }

            if (Successor != null)
            {
                await Successor.Process(testResult);
            }
        }
Example #10
0
 public override async Task HandlerRequest(Command command, Client client)
 {
     if (command.UserCommand == UserCommandServer.SignIn && command.AdminCommand == AdminCommandServer.NoCommand)
     {
         Command sendCommand = new Command();
         if (await LoginStudentService.AuthorizationAsync(new AuthorizationViewModel()
         {
             Login = command.Student.Login, Password = command.Student.Password
         }))
         {
             sendCommand.IsSignIn = true;
             sendCommand.Id       = LoginStudentService.CurrentUser.Id;
         }
         else
         {
             sendCommand.IsSignIn = false;
         }
         client.SendCommand(sendCommand);
     }
     else if (Successor != null)
     {
         await Successor.HandlerRequest(command, client);
     }
 }
Example #11
0
 public override IList <(CertificateValidationRules CertificateValidationRule, string Description)> HandleValidation(X509Certificate certificate, X509Certificate issuer, BasicOcspResp response)
 {
     if (!response.Verify(issuer.GetPublicKey()))
     {
         //Check to see if a certificate was sent back by the response
         var recievedCertificate = response.GetCerts()[0];
         if (recievedCertificate != null && response.Verify(recievedCertificate.GetPublicKey()))
         {
             if (!ValidateAlternateSigner(recievedCertificate, issuer))
             {
                 RecordError("The desginated OCSP signer did not sign the repsonse!");
             }
         }
     }
     else
     {
         RecordError("The issuer signature does not match the responder signature!");
     }
     if (Successor != null)
     {
         return(Successor.HandleValidation(certificate, issuer, response));
     }
     return(Errors);
 }
 public override async Task HandlerRequest(Command command, Client client)
 {
     if (command.UserCommand == UserCommandServer.NoCommand && command.AdminCommand == AdminCommandServer.SignUp)
     {
         Command sendCommand = new Command();
         if (await LoginTeacherService.AddNewUserAsync(new RegistrationViewModel()
         {
             FullName = command.Teacher.FullName, Login = command.Teacher.Login, Password = command.Teacher.Password, Subject = command.Teacher.Subject
         }))
         {
             sendCommand.IsSignIn = true;
             sendCommand.Id       = LoginTeacherService.CurrentUser.Id;
         }
         else
         {
             sendCommand.IsSignIn = false;
         }
         client.SendCommand(sendCommand);
     }
     else if (Successor != null)
     {
         await Successor.HandlerRequest(command, client);
     }
 }
Example #13
0
        public override List <RedirectItemValidationResult> HandleValidation(RedirectItem redirectItem, IEnumerable <RedirectItem> otherRedirectItems)
        {
            var response          = new RedirectItemValidationResult();
            var duplicateRedirect = otherRedirectItems.FirstOrDefault(item => item.Url == redirectItem.Url && item.QueryString == redirectItem.QueryString && item.UniqueId != redirectItem.UniqueId);

            if (duplicateRedirect != null)
            {
                response.Status       = ImportErrorLevel.Error;
                response.ErrorMessage = "This redirect has a duplicate row in the file with the same source URL. It has not been imported.";

                ErrorsResult.Add(response);

                return(ErrorsResult);
            }

            if (Successor != null)
            {
                return(Successor.HandleValidation(redirectItem, otherRedirectItems));
            }

            ErrorsResult.Add(response);

            return(ErrorsResult);
        }
        public override void ProcessRequest <TFilterModel>(IList <KeyValuePair <string, string> > queryStringParams,
                                                           TFilterModel filter)
        {
            Ensure.ArgumentNotNull(filter, nameof(filter));

            List <PropertyInfo> propertyInfos = filter.GetType()
                                                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                                .Where(info => Attribute.IsDefined(info, typeof(QueryAttribute)))
                                                .ToList();

            if (!propertyInfos.Any())
            {
                Successor?.ProcessRequest(queryStringParams, filter);

                return;
            }

            queryStringParams = queryStringParams ?? new List <KeyValuePair <string, string> >();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                object value = propertyInfo.GetValue(filter);

                if (value == null)
                {
                    continue;
                }

                var    customAttribute = propertyInfo.GetCustomAttribute <QueryAttribute>();
                string queryStringKey  = customAttribute.QueryStringKey;

                queryStringParams.Add(new KeyValuePair <string, string>(queryStringKey, value.ToString()));
            }

            Successor?.ProcessRequest(queryStringParams, filter);
        }
Example #15
0
        public override void HandleMessage(Message message, TelegramSession session, TelegramBotClient bot)
        {
            string text = message?.Text?.Trim();

            switch (text)
            {
            case BotCommands.StartInteractingWithBotCommand:
                bot.SendTextMessageAsync(message.From.Id,
                                         $"Привет! Давай сыграем в \"Морской Бой\". Для старта игры отправь мне команду  {BotCommands.StartNewGameCommand}");
                return;

            case BotCommands.StartNewGameCommand:
                //TODO снять ограничение на размер карты
                int width  = 10;
                int height = 10;
                session.RecreateGame(width, height);
                bot.SendTextMessageAsync(message.From.Id, "Игра началась! Для выстрела просто отправьте два числа (координаты поля противника)");
                session.SendPlayground(message, bot);
                return;

            case BotCommands.EndGameCommand:
                if (session.TryEndGame())
                {
                    bot.SendTextMessageAsync(message.From.Id, "Игра закончена");
                }
                else
                {
                    bot.SendTextMessageAsync(message.From.Id, "Игра не начиналась.");
                }
                return;

            case BotCommands.GetGameStatusCommand:
                if (session.Game.GameIsOn)
                {
                    bot.SendTextMessageAsync(message.From.Id, "Игра идёт");
                }
                else
                {
                    bot.SendTextMessageAsync(message.From.Id, "Игра не идёт");
                }
                return;

            case BotCommands.AutoShotCommand:
                //TODO убрать реализацию отсюда
                //TODO нужно вынести её в отдельный класс
                if (!session.Game.GameIsOn)
                {
                    bot.SendTextMessageAsync(message.From.Id, $"Игра ещё не началась. ");
                    return;
                }
                var coordinates = session.PlayerAutoShot().Coordinates;
                session.ComputerShot();
                bot.SendTextMessageAsync(message.From.Id, $"Автоматический выстрел за игрока по координатам x:{coordinates.X}, y:{coordinates.Y}.");
                session.SendPlayground(message, bot);
                return;

            case BotCommands.ShowPlaygroundCommand:
                session.SendPlayground(message, bot);
                return;
            }
            Successor?.HandleMessage(message, session, bot);
        }
 public override void HandleRequest(object obj)
 {
     Console.WriteLine($"ConcreteHandlerC.HandleRequest(): {obj}");
     Successor?.HandleRequest(obj);
 }
        public ArrayList getSuccessors(Object state)
        {
            ArrayList       list            = new ArrayList(20);
            JocksNerdsState jocksNerdsState = (JocksNerdsState)state;

            int numberNerdsLeft  = jocksNerdsState.locationArray[0];
            int numberJocksLeft  = jocksNerdsState.locationArray[1];
            int numberNerdsRight = 3 - jocksNerdsState.locationArray[0];
            int numberJocksRight = 3 - jocksNerdsState.locationArray[1];
            int turnCount        = jocksNerdsState.locationArray[2];

            /*
             *
             * if the turn count for the current state is even the boat is on on the left bank,
             * otherwise it's on the right side
             * try moving every combination of nerds and jocks to the opposite bank.
             * Also need to make sure that the # of jocks on one side never outnumbers the
             * number of nerds on that side.
             *
             */

            if (jocksNerdsState.locationArray[2] % 2 == 0)
            {
                //the boat's on the left so move people to the right
                JocksNerdsState successor_state;



                //move 1 nerd to the right if the Nerds won't be eaten as a result
                if (numberNerdsLeft > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] -= 1;
                    successor_state.locationArray[1]  = numberJocksLeft;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 1 nerd right (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }


                //move 2 Nerds right if the Nerds won't be eaten as a result
                if (numberNerdsLeft > 1)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] -= 2;
                    successor_state.locationArray[1]  = numberJocksLeft;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 2 Nerds right (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }


                //move 1 Jock right if the Nerds won't be eaten as a result
                if (numberJocksLeft > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0]  = numberNerdsLeft;
                    successor_state.locationArray[1] -= 1;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 1 Jock right (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }

                //move 2 Jocks right if the Nerds won't be eaten as a result
                if (numberJocksLeft > 1)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0]  = numberNerdsLeft;
                    successor_state.locationArray[1] -= 2;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 2 Jocks right (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }

                //move a Jock and a nerd right
                if (numberJocksLeft > 0 && numberNerdsLeft > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] -= 1;
                    successor_state.locationArray[1] -= 1;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move a nerd and Jock right (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }
            }
            else
            {
                //the boat is on the right so try moving people to the left

                //the boat is on the left so move people to the right
                JocksNerdsState successor_state;



                //move 1 nerd to the left if the Nerds won't be eaten as a result
                if (numberNerdsRight > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] += 1;
                    successor_state.locationArray[1]  = numberJocksLeft;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 1 nerd left (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }


                //move 2 Nerds left if the Nerds won't be eaten as a result
                if (numberNerdsRight > 1)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] += 2;
                    successor_state.locationArray[1]  = numberJocksLeft;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 2 Nerds left (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }


                //move 1 Jock left if the Nerds won't be eaten as a result
                if (numberJocksRight > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0]  = numberNerdsLeft;
                    successor_state.locationArray[1] += 1;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 1 Jock left (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }

                //move 2 Jocks left if the Nerds won't be eaten as a result
                if (numberJocksRight > 1)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0]  = numberNerdsLeft;
                    successor_state.locationArray[1] += 2;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move 2 Jocks left (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }

                //move a Jock and a nerd left
                if (numberJocksRight > 0 && numberNerdsRight > 0)
                {
                    successor_state = new JocksNerdsState(jocksNerdsState);
                    successor_state.locationArray[0] += 1;
                    successor_state.locationArray[1] += 1;
                    successor_state.locationArray[2]  = turnCount + 1;
                    if (isValidState(successor_state))
                    {
                        Successor s = new Successor("move a nerd and Jock left (array = " + successor_state.locationArray[0] + ", " + successor_state.locationArray[1] + ", " + successor_state.locationArray[2] + ")\n", successor_state);
                        list.Add(s);
                    }
                }
            }



            return(list);
        }
Example #18
0
        // What are the left and right widths and height of the object
        // (including its children and successors)?
        public override void footprint(System.Drawing.Graphics gr)
        {
            this.init();
            this.Diamond_Footprint(gr, this.scale > 0.4, W / 2 + W / 4);
            int leftbefore, leftafter, rightbefore, rightafter;
            int temp_FP_left = 0, temp_FP_right = 0;

            if (!Component.USMA_mode)
            {
                FP.height = H + H / 2 + H + H / 2 + H / 2;
            }
            else
            {
                FP.height = W / 4 + H / 2 + H + H / 2 + H / 2;
            }

            if ((after_Child != null) && (before_Child != null) && !this.is_compressed)
            {
                this.before_Child.footprint(gr);
                this.after_Child.footprint(gr);
                leftbefore    = before_Child.FP.left;
                leftafter     = after_Child.FP.left;
                temp_FP_left  = ((leftbefore > leftafter)?leftbefore:leftafter) + W / 2;
                rightbefore   = before_Child.FP.right;
                rightafter    = after_Child.FP.right;
                temp_FP_right = ((rightbefore > rightafter)?rightbefore:rightafter) + W / 2;
                FP.height    += before_Child.FP.height + after_Child.FP.height + CL + CL;
            }
            else if (before_Child != null && !this.is_compressed)
            {
                this.before_Child.footprint(gr);
                temp_FP_left  = before_Child.FP.left + W / 2;
                temp_FP_right = before_Child.FP.right + W / 2;
                FP.height    += before_Child.FP.height + CL;
            }
            else if (after_Child != null && !this.is_compressed)
            {
                this.after_Child.footprint(gr);
                temp_FP_left  = after_Child.FP.left + W / 2;
                temp_FP_right = after_Child.FP.right + W / 2;
                FP.height    += after_Child.FP.height + CL;
            }

            if (temp_FP_left > FP.left)
            {
                FP.left = temp_FP_left;
            }
            if (temp_FP_right > FP.right)
            {
                FP.right = temp_FP_right;
            }

            if (Successor != null)
            {
                Successor.footprint(gr);

                if (FP.left < Successor.FP.left)                 // successor has larger left footprint
                {
                    FP.left = Successor.FP.left;
                }
                if (FP.right < Successor.FP.right)                 // successor has larger right footprint
                {
                    FP.right = Successor.FP.right;
                }
                FP.height = FP.height + CL + Successor.FP.height;
            }
        }
Example #19
0
        public override void draw(System.Drawing.Graphics gr, int x, int y)
        {
            int  right, after_left, before_right, after_right;
            bool draw_text;

            X = x;
            Y = y;

            height_of_text = Convert.ToInt32((gr.MeasureString(
                                                  "Yes", PensBrushes.default_times)).Height);

            width_of_text = Convert.ToInt32((gr.MeasureString(
                                                 this.Text + "XX", PensBrushes.default_times)).Width);

            int length_of_yesStr = Convert.ToInt32((gr.MeasureString(
                                                        "Yes", PensBrushes.default_arial)).Width);
            int length_of_noStr = Convert.ToInt32((gr.MeasureString(
                                                       "No", PensBrushes.default_arial)).Width);

            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            if ((this.scale <= .4) || (this.head_heightOrig < 10))
            {
                draw_text = false;
            }
            else
            {
                draw_text = Component.text_visible;
            }

            System.Drawing.Pen head_pen    = PensBrushes.blue_pen;
            System.Drawing.Pen diamond_pen = PensBrushes.blue_pen;
            System.Drawing.Pen line_pen    = PensBrushes.blue_pen;

            // if the loop is selected make it red and select its children
            if (this.selected)
            {
                head_pen    = PensBrushes.red_pen;
                diamond_pen = PensBrushes.red_pen;
                line_pen    = PensBrushes.red_pen;
            }

            //Make diamond green for running
            else if (this.running && this.light_head == false)
            {
                head_pen    = PensBrushes.blue_pen;
                diamond_pen = PensBrushes.chartreuse_pen;
                line_pen    = PensBrushes.blue_pen;
            }

            //Make head green for running
            else if (this.running && this.light_head)
            {
                head_pen    = PensBrushes.chartreuse_pen;
                diamond_pen = PensBrushes.blue_pen;
                line_pen    = PensBrushes.blue_pen;
            }
            else if (this.is_compressed && this.have_child_running())
            {
                head_pen    = PensBrushes.chartreuse_pen;
                diamond_pen = PensBrushes.chartreuse_pen;
                line_pen    = PensBrushes.blue_pen;
            }

            if (!Component.USMA_mode)
            {
                // Draw the head
                gr.DrawEllipse(head_pen, x - W / 2, y, W, H);
                end_first_connector = Y + H + H / 2;
            }
            else
            {
                gr.DrawEllipse(head_pen, x - W / 8, y, W / 4, W / 4);
                end_first_connector = Y + W / 4 + H / 2;
            }


            if (this.has_breakpoint)
            {
                StopSign.Draw(gr, x - W / 2 - W / 6 - 2, y, W / 6);
            }

            // Draw arrow at top of the head oval
            if (!Component.USMA_mode)
            {
                gr.DrawLine(head_pen, x, y, x + CL / 4, y + CL / 4);     // draw down arrow
                gr.DrawLine(head_pen, x, y, x + CL / 4, y - CL / 4);     // draw up arrow
            }

            //Get the proper width based on the children's width
            // x_left is the location of the vertical connector leaving the loop
            // x_right is the location of the vertical connector going back to the top

            if ((before_Child != null) && (after_Child != null) && !this.is_compressed)
            {
                before_right = before_Child.FP.right;
                after_right  = after_Child.FP.right;
                right        = (before_right > after_right) ? before_right:after_right;
                x_right      = x + W / 2 + right;

                after_left = after_Child.FP.left;
                x_left     = x - W / 2 - after_left;
            }
            else if (before_Child != null && !this.is_compressed)
            {
                before_right = before_Child.FP.right;
                x_right      = x + W / 2 + before_right;

                x_left = x - W / 2 - W / 2;
            }
            else if (after_Child != null && !this.is_compressed)
            {
                after_right = after_Child.FP.right;
                x_right     = x + W / 2 + after_right;

                after_left = after_Child.FP.left;
                x_left     = x - W / 2 - after_left;
            }
            else
            {
                x_right = x + W / 2 + W / 2;
                x_left  = x - W / 2 - W / 2;
            }

            if (draw_text && this.Is_Wide_Diamond())
            {
                int temp_right = x + this.drawing_text_width / 2 + W / 2 + W / 4;
                int temp_left  = x - this.drawing_text_width / 2 - W / 2 - W / 4;

                if (temp_right > x_right)
                {
                    x_right = temp_right;
                }
                if (temp_left < x_left)
                {
                    x_left = temp_left;
                }
            }

            //Because there is a before child, draw a connector from the head to the
            //before child and then from the before child to the diamond.
            int start_first_connector;              // top y coordinate of first connector

            if (!Component.USMA_mode)
            {
                start_first_connector = y + H;
            }
            else
            {
                start_first_connector = y + W / 4;
            }

            // draw connector line
            gr.DrawLine(line_pen, x, start_first_connector, x, end_first_connector);
            // draw left side of arrow
            gr.DrawLine(line_pen, x, end_first_connector, x - CL / 4, end_first_connector - CL / 4);
            // draw right side of arrow
            gr.DrawLine(line_pen, x, end_first_connector, x + CL / 4, end_first_connector - CL / 4);


            if (before_Child != null && !this.is_compressed)
            {
                diamond_top = end_first_connector + before_Child.FP.height + CL;

                //Draw connector from head to before_child

                // Draw the before_Child graphic
                before_Child.draw(gr, x, end_first_connector);
                gr.DrawLine(line_pen, x, end_first_connector + before_Child.FP.height, x, diamond_top); // draw connector line to diamond
                gr.DrawLine(line_pen, x, diamond_top, x - CL / 4, diamond_top - CL / 4);                // draw left side of arrow
                gr.DrawLine(line_pen, x, diamond_top, x + CL / 4, diamond_top - CL / 4);                // draw right side of arrow
            }
            //Because there is not a before child, draw a connector from the head
            //to the diamond.
            else
            {
                diamond_top = end_first_connector;
            }

            // Draw the diamond shape
            this.Draw_Diamond_and_Text(gr, x, diamond_top,
                                       this.Text, diamond_pen,
                                       draw_text);

            if (this.has_diamond_breakpoint)
            {
                StopSign.Draw(gr, x - W / 2 - W / 6 - 2, diamond_top, W / 6);
            }

            // Draw connector from diamond
            gr.DrawLine(line_pen, x, diamond_top + H, x, diamond_top + H + H / 2);                           // draw connector line to top of before child
            gr.DrawLine(line_pen, x, diamond_top + H + H / 2, x - CL / 4, diamond_top + H + H / 2 - CL / 4); // draw left side of arrow
            gr.DrawLine(line_pen, x, diamond_top + H + H / 2, x + CL / 4, diamond_top + H + H / 2 - CL / 4); // draw right side of arrow

            //Because there is an after child, draw the after child and then a connector from the
            //after child to the bottom.
            if (after_Child != null && !this.is_compressed)
            {
                after_bottom = diamond_top + H + H / 2 + after_Child.FP.height + CL;

                // Draw the after_Child graphic
                after_Child.draw(gr, x, diamond_top + H + H / 2);

                //Draw connector from after_child to the bottom
                gr.DrawLine(line_pen, x, diamond_top + H + H / 2 + after_Child.FP.height, x, after_bottom); // draw connector line
                gr.DrawLine(line_pen, x, after_bottom, x - CL / 4, after_bottom - CL / 4);                  // draw left side of arrow
                gr.DrawLine(line_pen, x, after_bottom, x + CL / 4, after_bottom - CL / 4);                  // draw right side of arrow
            }
            //Because there is not an after child, draw the connector from the diamond
            //to the bottom.
            else
            {
                after_bottom = diamond_top + H + H / 2;
            }

            //draw line from bottom center to right, then up, then left to head
            gr.DrawLine(line_pen, x, after_bottom, x_right, after_bottom);         // draw connector line to right
            if (!Component.USMA_mode)
            {
                gr.DrawLine(line_pen, x_right, after_bottom, x_right, y + H / 2);                    // draw connector line up
                gr.DrawLine(line_pen, x_right, y + H / 2, x + W / 2, y + H / 2);                     // draw connector line to head
                gr.DrawLine(line_pen, x + W / 2, y + H / 2, x + W / 2 + CL / 4, y + H / 2 - CL / 4); // draw top side of arrow
                gr.DrawLine(line_pen, x + W / 2, y + H / 2, x + W / 2 + CL / 4, y + H / 2 + CL / 4); // draw bottom side of arrow
            }
            else
            {
                gr.DrawLine(line_pen, x_right, after_bottom, x_right, y + W / 8);                    // draw connector line up
                gr.DrawLine(line_pen, x_right, y + W / 8, x + W / 8, y + W / 8);                     // draw connector line to head
                gr.DrawLine(line_pen, x + W / 8, y + W / 8, x + W / 8 + CL / 4, y + W / 8 - CL / 4); // draw top side of arrow
                gr.DrawLine(line_pen, x + W / 8, y + W / 8, x + W / 8 + CL / 4, y + W / 8 + CL / 4); // draw bottom side of arrow
            }

            // Draw left line from the diamond
            if (draw_text && this.Is_Wide_Diamond())
            {
                gr.DrawLine(line_pen,
                            x_left, diamond_top + H / 2,
                            x - this.drawing_text_width / 2 - W / 4, diamond_top + H / 2); // draw left line
            }
            else
            {
                gr.DrawLine(line_pen,
                            x_left, diamond_top + H / 2,
                            x - W / 2, diamond_top + H / 2);                                  // draw left line
            }
            gr.DrawLine(line_pen, x_left, diamond_top + H / 2, x_left, after_bottom + H / 2); // draw down line
            gr.DrawLine(line_pen, x_left, after_bottom + H / 2, x, after_bottom + H / 2);     // draw line back to right


            if (this.Successor != null)
            {
                // draw connector line to successor
                gr.DrawLine(line_pen, x, after_bottom + H / 2, x, after_bottom + H / 2 + CL);
                // draw left side of arrow
                gr.DrawLine(line_pen, x, after_bottom + H / 2 + CL, x - CL / 4, after_bottom + H / 2 + CL - CL / 4);
                // draw right side of arrow
                gr.DrawLine(line_pen, x, after_bottom + H / 2 + CL, x + CL / 4, after_bottom + H / 2 + CL - CL / 4);
                Successor.draw(gr, x, after_bottom + H / 2 + CL);
            }

            if (this.W > 30)
            {
                LP = "Loop";
            }
            else
            {
                LP = "";
            }
            if (draw_text)
            {
                // swap Yes and No for reversed loop logic
                if (!Component.reverse_loop_logic)
                {
                    if (this.Is_Wide_Diamond())
                    {
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - this.drawing_text_width / 2 - W / 4 - length_of_yesStr / 2,
                                      diamond_top + H / 2 - 4,
                                      PensBrushes.centered_stringFormat);
                    }
                    else
                    {
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush, x - W / 2 - length_of_yesStr,
                                      diamond_top + H / 2 - 4,
                                      PensBrushes.centered_stringFormat);
                    }
                    gr.DrawString("No", PensBrushes.default_arial,
                                  PensBrushes.blackbrush, x + length_of_noStr,
                                  diamond_top + H + 5,
                                  PensBrushes.centered_stringFormat);
                }
                else
                {
                    if (this.Is_Wide_Diamond())
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - this.drawing_text_width / 2 - W / 4 - length_of_noStr / 2,
                                      diamond_top + H / 2 - 4,
                                      PensBrushes.centered_stringFormat);
                    }
                    else
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush, x - W / 2 - length_of_noStr,
                                      diamond_top + H / 2 - 4,
                                      PensBrushes.centered_stringFormat);
                    }
                    gr.DrawString("Yes", PensBrushes.default_arial,
                                  PensBrushes.blackbrush, x + length_of_yesStr,
                                  diamond_top + H + 5,
                                  PensBrushes.centered_stringFormat);
                }
                rect = new System.Drawing.Rectangle(x - W / 2, Y + (H * 6) / 16, W, this.height_of_text);

                // draw "Loop" inside oval if not USMA mode
                if (!Component.USMA_mode)
                {
                    gr.DrawString(LP, PensBrushes.default_times, PensBrushes.blackbrush,
                                  rect, PensBrushes.centered_stringFormat);
                }
            }
            if (draw_text)
            {
                base.draw(gr, x, y);
            }
        }
Example #20
0
        public void ProcessRequest(BankAccountBenefits accountBenefits)
        {
            if (accountBenefits.Status == BankAccountStatus.Silver)
            {
                accountBenefits.SilverAccountBenefits.IncludesCheckBook       = true;
                accountBenefits.SilverAccountBenefits.IncludesInternetBanking = true;
                accountBenefits.SilverAccountBenefits.Overdraft = new Overdraft()
                {
                    IncludesGracePeriod     = true,
                    IncludesOverdraftBuffer = true,
                    OverDraftBalance        = 100,
                    PerdayCharges           = 1.5m
                };
                accountBenefits.SilverAccountBenefits.AABreakdownCover = new AABreakdownCover()
                {
                    IncludesAccidentalManagement = true,
                    IncludesRoadSideAssistance   = true,
                    UpgradeOptions = new UpgradeOptions()
                    {
                        HomeStart          = true,
                        IncludesRelay      = true,
                        IncludesStayMobile = true
                    }
                };

                accountBenefits.SilverAccountBenefits.EuropeanTravelInsurance = new EuropeanTravelInsurance()
                {
                    BuggageCover            = 100,
                    CancellationTravel      = 200,
                    EmergencyMedicalTravel  = 50000,
                    PersonalAccidentalCover = 50000,
                    TravelDays = 30
                };

                accountBenefits.SilverAccountBenefits.IncludesCheckBook       = true;
                accountBenefits.SilverAccountBenefits.IncludesInternetBanking = true;
                accountBenefits.SilverAccountBenefits.MobilePhoneInsurance    = new MobilePhoneInsurance()
                {
                    MaximumRetailCostCover              = 500,
                    UnauthorisedCallsForContractsCover  = 1000,
                    UnauthorisedCallsForPayAsYouGoCover = 300
                };
                accountBenefits.SilverAccountBenefits.Overdraft = new Overdraft()
                {
                    IncludesGracePeriod     = true,
                    IncludesOverdraftBuffer = true,
                    PerdayCharges           = 2.5M
                };

                accountBenefits.SilverAccountBenefits.SentinelCardProtection = new SentinelCardProtection()
                {
                    Claims                    = 2500,
                    EmergencyCash             = 3000,
                    HotelBillsOverseas        = 1500,
                    HouseholdCover            = true,
                    IncludesReplacements      = true,
                    MedicalAssistanceInAbroad = 300000
                };
                _repository.Add(accountBenefits.SilverAccountBenefits);
            }
            else
            {
                Successor.ProcessRequest(accountBenefits);
            }
        }
        public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment)
        {
            var paymentStepResult = new PaymentStepResult();

            if (payment.TransactionType == TransactionType.Void.ToString())
            {
                try
                {
                    var orderId         = orderGroup.Properties[Constants.SwedbankPayOrderIdField]?.ToString();
                    var previousPayment = orderForm.Payments.FirstOrDefault(x => x.IsSwedbankPayPayment());

                    //If payed by swish, do a reversal
                    if (previousPayment != null && previousPayment.TransactionType == TransactionType.Sale.ToString() && !string.IsNullOrWhiteSpace(orderId))
                    {
                        var paymentOrder = AsyncHelper.RunSync(() => SwedbankPayClient.PaymentOrders.Get(new Uri(orderId, UriKind.Relative)));
                        if (paymentOrder.Operations.Reverse == null)
                        {
                            paymentStepResult.Message = "Reversal is not a valid operation";

                            AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"{paymentStepResult.Message}");
                        }
                        else
                        {
                            var reversalRequest  = _requestFactory.GetReversalRequest(payment, orderForm.GetAllLineItems(), _market, shipment, description: "Cancelling purchase order");
                            var reversalResponse = AsyncHelper.RunSync(() => paymentOrder.Operations.Reverse(reversalRequest));
                            if (reversalResponse.Reversal.Transaction.Type == Sdk.TransactionType.Reversal)
                            {
                                payment.Status = PaymentStatus.Processed.ToString();
                                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Refunded {payment.Amount}");
                                paymentStepResult.Status = true;
                                return(paymentStepResult);
                            }
                            else
                            {
                                paymentStepResult.Message = "Error when executing reversal";
                                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {paymentStepResult.Message}");
                            }
                        }
                    }

                    else if (!string.IsNullOrWhiteSpace(orderId))
                    {
                        var paymentOrder = AsyncHelper.RunSync(() => SwedbankPayClient.PaymentOrders.Get(new Uri(orderId, UriKind.Relative)));
                        if (paymentOrder.Operations.Cancel == null)
                        {
                            AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Cancel is not possible on this order {orderId}");
                            return(paymentStepResult);
                        }

                        var cancelRequest  = _requestFactory.GetCancelRequest();
                        var cancelResponse = AsyncHelper.RunSync(() => paymentOrder.Operations.Cancel(cancelRequest));
                        if (cancelResponse.Cancellation.Transaction.Type == Sdk.TransactionType.Cancellation && cancelResponse.Cancellation.Transaction.State.Equals(State.Completed))
                        {
                            payment.Status                = PaymentStatus.Processed.ToString();
                            payment.TransactionID         = cancelResponse.Cancellation.Transaction.Number;
                            payment.ProviderTransactionID = cancelResponse.Cancellation.Transaction.Id.ToString();
                            AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Order cancelled at SwedbankPay");
                            return(paymentStepResult);
                        }
                    }

                    return(paymentStepResult);
                }
                catch (Exception ex)
                {
                    payment.Status            = PaymentStatus.Failed.ToString();
                    paymentStepResult.Message = ex.Message;
                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {ex.Message}");
                    Logger.Error(ex.Message, ex);
                }
            }

            if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup, shipment));
            }

            return(paymentStepResult);
        }
Example #22
0
        public override PaymentStepResult Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment)
        {
            var paymentStepResult = new PaymentStepResult();

            if (payment.TransactionType == TransactionType.Credit.ToString())
            {
                try
                {
                    var orderId = orderGroup.Properties[Constants.SwedbankPayOrderIdField]?.ToString();
                    if (!string.IsNullOrEmpty(orderId))
                    {
                        if (orderGroup is IPurchaseOrder purchaseOrder)
                        {
                            var returnForm = purchaseOrder.ReturnForms.FirstOrDefault(x => ((OrderForm)x).Status == ReturnFormStatus.Complete.ToString() && ((OrderForm)x).ObjectState == MetaObjectState.Modified);

                            if (returnForm != null)
                            {
                                var transactionDescription = string.IsNullOrWhiteSpace(returnForm.ReturnComment)
                                        ? "Reversing payment."
                                        : returnForm.ReturnComment;


                                var reversalRequest = _requestFactory.GetReversalRequest(payment, returnForm.GetAllReturnLineItems(), _market, returnForm.Shipments.FirstOrDefault(), description: transactionDescription);
                                var paymentOrder    = AsyncHelper.RunSync(() => SwedbankPayClient.PaymentOrders.Get(new Uri(orderId, UriKind.Relative)));

                                if (paymentOrder.Operations.Reverse == null)
                                {
                                    payment.Status            = PaymentStatus.Failed.ToString();
                                    paymentStepResult.Message = "Reversal is not a valid operation";
                                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {paymentStepResult.Message}");
                                    Logger.Error($"Reversal is not a valid operation for {orderId}");
                                    return(paymentStepResult);
                                }

                                var reversalResponse = AsyncHelper.RunSync(() => paymentOrder.Operations.Reverse(reversalRequest));
                                if (reversalResponse.Reversal.Transaction.Type == Sdk.TransactionType.Reversal && reversalResponse.Reversal.Transaction.State.Equals(State.Completed))
                                {
                                    payment.Status                = PaymentStatus.Processed.ToString();
                                    payment.TransactionID         = reversalResponse.Reversal.Transaction.Number;
                                    payment.ProviderTransactionID = reversalResponse.Reversal.Transaction.Id.ToString();
                                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Refunded {payment.Amount}");

                                    paymentStepResult.Status = true;
                                }
                            }
                        }

                        return(paymentStepResult);
                    }
                }
                catch (Exception ex)
                {
                    payment.Status            = PaymentStatus.Failed.ToString();
                    paymentStepResult.Message = ex.Message;
                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {ex.Message}");
                    Logger.Error(ex.Message, ex);
                }
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup, shipment));
            }

            return(paymentStepResult);
        }
 public override TResult Parse <TResult>(object rawResult) => Successor.Parse <TResult>(rawResult);
Example #24
0
        public ArrayList getSuccessors(Object state)
        {
            ArrayList list   = new ArrayList(20);
            Q4State   jstate = (Q4State)state;

            string location = jstate.location;

            Successor s;
            Q4State   successor_state;


            //these functions are used to track the expanded nodes step/heuristic costs
            //Q4StepCostFunction sn = new Q4StepCostFunction();
            //Q4HeuristicFunction hn = new Q4HeuristicFunction();

            //System.out.println("Expanding " + location);

            if (location.Equals("Oradea"))
            {
                successor_state = new Q4State("Zerind");
                s = new Successor("go to  Zerind", successor_state);
                list.Add(s);

                successor_state = new Q4State("Sibiu");
                s = new Successor("go to  Sibiu", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Zerind"))
            {
                successor_state = new Q4State("Oradea");
                s = new Successor("go to  Oradea", successor_state);
                list.Add(s);

                successor_state = new Q4State("Arad");
                s = new Successor("go to Arad", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Arad"))
            {
                successor_state = new Q4State("Zerind");
                s = new Successor("go to Zerind", successor_state);
                list.Add(s);

                successor_state = new Q4State("Timisoara");
                s = new Successor("go to Timisoara", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Timisoara"))
            {
                successor_state = new Q4State("Arad");
                s = new Successor("go to Arad", successor_state);
                list.Add(s);

                successor_state = new Q4State("Lugoj");
                s = new Successor("go to  Lugoj", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Lugoj"))
            {
                successor_state = new Q4State("Timisoara");
                s = new Successor("go to Timisoara", successor_state);
                list.Add(s);

                successor_state = new Q4State("Mehadia");
                s = new Successor("go to Mehadia", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Mehadia"))
            {
                successor_state = new Q4State("Dobreta");
                s = new Successor("go to Dobreta", successor_state);
                list.Add(s);

                successor_state = new Q4State("Lugoj");
                s = new Successor("go to Lugoj", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Dobreta"))
            {
                successor_state = new Q4State("Mehadia");
                s = new Successor("go to Mehadia", successor_state);
                list.Add(s);

                successor_state = new Q4State("Craiova");
                s = new Successor("go to Craiova", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Sibiu"))
            {
                successor_state = new Q4State("Arad");
                s = new Successor("go to Arad", successor_state);
                list.Add(s);

                successor_state = new Q4State("Oradea");
                s = new Successor("go to Oradea", successor_state);
                list.Add(s);

                successor_state = new Q4State("Fagaras");
                s = new Successor("go to Fagaras", successor_state);
                list.Add(s);

                successor_state = new Q4State("Rimnicu Vilcea");
                s = new Successor("go to Rimnicu Vilcea", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Rimnicu Vilcea"))
            {
                successor_state = new Q4State("Sibiu");
                s = new Successor("go to Sibiu", successor_state);
                list.Add(s);

                successor_state = new Q4State("Pitesti");
                s = new Successor("go to Pitesti", successor_state);
                list.Add(s);

                successor_state = new Q4State("Craiova");
                s = new Successor("go to Craiova", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Craiova"))
            {
                successor_state = new Q4State("Rimnicu Vilcea");
                s = new Successor("go to Rimnicu Vilcea", successor_state);
                list.Add(s);

                successor_state = new Q4State("Dobreta");
                s = new Successor("go to Dobreta", successor_state);
                list.Add(s);

                successor_state = new Q4State("Pitesti");
                s = new Successor("go to Pitesti", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Pitesti"))
            {
                successor_state = new Q4State("Rimnicu Vilcea");
                s = new Successor("go to Rimnicu Vilcea", successor_state);
                list.Add(s);

                successor_state = new Q4State("Craiova");
                s = new Successor("go to Craiova", successor_state);
                list.Add(s);

                successor_state = new Q4State("Bucharest");
                s = new Successor("go to Bucharest", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Fagaras"))
            {
                successor_state = new Q4State("Sibiu");
                s = new Successor("go to Sibiu", successor_state);
                list.Add(s);

                successor_state = new Q4State("Bucharest");
                s = new Successor("go to Bucharest", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Bucharest"))
            {
                successor_state = new Q4State("Fagaras");
                s = new Successor("go to Fagaras", successor_state);
                list.Add(s);

                successor_state = new Q4State("Pitesti");
                s = new Successor("go to Pitesti", successor_state);
                list.Add(s);

                successor_state = new Q4State("Giurgiu");
                s = new Successor("go to Giurgiu", successor_state);
                list.Add(s);

                successor_state = new Q4State("Urziceni");
                s = new Successor("go to Urziceni", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Giurgiu"))
            {
                successor_state = new Q4State("Bucharest");
                s = new Successor("go to Bucharest", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Urziceni"))
            {
                successor_state = new Q4State("Bucharest");
                s = new Successor("go to Bucharest", successor_state);
                list.Add(s);

                successor_state = new Q4State("Vaslui");
                s = new Successor("go to Vaslui", successor_state);
                list.Add(s);

                successor_state = new Q4State("Hirsova");
                s = new Successor("go to Hirsova", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Vaslui"))
            {
                successor_state = new Q4State("Urziceni");
                s = new Successor("go to Urziceni", successor_state);
                list.Add(s);

                successor_state = new Q4State("Iasi");
                s = new Successor("go to Iasi", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Iasi"))
            {
                successor_state = new Q4State("Vaslui");
                s = new Successor("go to Vaslui", successor_state);
                list.Add(s);

                successor_state = new Q4State("Neamt");
                s = new Successor("go to Neamt", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Neamt"))
            {
                successor_state = new Q4State("Iasi");
                s = new Successor("go to Iasi", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Hirsova"))
            {
                successor_state = new Q4State("Urziceni");
                s = new Successor("go to Urziceni", successor_state);
                list.Add(s);

                successor_state = new Q4State("Eforie");
                s = new Successor("go to Eforie", successor_state);
                list.Add(s);
            }
            else if (location.Equals("Eforie"))
            {
                successor_state = new Q4State("Hirsova");
                s = new Successor("go to Hirsova", successor_state);
                list.Add(s);
            }



            return(list);
        }
Example #25
0
        // What are the left and right widths and height of the object
        // (including its children and successors)?
        public override void footprint(System.Drawing.Graphics gr)
        {
            bool draw_full_text = (Component.full_text &&
                                   this.scale > 0.4);

            this.init();
            // set footprint based on the diamond
            this.Diamond_Footprint(gr, this.scale > 0.4, W / 2 + W / 4);


            if (!Component.USMA_mode)
            {
                // Left footprint calculation, no change if no left child
                if (this.left_Child != null && !this.is_compressed)
                {
                    int temp_fp_left;

                    left_Child.footprint(gr);
                    // in regular mode, our left footprint is obtained by the full footprint of
                    // our left child, plus an offset for the diamond of W/2
                    temp_fp_left = (left_Child.FP.left + left_Child.FP.right) + W / 2;
                    if (temp_fp_left > FP.left)
                    {
                        FP.left = temp_fp_left;
                    }
                    // if wide diamond, add its left width plus left child plus two offsets
                    if (draw_full_text && this.Is_Wide_Diamond())
                    {
                        temp_fp_left = (left_Child.FP.left +
                                        this.drawing_text_width / 2 + W);
                        if (temp_fp_left > FP.left)
                        {
                            FP.left = temp_fp_left;
                        }
                    }
                }
                if (right_Child != null && !this.is_compressed)
                {
                    int temp_fp_right;

                    right_Child.footprint(gr);
                    // we need full right footprint plus buffer
                    temp_fp_right = (right_Child.FP.left + right_Child.FP.right) + W / 2;
                    if (temp_fp_right > FP.right)
                    {
                        FP.right = temp_fp_right;
                    }
                    // if wide diamond, then we need to just check to see
                    // if the text right side is bigger then the right child's
                    // left child
                    if (draw_full_text && this.Is_Wide_Diamond())
                    {
                        temp_fp_right = (right_Child.FP.right +
                                         this.drawing_text_width / 2 + W);
                        if (temp_fp_right > FP.right)
                        {
                            FP.right = temp_fp_right;
                        }
                    }
                }
            }
            // USMA mode
            else
            {
                if (right_Child != null && !this.is_compressed)
                {
                    // in USMA mode, we just need to worry about the right child footprint
                    // to update the right any wide diamond has already been handled above
                    right_Child.footprint(gr);
                    if (right_Child.FP.right > FP.right)
                    {
                        FP.right = right_Child.FP.right;
                    }
                }

                // USMA mode needs to check both children to get left footprint
                if (left_Child != null && right_Child != null && !this.is_compressed)
                {
                    int temp_fp_left;

                    left_Child.footprint(gr);
                    // on both kids, right's left plus full left plus buffer
                    // and some more
                    temp_fp_left = (right_Child.FP.left + left_Child.FP.left +
                                    left_Child.FP.right) + W / 2 + W / 8;
                    if (temp_fp_left > FP.left)
                    {
                        FP.left = temp_fp_left;
                    }
                    // maybe we just need diamond plus left on left
                    if (draw_full_text && this.Is_Wide_Diamond())
                    {
                        temp_fp_left = (left_Child.FP.left +
                                        this.drawing_text_width / 2 + W);
                        if (temp_fp_left > FP.left)
                        {
                            FP.left = temp_fp_left;
                        }
                    }
                }
                else if (right_Child != null & !this.is_compressed)
                {
                    int temp_fp_left;
                    temp_fp_left = (right_Child.FP.left) + W / 2 + W / 8;
                    if (temp_fp_left > FP.left)
                    {
                        FP.left = temp_fp_left;
                    }
                }
                // if we're here, then we have no right child, just a left one
                else if (left_Child != null && !this.is_compressed)
                {
                    int temp_fp_left;

                    left_Child.footprint(gr);
                    temp_fp_left = (left_Child.FP.left + left_Child.FP.right) + W / 2;
                    if (temp_fp_left > FP.left)
                    {
                        FP.left = temp_fp_left;
                    }
                    if (draw_full_text && this.Is_Wide_Diamond())
                    {
                        temp_fp_left = (left_Child.FP.left +
                                        this.drawing_text_width / 2 + W);
                        if (temp_fp_left > FP.left)
                        {
                            FP.left = temp_fp_left;
                        }
                    }
                }
            }

            int right_height = 0;

            // change height based on USMA mode
            if (right_Child != null)
            {
                if (!Component.USMA_mode)
                {
                    right_height = right_Child.FP.height;
                }
                else
                {
                    right_height = right_Child.FP.height + CL;
                }
            }

            if ((right_Child != null) && (left_Child != null) && !this.is_compressed)
            {
                FP.height = H + H / 2 + ((right_height > left_Child.FP.height) ? right_height:left_Child.FP.height) + CL;
            }
            else if (right_Child != null && !this.is_compressed)
            {
                FP.height = H + H / 2 + right_height + CL;
            }
            else if (left_Child != null && !this.is_compressed)
            {
                FP.height = H + H / 2 + left_Child.FP.height + CL;
            }
            else
            {
                FP.height = H + H / 2;
            }


            if (Successor != null)
            {
                Successor.footprint(gr);

                if (FP.left < Successor.FP.left)                 // successor has larger left footprint
                {
                    FP.left = Successor.FP.left;
                }
                if (FP.right < Successor.FP.right)                 // successor has larger right footprint
                {
                    FP.right = Successor.FP.right;
                }
                FP.height = FP.height + CL + Successor.FP.height;
            }
        }
Example #26
0
        public override void draw(System.Drawing.Graphics gr, int x, int y)
        {
            int  left_bottom, right_bottom;
            bool draw_text;

            if ((this.scale <= .4) || (this.head_heightOrig < 10))
            {
                draw_text = false;
            }
            else
            {
                draw_text = Component.text_visible;
            }

            X = x;
            Y = y;

            height_of_text = Convert.ToInt32((gr.MeasureString(
                                                  "Yes", PensBrushes.default_times)).Height);

            width_of_text = Convert.ToInt32((gr.MeasureString(
                                                 this.Text + "XX", PensBrushes.default_times)).Width);

            int length_of_yesStr = Convert.ToInt32((gr.MeasureString(
                                                        "Yes", PensBrushes.default_arial)).Width);
            int length_of_noStr = Convert.ToInt32((gr.MeasureString(
                                                       "No", PensBrushes.default_arial)).Width);


            //length of line from horizontal to children or bottom
            line_height = H;
            // y coord of top of right child connector or bottom
            left_connector_y  = Y + H / 2 + line_height;
            right_connector_y = Y + H / 2 + line_height;


            // bottom y coord without children
            min_bottom = Y + H / 2 + line_height;
            bottom     = min_bottom;

            x_left = x - W;
            y_left = y + H / 2;

            y_right = y + H / 2;
            x_right = x + W;

            if (draw_text && this.Is_Wide_Diamond())
            {
                x_left  -= this.drawing_text_width / 2 - W / 2;
                x_right += this.drawing_text_width / 2 - W / 2;
            }

            // same for either USMA or regular mode
            if (left_Child != null && !this.is_compressed)
            {
                int temp = x - left_Child.FP.right - W / 2;
                if (temp < x_left)
                {
                    x_left = temp;
                }
            }
            if (right_Child != null && !this.is_compressed)
            {
                int temp = x + right_Child.FP.left + W / 2;
                if (temp > x_right)
                {
                    x_right = temp;
                }
            }

            // for USMA mode, move down the right side below the diamond
            // add room for the connector
            if (Component.USMA_mode)
            {
                x_right            = x;
                y_right            = y + H;
                left_connector_y  -= CL;
                right_connector_y -= CL;

                // don't need to check the left child only case as it is handled above
                if (left_Child != null && right_Child != null && !this.is_compressed)
                {
                    int temp = x - (right_Child.FP.left + left_Child.FP.right + W / 2);
                    if (temp < x_left)
                    {
                        x_left = temp;
                    }
                }
                else if (right_Child != null && !this.is_compressed)
                {
                    int temp = x - (right_Child.FP.left + W / 2);
                    if (temp < x_left)
                    {
                        x_left = temp;
                    }
                }
            }


            if (left_Child != null && !this.is_compressed)
            {
                left_bottom = min_bottom + left_Child.FP.height + CL;
                bottom      = left_bottom;
            }

            if (right_Child != null && !this.is_compressed)
            {
                right_bottom = min_bottom + right_Child.FP.height + CL;
                if (Component.USMA_mode)
                {
                    right_bottom += CL;
                }
                // see also above-- we want bottom to be the max
                // of left, right and min_bottom
                if (right_bottom > bottom)
                {
                    bottom = right_bottom;
                }
            }


            gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            System.Drawing.Pen diamond_pen = PensBrushes.blue_pen;
            System.Drawing.Pen line_pen    = PensBrushes.blue_pen;

            // if the If control is selected make it red
            if (this.selected)
            {
                diamond_pen = PensBrushes.red_pen;
                line_pen    = PensBrushes.red_pen;
            }
            // else if the If control is running make the diamond green
            else if (this.running)
            {
                diamond_pen = PensBrushes.chartreuse_pen;
                line_pen    = PensBrushes.blue_pen;
            }
            else if (this.is_compressed && this.have_child_running())
            {
                diamond_pen = PensBrushes.chartreuse_pen;
                line_pen    = PensBrushes.chartreuse_pen;
            }


            if (this.has_breakpoint)
            {
                StopSign.Draw(gr, x - W / 2 - W / 6 - 2, y, W / 6);
            }

            // Draw the diamond shape
            this.Draw_Diamond_and_Text(gr, x, y, this.Text,
                                       diamond_pen, draw_text);

            // draw the left and right lines that extend horizontally
            if (draw_text && this.Is_Wide_Diamond())
            {
                gr.DrawLine(line_pen,
                            x - this.drawing_text_width / 2 - W / 4, y + H / 2,
                            x_left, y_left);                    // draw left line
                if (!Component.USMA_mode)
                {
                    gr.DrawLine(line_pen,
                                x + this.drawing_text_width / 2 + W / 4, y + H / 2,
                                x_right, y_right);        // draw right line
                }
            }
            else
            {
                gr.DrawLine(line_pen, x - W / 2, y + H / 2, x_left, y_left);     // draw left line
                if (!Component.USMA_mode)
                {
                    gr.DrawLine(line_pen, x + W / 2, y + H / 2, x_right, y_right); // draw right line
                }
            }

            // add extra space at the bottom for USMA mode
            if (!Component.USMA_mode)
            {
                left_bottom  = bottom;
                right_bottom = bottom;
            }
            else
            {
                left_bottom  = bottom - W / 8;
                right_bottom = bottom - W / 4;
            }

            if (left_Child != null && !this.is_compressed)
            {
                // draw the left connector to the left child
                // draw connector line to top of left child
                gr.DrawLine(line_pen, x_left, y_left, x_left, left_connector_y);
                // draw left side of arrow
                gr.DrawLine(line_pen, x_left, left_connector_y, x_left - CL / 4, left_connector_y - CL / 4);
                // draw right side of arrow
                gr.DrawLine(line_pen, x_left, left_connector_y, x_left + CL / 4, left_connector_y - CL / 4);

                // draw the left child
                left_Child.draw(gr, x_left, left_connector_y);

                // draw the left connector to last left child to the bottom
                // draw connector line to bottom left
                gr.DrawLine(line_pen, x_left, left_connector_y + left_Child.FP.height, x_left, left_bottom);
            }
            else
            {
                // draw the left connector to the bottom
                gr.DrawLine(line_pen, x_left, y_left, x_left, left_bottom);             // draw connector line to top of left child
            }
            // draw left side of arrow
            gr.DrawLine(line_pen, x_left, left_bottom, x_left - CL / 4, left_bottom - CL / 4);
            // draw left side of arrow
            gr.DrawLine(line_pen, x_left, left_bottom, x_left + CL / 4, left_bottom - CL / 4);

            if (right_Child != null && !this.is_compressed)
            {
                // draw the right connector to the right child
                gr.DrawLine(line_pen, x_right, y_right, x_right, right_connector_y);                             // draw connector line to top of right child
                gr.DrawLine(line_pen, x_right, right_connector_y, x_right - CL / 4, right_connector_y - CL / 4); // draw right side of arrow
                gr.DrawLine(line_pen, x_right, right_connector_y, x_right + CL / 4, right_connector_y - CL / 4); // draw right side of arrow

                // draw the right child
                right_Child.draw(gr, x_right, right_connector_y);

                // draw the right connector from last right child to the bottom
                gr.DrawLine(line_pen, x_right, right_connector_y + right_Child.FP.height,
                            x_right, right_bottom);            // draw connector line to bottom right
            }
            else
            {
                // draw the right connector to the bottom
                gr.DrawLine(line_pen, x_right, y_right, x_right, right_bottom);             // draw connector line to top of right child
            }
            // draw right side of arrow
            gr.DrawLine(line_pen, x_right, right_bottom, x_right - CL / 4, right_bottom - CL / 4);
            // draw right side of arrow
            gr.DrawLine(line_pen, x_right, right_bottom, x_right + CL / 4, right_bottom - CL / 4);


            if (Component.USMA_mode)
            {
                gr.DrawEllipse(line_pen, x_right - W / 8, right_bottom, W / 4, W / 4);
                // draw the bottom line
                gr.DrawLine(line_pen, x_left, left_bottom, x_right - W / 8, left_bottom);
            }
            else
            {
                // draw the bottom line
                gr.DrawLine(line_pen, x_left, bottom, x_right, bottom);
            }

            if (draw_text)
            {
                if (!Component.USMA_mode)
                {
                    if (this.Is_Wide_Diamond())
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x + this.drawing_text_width / 2 + W / 4 + length_of_noStr / 2,
                                      y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - this.drawing_text_width / 2 - W / 4 - length_of_yesStr / 2,
                                      y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                    }
                    else
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x + W / 2 + length_of_noStr, y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - W / 2 - length_of_yesStr, y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                    }
                }
                else                  // USMA mode
                {
                    if (this.Is_Wide_Diamond())
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - (this.drawing_text_width / 2 + W / 4 + length_of_noStr / 2),
                                      y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - W / 8 - length_of_yesStr / 2,
                                      y + H + 5,
                                      PensBrushes.centered_stringFormat);
                    }
                    else
                    {
                        gr.DrawString("No", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - (W / 2 + length_of_noStr), y + H / 2 - 5,
                                      PensBrushes.centered_stringFormat);
                        gr.DrawString("Yes", PensBrushes.default_arial,
                                      PensBrushes.blackbrush,
                                      x - W / 8 - length_of_yesStr, y + H + 5,
                                      PensBrushes.centered_stringFormat);
                    }
                }
            }

            if (Successor != null)
            {
                gr.DrawLine(line_pen, x, bottom, x, bottom + CL);                        // draw connector line to successor
                gr.DrawLine(line_pen, x, bottom + CL, x - CL / 4, bottom + CL - CL / 4); // draw left side of arrow
                gr.DrawLine(line_pen, x, bottom + CL, x + CL / 4, bottom + CL - CL / 4); // draw right side of arrow
                Successor.draw(gr, x, bottom + CL);
            }
            if (draw_text)
            {
                base.draw(gr, x, y);
            }
        }
 public void SetSuccesor(Successor successor)
 {
     succesorObject = successor;
 }
Example #28
0
        public override void Handle(Event evt)
        {
            if (evt.Category == 0 && evt is VehicleStopEvent arriveEvent)
            {
                Log(evt);
                evt.AlreadyHandled = true;
                var arrivalTime = evt.Time;

                //Handle arrival evt
                if (arriveEvent.Vehicle.TripIterator.Current != null && arriveEvent.Vehicle.CurrentStop == arriveEvent.Stop)
                {
                    arriveEvent.Vehicle.IsIdle = true;
                    if (arriveEvent.Vehicle.TripIterator.Current.StopsIterator.CurrentIndex == 0) //check if the trip has started
                    {
                        arriveEvent.Vehicle.TripIterator.Current.Start(arrivalTime);
                        _consoleLogger.Log(arriveEvent.Vehicle.ToString() + arriveEvent.Vehicle.TripIterator.Current + " STARTED at " +
                                           TimeSpan.FromSeconds(arrivalTime) + ".");
                    }

                    _consoleLogger.Log(arriveEvent.Vehicle.ToString() + "ARRIVED at " + arriveEvent.Stop + " at " + TimeSpan.FromSeconds(arrivalTime) + ".");
                    arriveEvent.Vehicle.VisitedStops.Add(arriveEvent.Stop);                                                        //adds the current stop to the visited stops
                    arriveEvent.Vehicle.StopsTimeWindows.Add(new long[] { arrivalTime, arrivalTime });                             //adds the current time window

                    if (arriveEvent.Vehicle.TripIterator.Current.StopsIterator.IsDone && arriveEvent.Vehicle.Customers.Count == 0) //this means that the trip is complete
                    {
                        arriveEvent.Vehicle.TripIterator.Current.Finish(arrivalTime);                                              //Finishes the trip
                        _consoleLogger.Log(arriveEvent.Vehicle.ToString() + arriveEvent.Vehicle.TripIterator.Current + " FINISHED at " +
                                           TimeSpan.FromSeconds(arrivalTime) + ", Duration:" +
                                           Math.Round(TimeSpan.FromSeconds(arriveEvent.Vehicle.TripIterator.Current.RouteDuration)
                                                      .TotalMinutes) + " minutes.");

                        arriveEvent.Vehicle.TripIterator.MoveNext();
                        if (arriveEvent.Vehicle.TripIterator.Current == null)
                        {
                            arriveEvent.Vehicle.TripIterator.Reset();
                            arriveEvent.Vehicle.TripIterator.MoveNext();
                        }
                    }
                }
                //end of arrival event handle

                //INSERTION (APPEND) OF CUSTOMER ENTER VEHICLE AND LEAVE VEHICLE EVENTS AND GENERATION OF THE DEPART EVENT FROM THE CURRENT STOP---------------------------------------
                var customerLeaveVehicleEvents = EventGenerator.Instance().GenerateCustomerLeaveVehicleEvents(arriveEvent.Vehicle, arriveEvent.Stop, arrivalTime); //Generates customer leave vehicle event
                var lastInsertedLeaveTime      = 0;
                var lastInsertedEnterTime      = 0;
                lastInsertedLeaveTime = customerLeaveVehicleEvents.Count > 0 ? customerLeaveVehicleEvents[customerLeaveVehicleEvents.Count - 1].Time : arrivalTime;

                List <Event> customersEnterVehicleEvents = null;
                if (arriveEvent.Vehicle.TripIterator.Current != null && arriveEvent.Vehicle.TripIterator.Current.HasStarted)
                {
                    int expectedDemand = 0;
                    try
                    {
                        expectedDemand = !arriveEvent.Vehicle.FlexibleRouting ? Simulation.Context.DemandsDataObject.GetDemand(arriveEvent.Stop.Id, arriveEvent.Vehicle.TripIterator.Current.Route.Id, TimeSpan.FromSeconds(arriveEvent.Time).Hours) : 0;
                    }
                    catch (Exception)
                    {
                        expectedDemand = 0;
                    }

                    customersEnterVehicleEvents = EventGenerator.Instance().GenerateCustomersEnterVehicleEvents(arriveEvent.Vehicle, arriveEvent.Stop, lastInsertedLeaveTime, expectedDemand);
                    if (customersEnterVehicleEvents.Count > 0)
                    {
                        lastInsertedEnterTime = customersEnterVehicleEvents[customersEnterVehicleEvents.Count - 1].Time;
                    }
                }

                Simulation.AddEvent(customersEnterVehicleEvents);
                Simulation.AddEvent(customerLeaveVehicleEvents);


                var maxInsertedTime = Math.Max(lastInsertedEnterTime, lastInsertedLeaveTime);;  //gets the highest value of the last insertion in order to maintain precedence constraints for the depart evt, meaning that the stop depart only happens after every customer has already entered and left the vehicle on that stop location

                //INSERTION OF CUSTOMER ENTER VEHICLE FOR THE FLEXIBLE REQUESTS!


                if (arriveEvent.Vehicle.TripIterator.Current != null && arriveEvent.Vehicle.FlexibleRouting)
                {
                    var currentVehicleTrip            = arriveEvent.Vehicle.TripIterator.Current;
                    var customersToEnterAtCurrentStop = currentVehicleTrip.ExpectedCustomers.FindAll(c => c.PickupDelivery[0] == arriveEvent.Stop && !c.IsInVehicle); //gets all the customers that have the current stop as the pickup stop

                    if (customersToEnterAtCurrentStop.Count > 0)                                                                                                      //check if there is customers to enter at current stop
                    {
                        foreach (var customer in customersToEnterAtCurrentStop)                                                                                       //iterates over every customer that has the actual stop as the pickup stop, in order to make them enter the vehicle
                        {
                            if (currentVehicleTrip.ScheduledTimeWindows[currentVehicleTrip.StopsIterator.CurrentIndex][1] >= customer.DesiredTimeWindow[0])           //if current stop expected depart time is greater or equal than the customer arrival time adds the customer
                            {
                                var enterTime = maxInsertedTime > customer.DesiredTimeWindow[0] ? maxInsertedTime + 1 : customer.DesiredTimeWindow[0] + 1;            //case maxinserted time is greather than desired time window the maxinserted time +1 will be the new enterTime of the customer, othersie it is the customer's desiredtimewindow
                                var customerEnterVehicleEvt =
                                    EventGenerator.Instance().GenerateCustomerEnterVehicleEvent(arriveEvent.Vehicle, (int)enterTime, customer);                       //generates the enter event
                                Simulation.AddEvent(customerEnterVehicleEvt);                                                                                         //adds to the event list
                                maxInsertedTime = (int)enterTime;                                                                                                     //updates the maxInsertedTime
                            }
                        }
                    }
                }


                // END OF INSERTION OF CUSTOMER ENTER VEHICLE FOR THE FLEXIBLE REQUESTS

                //VEHICLE DEPART STOP EVENT

                if (arriveEvent.Vehicle.TripIterator.Current?.ScheduledTimeWindows != null)
                {
                    var currentStopIndex = arriveEvent.Vehicle.TripIterator.Current.StopsIterator.CurrentIndex;
                    var newDepartTime    = arriveEvent.Vehicle.TripIterator.Current.ScheduledTimeWindows[currentStopIndex][1]; //gets the expected latest depart time
                    maxInsertedTime = newDepartTime != 0 ? (int)Math.Max(maxInsertedTime, newDepartTime) : maxInsertedTime;    //if new depart time != 0,new maxInsertedTime will be the max between maxInsertedtime and the newDepartTime, else the value stays the same.
                                                                                                                               //If maxInsertedTime is still max value between the previous maxInsertedTime and newDepartTime, this means that there has been a delay in the flexible trip (compared to the model generated by the solver)
                }

                var nextDepartEvent = EventGenerator.Instance().GenerateVehicleDepartEvent(arriveEvent.Vehicle, maxInsertedTime + 2);
                Simulation.AddEvent(nextDepartEvent);
            }
            else
            {
                Successor?.Handle(evt);
            }
        }
Example #29
0
 protected override void WriteRequest(string text)
 {
     Console.WriteLine($"Line manager accepted request for {text}");
     Successor.Request(text);
 }
 public override TResult Parse <TResult>(object rawResult) => rawResult == null
     ? default
     : Successor.Parse <TResult>(rawResult);