private void loadSomeData()
 {
     if (customers == null)
     {
         CustomerService customerService = new CustomerService();
         customers = customerService.GetCustomers().OrderBy(x => x.CustCode).ToList();
         customers.Insert(0, new Customer() { Id = 0, CustCode = "", CustomerName = "" });
     }
     if (customers != null)
     {
         cbxCustomer.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
         cbxCustomer.AutoCompleteSource = AutoCompleteSource.ListItems;
         cbxCustomer.DataSource = customers;
         cbxCustomer.DisplayMember = "CustCode";
         cbxCustomer.ValueMember = "Id";
     }
     if (bill != null)
     {
         txtAmount.Text = Global.formatVNDCurrencyText(bill.Amount.ToString());
         txtAmount.Enabled = false;
         txtCreatedDate.Text = bill.CreatedDate.ToString(BHConstant.DATE_FORMAT);
         txtNote.Text = bill.Note;
         txtOrderCode.Text = bill.BillCode;
         cbxCustomer.SelectedValue = bill.CustId;
         cbxCustomer.Enabled = false;
         btnSave.Text = "OK";
     }
     else
     {
         txtCreatedDate.Text = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate().ToString(BHConstant.DATE_FORMAT);
         txtOrderCode.Text = Global.GetTempSeedID(BHConstant.PREFIX_FOR_BILLING);
     }
     txtCreatedDate.Enabled = false;
 }
예제 #2
0
파일: User.cs 프로젝트: NanQi/demo
		/// <summary>
		///  更新一条数据
		/// </summary>
		public bool Update(CustomerService.Model.User model)
		{
			int rowsAffected=0;
			SqlParameter[] parameters = {
					new SqlParameter("@GUID", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@uID", SqlDbType.VarChar,50),
					new SqlParameter("@pwd", SqlDbType.VarChar,50),
					new SqlParameter("@power", SqlDbType.VarChar,500),
					new SqlParameter("@uName", SqlDbType.VarChar,20),
					new SqlParameter("@isEnable", SqlDbType.Bit,1),
					new SqlParameter("@isOnline", SqlDbType.Bit,1),
					new SqlParameter("@createDate", SqlDbType.DateTime)};
			parameters[0].Value = model.GUID;
			parameters[1].Value = model.uID;
			parameters[2].Value = model.pwd;
			parameters[3].Value = model.power;
			parameters[4].Value = model.uName;
			parameters[5].Value = model.isEnable;
			parameters[6].Value = model.isOnline;
			parameters[7].Value = model.createDate;

			DbHelperSQL.RunProcedure("T_User_Update",parameters,out rowsAffected);
			if (rowsAffected > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
예제 #3
0
        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            CustomerService cusService = new CustomerService();

            try
            {
                Customer obj = new Customer()
                    {
                        ID = Convert.ToInt32(txtID.Text),
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        Address = txtAddress.Text,
                        City = txtCity.Text,
                        State = txtState.Text,
                        Country = txtCountry.Text,
                        Email = txtEmail.Text,
                        Phone = txtPhone.Text,
                        mobile = txtMobile.Text
                    };

                cusService.AddNew(obj);
                ClearNewCustomerFields();
                MessageBox.Show(this, "Customer Added.", "Succeed", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Customer Insert Fail : " + ex.Message);
            }
        }
예제 #4
0
 public CustomersVM(CustomerService customersService)
 {
     _customersService = customersService;
     _addCustomerCommand = new Command(() => AddCustomer());
     _saveCustomersCommand = new Command(async () => await SaveCustomersAsync());
     _loadCustomersCommand = new Command(async () => await LoadCustomersAsync());
     _deleteSelectedCommand = new Command(async () => await DeleteSelectedItemAsync());
 }
예제 #5
0
        // GET /api/values
        public IEnumerable<Customer> Get()
        {
            List<Customer> customerList = new List<Customer>();
              CustomerService customerService = new CustomerService();

              customerList = customerService.GetCustomers();
              return customerList;
        }
예제 #6
0
 /// <summary>
 /// 实现控制反转
 /// </summary>
 /// <param name="moduleFunctionRepos"></param>
 public Admin_EmployeeController(IEmployeeRepository employeeRepos, IRoleRepository rolerepos, ICustomerRepository customerrepos, ecoBio.Wms.Backstage.Repositories.IDynamicToken tokenRepos,
       ecoBio.Wms.Backstage.Repositories.IDepartmentListRepository departmentListRepos)
 {
     _roleservice = new RoleService(rolerepos);
     _employeeservice = new EmployeeService(employeeRepos);
     _custoimerservice = new CustomerService(customerrepos);
     _tokenRepos = new Service.Management.DynamicTokenService(tokenRepos);
     _departmentListRepos = new Service.Management.DepartmentListService(departmentListRepos);
 }
예제 #7
0
        // GET /api/values/5
        public Customer Get(int customerID)
        {
            Customer customer = new Customer();
              CustomerService customerService = new CustomerService();

              customer = customerService.GetCustomerByID(customerID);
              return customer;

              //return "value";
        }
            public void Given()
            {
                emailSender = A.Fake<ISendEmail>();

                var customerRepository = A.Fake<ICustomerRepository>();
                A.CallTo(() => customerRepository.GetAllCustomers()).Returns(new List<Customer> { new Customer() });

                var sut = new CustomerService(emailSender, customerRepository);
                sut.SendEmailToAllCustomers();
            }
 public CustomerOrderWindow(OrderService orderService,
                            CustomerService customerService,
                            OrderItemService orderItemService,
                            InventoryItemService inventoryService,
                            MainWindowVM mainVM,
                            EventAggregator eventAggregator)
     : this()
 {
     var vm = new CustomerOrderVM(eventAggregator, orderService, orderItemService, inventoryService, mainVM);
     DataContext = vm;
 }
        public void Given()
        {
            var customerRepository = A.Fake<ICustomerRepository>();
            var customers = new List<Customer>() { new Customer { EmailAddress = "*****@*****.**" } };
            A.CallTo(() => customerRepository.GetAllCustomers()).Returns(customers);

            var emailSender = A.Fake<ISendEmail>();
            A.CallTo(() => emailSender.SendMail(customers)).Throws(new BadCustomerEmailException());

            var sut = new CustomerService(emailSender, customerRepository);
            sut.SendEmailToAllCustomers();
        }
        public void GetAll_InvokesRepository()
        {
            // Arrange
            var mockedRepository = new Mock<ICustomerRepository>();
            var service = new CustomerService(mockedRepository.Object);

            // Act
            service.Get(new Customers());

            // Assert
            mockedRepository.Verify(x => x.GetAll(), Times.Once());
        }
        void LoadCustomers()
        {
            CustomerService customerService = new CustomerService();
            customers = customerService.GetCustomers().OrderBy(x => x.CustCode).ToList();
            customers.Insert(0, new Customer() { Id = 0, CustomerName = "Tất cả", CustCode = "Tất cả"});

            cbmCustomers.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cbmCustomers.AutoCompleteSource = AutoCompleteSource.ListItems;
            cbmCustomers.DataSource = customers;
            cbmCustomers.DisplayMember = "CustCode";
            cbmCustomers.ValueMember = "Id";
        }
예제 #13
0
        public FormLineCanon()
        {
            InitializeComponent();

            _lineService = new LineService();
            _customerService = new CustomerService();
            _processService = new ProcessService();
            _modelService = new ModelService();
            _showResultService = new ShowResultService();
            _shiftService = new ShiftService();
            _timingService = new TimingService();
            _lineProcessService = new LineProcessService();
        }
        public void loadCustomerList()
        {
            EmployeeService service = new EmployeeService();
            List<Employee> salers = service.GetEmployees();
            salers.Add(new Employee() { Id = 0, FullName = "Tất cả" });
            salers = salers.OrderBy(x => x.Id).ToList();
            cmbSaler.DataSource = salers;
            cmbSaler.DisplayMember = "FullName";
            cmbSaler.ValueMember = "Id";

            CustomerService customerService = new CustomerService();
            customers = customerService.GetCustomers();
            setUpDataGrid(customers);
        }
예제 #15
0
        public FormLineDetails(string lineId)
        {
            InitializeComponent();
            _lineService = new LineService();
            _customerService = new CustomerService();
            _processService = new ProcessService();
            _modelService = new ModelService();
            _showResultService = new ShowResultService();
            _shiftService = new ShiftService();


            _line = _lineService.GetLineByName(lineId);
            _lineStatus = _modelService.GetLineStatusByLineAndCustomer(_line.Id_line, _line.Id_customer);
        }
예제 #16
0
        public OpenpayAPI( string api_key, string merchant_id,bool production = false)
        {
            this.httpClient = new OpenpayHttpClient(api_key, merchant_id, production);
            CustomerService = new CustomerService(this.httpClient);
            CardService = new CardService(this.httpClient);
            BankAccountService = new BankAccountService(this.httpClient);
            ChargeService = new ChargeService(this.httpClient);
            PayoutService = new PayoutService(this.httpClient);
            TransferService = new TransferService(this.httpClient);
            FeeService = new FeeService(this.httpClient);
            PlanService = new PlanService(this.httpClient);
            SubscriptionService = new SubscriptionService(this.httpClient);
			OpenpayFeesService = new OpenpayFeesService(this.httpClient);
			WebhooksService = new WebhookService (this.httpClient);
        }
 public void CanEnrollACustomer()
 {
     //Arrange
     FakeCustomerValidator validation = new FakeCustomerValidator();
     FakeCreditCheckValidator creditCheck = new FakeCreditCheckValidator();
     FakeCustomerRepository repository= new FakeCustomerRepository();
     var sut = new CustomerService(validation, creditCheck, repository);
     Customer customer = new Customer();
     //Act
     sut.EnrollCustomer(customer);
     //Assert
     Assert.That(validation.WasCalled);
     Assert.That(creditCheck.WasCalled);
     Assert.That(repository.WasCalled);
 }
예제 #18
0
 void MainWindow_Loaded(object sender, RoutedEventArgs e)
 {
     var productsDataProxy = new ProductRepository();
     var inventoryDataProxy = new InventoryItemRepository();
     var customerDataProxy = new CustomerRepository();
     var orderItemDataProxy = new OrderItemRepository();
     var orderRepository = new OrderRepository(customerDataProxy, orderItemDataProxy);
     _inventoryService = new InventoryItemService(inventoryDataProxy);
     _orderItemsService = new OrderItemService(orderItemDataProxy, productsDataProxy, inventoryDataProxy, new DTCTransactionContext());
     _ordersService = new OrderService(orderRepository, _orderItemsService, new DTCTransactionContext());
     _customersService = new CustomerService(customerDataProxy, _ordersService);
     _productsService = new ProductService(productsDataProxy, _ordersService, _inventoryService, new DTCTransactionContext());
     _categoriesService = new CategoryService(new CategoryRepository(), _productsService);
     this.DataContext = new MainWindowVM(_eventAggregator, _customersService, _productsService, _categoriesService, _ordersService, _inventoryService);
 }
예제 #19
0
 private void ConfigureEFUsage()
 {
     var productsDataProxy = new DAL.EF.ProductRepository();
     var inventoryDataProxy = new DAL.EF.InventoryItemRepository();
     var customerDataProxy = new DAL.EF.CustomerRepository();
     var orderItemDataProxy = new DAL.EF.OrderItemRepository();
     var orderRepository = new DAL.EF.OrderRepository();
     var categoriesDataProxy = new DAL.EF.CategoryRepository();
     _inventoryService = new InventoryItemService(inventoryDataProxy);
     _orderItemsService = new OrderItemService(orderItemDataProxy, productsDataProxy, inventoryDataProxy, new DTCTransactionContext());
     _ordersService = new OrderService(orderRepository, _orderItemsService, new DTCTransactionContext());
     _customersService = new CustomerService(customerDataProxy, _ordersService);
     _productsService = new ProductService(productsDataProxy, orderRepository, _inventoryService, new DTCTransactionContext());
     _categoriesService = new CategoryService(categoriesDataProxy, productsDataProxy);
     this.DataContext = new MainWindowVM(_eventAggregator, _customersService, _productsService, _categoriesService, _ordersService, _inventoryService);
 }
예제 #20
0
        public static void ConcurrencyDemo()
        {
            System.Console.WriteLine("------------------------------");
            System.Console.WriteLine(new StackTrace().GetFrame(0).GetMethod().Name);
            System.Console.WriteLine("------------------------------");

            Customer customer;
            // User 1 holt Customer
            using (var srv = new CustomerService())
            {
                customer = srv.All<Customer>().FirstOrDefault();
            }

            // User 2 will auch etwas machen und ist schneller
            var t = Task.Factory.StartNew(() =>
              {
                  using (var srv = new CustomerService())
                  {
                      var c = srv.All<Customer>().FirstOrDefault();
                      if (c != null)
                      {
                          c.LastName = "XYZ4";
                          c.State = State.Modified;
                          srv.Commit(new List<Customer>{c});
                      }
                  }
              });

            t.Wait();

            if (customer != null)
            {
                customer.LastName = "ABC";
                customer.State = State.Modified;

                System.Console.WriteLine("-Modified Customer: {0} {1}", customer.FistName, customer.LastName);

                using (var srv = new CustomerService())
                {
                    OperationResult result = srv.Commit(new List<Customer> {customer});
                    if (result.ResultType == OperationResultType.ConcurencyExeption)
                        System.Console.WriteLine(result.Message);

                }
                System.Console.WriteLine("-Reseted Customer: {0} {1}", customer.FistName, customer.LastName);
            }
        }
예제 #21
0
파일: Service.cs 프로젝트: NanQi/demo
		/// <summary>
		///  增加一条数据
		/// </summary>
		public bool Add(CustomerService.Model.Service model)
		{
			int rowsAffected;
			SqlParameter[] parameters = {
					new SqlParameter("@GUID", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@sNO", SqlDbType.VarChar,50),
					new SqlParameter("@customer", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@acceptDate", SqlDbType.DateTime),
					new SqlParameter("@solutionDate", SqlDbType.DateTime),
					new SqlParameter("@type", SqlDbType.VarChar,20),
					new SqlParameter("@content", SqlDbType.VarChar,500),
					new SqlParameter("@result", SqlDbType.VarChar,100),
					new SqlParameter("@evaluate", SqlDbType.VarChar,50),
					new SqlParameter("@material", SqlDbType.VarChar,50),
					new SqlParameter("@materialMoney", SqlDbType.Money,8),
					new SqlParameter("@serviceMoney", SqlDbType.Money,8),
					new SqlParameter("@payStatus", SqlDbType.VarChar,50),
					new SqlParameter("@traffic", SqlDbType.VarChar,50),
					new SqlParameter("@employee", SqlDbType.VarChar,20),
					new SqlParameter("@createDate", SqlDbType.DateTime)};
			parameters[0].Value = Guid.NewGuid();
			parameters[1].Value = model.sNO;
            parameters[2].Value = model.customer;
			parameters[3].Value = model.acceptDate;
			parameters[4].Value = model.solutionDate;
			parameters[5].Value = model.type;
			parameters[6].Value = model.content;
			parameters[7].Value = model.result;
			parameters[8].Value = model.evaluate;
			parameters[9].Value = model.material;
			parameters[10].Value = model.materialMoney;
			parameters[11].Value = model.serviceMoney;
			parameters[12].Value = model.payStatus;
			parameters[13].Value = model.traffic;
			parameters[14].Value = model.employee;
            parameters[15].Value = DateTime.Now;

            DbHelperSQL.RunProcedure("T_Service_ADD", parameters, out rowsAffected);
            if (rowsAffected > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
		}
예제 #22
0
 public MainWindowVM(EventAggregator eventAggregator,
                     CustomerService customerService,
                     ProductService productService,
                     CategoryService categoryService,
                     OrderService orderService,
                     InventoryItemService inventoryService)
 {
     _customersVM = new CustomersVM(customerService);
     _customersVM.LoadCustomersCommand.Execute(null);
     _productsVM = new ProductsVM(productService, this);
     _productsVM.LoadProductsCommand.Execute(null);
     _categoriesVM = new CategoriesVM(categoryService);
     _categoriesVM.LoadCategoriesCommand.Execute(null);
     _ordersVM = new OrdersVM(orderService, this, eventAggregator);
     _ordersVM.LoadOrdersCommand.Execute(null);
     _inventoryItemsVM = new InventoryItemsVM(inventoryService, this);
     _inventoryItemsVM.LoadInventoryCommand.Execute(null);
 }
예제 #23
0
 public CustomerOrderWindow(OrderVM currentOrder,
                            OrderService orderService,
                            CustomerService customerService,
                            OrderItemService orderItemService,
                            InventoryItemService inventoryService,
                            MainWindowVM mainVM,
                            EventAggregator eventAggregator)
     : this()
 {
     var order = new Order()
     {
         ID = currentOrder.ID,
         CustomerID = currentOrder.CustomerID,
         OrderDate = currentOrder.OrderDate,
     };
     var vm = new CustomerOrderVM(eventAggregator, order, orderService, orderItemService, inventoryService, mainVM);
     vm.RefreshCommand.Execute(null);
     DataContext = vm;
 }
        public void UnitOfWork_Transaction_Test()
        {
            using(IDataContextAsync context = new NorthwindContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                using (IUnitOfWorkAsync unitOfWorkAsync = new UnitOfWork(context))
                {
                    IRepositoryAsync<Customer> customerRepository = new Repository<Customer>(context, unitOfWork);
                
                    IService<Customer> customerService = new CustomerService(customerRepository, unitOfWorkAsync);

                    try
                    {
                        unitOfWork.BeginTransaction();
                
                        customerService.Insert(new Customer { CustomerID = "YODA", CompanyName = "SkyRanch", ObjectState = ObjectState.Added});
                        customerService.Insert(new Customer { CustomerID = "JEDI", CompanyName = "SkyRanch", ObjectState = ObjectState.Added});

                        var customer = customerService.Find("YODA");
                        Assert.AreSame(customer.CustomerID, "YODA");

                        customer = customerService.Find("JEDI");
                        Assert.AreSame(customer.CustomerID, "JEDI");

                        // save
                        var saveChangesAsync = unitOfWork.SaveChanges();
                        //Assert.AreSame(saveChangesAsync, 2);

                        // Will cause an exception, cannot insert customer with the same CustomerId (primary key constraint)
                        customerService.Insert(new Customer { CustomerID = "JEDI", CompanyName = "SkyRanch", ObjectState = ObjectState.Added });
                        //save 
                        unitOfWork.SaveChanges();

                        unitOfWork.Commit();
                    }
                    catch (Exception e)
                    {
                        unitOfWork.Rollback();
                    }
                }
            }
        }
예제 #25
0
        /// <summary>
        ///     查看销售任务
        /// </summary>
        /// <param name="taskNumber">任务编号</param>
        /// <returns></returns>
        public SaleTask GetSaleTask(string taskNumber)
        {
            var taskService = new TaskService();
            var taskEmployeeService = new TaskEmployeeService();
            var pigTypeService = new PigTypeService();

            task task = taskService.FindByTaskNumber(taskNumber);

            if (task == null)
            {
                return null;
            }

            var customerService = new CustomerService();
            var checkTask = new SaleTask
                                {
                                    TaskNumber = task.TaskNumber,
                                    StartTime = task.StartTime,
                                    EndTime = task.EndTime,
                                    EmployeeName = taskEmployeeService.GetEmployeeNames(task.Id),
                                    EmployeeNumber = taskEmployeeService.GetEmployeeNumbers(task.Id),
                                    Customer = customerService.Find(task.CustomerId).Name,
                                    Status = task.task_status_type.Name,
                                    Memo = task.Memo
                                };

            List<SaleDetail> saleDetailList = task.sale_task_quality.Select(item => new SaleDetail
                                                                                        {
                                                                                            PigType =
                                                                                                pigTypeService.Find(
                                                                                                    item.PigTypeId).Name,
                                                                                            Price = item.Price,
                                                                                            Quantity = item.Quality
                                                                                        }).ToList();

            if (saleDetailList.Count != 0)
            {
                checkTask.SaleDetailList = saleDetailList;
            }
            return checkTask;
        }
        private void loadSomeData()
        {
            CustomerService customerService = new CustomerService();
            customers = customerService.GetCustomers().OrderBy(x => x.CustCode).ToList();
            customers.Insert(0, new Customer() { Id = 0, CustomerName = "Tất cả", CustCode = "Tất cả" });

            cbmCustomers.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cbmCustomers.AutoCompleteSource = AutoCompleteSource.ListItems;
            cbmCustomers.DataSource = customers;
            cbmCustomers.DisplayMember = "CustCode";
            cbmCustomers.ValueMember = "Id";

            SystemUserService systemUserService = new SystemUserService();
            systemUsers = systemUserService.GetSystemUsers();
            systemUsers.Add(new SystemUser() { Id = 0, FullName = "Tất cả" });
            systemUsers = systemUsers.OrderBy(x => x.Id).ToList();

            cbmUsers.DataSource = systemUsers;
            cbmUsers.DisplayMember = "FullName";
            cbmUsers.ValueMember = "Id";
        }
        public void FetchData(Action<Exception> onError)
        {
            IsLoading = true;
            var service = new AccountService(new ApiConfiguration(), null, _keyService);
            var cService = new CustomerService(new ApiConfiguration(), null, _keyService);
            var iService = new ServiceInvoiceService(new ApiConfiguration(), null, _keyService);

            Task.WhenAll(new[]
                {
                    service.GetRangeAsync(CompanyFile.CompanyFile, null, CompanyFile.Authentication[0])
                        .ContinueWith(t => DisplayAccounts(t.Result.Items), TaskScheduler.FromCurrentSynchronizationContext()),
                    cService.GetRangeAsync(CompanyFile.CompanyFile, null, CompanyFile.Authentication[0])
                        .ContinueWith(t => DisplayCustomers(t.Result.Items), TaskScheduler.FromCurrentSynchronizationContext()),
                    iService.GetRangeAsync(CompanyFile.CompanyFile, null, CompanyFile.Authentication[0])
                        .ContinueWith(t => DisplayInvoices(t.Result.Items), TaskScheduler.FromCurrentSynchronizationContext())
                })
                .ContinueWith(t =>
                    {
                        IsLoading = false;
                    }, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
            global::Xamarin.Forms.Forms.Init ();

            window = new UIWindow (UIScreen.MainScreen.Bounds);

            #region Azure stuff
            CurrentPlatform.Init ();
            Client = new MobileServiceClient (
                Constants.Url,
                Constants.Key);
            custTable = Client.GetTable<Customers>();
            custService = new CustomerService(custTable);

            App.SetCustManager (custService);
            #endregion region

            LoadApplication (new App ());

            return base.FinishedLaunching (app, options);
        }
예제 #29
0
파일: Argument.cs 프로젝트: NanQi/demo
		/// <summary>
		///  更新一条数据
		/// </summary>
		public bool Update(CustomerService.Model.Argument model)
		{
			int rowsAffected=0;
			SqlParameter[] parameters = {
					new SqlParameter("@GUID", SqlDbType.UniqueIdentifier,16),
					new SqlParameter("@aName", SqlDbType.VarChar,50),
					new SqlParameter("@type", SqlDbType.VarChar,20),
					new SqlParameter("@createDate", SqlDbType.DateTime)};
			parameters[0].Value = model.GUID;
			parameters[1].Value = model.aName;
			parameters[2].Value = model.type;
			parameters[3].Value = model.createDate;

			DbHelperSQL.RunProcedure("T_Argument_Update",parameters,out rowsAffected);
			if (rowsAffected > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
        public void CanReadAllCustomerProperties()
        {
            OrdersManagementDataSet ds = new OrdersManagementDataSet();
            OrdersManagementDataSet.CustomersRow row = ds.Customers.NewCustomersRow();
            row.CustomerId = "42";
            row.Address = "My Address";
            row.City = "My City";
            row.CompanyName = "My Company";
            row.PostalCode = "12345";
            row.Region = "My Region";
            ds.Customers.AddCustomersRow(row);
            ds.Customers.AcceptChanges();
            CustomerService customerService = new CustomerService(ds);

            Customer customer = customerService.GetCustomerById("42");

            Assert.IsNotNull(customer);
            Assert.AreEqual("My Address", customer.Address);
            Assert.AreEqual("My City", customer.City);
            Assert.AreEqual("My Company", customer.CompanyName);
            Assert.AreEqual("12345", customer.PostalCode);
            Assert.AreEqual("My Region", customer.Region);
        }
예제 #31
0
        public void GetAllReceiptsMethod()
        {
            GetInMemoryContext().Database.EnsureDeleted();

            CustomerBO cust1 = new CustomerBO()
            {
                Firstname = "ham her",
                Lastname  = "Fuhlendorff",
                Address   = "testvej1",
                CVR       = 12312312,
                City      = "Kolding",
                Email     = "*****@*****.**",
                Phone     = 12345678,
                ZipCode   = 6000
            };

            cust1 = new CustomerService(GetDalFacadeMock(GetInMemoryContext()).Object).Create(cust1);

            CustomerBO cust2 = new CustomerBO()
            {
                Firstname = "ikke ham her",
                Lastname  = "Meyer",
                Address   = "testvej2222",
                CVR       = 12312312,
                City      = "Esbjerg",
                Email     = "*****@*****.**",
                Phone     = 12345678,
                ZipCode   = 6700
            };
            EmployeeBO employee = new EmployeeBO()
            {
                Firstname  = "Sigurd",
                Lastname   = "Hansen",
                Username   = "******",
                Password   = "******",
                MacAddress = "dfkmgkldfnmg"
            };

            employee = new EmployeeService(GetDalFacadeMock(this.GetInMemoryContext()).Object).Create(employee);

            cust2 = new CustomerService(GetDalFacadeMock(GetInMemoryContext()).Object).Create(cust2);

            ReceiptBO prop1 = new ReceiptBO()
            {
                Title      = "qwe1",
                CustomerId = cust1.Id,
                EmployeeId = employee.Id
            };

            prop1 = GetMockService().Create(prop1);

            ReceiptBO prop2 = new ReceiptBO()
            {
                Title      = "qwe2",
                CustomerId = cust1.Id,
                EmployeeId = employee.Id
            };

            prop2 = GetMockService().Create(prop2);

            ReceiptBO prop3 = new ReceiptBO()
            {
                Title      = "qwe3",
                CustomerId = cust1.Id,
                EmployeeId = employee.Id
            };

            prop3 = GetMockService().Create(prop3);

            ReceiptBO prop4 = new ReceiptBO()
            {
                Title      = "qwe4",
                CustomerId = cust2.Id,
                EmployeeId = employee.Id
            };

            prop4 = GetMockService().Create(prop4);

            ReceiptBO prop5 = new ReceiptBO()
            {
                Title      = "qwe5",
                CustomerId = cust2.Id,
                EmployeeId = 1
            };

            prop5 = GetMockService().Create(prop5);

            ReceiptBO prop6 = new ReceiptBO()
            {
                Title      = "qwe6",
                CustomerId = cust2.Id,
                EmployeeId = employee.Id
            };

            prop6 = GetMockService().Create(prop6);

            List <ReceiptBO> allProps = GetMockService().GetAllById(cust1.Id);

            Assert.IsNotNull(allProps);
            Assert.AreEqual(3, allProps.Count);
            Assert.AreEqual(cust1.Firstname, allProps.Find(x => x.Title == "qwe3").Customer.Firstname);
            Assert.IsNull(allProps.Find(x => x.Title == "qwe4"));
        }
예제 #32
0
 public CustomerController(MiniBankingDbContext context, IHttpContextAccessor httpContextAccessor) : base(context, httpContextAccessor)
 {
     customerService      = new CustomerService(context);
     _httpContextAccessor = httpContextAccessor;
 }
 public CustomersController()
 {
     service = new CustomerService();
 }
예제 #34
0
 public CustomersController(CustomerService customerService)
 {
     _customerService = customerService;
 }
예제 #35
0
 public InvoicePaymentFailedEvent(IOperationsCRUD <StripeEvent> eventsBL, IOperationsCRUD <Owner> ownerBL) : base(eventsBL)
 {
     this.ownerBL    = ownerBL;
     customerService = new CustomerService();
 }
        public async Task <IActionResult> OnPostAsync([FromForm] string stripeToken)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            UserEmail        = user.Email;
            StripeCustomerId = user.CustomerIdentifier;
            var nullCustomerId = string.IsNullOrEmpty(StripeCustomerId);
            var planId         = Input.PlanId;
            var planAmount     = GetPlanPrice(planId);

            var      customerService = new CustomerService();
            Customer customerLookup  = new Customer();

            if (!nullCustomerId)
            {
                customerLookup = customerService.Get(StripeCustomerId);
            }

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            //Create new customer if doesnt exist
            if (nullCustomerId || customerLookup.Deleted == true)
            {
                var customers = new CustomerService();

                var customer = customers.Create(new CustomerCreateOptions
                {
                    Email       = UserEmail,
                    Plan        = planId,
                    Description = UserEmail + " " + "[" + user.Id + "]"
                });

                user.CustomerIdentifier = customer.Id;
                StripeCustomerId        = user.CustomerIdentifier;
            }
            else
            {
                var subcriptionService = new SubscriptionService();
                var subscriptionItems  = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Plan = planId
                    }
                };
                var stripeSubscription = subcriptionService.Create(new SubscriptionCreateOptions
                {
                    Customer = StripeCustomerId,
                    Items    = subscriptionItems
                });
            }

            Charge charge = new Charge();

            if (planAmount > 0)
            {
                var chargeOptions = new ChargeCreateOptions
                {
                    Amount      = planAmount,
                    Currency    = "usd",
                    Description = "RazorStripe for" + " " + UserEmail,
                    Customer    = StripeCustomerId,
                };
                var chargeService = new ChargeService();
                charge = chargeService.Create(chargeOptions);
            }
            await _db.SaveChangesAsync();

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your payment: " + charge.Status;

            return(RedirectToPage());
        }
 public CustomerOrderHistoryMenu(Customer customer, ref IRepository repo) : base(ref repo)
 {
     CurrentCustomer = customer;
     CustomerService = new CustomerService(ref Repo);
     OrderService    = new OrderService(ref Repo);
 }
예제 #38
0
        private async Task <bool> SetShippingOptionAsync(
            string shippingRateComputationMethodSystemName, string shippingOptionName, int storeId, Customer customer, List <ShoppingCartItem> shoppingCartItems)
        {
            var isValid = true;

            if (string.IsNullOrEmpty(shippingRateComputationMethodSystemName))
            {
                isValid = false;

                ModelState.AddModelError("shipping_rate_computation_method_system_name",
                                         "Please provide shipping_rate_computation_method_system_name");
            }
            else if (string.IsNullOrEmpty(shippingOptionName))
            {
                isValid = false;

                ModelState.AddModelError("shipping_option_name", "Please provide shipping_option_name");
            }
            else
            {
                var shippingOptionResponse = await _shippingService.GetShippingOptionsAsync(shoppingCartItems, await CustomerService.GetCustomerShippingAddressAsync(customer), customer,
                                                                                            shippingRateComputationMethodSystemName, storeId);

                if (shippingOptionResponse.Success)
                {
                    var shippingOptions = shippingOptionResponse.ShippingOptions.ToList();

                    var shippingOption = shippingOptions
                                         .Find(so => !string.IsNullOrEmpty(so.Name) && so.Name.Equals(shippingOptionName, StringComparison.InvariantCultureIgnoreCase));

                    await _genericAttributeService.SaveAttributeAsync(customer,
                                                                      NopCustomerDefaults.SelectedShippingOptionAttribute,
                                                                      shippingOption, storeId);
                }
                else
                {
                    isValid = false;

                    foreach (var errorMessage in shippingOptionResponse.Errors)
                    {
                        ModelState.AddModelError("shipping_option", errorMessage);
                    }
                }
            }

            return(isValid);
        }
예제 #39
0
        public async Task <IActionResult> UpdateOrder(
            [ModelBinder(typeof(JsonModelBinder <OrderDto>))]
            Delta <OrderDto> orderDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            var currentOrder = _orderApiService.GetOrderById(orderDelta.Dto.Id);

            if (currentOrder == null)
            {
                return(Error(HttpStatusCode.NotFound, "order", "not found"));
            }

            var customer = await CustomerService.GetCustomerByIdAsync(currentOrder.CustomerId);

            var shippingRequired = await(await _orderService.GetOrderItemsAsync(currentOrder.Id)).AnyAwaitAsync(async item => !(await _productService.GetProductByIdAsync(item.Id)).IsFreeShipping);

            if (shippingRequired)
            {
                var isValid = true;

                if (!string.IsNullOrEmpty(orderDelta.Dto.ShippingRateComputationMethodSystemName) ||
                    !string.IsNullOrEmpty(orderDelta.Dto.ShippingMethod))
                {
                    var storeId = orderDelta.Dto.StoreId ?? _storeContext.GetCurrentStore().Id;

                    isValid &= await SetShippingOptionAsync(orderDelta.Dto.ShippingRateComputationMethodSystemName ?? currentOrder.ShippingRateComputationMethodSystemName,
                                                            orderDelta.Dto.ShippingMethod,
                                                            storeId,
                                                            customer, BuildShoppingCartItemsFromOrderItems(await _orderService.GetOrderItemsAsync(currentOrder.Id), customer.Id, storeId));
                }

                if (isValid)
                {
                    currentOrder.ShippingMethod = orderDelta.Dto.ShippingMethod;
                }
                else
                {
                    return(Error(HttpStatusCode.BadRequest));
                }
            }

            orderDelta.Merge(currentOrder);

            customer.BillingAddressId  = currentOrder.BillingAddressId = orderDelta.Dto.BillingAddress.Id;
            customer.ShippingAddressId = currentOrder.ShippingAddressId = orderDelta.Dto.ShippingAddress.Id;


            await _orderService.UpdateOrderAsync(currentOrder);

            await CustomerActivityService.InsertActivityAsync("UpdateOrder", await LocalizationService.GetResourceAsync("ActivityLog.UpdateOrder"), currentOrder);

            var ordersRootObject = new OrdersRootObject();

            var placedOrderDto = await _dtoHelper.PrepareOrderDTOAsync(currentOrder);

            placedOrderDto.ShippingMethod = orderDelta.Dto.ShippingMethod;

            ordersRootObject.Orders.Add(placedOrderDto);

            var json = JsonFieldsSerializer.Serialize(ordersRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
예제 #40
0
 public CustomerController(EShopServices services)
 {
     Services = services;
     //Ovde uvedeno ovo cudo
     service = new CustomerService(new EShopUnitOfWork(new ShopContext()));
 }
예제 #41
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which sitelinks will
        /// be added.</param>
        public void Run(AdWordsUser user, long campaignId)
        {
            using (CampaignExtensionSettingService campaignExtensionSettingService =
                       (CampaignExtensionSettingService)user.GetService(
                           AdWordsService.v201708.CampaignExtensionSettingService)) {
                Customer customer = null;
                using (CustomerService customerService = (CustomerService)user.GetService(
                           AdWordsService.v201708.CustomerService)) {
                    // Find the matching customer and its time zone. The getCustomers method
                    // will return a single Customer object corresponding to the session's
                    // clientCustomerId.
                    customer = customerService.getCustomers()[0];
                    Console.WriteLine("Found customer ID {0:###-###-####} with time zone '{1}'.",
                                      customer.customerId, customer.dateTimeZone);
                }
                List <ExtensionFeedItem> extensions = new List <ExtensionFeedItem>();

                // Create your sitelinks.
                SitelinkFeedItem sitelink1 = new SitelinkFeedItem()
                {
                    sitelinkText      = "Store Hours",
                    sitelinkFinalUrls = new UrlList()
                    {
                        urls = new string[] { "http://www.example.com/storehours" }
                    }
                };
                extensions.Add(sitelink1);

                DateTime startOfThanksGiving = new DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0);
                DateTime endOfThanksGiving   = new DateTime(DateTime.Now.Year, 11, 27, 23, 59, 59);

                // Add check to make sure we don't create a sitelink with end date in the
                // past.
                if (DateTime.Now < endOfThanksGiving)
                {
                    // Show the Thanksgiving specials link only from 20 - 27 Nov.
                    SitelinkFeedItem sitelink2 = new SitelinkFeedItem()
                    {
                        sitelinkText      = "Thanksgiving Specials",
                        sitelinkFinalUrls = new UrlList()
                        {
                            urls = new string[] { "http://www.example.com/thanksgiving" }
                        },
                        startTime = string.Format("{0} {1}", startOfThanksGiving.ToString("yyyyMMdd HHmmss"),
                                                  customer.dateTimeZone),
                        endTime = string.Format("{0} {1}", endOfThanksGiving.ToString("yyyyMMdd HHmmss"),
                                                customer.dateTimeZone),

                        // Target this sitelink for United States only. See
                        // https://developers.google.com/adwords/api/docs/appendix/geotargeting
                        // for valid geolocation codes.
                        geoTargeting = new Location()
                        {
                            id = 2840
                        },

                        // Restrict targeting only to people physically within the United States.
                        // Otherwise, this could also show to people interested in the United States
                        // but not physically located there.
                        geoTargetingRestriction = new FeedItemGeoRestriction()
                        {
                            geoRestriction = GeoRestriction.LOCATION_OF_PRESENCE
                        }
                    };
                    extensions.Add(sitelink2);
                }
                // Show the wifi details primarily for high end mobile users.
                SitelinkFeedItem sitelink3 = new SitelinkFeedItem()
                {
                    sitelinkText      = "Wifi available",
                    sitelinkFinalUrls = new UrlList()
                    {
                        urls = new string[] { "http://www.example.com/mobile/wifi" }
                    },
                    devicePreference = new FeedItemDevicePreference()
                    {
                        // See https://developers.google.com/adwords/api/docs/appendix/platforms
                        // for device criteria IDs.
                        devicePreference = 30001
                    },

                    // Target this sitelink for the keyword "free wifi".
                    keywordTargeting = new Keyword()
                    {
                        text      = "free wifi",
                        matchType = KeywordMatchType.BROAD
                    }
                };
                extensions.Add(sitelink3);

                // Show the happy hours link only during Mon - Fri 6PM to 9PM.
                SitelinkFeedItem sitelink4 = new SitelinkFeedItem()
                {
                    sitelinkText      = "Happy hours",
                    sitelinkFinalUrls = new UrlList()
                    {
                        urls = new string[] { "http://www.example.com/happyhours" },
                    },
                    scheduling = new FeedItemSchedule[] {
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.MONDAY,
                            startHour   = 18,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 21,
                            endMinute   = MinuteOfHour.ZERO
                        },
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.TUESDAY,
                            startHour   = 18,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 21,
                            endMinute   = MinuteOfHour.ZERO
                        },
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.WEDNESDAY,
                            startHour   = 18,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 21,
                            endMinute   = MinuteOfHour.ZERO
                        },
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.THURSDAY,
                            startHour   = 18,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 21,
                            endMinute   = MinuteOfHour.ZERO
                        },
                        new FeedItemSchedule()
                        {
                            dayOfWeek   = DayOfWeek.FRIDAY,
                            startHour   = 18,
                            startMinute = MinuteOfHour.ZERO,
                            endHour     = 21,
                            endMinute   = MinuteOfHour.ZERO
                        }
                    }
                };
                extensions.Add(sitelink4);

                // Create your campaign extension settings. This associates the sitelinks
                // to your campaign.
                CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting();
                campaignExtensionSetting.campaignId       = campaignId;
                campaignExtensionSetting.extensionType    = FeedType.SITELINK;
                campaignExtensionSetting.extensionSetting = new ExtensionSetting()
                {
                    extensions = extensions.ToArray()
                };

                CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation()
                {
                    operand   = campaignExtensionSetting,
                    @operator = Operator.ADD
                };

                try {
                    // Add the extensions.
                    CampaignExtensionSettingReturnValue retVal = campaignExtensionSettingService.mutate(
                        new CampaignExtensionSettingOperation[] { operation });

                    // Display the results.
                    if (retVal.value != null && retVal.value.Length > 0)
                    {
                        CampaignExtensionSetting newExtensionSetting = retVal.value[0];
                        Console.WriteLine("Extension setting with type = {0} was added to campaign ID {1}.",
                                          newExtensionSetting.extensionType, newExtensionSetting.campaignId);
                    }
                    else
                    {
                        Console.WriteLine("No extension settings were created.");
                    }
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create extension settings.", e);
                }
            }
        }
예제 #42
0
 public void call_is_made_to_business_service_to_fetch_customer()
 {
     CustomerService.Received(1).GetCustomerById(_id);
 }
        private void LoadCustomers()
        {
            var customerSvc = new CustomerService(MyConfiguration, null, MyOAuthKeyService);

            customerSvc.GetRange(MyCompanyFile, null, MyCredentials, OnCustomerComplete, OnError);
        }
        public async Task <IActionResult> SummaryPost(string stripeEmail, string stripeToken)
        {
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);


            DetailCart.ListCart = await _db.ShoppingCart
                                  .Where(c => c.ApplicationUserId == claim.Value).ToListAsync();

            DetailCart.OrderHeader.PaymentStatus = SD.PaymentStatusPendeing;
            DetailCart.OrderHeader.OrderDate     = DateTime.Now;
            DetailCart.OrderHeader.UserId        = claim.Value;
            DetailCart.OrderHeader.Status        = SD.PaymentStatusPendeing;
            DetailCart.OrderHeader.PickUpTime    = Convert.ToDateTime(DetailCart.OrderHeader.PickUpTime.ToShortDateString() +
                                                                      " " + DetailCart.OrderHeader.PickUpTime.ToLongTimeString());

            List <OrderDetails> orderDetailsList = new List <OrderDetails>();

            _db.OrderHeader.Add(DetailCart.OrderHeader);
            await _db.SaveChangesAsync();

            DetailCart.OrderHeader.OrderTotalOriginal = 0;



            foreach (var item in DetailCart.ListCart)
            {
                item.MenuItem = await _db.MenuItem.FirstOrDefaultAsync(m => m.Id == item.MenuItemId);

                OrderDetails orderDetails = new OrderDetails
                {
                    MenuItemId  = item.MenuItemId,
                    OrderId     = DetailCart.OrderHeader.Id,
                    Description = item.MenuItem.Description,
                    Name        = item.MenuItem.Name,
                    Price       = item.MenuItem.Price,
                    Count       = item.Count
                };
                DetailCart.OrderHeader.OrderTotalOriginal += orderDetails.Count * orderDetails.Price;
                _db.OrderDetails.Add(orderDetails);
            }

            if (HttpContext.Session.GetString(SD.ssCouponCode) != null)
            {
                DetailCart.OrderHeader.CouponCode = HttpContext.Session.GetString(SD.ssCouponCode);
                var couponFromDB = await _db.Cupon.Where(c => c.Name.ToLower()
                                                         == DetailCart.OrderHeader.CouponCode.ToLower()).FirstOrDefaultAsync();

                DetailCart.OrderHeader.OrderTotal = SD.DicountedPrice(couponFromDB, DetailCart.OrderHeader.OrderTotalOriginal);
            }
            else
            {
                DetailCart.OrderHeader.OrderTotal = DetailCart.OrderHeader.OrderTotalOriginal;
            }
            DetailCart.OrderHeader.CouponCodeDiscount = DetailCart.OrderHeader.OrderTotalOriginal - DetailCart.OrderHeader.OrderTotal;

            _db.ShoppingCart.RemoveRange(DetailCart.ListCart);
            HttpContext.Session.SetInt32(SD.ssShoppingCartCount, 0);
            await _db.SaveChangesAsync();

            //STRIPE LOGIC
            if (stripeToken != null)
            {
                var customers = new CustomerService();
                var charges   = new ChargeService();

                var customer = customers.Create(new CustomerCreateOptions
                {
                    Email       = stripeEmail,
                    SourceToken = stripeToken
                });

                var charge = charges.Create(new ChargeCreateOptions
                {
                    Amount      = Convert.ToInt32(DetailCart.OrderHeader.OrderTotal * 100),
                    Description = "Order Id" + DetailCart.OrderHeader.Id,
                    Currency    = "usd",
                    CustomerId  = customer.Id
                });

                DetailCart.OrderHeader.TransactionId = charge.BalanceTransactionId;
                if (charge.Status.ToLower() == "succeeded")
                {
                    //email for successful order

                    DetailCart.OrderHeader.PaymentStatus = SD.PaymentStatusApproved;
                    DetailCart.OrderHeader.Status        = SD.StatusSubmitted;
                }
                else
                {
                    DetailCart.OrderHeader.PaymentStatus = SD.PaymentStatusRejected;
                }
            }
            else
            {
                DetailCart.OrderHeader.PaymentStatus = SD.PaymentStatusRejected;
            }

            await _db.SaveChangesAsync();

            //return RedirectToAction("Index", "Home");
            return(RedirectToAction("Confirm", "Order", new { id = DetailCart.OrderHeader.Id }));
        }
예제 #45
0
 //public static int currentSession;
 public LoginController()
 {
     customerService = new CustomerService();
 }
예제 #46
0
        public ActionResult Purchase(Customer customer)
        {
            if (ModelState.IsValid)
            {
                if (customer.ExpDate <= DateTime.Now)
                {
                    ModelState.AddModelError("", "Credit card has already expired");
                }

                if (customer.PaymentMethodCode == "AMEX")
                {
                    if (customer.CardNo.Length != 15)
                    {
                        ModelState.AddModelError("", "AMEX must be 15 digits");
                    }
                }
                else
                {
                    if (customer.CardNo.Length != 16)
                    {
                        ModelState.AddModelError("", customer.PaymentMethodCode + "must be 16 digits");
                    }
                }

                if (ModelState.IsValid)
                {
                    var c = new Customer
                    {
                        FName             = customer.FName,
                        LName             = customer.LName,
                        Email             = Request.Cookies["User"] == null? customer.Email : Request.Cookies["User"]["Email"],
                        Phone             = customer.Phone,
                        Address1          = customer.Address1,
                        Address2          = customer.Address2,
                        Postcode          = customer.Postcode,
                        State             = customer.State,
                        PaymentMethodCode = customer.PaymentMethodCode,
                        CardNo            = customer.CardNo,
                        ExpDate           = customer.ExpDate
                    };

                    var customerService = new CustomerService();
                    customerService.CreateCustomerOrder(c, Session.SessionID, Convert.ToInt32(Session["ShippingCost"]));

                    return(RedirectToAction("PurchasedSuccess"));
                }

                SetStates();
                SetPaymentMethods();
            }

            List <ModelError> errors = new List <ModelError>();

            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    errors.Add(error);
                }
            }
            return(View(customer));
        }
예제 #47
0
 public void InitService(ApiConfiguration myConfiguration, OAuthKeyService myOAuthKeyService)
 {
     _myService         = new AccountService(myConfiguration, null, myOAuthKeyService);
     items              = new List <Account>();
     _myCustomerService = new CustomerService(myConfiguration, null, myOAuthKeyService);
 }
예제 #48
0
        public CustomerModule(CustomerService custService, Logger logger) : base("/customer")
        {
            this.Get["/"] = parameters =>
            {
                // Razor
                // 1. 先用匿名型別產生匿名物件再可列舉
                // 2. 由匿名物件的值轉為dynamic物件(實際上為ExpandoObject物件)
                // IEnumerable<dynamic> custList = webAppService.Entities.Customer
                //    .Select(c => new { Id = c.Id, CustName = c.CustName, Created = c.Created }).AsEnumerable()
                //    .Select(x => new { Id = x.Id, CustName = x.CustName, Created = x.Created }.ToDynamic());

                // Super Simple View Engine
                // 匿名型別產生匿名物件
                /// var custList = appService.Entities.Customer.Select(c => new { Id = c.Id, CustName = c.CustName, Created = c.Created });

                IList <Customer> custList = custService.FindRecords();
                logger.Info("test NLog");
                logger.Debug(custList.ToArray <dynamic>()[0].CustName);

                return(Negotiate.WithModel(custList).WithView("ListS.sshtml"));
            };

            this.Get["/new"] = parameters =>
            {
                return(View["NewS.sshtml", new Customer()]);
            };

            this.Post["/new"] = parameters =>
            {
                custService.AddRecord(this.Bind <Customer>());

                return(Response.AsRedirect("/customer"));
            };

            this.Get["/{id:int}"] = parameters =>
            {
                int      id   = (int)parameters.id;
                Customer cust = custService.GetRecordById(id);
                if (cust != null)
                {
                    return(View["ViewS.sshtml", cust]);
                }
                else
                {
                    return(Response.AsRedirect("/customer"));
                }
            };

            this.Post["/update/{id:int}"] = parameters =>
            {
                Customer c = this.Bind <Customer>();
                custService.UpdateRecord(c);

                return(Response.AsRedirect("/customer"));
            };

            this.Post["/delete/{id:int}"] = parameters =>
            {
                int      id   = (int)parameters.id;
                Customer cust = custService.GetRecordById(id);
                if (cust != null)
                {
                    custService.DeleteRecord(cust);
                }

                return(Response.AsRedirect("/customer"));
            };
        }
예제 #49
0
     public void MyFirstTest()
     {
         ICustomerRepository customerRepository = new CustomerRepository(fixture.Configuration);
         CustomerService customerService = new CustomerService(customerRepository);        
 }
예제 #50
0
        public void Setup()
        {
            var conn = TestHelper.PostgresConnectionString;

            _db = new CustomerService(conn);
        }
 public CustomerProvider()
 {
     _service = new CustomerService();
 }
예제 #52
0
 public FormCustomer()
 {
     InitializeComponent();
     _customerService = new CustomerService();
     LoadData();
 }
 public MaintenanceController()
 {
     _uow             = new UnitOfWork <PowerfrontDbContext>();
     _customerService = new CustomerService(_uow);
     _propertyService = new PropertyService(_uow);
 }
예제 #54
0
        private List <Payment> _ExportPayment(DateRangeOptions range)
        {
            var payments = new List <Payment>();

            try
            {
                var options = new PaymentIntentListOptions
                {
                    Limit   = 100,
                    Created = range,
                };
                var paymentIntentService = new PaymentIntentService();
                var transactionService   = new BalanceTransactionService();
                var customerService      = new CustomerService();
                var chargeService        = new ChargeService();

                StripeList <PaymentIntent> pis = paymentIntentService.List(options);

                for (int i = 0; i < pis.Data.Count; i++)
                {
                    var pi = pis.Data[i];

                    var payment = new Payment()
                    {
                        Description         = pi.Description,
                        Created             = pi.Created,
                        Amount              = Convert.ToDecimal(pi.Amount) / 100,
                        Currency            = pi.Currency,
                        Status              = pi.Status,
                        StatementDescriptor = pi.StatementDescriptor,
                        CustomerId          = pi.CustomerId,
                        CardId              = pi.PaymentMethodId,
                        InvoiceId           = pi.InvoiceId
                    };

                    if (pi.Charges.Data.Count > 0)
                    {
                        var charge = pi.Charges.Data[0];
                        try
                        {
                            charge.BalanceTransaction = transactionService.Get(charge.BalanceTransactionId);
                            payment.Id = charge.Id;
                            payment.ConvertedAmount   = Convert.ToDecimal(charge.BalanceTransaction.Amount) / 100;
                            payment.AmountRefunded    = Convert.ToDecimal(charge.AmountRefunded) / 100;
                            payment.Fee               = Convert.ToDecimal(charge.BalanceTransaction.Fee) / 100;
                            payment.ConvertedCurrency = charge.BalanceTransaction.Currency;
                            payment.Tax               = 0;
                            payment.Captured          = charge.Captured;
                            payment.Transfer          = charge.TransferId;
                            try
                            {
                                if (charge.Refunds.Data.Count > 0)
                                {
                                    var refundTx = transactionService.Get(charge.Refunds.Data[0].BalanceTransactionId);
                                    payment.ConvertedAmountRefunded = Convert.ToDecimal(refundTx.Amount) / 100;
                                }
                            }
                            catch (Exception) { }
                        }
                        catch (Exception) { }
                    }

                    try
                    {
                        pi.Customer = customerService.Get(pi.CustomerId);
                        payment.CustomerDescription = pi.Customer.Description;
                        payment.CustomerEmail       = pi.Customer.Email;
                    }
                    catch (Exception) { }


                    payment.Description = pi.Description;
                    payments.Add(payment);
                }

                var optionsC = new ChargeListOptions
                {
                    Limit   = 100,
                    Created = range,
                };
                StripeList <Charge> chs = chargeService.List(optionsC);
                for (int i = 0; i < chs.Data.Count; i++)
                {
                    var ch = chs.Data[i];
                    if (FindPayment(payments, ch.Id))
                    {
                        continue;
                    }

                    var payment = new Payment()
                    {
                        Id                  = ch.Id,
                        Description         = ch.Description,
                        Created             = ch.Created,
                        Amount              = Convert.ToDecimal(ch.Amount) / 100,
                        Currency            = ch.Currency,
                        Status              = ch.Status,
                        StatementDescriptor = ch.StatementDescriptor,
                        CustomerId          = ch.CustomerId,
                        Captured            = ch.Captured,
                        CardId              = ch.PaymentMethod,
                        InvoiceId           = ch.InvoiceId,
                        Transfer            = ch.TransferId
                    };
                    try
                    {
                        ch.BalanceTransaction     = transactionService.Get(ch.BalanceTransactionId);
                        payment.ConvertedAmount   = Convert.ToDecimal(ch.BalanceTransaction.Amount) / 100;
                        payment.AmountRefunded    = Convert.ToDecimal(ch.AmountRefunded) / 100;
                        payment.Fee               = Convert.ToDecimal(ch.BalanceTransaction.Fee) / 100;
                        payment.ConvertedCurrency = ch.BalanceTransaction.Currency;
                        payment.Tax               = 0;
                    }
                    catch (Exception) { }
                    try
                    {
                        ch.Customer = customerService.Get(ch.CustomerId);
                        payment.CustomerDescription = ch.Customer.Description;
                        payment.CustomerEmail       = ch.Customer.Email;
                    }
                    catch (Exception) { }

                    payments.Add(payment);
                }
            }
            catch (Exception) { }

            payments.Sort(
                delegate(Payment a, Payment b)
            {
                return(b.Created.CompareTo(a.Created));
            }
                );
            return(payments);
        }
예제 #55
0
 public AddCustomerCommand(CustomerService customerService, CustomerModel customerModel = null)
 {
     _customerService = customerService;
     _customerModel   = customerModel;
 }
예제 #56
0
        public string SendInvoice(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "",
            bool sendInvoice   = true)
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description,
                    AutoAdvance      = true
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);
                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                if (sendInvoice)
                {
                    invoice = service.SendInvoice(invoice.Id);
                }

                return(invoice.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
예제 #57
0
        public InvoiceInfo GeneratePayNowLink(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "")
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);

                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                var result = new InvoiceInfo
                {
                    Url = invoice.HostedInvoiceUrl,
                    Id  = invoice.Id
                };
                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
예제 #58
0
        private bool IsUserValid(string username, string password)
        {
            var customer = CustomerService.GetCustomerByEmailAndPassword(username, password, false);

            return(customer != null);
        }
예제 #59
0
        public async Task <IActionResult> CreateOrder(
            [ModelBinder(typeof(JsonModelBinder <OrderDto>))]
            Delta <OrderDto> orderDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            if (orderDelta.Dto.CustomerId == null)
            {
                return(Error());
            }

            // We doesn't have to check for value because this is done by the order validator.
            var customer = await CustomerService.GetCustomerByIdAsync(orderDelta.Dto.CustomerId.Value);

            if (customer == null)
            {
                return(Error(HttpStatusCode.NotFound, "customer", "not found"));
            }

            var shippingRequired = false;

            if (orderDelta.Dto.OrderItems != null)
            {
                var shouldReturnError = await AddOrderItemsToCartAsync(orderDelta.Dto.OrderItems, customer, orderDelta.Dto.StoreId ?? _storeContext.GetCurrentStore().Id);

                if (shouldReturnError)
                {
                    return(Error(HttpStatusCode.BadRequest));
                }

                shippingRequired = await IsShippingAddressRequiredAsync(orderDelta.Dto.OrderItems);
            }

            if (shippingRequired)
            {
                var isValid = true;

                isValid &= await SetShippingOptionAsync(orderDelta.Dto.ShippingRateComputationMethodSystemName,
                                                        orderDelta.Dto.ShippingMethod,
                                                        orderDelta.Dto.StoreId ?? _storeContext.GetCurrentStore().Id,
                                                        customer,
                                                        BuildShoppingCartItemsFromOrderItemDtos(orderDelta.Dto.OrderItems.ToList(),
                                                                                                customer.Id,
                                                                                                orderDelta.Dto.StoreId ?? _storeContext.GetCurrentStore().Id));

                if (!isValid)
                {
                    return(Error(HttpStatusCode.BadRequest));
                }
            }

            var newOrder = await _factory.InitializeAsync();

            orderDelta.Merge(newOrder);

            customer.BillingAddressId  = newOrder.BillingAddressId = orderDelta.Dto.BillingAddress.Id;
            customer.ShippingAddressId = newOrder.ShippingAddressId = orderDelta.Dto.ShippingAddress.Id;


            // If the customer has something in the cart it will be added too. Should we clear the cart first?
            newOrder.CustomerId = customer.Id;

            // The default value will be the currentStore.id, but if it isn't passed in the json we need to set it by hand.
            if (!orderDelta.Dto.StoreId.HasValue)
            {
                newOrder.StoreId = _storeContext.GetCurrentStore().Id;
            }

            var placeOrderResult = await PlaceOrderAsync(newOrder, customer);

            if (!placeOrderResult.Success)
            {
                foreach (var error in placeOrderResult.Errors)
                {
                    ModelState.AddModelError("order placement", error);
                }

                return(Error(HttpStatusCode.BadRequest));
            }

            await CustomerActivityService.InsertActivityAsync("AddNewOrder", await LocalizationService.GetResourceAsync("ActivityLog.AddNewOrder"), newOrder);

            var ordersRootObject = new OrdersRootObject();

            var placedOrderDto = await _dtoHelper.PrepareOrderDTOAsync(placeOrderResult.PlacedOrder);

            ordersRootObject.Orders.Add(placedOrderDto);

            var json = JsonFieldsSerializer.Serialize(ordersRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
        public static void CreateContextForPendingItemTests(
            Guid customerId1, Guid customerId2,
            Guid job1Id, Guid job2Id, Guid job3Id,
            Guid jobItem1Id, Guid jobItem2Id, Guid jobItem3Id,
            Guid jobItem4Id, Guid jobItem5Id, Guid jobItem6Id, Guid jobItem7Id, Guid jobItem8Id, Guid jobItem9Id)
        {
            var dispatcher     = MockRepository.GenerateMock <IQueueDispatcher <IMessage> >();
            var userRepository = new UserAccountRepository();
            var user           = userRepository.GetByEmail("*****@*****.**", false);
            var userContext    = new TestUserContext(user);

            var quoteRepository      = new QuoteRepository();
            var quoteItemRepository  = new QuoteItemRepository();
            var customerRepository   = new CustomerRepository();
            var jobRepository        = new JobRepository();
            var jobItemRepository    = new JobItemRepository();
            var listItemRepository   = new ListItemRepository();
            var entityIdProvider     = new DirectEntityIdProvider();
            var instrumentRepository = new InstrumentRepository();

            var instrumentId      = Guid.NewGuid();
            var instrumentService = new InstrumentService(userContext, instrumentRepository, dispatcher);

            instrumentService.Create(instrumentId, "Druck", "DPI601IS", "None", "Description", 15);

            var customerService = new CustomerService(userContext, customerRepository, dispatcher);

            customerService.Create(customerId1, "Gael Ltd", String.Empty, new Address(), new ContactInfo(), "Gael Ltd", new Address(), new ContactInfo(), "Gael Ltd", new Address(), new ContactInfo());
            customerService.Create(customerId2, "EMIS (UK) Ltd", String.Empty, new Address(), new ContactInfo(), "Gael Ltd", new Address(), new ContactInfo(), "Gael Ltd", new Address(), new ContactInfo());

            var listItemService = new ListItemService(userContext, listItemRepository, dispatcher);
            var jobService      = new JobService(userContext, null, jobRepository, listItemRepository, customerRepository, entityIdProvider, dispatcher);

            jobService.CreateJob(job1Id, "some instructions", "order no", "advice no", listItemService.GetAllByCategory(ListItemCategoryType.JobType).First().Id, customerId1, "notes", "contact");
            jobService.CreateJob(job2Id, "some instructions", "order no", "advice no", listItemService.GetAllByCategory(ListItemCategoryType.JobType).First().Id, customerId1, "notes", "contact");
            jobService.CreateJob(job3Id, "some instructions", "order no", "advice no", listItemService.GetAllByCategory(ListItemCategoryType.JobType).First().Id, customerId2, "notes", "contact");

            var jobItemService = new JobItemService(userContext, jobRepository, jobItemRepository, listItemService, instrumentService, dispatcher);

            jobItemService.CreateJobItem(
                job1Id, jobItem1Id, instrumentId, "12345", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job1Id, jobItem2Id, instrumentId, "123456", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job1Id, jobItem3Id, instrumentId, "123457", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job1Id, jobItem4Id, instrumentId, "12345", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);

            jobItemService.CreateJobItem(
                job2Id, jobItem5Id, instrumentId, "12345", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job2Id, jobItem6Id, instrumentId, "123456", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job2Id, jobItem7Id, instrumentId, "123457", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);

            jobItemService.CreateJobItem(
                job3Id, jobItem8Id, instrumentId, "12345", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobItemService.CreateJobItem(
                job3Id, jobItem9Id, instrumentId, "123456", String.Empty,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemInitialStatus).First().Id,
                listItemService.GetAllByCategory(ListItemCategoryType.JobItemCategory).First().Id,
                12, "instructions", String.Empty, false, String.Empty, String.Empty);
            jobService.ApproveJob(job1Id);
            jobService.ApproveJob(job2Id);
            jobService.ApproveJob(job3Id);
        }