Beispiel #1
0
        public LoanResponse Read(long LoanID)
        {
            LoanResponse response = new LoanResponse();

            try
            {
                using (IDbConnection conn = GetConnection())
                {
                    response.loan = conn.Get <Loans>(LoanID);
                    if (response.loan != null)
                    {
                        response.Status      = true;
                        response.Description = "Successful";
                    }
                    else
                    {
                        response.Status      = false;
                        response.Description = "No data";
                    }
                }
            }
            catch (Exception ex)
            {
                response.Status      = false;
                response.Description = ex.Message;
            }
            return(response);
        }
        public async Task <IActionResult> CreateModalAsync(Guid loanUID)
        {
            if (loanUID == Guid.Empty)
            {
                return(Json(new { message = $"{GlobalConstants.ERROR_ACTION_PREFIX} find Loan." }));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(loanUID);

            if (_Loan == null)
            {
                return(Json(new { message = $"{GlobalConstants.ERROR_ACTION_PREFIX} find Loan." }));
            }

            CreateLoanExtensionViewModel _Model = new CreateLoanExtensionViewModel
            {
                LoanUID            = loanUID,
                PreviousExpiryDate = _Loan.ExpiryTimestamp,
                ExtenderEmail      = __UserManager.GetUserAsync(HttpContext.User).Result.Email
            };

            IList <LoanExtensionResponse> _Extensions = (await __LoanExtensionManager.GetAsync(loanUID))?.OrderByDescending(x => x.NewExpiryDate)?.ToList() ?? null;

            if (_Extensions?.Count > 0)
            {
                _Model.PreviousExpiryDate = _Extensions[0].NewExpiryDate;
            }

            _Model.NewExpiryDate = _Model.PreviousExpiryDate < DateTime.Now ? DateTime.Today.AddDays(7) : _Model.PreviousExpiryDate.AddDays(7);

            return(PartialView("_CreateModal", _Model));
        }
        public async Task <IActionResult> CreateAsync(CreateLoanExtensionViewModel model)
        {
            if (model == null)
            {
                return(Json(new { message = $"{GlobalConstants.ERROR_ACTION_PREFIX} find Loan." }));
            }
            else if (model?.NewExpiryDate <= model.PreviousExpiryDate)
            {
                ModelState.AddModelError("Error", "New Expiry Date cannot be less than or equal to the Previous Expiry Date.");
            }

            if (!ModelState.IsValid)
            {
                return(PartialView("_CreateModal", model));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(model.LoanUID);

            if (_Loan.Status == Enums.Loan.Status.EarlyComplete || _Loan.Status == Enums.Loan.Status.Complete)
            {
                return(Json(new { message = $"{GlobalConstants.ERROR_ACTION_PREFIX} extend Loan because the loan is completed. Please create a new loan instead." }));
            }

            LoanExtensionResponse _Response = await __LoanExtensionManager.CreateAsync(__Mapper.Map <CreateLoanExtensionRequest>(model));

            if (_Response?.Success == false)
            {
                return(Json(new { error = $"{GlobalConstants.ERROR_ACTION_PREFIX} create {MODEL_NAME}." }));
            }

            return(Json(new { success = $"{GlobalConstants.SUCCESS_ACTION_PREFIX} created {MODEL_NAME}." }));
        }
Beispiel #4
0
        public void StartReceiving()
        {
            LoanRequest loanRequest;
            var         consumer = new EventingBasicConsumer(rabbitConn.Channel);

            rabbitConn.Channel.BasicConsume(queue: receiveQueueName,
                                            noAck: false,
                                            consumer: consumer);
            //If a message is detected then it consumes it, and process it
            consumer.Received += (model, ea) =>
            {
                var body   = ea.Body;
                var header = ea.BasicProperties;
                //Deserialize message
                loanRequest = JsonConvert.DeserializeObject <LoanRequest>(Encoding.UTF8.GetString(body));

                Console.WriteLine();
                Console.WriteLine(" [x] Received {0}", loanRequest.ToString());

                string   mesage = WBC.Call(loanRequest.SSN, loanRequest.Duration, loanRequest.CreditScore);
                string[] values;
                values = mesage.Split('#');
                LoanResponse loanResponse = new LoanResponse();
                loanResponse.SSN          = values[0];
                loanResponse.InterestRate = Double.Parse(values[1]);

                rabbitConn.Send(loanResponse.ToString(), "groupB.web.bank.reply", header, false);

                rabbitConn.Channel.BasicAck(ea.DeliveryTag, false);
            };
        }
Beispiel #5
0
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            aTimer.Stop();
            if (requests.Count > 0)
            {
                //if no responses had been received within the time limit
                if (responses.Count == 0)
                {
                    rabbitConn.Send("No bank responded within the time limit", requests.First().Key.ReplyTo, requests.First().Key, false);
                    Console.WriteLine();
                    Console.WriteLine("No bank responded within the time limit");
                    requests.Remove(requests.First().Key);
                }
                //find the best of the responses it did receive
                else
                {
                    bestRate = BestOffer();
                    string bestoffer = "The best offer on: " + bestRate.SSN + " loan request, is from: " + bestRate.BankName +
                                       " which offer an interest rate on: " + bestRate.InterestRate;
                    rabbitConn.Send(bestoffer, requests.First().Key.ReplyTo, requests.First().Key, false);

                    bankCount = 0;
                    requests.Remove(requests.First().Key);
                    responses.Clear();
                }
            }
        }
Beispiel #6
0
        public async Task <IActionResult> LoanPreviewAsync(Guid uid)
        {
            if (uid == null || uid == Guid.Empty)
            {
                return(Json("Page not found"));
            }

            LoanResponse _Response = await __LoanManager.GetByUIDAsync(uid);

            if (_Response == null)
            {
                return(Json("Page not found"));
            }

            LoanViewModel _Model = __Mapper.Map <LoanViewModel>(_Response);

            IList <Guid> _EquipmentUIDs = (await __LoanEquipmentManager.GetAsync(_Response.UID)).Select(x => x.EquipmentUID).ToList();

            if (_EquipmentUIDs != null && _EquipmentUIDs.Count > 0)
            {
                _Model.EquipmentList = __Mapper.Map <IList <Equipment.Models.EquipmentViewModel> >((await __EquipmentManager.GetAsync(_EquipmentUIDs)).Equipments);
            }

            return(View("LoanPreview", _Model));
        }
Beispiel #7
0
        public async Task <ActionResult <LoanResponse> > PostLoan(Loan loanRequest)
        {
            Logger.LogInformation("Received loan application request");
            var payload = ConvertLoan(loanRequest);

            var loan = await blend.PostLendingAppAsync(payload);

            var lender = await blend.GetLenderByEmailAsync(loanRequest.ReferrerEmail);

            if (lender != null && loan != null && !String.IsNullOrEmpty(loan.Id))
            {
                Logger.LogInformation("Adding lender to loan application");
                List <Models.Blend.Lender> lenders = new List <Models.Blend.Lender>();
                lenders.Add(lender);
                blend.UpdateAllAssigned(loan.Id, lenders);
            }
            else
            {
                throw new SystemException("Error detected in processing your application with downstream systems");
            }

            var sfdcLead = await sfdc.PostLeadAsync(ConvertLead(loan.Id, loanRequest));

            var result = new LoanResponse()
            {
                LoanId   = loan.Id,
                LenderId = lender.Id,
                LeadId   = sfdcLead
            };

            return(result);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            LoanRequest loanRequest = new LoanRequest
            {
                LoanAmount = double.Parse(args[1]),
                Offers     = ReadFile(args[0])
            };
            LoanResponse loanResponse = null;
            Controller   controller   = new Controller();

            try
            {
                controller.ValidateRequest(loanRequest);
                loanResponse = controller.Calculate(loanRequest) as LoanResponse;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            if (loanResponse != null)
            {
                CultureInfo culture = new CultureInfo(ConfigurationManager.AppSettings["DefaultCulture"]);
                Console.WriteLine("Requested amount: " + loanResponse.RequestedAmount.ToString("C", culture));
                Console.WriteLine("Rate: " + loanResponse.Rate.ToString("P1"));
                Console.WriteLine("Monthly repayment: " + loanResponse.MounthlyRepayment.ToString("C2", culture));
                Console.WriteLine("Total repayment: " + loanResponse.TotalRepayment.ToString("C2", culture));
            }
        }
Beispiel #9
0
        private LoanResponse BestOffer()
        {
            LoanResponse best = responses[0];

            foreach (LoanResponse res in responses)
            {
                if (res.InterestRate < best.InterestRate)
                {
                    best = res;
                }
            }
            return(best);
        }
Beispiel #10
0
        public static void Main(string[] args)
        {
            Console.Title = "RabbitMQJSONBankNormalizer";
            Console.SetWindowSize(80, 5);
            Console.WriteLine("Listening on queue: " + Queues.RABBITMQJSONBANK_OUT);

            HandleMessaging.RecieveMessage(Queues.RABBITMQJSONBANK_OUT, (object model, BasicDeliverEventArgs ea) =>
            {
                Console.WriteLine("<--Message recieved on queue: " + Queues.RABBITMQJSONBANK_OUT);

                LoanResponse loanResponse;
                JsonBankResponse bankResponse;

                string msg = Encoding.UTF8.GetString(ea.Body);

                try
                {
                    bankResponse = JsonConvert.DeserializeObject <JsonBankResponse>(msg);
                    loanResponse = new LoanResponse()
                    {
                        InterestRate = bankResponse.InterestRate,
                        SSN          = bankResponse.SSN,
                        BankName     = ea.RoutingKey.Split('_')[1] // Gets the bank name from the queue name
                    };

                    Console.WriteLine("<--Sending message on queue: " + Queues.NORMALIZER_OUT);
                    Console.WriteLine();
                    HandleMessaging.SendMessage <LoanResponse>(Queues.NORMALIZER_OUT, loanResponse);
                }
                catch (Exception ex)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                    Console.BackgroundColor = ConsoleColor.Black;

                    /*
                     * String format from pdf:
                     * string msg = "{\"ssn\":" + loanRequest.SSN + ",\"creditScore\":" + loanRequest.CreditScore.ToString() +
                     *     ",\"loanAmount\":" + loanRequest.Amount.ToString() + ",\"loanDuration\":" + loanRequest.Duration +" }";
                     *
                     * but getting this from the bank:
                     *
                     * Exception: Something went wrong.Data should be sent like: { "ssn":1605789787,"loanAmount":10.0,"loanDuration":360,"rki":false}
                     * Can not instantiate value of type[simple type, class dk.cphbusiness.si.banktemplate.JsonDTO.BankLoanDTO] from JSON String; no single-String constructor/factory method
                     *
                     *  Gonna send the pdf version, and just catch the exception here...
                     */
                }
            });
        }
        private static void handleWebServiceBank(LoanRequest loanRequest)
        {
            WebServiceBank.WebServiceBank webBank = new WebServiceBank.WebServiceBank();
            decimal msg = webBank.ProcessLoanRequest(loanRequest.SSN, loanRequest.CreditScore, loanRequest.Amount, loanRequest.Duration);
            //TODO: Send loanrequest info aswell as decimal msg
            //HandleMessaging.SendMessage<decimal>(Queues.WEBSERVICEBANK_OUT, msg);
            LoanResponse loanResponse = new LoanResponse()
            {
                SSN          = loanRequest.SSN,
                BankName     = "Our Web Bank",
                InterestRate = msg
            };

            HandleMessaging.SendMessage <LoanResponse>(Queues.NORMALIZER_OUT, loanResponse);
        }
Beispiel #12
0
        public async Task <IActionResult> EditAsync(UpdateLoanViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("DetailsView", new { Area = "Loan", uid = model.UID, errorMessage = $"{GlobalConstants.ERROR_ACTION_PREFIX} update {ENTITY_NAME} details." }));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(model.UID);

            if (_Loan == null)
            {
                return(RedirectToAction("DetailsView", new { Area = "Loan", uid = model.UID, errorMessage = $"{GlobalConstants.ERROR_ACTION_PREFIX} find {ENTITY_NAME} details." }));
            }

            UpdateLoanRequest _Request = new UpdateLoanRequest
            {
                UID                        = model.UID,
                FromTimestamp              = model.StartTimestamp,
                ExpiryTimestamp            = model.ExpiryTimestamp,
                AcceptedTermsAndConditions = model.AcceptedTermsAndConditions
            };

            if (model.AcceptedTermsAndConditions)
            {
                if (_Loan.Status == Enums.Loan.Status.Pending)
                {
                    if (model.StartTimestamp <= DateTime.Now)
                    {
                        _Request.Status = Enums.Loan.Status.ActiveLoan;
                    }
                    else
                    {
                        _Request.Status = Enums.Loan.Status.InactiveLoan;
                    }
                }
            }

            BaseResponse _Response = await __LoanManager.UpdateAsync(_Request);

            if (!_Response.Success)
            {
                return(RedirectToAction("DetailsView", new { Area = "Loan", uid = model.UID, errorMessage = $"{GlobalConstants.ERROR_ACTION_PREFIX} update {ENTITY_NAME} details." }));
            }

            return(RedirectToAction("DetailsView", new { Area = "Loan", uid = model.UID, successMessage = $"{GlobalConstants.SUCCESS_ACTION_PREFIX} updated {ENTITY_NAME} details." }));
        }
Beispiel #13
0
        public async Task <IActionResult> CreateAsync(ConfirmationLoanViewModel model)
        {
            if (!ModelState.IsValid)
            {
                if (model.ExpiryTimestamp <= model.FromTimestamp)
                {
                    ModelState.AddModelError("Error", "Schedule From field must be less than Schedule To");
                    return(View("CreateLoan", model));
                }

                IList <LoanResponse> _Loans            = (await __LoanManager.GetAsync()).Where(loan => loan.Status != Enums.Loan.Status.Complete && loan.Status != Enums.Loan.Status.EarlyComplete).ToList();
                List <Guid>          _ExcludeEquipment = new List <Guid>();
                foreach (LoanResponse loan in _Loans)
                {
                    IList <LoanEquipmentResponse> _LoanEquipment = await __LoanEquipmentManager.GetAsync(loan.UID);

                    _ExcludeEquipment.AddRange(_LoanEquipment.Select(x => x.EquipmentUID));
                }
                _ExcludeEquipment = _ExcludeEquipment.Distinct().ToList();

                CreateLoanViewModel _CreateLoanViewModel = new CreateLoanViewModel
                {
                    EquipmentSelectList = __Mapper.Map <IList <Equipment.Models.EquipmentViewModel> >((await __EquipmentManager.GetAsync()).Where(x => x.Status == NsEquipmentEnum.Status.Available && !_ExcludeEquipment.Contains(x.UID))),
                    UserSelectList      = await __UserRepository.GetAsync(),
                    Blacklists          = __Mapper.Map <IList <Admin.Models.Blacklist.BlacklistViewModel> >(await __BlacklistManager.GetAsync())
                };

                ModelState.AddModelError("Error", "Unable to create Loan");
                return(View("CreateLoan", _CreateLoanViewModel));
            }

            model.LoanerEmail = __UserManager.GetUserAsync(HttpContext.User).Result.Email;
            LoanResponse _Response = await __LoanManager.CreateAsync(__Mapper.Map <CreateLoanRequest>(model));

            if (!_Response.Success)
            {
                ModelState.AddModelError("Error", _Response.Message);
                return(View("CreateLoan", model));
            }

            LoanResponse _LoanResponse = await __LoanManager.GetByUIDAsync(_Response.UID);

            await __EmailScheduleManager.CreateLoanConfirmScheduleAsync(_LoanResponse, $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}", true);

            return(RedirectToAction("Index", "Loan", new { Area = "Loan", successMessage = $"{GlobalConstants.SUCCESS_ACTION_PREFIX} created {ENTITY_NAME}." }));
        }
Beispiel #14
0
        public async Task <IActionResult> AcceptTermsAndConditionsViewAsync(Guid loanUID)
        {
            if (loanUID == null || loanUID == Guid.Empty)
            {
                return(Json("Page not found"));
            }

            LoanResponse _Response = await __LoanManager.GetByUIDAsync(loanUID);

            if (_Response == null)
            {
                return(Json("Page not found"));
            }

            LoanViewModel _LoanViewModel = __Mapper.Map <LoanViewModel>(_Response);
            IList <Guid>  _EquipmentUIDs = (await __LoanEquipmentManager.GetAsync(_Response.UID)).Select(x => x.EquipmentUID).ToList();

            if (_EquipmentUIDs != null && _EquipmentUIDs.Count > 0)
            {
                _LoanViewModel.EquipmentList = __Mapper.Map <IList <Equipment.Models.EquipmentViewModel> >((await __EquipmentManager.GetAsync(_EquipmentUIDs)).Equipments);
            }

            if (_Response.AcceptedTermsAndConditions)
            {
                AlreadyAcceptedTermsAndConditionsViewModel _AlreadyAcceptedModel = new AlreadyAcceptedTermsAndConditionsViewModel
                {
                    UID      = loanUID,
                    Accepted = _Response.AcceptedTermsAndConditions,
                    Loan     = _LoanViewModel
                };

                return(View("AlreadyAcceptedTermsAndConditions", _AlreadyAcceptedModel));
            }

            AcceptTermsAndConditionsViewModel _Model = new AcceptTermsAndConditionsViewModel
            {
                UID      = loanUID,
                Accepted = _Response.AcceptedTermsAndConditions,
                Loan     = _LoanViewModel,
                TermsAndConditionsStatement = (await __ConfigurationManager.GetByNormalizedNameAsync(__Configuration.GetValue <string>("Configuration:Loan:TERMS_AND_CONDITIONS")))?.Value ?? string.Empty
            };

            return(View("AcceptTermsAndConditions", _Model));
        }
        public static void Main(string[] args)
        {
            Console.Title = "RabbitMQXMLBankNormalizer";
            Console.SetWindowSize(80, 5);
            HandleMessaging.RecieveMessage(Queues.RABBITMQXMLBANK_OUT, (object model, BasicDeliverEventArgs ea) =>
            {
                Console.WriteLine("<--Message recieved on queue: " + Queues.RABBITMQXMLBANK_OUT);
                try
                {
                    LoanResponse loanResponse;
                    XMLBankResponse bankResponse;
                    System.Xml.Serialization.XmlSerializer serializer;

                    serializer = new System.Xml.Serialization.XmlSerializer(typeof(XMLBankResponse));

                    using (TextReader reader = new StringReader(Encoding.UTF8.GetString(ea.Body)))
                    {
                        bankResponse = serializer.Deserialize(reader) as XMLBankResponse;

                        loanResponse = new LoanResponse()
                        {
                            InterestRate = bankResponse.InterestRate,
                            SSN          = bankResponse.SSN,
                            BankName     = ea.RoutingKey.Split('_')[1] // Gets the bank name from the queue name
                        };
                    }

                    Console.WriteLine("<--Sending message on queue: " + Queues.NORMALIZER_OUT);
                    Console.WriteLine();
                    HandleMessaging.SendMessage <LoanResponse>(Queues.NORMALIZER_OUT, loanResponse);
                }
                catch (Exception ex)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                    Console.BackgroundColor = ConsoleColor.Black;
                }
            });
        }
Beispiel #16
0
        public async Task <IActionResult> ForceCompleteAsync(ForceCompleteLoanViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(model));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(model.UID);

            if (_Loan == null)
            {
                return(Json(new { error = $"{GlobalConstants.ERROR_ACTION_PREFIX} find {ENTITY_NAME}." }));
            }

            if (DateTime.Now >= _Loan.ExpiryTimestamp)
            {
                await __LoanManager.ChangeStatusAsync(_Loan.UID, Status.Complete);
            }
            else
            {
                await __LoanManager.ChangeStatusAsync(_Loan.UID, Status.EarlyComplete);
            }

            await __LoanManager.CompleteLoanAsync(model.UID);

            foreach (LoanEquipmentResponse loanEquipment in await __LoanEquipmentManager.GetAsync(model.UID))
            {
                await __EquipmentManager.UpdateStatusAsync(loanEquipment.EquipmentUID, NsEquipmentEnum.Status.Available);
            }

            EmailScheduleResponse _Schedule = (await __EmailScheduleManager.GetAsync()).FirstOrDefault(s => s.Sent == false && s.RecipientEmailAddress == _Loan.LoaneeEmail && s.SendTimestamp == _Loan.ExpiryTimestamp);

            if (_Schedule != null)
            {
                await __EmailScheduleManager.UpdateSentAsync(_Schedule.UID, true);
            }

            return(Json(new { success = $"{GlobalConstants.SUCCESS_ACTION_PREFIX} completed {ENTITY_NAME}." }));
        }
Beispiel #17
0
        public async Task <IActionResult> AcceptTermsAndConditionsAsync(AcceptTermsAndConditionsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewData["ErrorMessage"] = "Invalid form submission";
                return(View("AcceptTermsAndConditions", model));
            }

            BaseResponse _Response = await __LoanManager.AcceptTermsAndConditions(model.UID);

            if (!_Response.Success)
            {
                ModelState.AddModelError("Error", _Response.Message);
                return(await AcceptTermsAndConditionsViewAsync(model.UID));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(model.UID);

            await __EmailScheduleManager.CreateLoanConfirmedScheduleAsync(_Loan, $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}", true);

            return(View("AcceptedTermsAndConditions"));
        }
Beispiel #18
0
        public async Task <IActionResult> ForceCompleteModalAsync(Guid uid)
        {
            if (uid == Guid.Empty)
            {
                return(Json(new { error = $"{GlobalConstants.ERROR_ACTION_PREFIX} find {ENTITY_NAME}." }));
            }

            LoanResponse _Loan = await __LoanManager.GetByUIDAsync(uid);

            if (_Loan == null)
            {
                return(Json(new { error = $"{GlobalConstants.ERROR_ACTION_PREFIX} find {ENTITY_NAME}." }));
            }

            ForceCompleteLoanViewModel _Model = new ForceCompleteLoanViewModel
            {
                UID             = uid,
                LoaneeEmail     = _Loan.LoaneeEmail,
                StartTimestamp  = _Loan.FromTimestamp,
                ExpiryTimestamp = _Loan.ExpiryTimestamp
            };

            return(PartialView("_ForceCompleteModal", _Model));
        }
Beispiel #19
0
        public void StartReceiving()
        {
            LoanResponse loanResponse;

            var consumer = new EventingBasicConsumer(rabbitConn.Channel);

            //We set noAck to false so consumer would not acknowledge that you have received and processed the message and remove it from the queue;
            //This is done to ensure that the message has been processed before it is remove from the queue it is consumed from.
            //this way, if the program has a breakdown, the message will still be on the queue and another can consume the message and process it.
            rabbitConn.Channel.BasicConsume(queue: receiveQueueName,
                                            noAck: false,
                                            consumer: consumer);
            rabbitConn.Channel.BasicConsume(queue: requestInfoQueueName,
                                            noAck: false,
                                            consumer: consumer);
            //If a message is detected then it consumes it, and process it
            consumer.Received += (model, ea) =>
            {
                var body   = ea.Body;
                var header = ea.BasicProperties;

                //if the consumer get a message from the recipient list it will store up to 3 loanRequest at the time
                if (ea.RoutingKey == requestInfoQueueName && requests.Count < 4)
                {
                    LoanRequest loanRequest   = JsonConvert.DeserializeObject <LoanRequest>(Encoding.UTF8.GetString(body));
                    string      stringRequest = Encoding.UTF8.GetString(body);
                    //saves it in a dictionary
                    requests.Add(header, loanRequest);

                    //Acknowledge that the message has been received and processed, then release the message from the queue, allowing us to take in the next message
                    rabbitConn.Channel.BasicAck(ea.DeliveryTag, false);
                }
                // if the message is from the normalizer and there at lest one loanRequest in the dictionary
                else if (ea.RoutingKey == receiveQueueName && requests.Count != 0)
                {
                    if (requests.First().Key.CorrelationId == header.CorrelationId)
                    {
                        loanResponse = JsonConvert.DeserializeObject <LoanResponse>(Encoding.UTF8.GetString(body));
                        responses.Add(loanResponse);
                        bankCount++;
                        //Acknowledge that the message has been received and processed, then release the message from the queue, allowing us to take in the next message
                        rabbitConn.Channel.BasicAck(ea.DeliveryTag, false);
                        Console.WriteLine();
                        Console.WriteLine(" [x] Received {0}", loanResponse.ToString());
                        //checks and see if all banks there has been sent this loanRequest has answered.
                        if (bankCount == requests.First().Value.Banks.Count)
                        {
                            //finds the best offer of the banks
                            bestRate = BestOffer();
                            string bestoffer = "The best offer on: " + bestRate.SSN + " loan request, is from: " + bestRate.BankName +
                                               " which offer an interest rate on: " + bestRate.InterestRate;
                            //send the best offer to the original loanRequests ReplyTo Queue
                            rabbitConn.Send(bestoffer, requests.First().Key.ReplyTo, requests.First().Key, false);

                            aTimer.Stop();

                            bankCount = 0;

                            requests.Remove(requests.First().Key);
                            responses.Clear();
                        }
                    }
                    else
                    {
                        //release the message from the queue, allowing us to take in the next message
                        rabbitConn.Channel.BasicReject(ea.DeliveryTag, true);
                    }
                }
                else
                {
                    //basic.reject will do: if you supply requeue=false it will discard the message
                    //if you supply requeue=true, it will release it back on to the queue, to be delivered again.
                    //release the message from the queue, allowing us to take in the next message
                    rabbitConn.Channel.BasicReject(ea.DeliveryTag, true);
                }
                //if there are any request to check correlationID with start timer, so if the all the banks has not responded within the time limit, it will send what it has
                if (requests.Count > 0)
                {
                    if (!aTimer.Enabled)
                    {
                        aTimer.Start();
                    }
                }
                //If the a set time has past it will find the best offer of the response received and send it
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            };
        }
Beispiel #20
0
        public IPostResponse LoanCamera([FromContent] LoanRequest LoanRequest)
        {
            var Loan = new DeviceLoan {
                Mac = LoanRequest.SerialNumber, Email = LoanRequest.Email, LoanReason = LoanRequest.Reason
            };

            if ((LoanRequest.LoanDays == 1 || LoanRequest.LoanDays == 7 || LoanRequest.LoanDays == 14) == false)
            {
                return(new PostResponse(PostResponse.ResponseStatus.Conflict, null, new ResponseData {
                    Code = 4, Message = "Loan days can only be set to 1,7 or 14", Status = "Failed"
                }));
            }
            var db = new SqliteDB();

            Loan.ExpireDate = DateTime.Now.AddDays(LoanRequest.LoanDays).Ticks;
            var dbres = db.GetLastLoanInfo(Loan);

            if (dbres == null)
            {
                var username = "******" + new Random().Next(1000, 9999).ToString();
                var password = RandomString(16);
                Loan.GeneratedPassword = password;
                Loan.GeneratedUsername = username;

                DeviceList loandevice = new DeviceList {
                    SerialNumber = Loan.Mac
                };
                var loanres = db.GetDevice(loandevice);
                if (loanres == null)
                {
                    return(new PostResponse(PostResponse.ResponseStatus.Conflict, null, new ResponseData {
                        Code = 2, Message = "Device not found", Status = "Failed"
                    }));
                }

                var device = new AxisVapixLib.Device();
                device.Host     = loanres.Host;
                device.Username = loanres.Username;
                device.Password = loanres.Password;

                var userres = Task.Run(async() => await device.AddUser(username, password, AxisVapixLib.Device.UserGroups.Admin));
                while (!userres.IsCompleted)
                {
                    Task.Delay(100);
                }



                if (!userres.Result)
                {
                    return(new PostResponse(PostResponse.ResponseStatus.Conflict, null, new ResponseData {
                        Code = 3, Message = "Failed to create username", Status = "Failed"
                    }));
                }
                var overlay = new AxisVapixLib.Overlay.Overlay(device);
                Task.Run(() => overlay.SetTextOverlayAsync(0, AxisVapixLib.Overlay.Overlay.TextOverlayBackgroundColor.White, false, false, AxisVapixLib.Overlay.Overlay.TextColor.Black, AxisVapixLib.Overlay.Overlay.TextOverlayPosition.Top, "Reserved to " + Loan.Email));

                Loan.LoanDate = DateTime.Now.Ticks;

                db.SaveLoanInfo(Loan);

                EmailController e = new EmailController();
                Task.Run(async() => await e.SendEmail(Loan.Email, "Device Loaned", string.Format("You have successfully loaned\nUrl: {0}\nUsername: {1}\nPassword: {2}, Expires: {3}", device.Host, Loan.GeneratedUsername, Loan.GeneratedPassword, DateTime.FromBinary(Loan.ExpireDate).ToString())));


                LoanResponse lr = new LoanResponse();
                lr.DateExpire     = DateTime.FromBinary(Loan.ExpireDate).ToString();
                lr.DateExpireTick = Loan.ExpireDate;
                lr.SerialNumber   = Loan.Mac;
                lr.Username       = username;
                lr.Password       = password;
                lr.Host           = device.Host;

                return(new PostResponse(PostResponse.ResponseStatus.Created, null, lr));
            }
            var d = new PostResponse(PostResponse.ResponseStatus.Conflict, null, new ResponseData()
            {
                Code = 1, Message = "Already loaned", Status = "Failed"
            });

            return(d);
        }