예제 #1
0
        public MainPresenter(IMainView view)
        {
            _db     = new PaymentContext();
            _fuelDb = new FuelContext();

            _view = view;

            _view.ButtonAddClicked += ButtonAddClicked;
            _view.ComboBoxFuelsSelectedIndexChanged += ComboBoxFuelsSelectedIndexChanged;
            _view.RadioButtonLiterCheckedChanged    += RadioButtonLiterCheckedChanged;
            _view.RadioButtonPriceCheckedChanged    += RadioButtonPriceCheckedChanged;
            _view.ButtonClearClicked          += ButtonClearClicked;
            _view.ButtonLoadClicked           += ButtonLoadClicked;
            _view.TextBoxFuelLiterTextChanged += TextBoxFuelLiterTextChanged;
            _view.TextBoxFuelPriceTextChanged += TextBoxFuelPriceTextChanged;
            _view.PanelFormTopMouseDown       += PanelFormTopMouseDown;
            _view.PanelFormTopMouseMove       += PanelFormTopMouseMove;
            _view.PanelFormTopMouseUp         += PanelFormTopMouseUp;
            _view.PictureBoxCloseMouseEnter   += PictureBoxCloseMouseEnter;
            _view.PictureBoxCloseMouseLeave   += PictureBoxCloseMouseLeave;
            _view.PictureBoxCloseMouseClick   += PictureBoxCloseMouseClick;
            _view.ButtonRemoveClicked         += ButtonRemoveClicked;
            _view.TextBoxKeyPress             += TextBoxKeyPress;
            _view.TextBoxHandleText           += TextBoxHandleText;

            _view.Fuels = _fuelDb.Fuels.ToList();
        }
예제 #2
0
        static void Main(string[] args)
        {
            // var ctx = new PaymentContext((EStrategy)1);
            // ctx.Execute();

            System.Console.WriteLine("Select strategy");
            ConsoleKeyInfo key;

            do
            {
                //while (!Console.KeyAvailable) {
                key = Console.ReadKey();
                System.Console.WriteLine();
                if (int.TryParse(key.KeyChar.ToString(), out var n))
                {
                    if (Enum.IsDefined(typeof(EStrategy), n))
                    {
                        var ctx = new PaymentContext((EStrategy)n);
                        ctx.Execute();
                    }
                    else
                    {
                        System.Console.WriteLine("Wrong type");
                    }
                }
                //}
            } while (key.Key != ConsoleKey.Escape);
        }
예제 #3
0
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            using (var ctx = new PaymentContext())
            {
                var mode = new PaymentMode();

                mode.Mode = TxtMode.Text;

                int UserId = Convert.ToInt32(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData);

                mode.UserProfileId = UserId;

                mode.IsDeleted = false;

                if (ctx.PaymentModes.Any(x => (x.Mode == TxtMode.Text) && x.UserProfileId == UserId))
                {
                    LblMessage.Text = null;
                    LblError.Text   = "* Payment mode already exists!";
                }
                else
                {
                    ctx.PaymentModes.Add(mode);
                    ctx.SaveChanges();
                    LblError.Text   = null;
                    LblMessage.Text = "Payment mode Added";
                }
            }
            GridViewModes.DataBind();
            TxtMode.Text = null;
        }
        public void GivenAPaymentRecordIdTheExistsInTheContextIsProvided_WhenGettingIt_ThenItReturnsThePaymentRecord()
        {
            // Given

            using var localTestContext = new PaymentContext(new DbContextOptionsBuilder <PaymentContext>()
                                                            .UseInMemoryDatabase(databaseName: $"PaymentDatabase-Test-{Guid.NewGuid()}")
                                                            .Options);

            var mockedLogger        = Substitute.For <ILogger <Domain.PaymentRepository.PaymentRepository> >();
            var mockedDataEncryptor = Substitute.For <IDataEncryptor>();

            var realPaymentRepository = new Domain.PaymentRepository.PaymentRepository(mockedLogger, localTestContext, mockedDataEncryptor);

            var expectedId = Guid.NewGuid();

            var expectedPaymentRecord = new PaymentRecord {
                PaymentGatewayId = expectedId
            };

            localTestContext.Payments.Add(expectedPaymentRecord);
            localTestContext.SaveChanges();

            // When

            var response = realPaymentRepository.Get(expectedId).GetAwaiter().GetResult();

            // Then

            response.Should().NotBeNull();
            response.Should().BeOfType <PaymentRecord>();
            response.PaymentGatewayId.Should().Be(expectedId);
        }
예제 #5
0
 public OrderStatusChangedToStockConfirmedIntegrationEventHandler(IPublishEndpoint endpoint,
                                                                  IOptionsSnapshot <PaymentSettings> settings, PaymentContext context)
 {
     _endpoint = endpoint;
     _settings = settings.Value;
     _context  = context;
 }
 public PaymentsController(PaymentContext paymentContext,
                           IPaymentGatewaySelector paymentGatewaySelector, IPaymentUpdater paymentUpdater)
 {
     _paymentGatewaySelector = paymentGatewaySelector;
     _paymentContext         = paymentContext;
     _paymentUpdater         = paymentUpdater;
 }
예제 #7
0
        public async Task <PaymentExpVat> PostPaymentVat(PostPaymentVAT model)
        {
            var output = new PaymentExpVat();

            try
            {
                output.OrderCode          = model.OrderCode;
                output.CompanyName        = model.CompanyName;
                output.TaxCode            = model.TaxCode;
                output.BuyerName          = model.BuyerName;
                output.CompanyAddress     = model.CompanyAddress;
                output.ReceiveBillAddress = model.ReceiveBillAddress;
                output.CreateBy           = Guid.Parse(model.UserId);
                output.CreateDate         = DateTime.Now;
                output.LastEditBy         = Guid.Parse(model.UserId);
                output.LastEditDate       = DateTime.Now;
                output.Email = model.Email;
                PaymentContext.PaymentExpVat.Add(output);
                await PaymentContext.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(output);
        }
예제 #8
0
        public async Task <PaymentContext> ExecutePaymentAsync(PaymentContext PaymentCtx, string PayerId)
        {
            using (var client = await _connectionManager.CreateClientAsync(Settings)) {
                try {
                    var response = await client.PostAsJsonAsync("v1/payments/payment/" + PaymentCtx.Payment.Id + "/execute", new { payer_id = PayerId });

                    if (response.IsSuccessStatusCode)
                    {
                        var executedPayment = await response.Content.ReadAsAsync <Payment>();

                        return(new PaymentContext()
                        {
                            UseSandbox = PaymentCtx.UseSandbox,
                            Payment = executedPayment
                        });
                    }
                    else
                    {
                        var errorMsg = await response.Content.ReadAsStringAsync();

                        Logger.Error("Payment execution failed. ({0}) {1}\r\n{2}", response.StatusCode, response.ReasonPhrase, errorMsg);
                        throw new OrchardException(T("Payment execution failed."));
                    }
                }
                catch (Exception exp) {
                    throw new OrchardException(T("Payment execution failed."), exp);
                }
            }
        }
        public void VerifyAddFirstAidVideoCalledOnce()
        {
            #region Arrange
            PaymentContext payment = new PaymentContext()
            {
                Amount     = 1000,
                Type       = PaymentType.Learning,
                CustomerId = Guid.NewGuid(),
                OrderId    = Guid.NewGuid(),
            };
            var mockPayment = new Mock <IRuleAction>();
            mockPayment.Setup(m => m.AddFirstAidVideo(It.IsAny <PaymentContext>())).Returns(true);
            var rules = new List <IRule>()
            {
                new LearningRule(mockPayment.Object)
            };
            RuleEngine ruleEngine = new RuleEngine(rules);

            #endregion
            #region Act
            ruleEngine.Execute(payment);
            #endregion

            #region Assert
            mockPayment.Verify(m => m.AddFirstAidVideo(It.IsAny <PaymentContext>()), Times.Once);
            #endregion
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PaymentContext context)
        {
            if (env.IsDevelopment())
            {
                context.Database.EnsureCreated();

                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // Enable swagger middleware
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Payment API V1");
            });
        }
예제 #11
0
 public MainViewPresenter(IMainView view)
 {
     _view = view;
     _view.AddButtonClick  += ViewAddButtonClick;
     _view.LoadButtonClick += ViewLoadButtonClick;
     _db = new PaymentContext();
 }
        public void VerifySendEmailCalledOnce()
        {
            #region Arrange
            PaymentContext payment = new PaymentContext()
            {
                Amount     = 1000,
                Type       = PaymentType.UpgradeMembership,
                CustomerId = Guid.NewGuid(),
                OrderId    = Guid.NewGuid(),
            };
            var mockPayment = new Mock <IRuleAction>();
            mockPayment.Setup(m => m.SendEmail(It.IsAny <PaymentContext>())).Returns(true);
            var rules = new List <IRule>()
            {
                new UpgradeMembershipRule(mockPayment.Object)
            };
            RuleEngine ruleEngine = new RuleEngine(rules);

            #endregion
            #region Act
            ruleEngine.Execute(payment);
            #endregion

            #region Assert
            mockPayment.Verify(m => m.SendEmail(It.IsAny <PaymentContext>()), Times.Once);
            #endregion
        }
예제 #13
0
        public void VerifyDuplicatePackagingSlipCalledOnce()
        {
            #region Arrange
            PaymentContext payment = new PaymentContext()
            {
                Amount     = 1000,
                Type       = PaymentType.Book,
                CustomerId = Guid.NewGuid(),
                OrderId    = Guid.NewGuid(),
            };
            var mockPayment = new Mock <IRuleAction>();
            mockPayment.Setup(m => m.DuplicatePackagingSlip(It.IsAny <PaymentContext>())).Returns(true);
            var rules = new List <IRule>()
            {
                new PhysicalProductRule(mockPayment.Object),
                new LearningRule(mockPayment.Object),
                new BookRule(mockPayment.Object)
            };
            RuleEngine ruleEngine = new RuleEngine(rules);

            #endregion
            #region Act
            ruleEngine.Execute(payment);
            #endregion

            #region Assert
            mockPayment.Verify(m => m.DuplicatePackagingSlip(It.IsAny <PaymentContext>()), Times.Once);
            #endregion
        }
예제 #14
0
        public static void SeedProcedure()
        {
            PaymentContext context = new PaymentContext();

            int entitiesToGenerate = SetEntitiesToGenerate();

            Console.WriteLine("Generating values...");

            User[] userEntities = GenerateUsers(entitiesToGenerate);
            context.Users.AddRange(userEntities);

            CreditCard[] creditCards = GenerateUsersCreditCards(entitiesToGenerate);
            context.CreditCards.AddRange(creditCards);

            BankAccount[] bankAccounts = GenerateBankAccounts(entitiesToGenerate);
            context.BankAccounts.AddRange(bankAccounts);

            context.SaveChanges();

            // Add payments methods
            PaymentMethod[] paymentMethods = GeneratePaymentMethods(context);
            context.PaymentMethods.AddRange(paymentMethods);

            context.SaveChanges();

            Console.WriteLine("Seed data successful!");
        }
예제 #15
0
        /// <summary>
        /// This method takes paymet as an input, Process the payment and returns list of actions performed during processing of the payment
        /// </summary>
        /// <param name="payment"></param>
        /// <returns></returns>
        public List <string> ProcessPayment(Payment payment)
        {
            //Create a payment context object
            PaymentContext paymentContext = new PaymentContext
            {
                Payment = payment
            };

            //Create list of IRules instance defined in this assembly
            List <Type> ruleTypes = Assembly.GetExecutingAssembly().GetTypes().Where(type => type.GetInterfaces().Contains(typeof(IRule))).ToList();

            //stores object of IRule type
            List <IRule> rules = new List <IRule>();

            foreach (var ruleType in ruleTypes)
            {
                //Create a instance of IRule type defined
                rules.Add((IRule)Activator.CreateInstance(ruleType));
            }

            //For each rule process the payment context if processing precondition satisfied
            foreach (var rule in rules)
            {
                //check if pre condition is satisfied
                if (rule.ShouldProcess(paymentContext))
                {
                    //do processing
                    rule.Process(paymentContext);
                }
            }

            return(paymentContext.GetActionPerformed());
        }
예제 #16
0
        public void VerifyGenerateCommisionPaymentCalledNeverIfRuleIsNotApplicable()
        {
            #region Arrange
            PaymentContext payment = new PaymentContext()
            {
                Amount     = 1000,
                Type       = PaymentType.Learning,
                CustomerId = Guid.NewGuid(),
                OrderId    = Guid.NewGuid(),
            };
            var mockPayment = new Mock <IRuleAction>();
            mockPayment.Setup(m => m.GenerateCommisionPayment(It.IsAny <PaymentContext>())).Returns(true);
            var rules = new List <IRule>()
            {
                new PhysicalProductRule(mockPayment.Object)
            };
            RuleEngine ruleEngine = new RuleEngine(rules);
            #endregion

            #region Act
            ruleEngine.Execute(payment);
            #endregion

            #region Assert
            mockPayment.Verify(m => m.GenerateCommisionPayment(It.IsAny <PaymentContext>()), Times.Never);
            #endregion
        }
        public void VerifyUppgradeMemberShipCalledNeverIfRuleIsNotApplicable()
        {
            #region Arrange
            PaymentContext payment = new PaymentContext()
            {
                Amount     = 1000,
                Type       = PaymentType.Book,
                CustomerId = Guid.NewGuid(),
                OrderId    = Guid.NewGuid(),
            };
            var mockPayment = new Mock <IRuleAction>();
            mockPayment.Setup(m => m.AddFirstAidVideo(It.IsAny <PaymentContext>())).Returns(true);
            var rules = new List <IRule>()
            {
                new UpgradeMembershipRule(mockPayment.Object)
            };
            RuleEngine ruleEngine = new RuleEngine(rules);

            #endregion
            #region Act
            ruleEngine.Execute(payment);
            #endregion

            #region Assert
            mockPayment.Verify(m => m.UppgradeMemberShip(It.IsAny <PaymentContext>()), Times.Never);
            #endregion
        }
예제 #18
0
        public async Task <PaymentContext> ExecutePaymentAsync(PaymentContext PaymentCtx, string PayerId)
        {
            if (PaymentCtx == null || PaymentCtx.ValidUntil < _clock.UtcNow)
            {
                throw new OrchardException(T("Invalid PaymentContext."));
            }
            using (var client = CreateClient(PaymentCtx.UseSandbox, PaymentCtx.Token)) {
                try {
                    var response = await client.PostAsJsonAsync("v1/payments/payment/" + PaymentCtx.Payment.Id + "/execute", new { payer_id = PayerId });

                    if (response.IsSuccessStatusCode)
                    {
                        var executedPayment = await response.Content.ReadAsAsync <Payment>();

                        return(new PaymentContext()
                        {
                            UseSandbox = PaymentCtx.UseSandbox,
                            Payment = executedPayment,
                            Token = PaymentCtx.Token
                        });
                    }
                    else
                    {
                        var errorMsg = await response.Content.ReadAsStringAsync();

                        Logger.Error("Payment execution failed. ({0}) {1}\r\n{2}", response.StatusCode, response.ReasonPhrase, errorMsg);
                        throw new OrchardException(T("Payment execution failed."));
                    }
                }
                catch (Exception exp) {
                    throw new OrchardException(T("Payment execution failed."), exp);
                }
            }
        }
        public void GivenAPendingPaymentRecordIsProvided_WhenUpsertingIt_ThenItAddsToTheContext()
        {
            // Given

            using var localTestContext = new PaymentContext(new DbContextOptionsBuilder <PaymentContext>()
                                                            .UseInMemoryDatabase(databaseName: $"PaymentDatabase-Test-{Guid.NewGuid()}")
                                                            .Options);

            var mockedLogger        = Substitute.For <ILogger <Domain.PaymentRepository.PaymentRepository> >();
            var mockedDataEncryptor = Substitute.For <IDataEncryptor>();

            var realPaymentRepository = new Domain.PaymentRepository.PaymentRepository(mockedLogger, localTestContext, mockedDataEncryptor);

            var expectedId            = Guid.NewGuid();
            var expectedPaymentRecord = new PaymentRecord
            {
                PaymentGatewayId = expectedId,
                PaymentStatus    = PaymentStatus.Pending
            };

            // When

            realPaymentRepository.Upsert(expectedPaymentRecord).GetAwaiter().GetResult();

            var actualPaymentRecord = realPaymentRepository.Get(expectedId).GetAwaiter().GetResult();

            // Then

            actualPaymentRecord.Should().NotBeNull();
            actualPaymentRecord.Should().BeOfType <PaymentRecord>();
            actualPaymentRecord.PaymentGatewayId.Should().Be(expectedId);
        }
예제 #20
0
    static void Main(string[] args)
    {
        Console.WriteLine("Please Select Payment Type : CreditCard or DebitCard or Cash");
        string PaymentType = Console.ReadLine();

        Console.WriteLine("Payment type is : " + PaymentType);
        Console.WriteLine("\nPlease enter Amount to Pay : ");
        double Amount = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Amount is : " + Amount);
        PaymentContext context = new PaymentContext();

        if ("CreditCard".Equals(PaymentType, StringComparison.InvariantCultureIgnoreCase))
        {
            context.SetPaymentStrategy(new CreditCardPaymentStrategy());
        }
        else if ("DebitCard".Equals(PaymentType, StringComparison.InvariantCultureIgnoreCase))
        {
            context.SetPaymentStrategy(new DebitCardPaymentStrategy());
        }
        else if ("Cash".Equals(PaymentType, StringComparison.InvariantCultureIgnoreCase))
        {
            context.SetPaymentStrategy(new CashPaymentStrategy());
        }
        context.Pay(Amount);
        Console.ReadKey();
    }
예제 #21
0
 public WxPayController(wx.IWxPayPaymentService service, PaymentContext context, ILogger <WxPayController> logger, SignatureService signatureService, INotifyService notifyService)
 {
     this.paymentService   = service;
     this.context          = context;
     this.logger           = logger;
     this.signatureService = signatureService;
     this.notifyService    = notifyService;
 }
 public ReadPaymentProcessController(PaymentContext context,
                                     IPaymentProcessGetAllQuery paymentProcessGetAllQuery,
                                     IPaymentProcessGetByIdQuery paymentProcessGetByIdQuery)
 {
     _context      = context;
     _getAllQuery  = paymentProcessGetAllQuery;
     _getByIDQuery = paymentProcessGetByIdQuery;
 }
예제 #23
0
 public async void ShouldNotMakePaymentForInactiveSession(Card paymentCard)
 {
     using (var context = new PaymentContext(optionsFactory))
     {
         DbPaymentRepository repository = new DbPaymentRepository(context);
         await Assert.ThrowsAsync <PaymentException>(() => repository.MakePaymentAsync(Guid.Empty, paymentCard));
     }
 }
예제 #24
0
 public async void ShouldNotAcceptAnyGuidAsActiveSessionId()
 {
     using (var context = new PaymentContext(optionsFactory))
     {
         DbPaymentRepository repository = new DbPaymentRepository(context);
         await Assert.ThrowsAsync <SessionException>(() => repository.SessionIsActiveAsync(Guid.Empty));
     }
 }
예제 #25
0
 public async void ShouldRememberSession(PaymentRequest payment)
 {
     using (var context = new PaymentContext(optionsFactory))
     {
         DbPaymentRepository repository = new DbPaymentRepository(context);
         await repository.SessionIsActiveAsync(await repository.RecordPaymentAsync(payment));
     }
 }
예제 #26
0
        protected void BtnSave_Click(object sender, EventArgs e)
        {
            bool amountIsValid = true;

            using (var ctx = new PaymentContext())
            {
                var payment = new Payment();
                payment.TransactionDate = DateTime.Parse(TxtDate.Text);

                payment.UserProfileId = Convert.ToInt32(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket.UserData);
                try
                {
                    payment.Amount = decimal.Parse(TxtAmount.Text);
                }
                catch
                {
                    amountIsValid = false;
                }

                payment.CategoryId = int.Parse(DropDownCategory.SelectedValue);

                payment.IsCredit = CheckBoxIsCredit.Checked;

                try
                {
                    payment.BeneficiaryId = int.Parse(DropDownBeneficiary.SelectedValue);
                }
                catch
                {
                    payment.BeneficiaryId = null;
                }

                payment.PaymentModeId = int.Parse(DropDownMode.SelectedValue);

                payment.PaymentDetails = TxtDetails.Text;

                if (amountIsValid)
                {
                    ctx.Payments.Add(payment);
                    ctx.SaveChanges();
                    TxtDate.Text   = null;
                    TxtAmount.Text = null;
                    DropDownCategory.SelectedValue    = null;
                    CheckBoxIsCredit.Checked          = false;
                    DropDownBeneficiary.SelectedValue = null;
                    TxtDetails.Text = null;
                    LblError.Text   = null;
                    LblMessage.Text = "Payment Added";
                }
                else
                {
                    if (!amountIsValid)
                    {
                        LblError.Text = "Invalid Amount!";
                    }
                }
            }
        }
예제 #27
0
 public Payment(IPaymentGateway paymentGateway, PaymentContext paymentContext)
 {
     _PaymentContext        = paymentContext;
     _Encryption            = new RSAEncryption();
     _PaymentGatewayFactory = new PaymentGatewayFactory();
     _PeopleRepo            = new GenericRepository <Person>(paymentGateway, paymentContext);
     _CardInfoRepo          = new GenericRepository <CardInformation>(paymentGateway, paymentContext);
     _TransactionRepo       = new GenericRepository <Transactions>(paymentGateway, paymentContext);
 }
예제 #28
0
 public async Task <PaymentLog> SavePaymentLog(PaymentLog model)
 {
     if (model != null)
     {
         PaymentContext.PaymentLog.Add(model);
         PaymentContext.SaveChanges();
     }
     return(model);
 }
        public void FixtureSetUp()
        {
            PaymentContext.Delete();
            var context = Activator.CreateInstance <PaymentContext>();

            context.Database.Create();
            DatabaseInitializer.Seed(context);
            InitializeNakedObjectsFramework(this);
        }
예제 #30
0
 public PaymentMutations(PaymentContext context, IEventService template1EventService, IMapper mapper,
                         IAuthorizationService authorizationService, StripeService stripeService, IPaymentService service) : base(authorizationService)
 {
     _context = context ?? throw new ArgumentNullException(nameof(context));
     ;
     _eventService  = template1EventService ?? throw new ArgumentNullException(nameof(template1EventService));
     _mapper        = mapper;
     _stripeService = stripeService;
     _service       = service;
 }