protected Customer createBusinessCustomer() { Dictionary<string, string> meta = new Dictionary<string, string>(); meta.Add("meta can store", "any flat key/value data you like"); meta.Add("github", "https://github.com/balanced"); meta.Add("more_additional_data", "54.8"); Dictionary<string, string> address = new Dictionary<string, string>(); address.Add("city", "San Francisco"); address.Add("state", "CA"); address.Add("postal_code", "94103"); address.Add("line1", "965 Mission St"); address.Add("country_code", "US"); Customer customer = new Customer(); customer.business_name = "Balanced"; customer.ein = "123456789"; customer.name = "John Lee Hooker"; customer.phone = "(904) 555-1796"; customer.meta = meta; customer.address = address; customer.Save(); return customer; }
public void Test() { PaymentsApi.PublicApiKey = "sbpb_MDllNDA0OTctZWFkYS00YjU4LThjNjQtNzlkOWRkNmYyOTdl"; PaymentsApi.PrivateApiKey = "0mGscVpVCqrGTNQD/yIYRei75eyUxPr+CRqv7ce9Zzx5YFFQL0ODSXAOkNtXTToq"; PaymentsApi api = new PaymentsApi(); CardToken cardToken = new CardToken(); Card card = new Card(); card.Cvc = "123"; card.ExpMonth = 11; card.ExpYear = 19; card.Number = "5105105105105100"; Customer customer = new Customer(); customer.Card = card; customer.Email = "*****@*****.**"; customer.Name = "Customer Customer"; customer.Reference = "Ref1"; customer = (Customer)api.Create(customer); Payment payment = new Payment(); payment.Amount = 1000; payment.Currency = "USD"; payment.Description = "payment description"; payment.Reference = "7a6ef6be31"; payment.Customer = customer; payment = (Payment)api.Create(payment); }
// Methods public void Execute(Customer customer) { if (customer.CustomerType.Equals("INACTIVE")) { throw new Exception("INACTIVE ID"); } Boolean decrement = customer.PlanId.ToUpper().StartsWith("BLOCK"); Transaction transaction = new Transaction(); if (!decrement) { transaction.find(string.Concat(new object[] { "([PeopleID]='", customer.PeopleID, "') AND ([DateTime] > '", customer.MealCost.StartTime, "') AND [TTID] = 'MEALCHRG'" })); decrement = transaction.PeopleID == null; } if (decrement) { if (customer.CurrentMeals <= 0) { throw new Exception("Zero Meals Left"); } transaction.PeopleID = customer.PeopleID; transaction.Amount = 0M; transaction.PlanID = customer.PlanId; transaction.LocationID = this.location; transaction.Ttid = this.ttid; transaction.currentMeals(); customer.CurrentMeals--; } }
public void CreateCustomer(Customer customer) { using (TransactionScope scope = new TransactionScope()) { try { Log.Info($"Criando um novo usuário com o CPF {customer.CPF}"); if (this.ExistsCustomer(customer)) throw new Exception($"CPF {customer.CPF} já cadastrado"); var userId = Guid.NewGuid(); customer.Id = userId; customer.Password = Infra.Utils.SecurityUtils.HashSHA1(customer.Password); this.customerRepository.Save(customer); if (!this.Login(customer.Email, customer.Password, true, false)) throw new Exception("Usuário não cadastrado, por favor tente mais tarde"); } catch (Exception ex) { Log.Error(ex.Message, ex); this.LogOut(); throw; } finally { Log.Info($"Finalizando a criação de um novo usuário com o CPF {customer.CPF}"); scope.Complete(); } } }
public void Serialize(SerializedData data, Customer customer) { foreach (var formatter in _formatters) { formatter.Serialize(data, customer); } }
public Customer GetCustomer() { Customer c = new Customer(); c.CustomerName = "Customer 1"; c.Address = "Address1"; return c; }
private void ShowCustomerDetails(Customer customer) { hidCustomerID.Value = customer.ID; lblCustomerID.Text = customer.ID; txtCompanyName.Text = customer.CompanyName; txtContactName.Text = customer.ContactName; }
public void OrderByClauseTest() { // OrderBy, OrderByDescending, ThenBy, ThenByDescending는 // orderby syntax로 사용가능 Customer[] customers = new Customer[] { new Customer() { City = "Seoul", Name = "a", }, new Customer() { City = "London", Name = "b", }, new Customer() { City = "NewYork", Name = "z", }, }; var query = (from cust in customers where cust.City != "London" orderby cust.Name descending // ascending이 default select cust).ToArray(); Assert.AreEqual("z", query[0].Name, "Customer 이름으로 내림차순 정렬이기 때문"); Assert.AreEqual("a", query[1].Name); }
//Update public static void Update(Customer customer, string lastName, string firstName, string telephone, string emailAddress) { customer.FirstName = firstName; customer.LastName = lastName; customer.TelephoneNumber = telephone; customer.EmailAddress = emailAddress; }
public virtual string CreateResponse(Customer customer, ResponseKind responseKind) { if (responseKind == ResponseKind.HTML) return new HtmlSerializer().SerializeToHtml(customer); return new XmlSerializer().SerializeToXml(customer); }
public void InsertCustomer(Customer customer) { using (SqlConnection conn = CreateConnection()) { try { SqlCommand cmd = new SqlCommand("dbo.usp_createKund",conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("@Personnummer",SqlDbType.VarChar, 15).Value = customer.PersonalNumber; cmd.Parameters.Add("@Förnamn",SqlDbType.VarChar,15).Value = customer.FirstName; cmd.Parameters.Add("@Efternamn",SqlDbType.VarChar,40).Value = customer.LastName; cmd.Parameters.Add("@Adress",SqlDbType.VarChar,6).Value = customer.PostalCode; cmd.Parameters.Add("@Ort",SqlDbType.VarChar,20).Value = customer.Town; cmd.Parameters.Add("@Epost",SqlDbType.VarChar,30).Value = customer.Email; cmd.Parameters.Add("@KundID",SqlDbType.Int,4).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); customer.CustomerID = (int)cmd.Parameters["@KundID"].Value; } catch { throw new ApplicationException("Något gick fel när du försökte lägga till en ny kund"); } } }
protected void btnAdd_Click(object sender, EventArgs e) { MealPlan mp = new MealPlan(); mp.find("PlanID = '" + this.ddlMealPlan.Text + "'"); this.customer = (Customer)ViewState["customer"]; this.tbCurrentMeals.Text = (this.customer.CurrentMeals + mp.MealsPerWeek).ToString(); }
public ActionResult Create(Customer cs, FormCollection collection) { IFormatProvider iFP = new System.Globalization.CultureInfo("vi-VN", true); cs.CreateDate = DateTime.Parse(collection["CreateDate"], iFP); var result = CustomerBusiness.Insert(cs); return PartialView(cs); }
public Deposit(Customer customer, decimal balance, decimal interestRate, byte months) { this.Customer = customer; this.Balance = balance; this.InterestRate = interestRate; this.Months = months; }
public void RegisterCustomer(string name, CustomerType customerType) { try { using (var transaction = new TransactionScope()) { Customer customer = new Customer(); customer.Name = name; customer.Type = customerType; customer.Agreements.Add( new Agreement { Number = agreementManagementService.GenerateAgreementNumber(), CreatedOn = DateTime.Now, Customer = customer }); repository.Save(customer); repository.Commit(); transaction.Complete(); } } catch (Exception ex) { throw new RegistrationException(string.Format("Failed to register customer with name '{0}' and type {1}.", name, customerType), ex); } }
public static void InsertNewCustomer( string customerID, string companyName, string contactName, string contactTitle, string address, string city, string region, string postalCode, string country, string phone, string fax) { Customer newCustomer = new Customer() { CustomerID = customerID, CompanyName = companyName, ContactName = contactName, ContactTitle = contactTitle, Address = address, City = city, Region = region, PostalCode = postalCode, Country = country, Phone = phone, Fax = fax }; northwind.Customers.Add(newCustomer); northwind.SaveChanges(); }
private Customer AddCustomer() { Customer customer = new Customer() { Address = BillingAddressControl.Address, CellPhone = CellPhoneTextBox.Text, City = BillingAddressControl.City, Company = ComapnyTextBox.Text, CountryID = BillingAddressControl.CountryID, DateCreated = DateTime.Now, DateUpdated = DateTime.Now, DayPhone = DayPhoneTextBox.Text, Email = EmailTextBox.Text, EveningPhone = EveningPhoneTextBox.Text, Fax = FaxTextBox.Text, StateID = BillingAddressControl.StateID, FirstName = FirstNameTextBox.Text, LastName = LastNameTextBox.Text, ProvinceID = BillingAddressControl.ProvinceID, Zipcode = BillingAddressControl.Zipcode, Active = true }; return CustomerManager.AddCustomer(customer); }
public IEnumerable<Task> IncludingARelatedEntityShouldAvoidHittingTheServerTwice() { var dbname = GenerateNewDatabaseName(); using (var documentStore = new DocumentStore {Url = Url + Port}.Initialize()) { yield return documentStore.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname); var customer = new Customer {Name = "Customer #1", Id = "customer/1", Email = "*****@*****.**"}; var order = new Order {Id = "orders/1", Note = "Hello", Customer = new DenormalizedReference {Id = customer.Id, Name = customer.Name}}; using (var session = documentStore.OpenAsyncSession(dbname)) { session.Store(customer); session.Store(order); yield return session.SaveChangesAsync(); } using (var session = documentStore.OpenAsyncSession(dbname)) { var query = session.Advanced.AsyncLuceneQuery<Order>() .Include(x => x.Customer.Id) .WhereEquals("Id", "orders/1") .ToListAsync(); yield return query; Assert.AreEqual("Hello", query.Result.Item2[0].Note); // NOTE: this call should not hit the server var load = session.LoadAsync<Customer>(customer.Id); yield return load; Assert.AreEqual(1, session.Advanced.NumberOfRequests); } } }
public ActionResult InputNewCustomer(Customer newCustomer) { newCustomer.AddNewCustomer(); return RedirectToAction("Index"); }
public async Task<ActionResult> Register() { var pcats = CURTAPI.GetParentCategoriesAsync(); await Task.WhenAll(new Task[] { pcats }); ViewBag.parent_cats = await pcats; List<Country> countries = UDF.GetCountries(); Customer cust = new Customer(); Address billing = new Address(); Address shipping = new Address(); bool same = true; try { cust = (Customer)TempData["customer"]; billing = (Address)TempData["billing"]; shipping = (Address)TempData["customer"]; same = (bool)TempData["same"]; } catch (Exception) { } ViewBag.cust = cust; ViewBag.billing = billing; ViewBag.shipping = shipping; ViewBag.same = same; ViewBag.countries = countries; ViewBag.error = TempData["error"]; return View(); }
public formOperate(Customer c, int i, int opt) { InitializeComponent(); customer = c; accountIndex = i; operateType = opt; }
public void AddThreeItems_RemoveMiddleItem_CheckConsistency() { string path = AppDomain.CurrentDomain.BaseDirectory; BackingUnknownSize<Customer, string> backingFile = new BackingUnknownSize<Customer, string>(path, 100); MMFDictionary<Customer, string> dict = new MMFDictionary<Customer, string>(path, 1000); Customer c1 = new Customer {Name = "Mikael"}; Customer c2 = new Customer {Name = "Svenson"}; Customer c3 = new Customer {Name = "Boss"}; dict.Add(c1, "test"); dict.Add(c2, "test2"); dict.Add(c3, "test3"); var result = dict.Remove(c2); Assert.IsTrue(result); result = dict.Remove(c2); Assert.IsFalse(result); dict.Add(c2, "test2"); result = dict.Remove(c2); Assert.IsTrue(result); var res2 = dict[c3]; Assert.AreEqual("test3", res2); }
protected Account(Customer customer, decimal balance, decimal interestRate, uint validityInMonths = 6) { this.Customer = customer; this.Balance = balance; this.InterestRate = interestRate; this.ValidityInMonths = validityInMonths; }
static void Main() { Customer examplePerson = new Customer("Example Person", CustomerType.Individual); Customer exampleCompany = new Customer("Example Company", CustomerType.Company); DepositAccount deposit = new DepositAccount(examplePerson, 1200, (decimal)0.02); int period = 2; Console.WriteLine("Interest for: {0}, account type: {1}, balance: {2}, period: {3} months, interest rate: {4}%\n{5}%", deposit.Customer, deposit.GetType(), deposit.Balance, period, deposit.IntrestRate, deposit.CalcInterestAmount(period)); deposit.Withdraw(300); Console.WriteLine("Interest for: {0}, account type: {1}, balance: {2}, period: {3} months, interest rate: {4}%\n{5}%", deposit.Customer, deposit.GetType(), deposit.Balance, period, deposit.IntrestRate, deposit.CalcInterestAmount(period)); deposit.Deposit(1000); Console.WriteLine("Test depositing money balance: {0}", deposit.Balance); period = 3; Loan loan = new Loan(examplePerson, 1200, (decimal)0.02); Console.WriteLine("Interest for: {0}, account type: {1}, balance: {2}, period: {3} months, interest rate: {4}%\n{5}%", loan.Customer, loan.GetType(), loan.Balance, period, loan.IntrestRate, loan.CalcInterestAmount(period)); period = 4; Console.WriteLine("Interest for: {0}, account type: {1}, balance: {2}, period: {3} months, interest rate: {4}%\n{5}%", loan.Customer, loan.GetType(), loan.Balance, period, loan.IntrestRate, loan.CalcInterestAmount(period)); loan.Deposit(1200); Console.WriteLine("After repaying the loan the balance is: {0}", loan.Balance); //invalid period test //Console.WriteLine(loan.CalcInterestAmount(-3)); }
public void can_commit_multiple_db_operations() { var customer = new Customer { FirstName = "John", LastName = "Doe" }; var salesPerson = new SalesPerson { FirstName = "Jane", LastName = "Doe", SalesQuota = 2000 }; using (var scope = new UnitOfWorkScope()) { new EFRepository<Customer>().Add(customer); new EFRepository<SalesPerson>().Add(salesPerson); scope.Commit(); } using (var ordersTestData = new EFTestData(OrdersContextProvider())) using (var hrTestData = new EFTestData(HRContextProvider())) { Customer savedCustomer = null; SalesPerson savedSalesPerson = null; ordersTestData.Batch(action => savedCustomer = action.GetCustomerById(customer.CustomerID)); hrTestData.Batch(action => savedSalesPerson = action.GetSalesPersonById(salesPerson.Id)); Assert.That(savedCustomer, Is.Not.Null); Assert.That(savedSalesPerson, Is.Not.Null); Assert.That(savedCustomer.CustomerID, Is.EqualTo(customer.CustomerID)); Assert.That(savedSalesPerson.Id, Is.EqualTo(salesPerson.Id)); } }
public void testThreeAcounts() { Customer oscar = new Customer("Oscar") .openAccount(new Account(Account.SAVINGS)); oscar.openAccount(new Account(Account.CHECKING)); Assert.AreEqual(3, oscar.getNumberOfAccounts()); }
public static bool Charge(Customer customer, CreditCard creditCard, decimal amount) { var chargeDetails = new StripeChargeCreateOptions(); chargeDetails.Amount = (int)amount * 100; chargeDetails.Currency = "usd"; chargeDetails.Source = new StripeSourceOptions { Object = "card", Number = creditCard.CcNumber, ExpirationMonth = creditCard.ExpireDate.Month.ToString(), ExpirationYear = creditCard.ExpireDate.Year.ToString(), Cvc = creditCard.CVCCode }; var chargeService = new StripeChargeService(stripeApiKey); var response = chargeService.Create(chargeDetails); if(response.Paid == false) { throw new Exception(response.FailureMessage); } return response.Paid; }
public void Should_Return_The_Last_Inserted_Ids() { // Arrange const string sql = @" CREATE TABLE IF NOT EXISTS Customer ( CustomerId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL );"; var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqliteInMemoryDatabaseConnectionString ); new DatabaseCommand( dbConnection ) .SetCommandText( sql ) .ExecuteNonQuery( true ); var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) }; var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) }; var list = new List<Customer> { customer1, customer2, customer3 }; // Act var customerIds = new DatabaseCommand( dbConnection ) .GenerateInsertsForSQLite( list ) .ExecuteToList<long>(); // Assert Assert.That( customerIds.Count == 3 ); Assert.That( customerIds[0] == 1 ); Assert.That( customerIds[1] == 2 ); Assert.That( customerIds[2] == 3 ); }
public void testAppWithTransfer() { Account checkingAccount = new Account(Account.CHECKING); Account savingsAccount = new Account(Account.SAVINGS); Customer henry = new Customer("Henry").openAccount(checkingAccount).openAccount(savingsAccount); checkingAccount.deposit(100.0, false); savingsAccount.deposit(4000.0, false); savingsAccount.withdraw(200.0, false); henry.transfer(savingsAccount, checkingAccount, 400); Assert.AreEqual("Statement for Henry\n" + "\n" + "Checking Account\n" + " deposit $100.00\n" + " transfer to $400.00\n" + "Total $500.00\n" + "\n" + "Savings Account\n" + " deposit $4,000.00\n" + " withdrawal $200.00\n" + " transfer from $400.00\n" + "Total $3,400.00\n" + "\n" + "Total In All Accounts $3,900.00", henry.getStatement()); }
static void CustomerRepo() { var _repository = new CustomerRepository(); var aCustomer = new Customer { Name = "ABC Rentals" }; var aRetrievedCustomer = _repository.GetCustomerByNameAsync(aCustomer.Name).Result; if (aRetrievedCustomer == null) { var aKey = _repository.AddCustomer(aCustomer); var aSavedCustomer = _repository.GetCustomer(aKey); Console.WriteLine(aSavedCustomer.Id == aKey ? "Customer was saved and retrieved successfully!" : $"Saved customer key was {aSavedCustomer.Id} and new customer key was {aKey}"); } else { var aSavedCustomer = _repository.GetCustomer(aRetrievedCustomer.Id); Console.WriteLine(aSavedCustomer.Id == aRetrievedCustomer.Id ? "Customer was already in the database and retrieved successfully!" : $"Saved customer key was {aSavedCustomer.Id} and new customer key was {aRetrievedCustomer.Id}"); } }
public IResult Add(Customer customer) { _customerService.Add(customer); return(new SuccessResult(Messages.CustomerAdded)); }
public IResult Update(Customer customer) { _customerDal.Update(customer); return new SuccessResult(Messages.CustomerUpdated); }
public IResult Delete(Customer customer) { _customerDal.Delete(customer); return new SuccessResult(Messages.CustomerDeleted); }
public IResult Add(Customer customer) { _customerDal.Add(customer); return new SuccessResult(Messages.CustomerAdded); }
/// <summary> /// Formats attributes /// </summary> /// <param name="attributes">Attributes</param> /// <param name="customer">Customer</param> /// <param name="serapator">Serapator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <returns>Attributes</returns> public string FormatAttributes(string attributes, Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true) { var result = new StringBuilder(); var caCollection = _checkoutAttributeParser.ParseCheckoutAttributes(attributes); for (int i = 0; i < caCollection.Count; i++) { var ca = caCollection[i]; var valuesStr = _checkoutAttributeParser.ParseValues(attributes, ca.Id); for (int j = 0; j < valuesStr.Count; j++) { string valueStr = valuesStr[j]; string caAttribute = string.Empty; if (!ca.ShouldHaveValues()) { if (ca.AttributeControlType == AttributeControlType.MultilineTextbox) { caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), HtmlHelper.FormatText(valueStr, false, true, true, false, false, false)); } else { caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr); } } else { int caId = 0; if (int.TryParse(valueStr, out caId)) { var caValue = _checkoutAttributeService.GetCheckoutAttributeValueById(caId); if (caValue != null) { caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), caValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)); if (renderPrices) { decimal priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(caValue, customer); decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment); caAttribute += string.Format(" [+{0}]", priceAdjustmentStr); } } } } } if (!String.IsNullOrEmpty(caAttribute)) { if (i != 0 || j != 0) { result.Append(serapator); } //we don't encode multiline textbox input if (htmlEncode && ca.AttributeControlType != AttributeControlType.MultilineTextbox) { result.Append(HttpUtility.HtmlEncode(caAttribute)); } else { result.Append(caAttribute); } } } } return(result.ToString()); }
public IResult Update(Customer customer) { _customerService.Update(customer); return(new SuccessResult(Messages.CustomerUpdated)); }
public IResult Delete(Customer customer) { _customerService.Delete(customer); return(new SuccessResult(Messages.CustomerDeleted)); }
public void QuantitySelection(string s, KeyValuePair <Product, int>?purchase_item, Customer customer) { int qty; if (s.Equals("0", StringComparison.OrdinalIgnoreCase)) { return; } try { qty = int.Parse(s); } catch (Exception) { return; } if (qty <= purchase_item.Value.Value && qty > 0) { customer.AddToCart(purchase_item.Value.Key, qty); } }
public void LoadData(string fromDate, string toDate, string userID) { // create and execute query t = new DataTable(); t.Columns.Add("id"); t.Columns.Add("Date"); t.Columns.Add("Customer"); t.Columns.Add("Start"); t.Columns.Add("End"); t.Columns.Add("Details"); t.Columns.Add("Indicator"); t.Columns.Add("Period"); t.Columns.Add("Category"); t.Columns.Add("Status"); t.Columns.Add("Rate"); t.Columns.Add("Cost"); t.Columns.Add("Week"); t.Columns.Add(new DataColumn("Delete", typeof(Image))); Image delete = new Bitmap(Properties.Resources.Server_Delete_16); string Q = "SELECT * FROM schedule WHERE (`date` >= '" + fromDate + "' AND `date` <= '" + toDate + "' ) AND UserID ='" + userID + "'"; hoursDictionary.Clear(); costDictionary.Clear(); foreach (Schedule c in Schedule.List(Q)) { string user = ""; string cus = ""; try { user = Users.Select(c.UserID).Name; } catch { } try { cus = Customer.Select(c.CustomerID).Name; } catch { } double rate = Convert.ToDouble(c.Cost) / Convert.ToDouble(c.Period); t.Rows.Add(new object[] { c.Id, c.Date, cus, c.Starts, c.Ends, c.Details, c.Indicator, c.Period, c.Category, c.Status, rate, c.Cost, c.Week, delete }); hoursDictionary.Add(c.Id, Convert.ToDouble(c.Period)); costDictionary.Add(c.Id, Convert.ToDouble(c.Cost)); } hrs = hoursDictionary.Sum(y => y.Value); hourTxt.Text = hrs.ToString(); dtGrid.DataSource = t; totalPayTxt.Text = costDictionary.Sum(y => y.Value).ToString(); cost = costDictionary.Sum(y => y.Value); workedTxt.Text = cost.ToString("N0"); rateLbl.Text = (cost / hrs).ToString("N0"); dtGrid.AllowUserToAddRows = false; dtGrid.Columns["Start"].DefaultCellStyle.BackColor = Color.LightGreen; dtGrid.Columns["End"].DefaultCellStyle.BackColor = Color.LightPink; dtGrid.Columns["id"].Visible = false; string summary = ""; foreach (DataGridViewRow row in dtGrid.Rows) { try { summary = row.Cells["Status"].Value.ToString(); } catch { } if (summary.Contains("Paid")) { row.DefaultCellStyle.ForeColor = Color.Green; row.DefaultCellStyle.Font = new Font("Calibri", 9.5F, FontStyle.Bold, GraphicsUnit.Pixel); } else if (summary.Contains("Pending")) { row.DefaultCellStyle.ForeColor = Color.DarkGray; } else { row.DefaultCellStyle.ForeColor = Color.Black; } } }
public string Add(Customer customer) { return("Customer added successfully"); }
public async System.Threading.Tasks.Task Delete(Customer entity) { await _session.DeleteAsync(entity); }
public bool Transfer(double amount, string toAccountID, Bank toBank, string currencyId, Customer customer, int modeOfTransacation) { double RateOfExchange = 0; TransactionMode ModeOfTransaction = (TransactionMode)modeOfTransacation; foreach (var currency in Bank.Currencies) { if (currency.Id.Equals(currencyId)) { RateOfExchange = currency.ExchangeRate; } } if (RateOfExchange == 0) { return(false); } double ConvertedAmount = amount * RateOfExchange; double ServiceCharges = 0; if (toBank != null) { CustomerServices NewService = new CustomerServices(Bank); Customer ToCustomer = NewService.GetCustomer(toBank, toAccountID); if (ToCustomer != null) { switch (ModeOfTransaction) { case TransactionMode.RTGS: { if (toBank.BankID.Equals(Bank.BankID)) { ServiceCharges = amount * (Bank.same.rtgs * 0.01); } else { ServiceCharges = amount * (Bank.different.rtgs * 0.01); } break; } case TransactionMode.IMPS: { if (toBank.BankID.Equals(Bank.BankID)) { ServiceCharges = amount * (Bank.same.imps * 0.01); } else { ServiceCharges = amount * (Bank.different.imps * 0.01); } break; } } if (customer.Balance > amount + ServiceCharges) { customer.Balance -= (amount + ServiceCharges); ToCustomer.Balance += ConvertedAmount; TransactionServices NewTransaction = new TransactionServices(customer); string TransactionID = NewTransaction.GenerateTransactionID(Bank); NewTransaction.AddTransaction(amount, TransactionID, "Transfer", "success", DateTime.Now.ToString("yyyymmdd")); return(true); } else { TransactionServices NewTransaction = new TransactionServices(customer); string TransactionID = NewTransaction.GenerateTransactionID(Bank); NewTransaction.AddTransaction(amount, TransactionID, "Transfer", "Failed", DateTime.Now.ToString("yyyymmdd")); return(false); } } } return(false); }
void Update() { //store script component of interactables. if (timeForMaxSpeed >= 0) { timeForMaxSpeed -= Time.deltaTime; } if (toInteract) { Interactable objToInteract = toInteract.GetComponent <Interactable>(); //check for vegetables if (objToInteract.Type == "Vegetable" && Input.GetKeyDown(useKey) && vegetablesInHand.Count < 2) { //add vege to hand string vegeName = objToInteract.Name; AddToPlayerHand(vegeName); } //check for chopping Board if (objToInteract.Type == "Board") { //storing argument to pass on function.. int boardID = objToInteract.ID; choppedVege = toInteract.GetComponent <ChoppingBoard>(); //chop vegetables. if (vegetablesInHand.Count > 0 && Input.GetKeyDown(useKey) && choppedVege.Container.Count < 3 && !startChoping) { isChopping = true; StartCoroutine(ChoppingVege(boardID, choppedVege)); } //pick up dish from Board. else if (vegetablesInHand.Count == 0 && Input.GetKeyDown(useKey) && readyDish.text == "") { //add dish on player hand AddSaladOnPlayer(boardID); } } //check for Dustbin if (objToInteract.Type == "Dustbin") { //delete choppedvege list if (Input.GetKeyDown(useKey)) { if (choppedVege) { ClearChoppedVegeBoard(choppedVege); } } } //check for Dish if (objToInteract.Type == "Dish" && Input.GetKeyDown(useKey)) { int dishID = objToInteract.ID; dishItem = toInteract.GetComponent <Dish>(); AddToDish(dishID, dishItem); } //check for Customer if (objToInteract.Type == "Customer" && Input.GetKeyDown(useKey)) { // Debug.Log("Customer Interaction."); cust = objToInteract.GetComponent <Customer>(); isCustomerDone(); } } }
public async Task<IActionResult> Get([FromRoute] int id, [FromQuery] string include) { using (SqlConnection conn = Connection) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" SELECT c.Id AS CustomerIdNumber, c.FirstName, c.LastName, c.CreatedDate, c.Active, c.Address, c.City, c.State, c.Email, c.Phone"; if (include == "products") { cmd.CommandText += ", p.Id as ProductId, p.ProductTypeId, p.Price, p.Title, p.Description, p.CustomerId, p.DateAdded"; } cmd.CommandText += " FROM Customer c"; if (include == "products") { cmd.CommandText += " LEFT JOIN Product p ON p.CustomerId = c.Id"; } cmd.CommandText += " WHERE c.Id = @id"; cmd.Parameters.Add(new SqlParameter("@id", id)); SqlDataReader reader = cmd.ExecuteReader(); Customer customer = null; while (reader.Read()) { if (customer == null) { customer = new Customer { Id = reader.GetInt32(reader.GetOrdinal("CustomerIdNumber")), FirstName = reader.GetString(reader.GetOrdinal("FirstName")), LastName = reader.GetString(reader.GetOrdinal("LastName")), CreatedDate = reader.GetDateTime(reader.GetOrdinal("CreatedDate")), Active = reader.GetBoolean(reader.GetOrdinal("Active")), Address = reader.GetString(reader.GetOrdinal("Address")), City = reader.GetString(reader.GetOrdinal("City")), State = reader.GetString(reader.GetOrdinal("State")), Email = reader.GetString(reader.GetOrdinal("Email")), Phone = reader.GetString(reader.GetOrdinal("Phone")), Products = new List<Product>() }; } if (include == "products") { if (include == "products" && !reader.IsDBNull(reader.GetOrdinal("ProductId"))) { customer.Products.Add(new Product() { Id = reader.GetInt32(reader.GetOrdinal("ProductId")), Price = reader.GetDecimal(reader.GetOrdinal("Price")), Title = reader.GetString(reader.GetOrdinal("Title")), Description = reader.GetString(reader.GetOrdinal("Description")), DateAdded = reader.GetDateTime(reader.GetOrdinal("DateAdded")), ProductTypeId = reader.GetInt32(reader.GetOrdinal("ProductTypeId")), CustomerId = reader.GetInt32(reader.GetOrdinal("CustomerId")) }); } } } reader.Close(); return Ok(customer); } } }
/// <summary> /// The main purpose of this function is to run a while loop until the user is done with all of their interactions. /// It has checks to make sure that input for a menu selection is valid as well as checks for input from the user in each selection menu option /// </summary> /// <param name="storeRepository"> This is the reference to the StoreRepository to call the functions to be handled by the db</param> public static void RunMenuSelection(IStoreRepository storeRepository) { // Begin the app loop to collect input string menuOption = ""; string response; // Display Options Console.WriteLine(menu); while (menuOption != "q") { // Collect Input menuOption = Console.ReadLine(); if (InputValidation.IsValidMainMenuSelection(menuOption, out response)) { string input = ""; switch (menuOption) { case "p": Console.WriteLine("You have selected [Place an order for an existing customer]. Please enter the customer ID you want to place the order for:"); string number = Console.ReadLine(); // Get input until a valid name is given while (!InputValidation.IsValidNumber(number)) { Console.WriteLine(response); number = Console.ReadLine(); } int id = Int32.Parse(number); // Once a valid name is given try to assign it to a new object var existingCustomer = new Customer(); // Get a customer from the database Console.WriteLine("Searching db for customer..."); existingCustomer = storeRepository.GetCustomerWithLocationAndInventory(id); // if an exception was thrown then end this switch if (existingCustomer == null) { Console.WriteLine("Customer does not exist. Please pick a menu option to begin again."); break; } // Continue though if the customer did exist Console.WriteLine($"Selected Customer: {existingCustomer}"); // Begin the prompt to get each order line. Console.WriteLine("Please enter the product ISBN and quantity separated by a comma.\nType [done] when order is complete."); string orderlineItem; // Create the new order to add the orderlines and to use the library methods to ensure that it is possible to create the order. var order = new Order(); orderlineItem = Console.ReadLine(); // This function will fill the static list of the entire catalog to be used by any function or object storeRepository.FillBookLibrary(); bool success = true; // Collect input untill there is a failure while (orderlineItem != "done") { // If a failure does occur let the user know they must begin transaction from the beginning if (!order.AddNewOrderLine(orderlineItem)) { Console.WriteLine("Either the ISBN does not exist in our library, our quantity was not a valid number," + " or you attempted to place an order with an unreasonable amount of product." + "\nPlease start process again from the main menu."); success = !success; break; } // Let them know if it a success and then continue collecting input until it fails Console.WriteLine("Successfully added to the order."); orderlineItem = Console.ReadLine(); } if (!success) { break; } // Now that we've collected and created all the objects we assign them to the order to be mapped later order.CustomerPlaced = existingCustomer; order.LocationPlaced = existingCustomer.MyStoreLocation; // Before that though we want to make sure we can place the order with the given locations inventory if (!order.LocationPlaced.AttemptOrderAtLocation(order, out response)) { // If it failed, let the user know why and then end the switch Console.WriteLine(response); break; } Console.WriteLine(response); // If it is possible then we send the data over to the db so that it is saved Console.WriteLine("Placing order..."); storeRepository.PlaceAnOrderForACustomer(order); Console.WriteLine("Order Placed!"); break; case "a": Console.WriteLine("You Have selected [Add New Customer]." + "\nPlease enter the name of the first and last name of the customer separated by a space:"); input = Console.ReadLine(); // Collect input until a valid name is given while (!InputValidation.IsValidCustomerName(input, out response)) { Console.WriteLine(response); input = Console.ReadLine(); } // attempt to attach the name to a model object if it fails let the user know that it failed and why string[] newCustomerNames = input.Split(' '); var newCustomer = new Customer(); try { newCustomer.FirstName = newCustomerNames[0]; newCustomer.LastName = newCustomerNames[1]; } catch (ArgumentException ex) { Console.WriteLine(ex.Message + "\nPlease start process again from the main menu."); break; } // Add the new customer to the database storeRepository.AddACustomer(newCustomer); // let the user know that it was successful Console.WriteLine($"Customer {newCustomer.FirstName} {newCustomer.LastName} was added with the default location."); break; case "sc": Console.WriteLine("You Have selected [Search By Customer Name]." + "\nPlease enter the full name of the customer:"); input = Console.ReadLine(); // Collect input until a valid name is given while (!InputValidation.IsValidCustomerName(input, out response)) { Console.WriteLine(response); input = Console.ReadLine(); } string[] candidate = input.Split(' '); var a = new Customer(); // Attempt to take the name and split it into two the customer try { a.FirstName = candidate[0]; a.LastName = candidate[1]; } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } // If the strings are valid then we attempt to find the customer List <Customer> foundCustomer = storeRepository.FindCustomerByName(candidate); // Let the user know what we found if (foundCustomer.Count() == 0) { Console.WriteLine($"No customer by the name of {candidate[0]} {candidate[1]} exists in the database."); } else { foreach (Customer c in foundCustomer) { Console.WriteLine(c); } } break; case "ddo": Console.WriteLine("You Have selected [Display Details of an Order]." + "\nPlease enter the order number:"); input = Console.ReadLine(); // Do Some input validation while (!InputValidation.IsValidNumber(input)) { Console.WriteLine("Input was not a number, please input a number."); input = Console.ReadLine(); } Console.WriteLine(storeRepository.GetDetailsForOrder(Int32.Parse(input))); break; case "dhl": Console.WriteLine("You Have selected [Display Order History of Location]." + "\nPlease enter the location ID:"); input = Console.ReadLine(); // do some input validation while (!InputValidation.IsValidNumber(input)) { Console.WriteLine("Input was not a number, please input a number."); input = Console.ReadLine(); } Console.WriteLine(storeRepository.GetOrderHistoryByLocationID(Int32.Parse(input))); break; case "dhc": Console.WriteLine("You Have selected [Display Order History of Customer]. Please enter the customer ID:"); input = Console.ReadLine(); // do some input validation until a valid two string is given while (!InputValidation.IsValidNumber(input)) { Console.WriteLine(response); input = Console.ReadLine(); } // Print what was found Console.WriteLine(storeRepository.GetOrderHistoryByCustomer(Int32.Parse(input))); break; case "help": // Print the menu options again for those that need it Console.WriteLine(menu); break; case "q": // Exit the program. Console.WriteLine("You Have selected [Quit]."); break; } } else { Console.WriteLine(response); } } }
public async System.Threading.Tasks.Task Save(Customer entity) { await _session.SaveOrUpdateAsync(entity); }
public IPremiumCalculatorBuilder SetCustomer(Customer customer) { this.customer = customer; return(this); }
public bool CheckIfRealPerson(Customer customer) { return(true); }
/// <summary> /// Prepare the customer info model /// </summary> /// <param name="model">Customer info model</param> /// <param name="customer">Customer</param> /// <param name="excludeProperties">Whether to exclude populating of model properties from the entity</param> /// <param name="overrideCustomCustomerAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param> /// <returns>Customer info model</returns> public virtual CustomerInfoModel PrepareCustomerInfoModel(CustomerInfoModel model, Customer customer, bool excludeProperties, string overrideCustomCustomerAttributesXml = "") { if (model == null) { throw new ArgumentNullException("model"); } if (customer == null) { throw new ArgumentNullException("customer"); } model.AllowCustomersToSetTimeZone = _dateTimeSettings.AllowCustomersToSetTimeZone; foreach (var tzi in _dateTimeHelper.GetSystemTimeZones()) { model.AvailableTimeZones.Add(new SelectListItem { Text = tzi.DisplayName, Value = tzi.Id, Selected = (excludeProperties ? tzi.Id == model.TimeZoneId : tzi.Id == _dateTimeHelper.CurrentTimeZone.Id) }); } if (!excludeProperties) { model.VatNumber = customer.GetAttribute <string>(SystemCustomerAttributeNames.VatNumber); model.FirstName = customer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName); model.LastName = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastName); model.Gender = customer.GetAttribute <string>(SystemCustomerAttributeNames.Gender); var dateOfBirth = customer.GetAttribute <DateTime?>(SystemCustomerAttributeNames.DateOfBirth); if (dateOfBirth.HasValue) { model.DateOfBirthDay = dateOfBirth.Value.Day; model.DateOfBirthMonth = dateOfBirth.Value.Month; model.DateOfBirthYear = dateOfBirth.Value.Year; } model.Company = customer.GetAttribute <string>(SystemCustomerAttributeNames.Company); model.StreetAddress = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress); model.StreetAddress2 = customer.GetAttribute <string>(SystemCustomerAttributeNames.StreetAddress2); model.ZipPostalCode = customer.GetAttribute <string>(SystemCustomerAttributeNames.ZipPostalCode); model.City = customer.GetAttribute <string>(SystemCustomerAttributeNames.City); model.CountryId = customer.GetAttribute <int>(SystemCustomerAttributeNames.CountryId); model.StateProvinceId = customer.GetAttribute <int>(SystemCustomerAttributeNames.StateProvinceId); model.Phone = customer.GetAttribute <string>(SystemCustomerAttributeNames.Phone); model.Fax = customer.GetAttribute <string>(SystemCustomerAttributeNames.Fax); //newsletter var newsletter = _newsLetterSubscriptionService.GetNewsLetterOrderByEmailAndStoreId(customer.Email, _storeContext.CurrentStore.Id); model.Newsletter = newsletter != null && newsletter.Active; model.Signature = customer.GetAttribute <string>(SystemCustomerAttributeNames.Signature); model.Email = customer.Email; model.Username = customer.Username; } else { if (_customerSettings.UsernamesEnabled && !_customerSettings.AllowUsersToChangeUsernames) { model.Username = customer.Username; } } if (_customerSettings.UserRegistrationType == UserRegistrationType.EmailValidation) { model.EmailToRevalidate = customer.EmailToRevalidate; } //countries and states if (_customerSettings.CountryEnabled) { model.AvailableCountries.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectCountry"), Value = "0" }); foreach (var c in _countryService.GetAllCountries(_workContext.WorkingLanguage.Id)) { model.AvailableCountries.Add(new SelectListItem { Text = c.GetLocalized(x => x.Name), Value = c.Id.ToString(), Selected = c.Id == model.CountryId }); } if (_customerSettings.StateProvinceEnabled) { //states var states = _stateProvinceService.GetStateProvincesByCountryId(model.CountryId, _workContext.WorkingLanguage.Id).ToList(); if (states.Any()) { model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource("Address.SelectState"), Value = "0" }); foreach (var s in states) { model.AvailableStates.Add(new SelectListItem { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = (s.Id == model.StateProvinceId) }); } } else { bool anyCountrySelected = model.AvailableCountries.Any(x => x.Selected); model.AvailableStates.Add(new SelectListItem { Text = _localizationService.GetResource(anyCountrySelected ? "Address.OtherNonUS" : "Address.SelectState"), Value = "0" }); } } } model.DisplayVatNumber = _taxSettings.EuVatEnabled; model.VatNumberStatusNote = ((VatNumberStatus)customer.GetAttribute <int>(SystemCustomerAttributeNames.VatNumberStatusId)) .GetLocalizedEnum(_localizationService, _workContext); model.GenderEnabled = _customerSettings.GenderEnabled; model.DateOfBirthEnabled = _customerSettings.DateOfBirthEnabled; model.DateOfBirthRequired = _customerSettings.DateOfBirthRequired; model.CompanyEnabled = _customerSettings.CompanyEnabled; model.CompanyRequired = _customerSettings.CompanyRequired; model.StreetAddressEnabled = _customerSettings.StreetAddressEnabled; model.StreetAddressRequired = _customerSettings.StreetAddressRequired; model.StreetAddress2Enabled = _customerSettings.StreetAddress2Enabled; model.StreetAddress2Required = _customerSettings.StreetAddress2Required; model.ZipPostalCodeEnabled = _customerSettings.ZipPostalCodeEnabled; model.ZipPostalCodeRequired = _customerSettings.ZipPostalCodeRequired; model.CityEnabled = _customerSettings.CityEnabled; model.CityRequired = _customerSettings.CityRequired; model.CountryEnabled = _customerSettings.CountryEnabled; model.CountryRequired = _customerSettings.CountryRequired; model.StateProvinceEnabled = _customerSettings.StateProvinceEnabled; model.StateProvinceRequired = _customerSettings.StateProvinceRequired; model.PhoneEnabled = _customerSettings.PhoneEnabled; model.PhoneRequired = _customerSettings.PhoneRequired; model.FaxEnabled = _customerSettings.FaxEnabled; model.FaxRequired = _customerSettings.FaxRequired; model.NewsletterEnabled = _customerSettings.NewsletterEnabled; model.UsernamesEnabled = _customerSettings.UsernamesEnabled; model.AllowUsersToChangeUsernames = _customerSettings.AllowUsersToChangeUsernames; model.CheckUsernameAvailabilityEnabled = _customerSettings.CheckUsernameAvailabilityEnabled; model.SignatureEnabled = _forumSettings.ForumsEnabled && _forumSettings.SignaturesEnabled; //external authentication model.NumberOfExternalAuthenticationProviders = _openAuthenticationService .LoadActiveExternalAuthenticationMethods(_workContext.CurrentCustomer, _storeContext.CurrentStore.Id).Count; foreach (var ear in _openAuthenticationService.GetExternalIdentifiersFor(customer)) { var authMethod = _openAuthenticationService.LoadExternalAuthenticationMethodBySystemName(ear.ProviderSystemName); if (authMethod == null || !authMethod.IsMethodActive(_externalAuthenticationSettings)) { continue; } model.AssociatedExternalAuthRecords.Add(new CustomerInfoModel.AssociatedExternalAuthModel { Id = ear.Id, Email = ear.Email, ExternalIdentifier = ear.ExternalIdentifier, AuthMethodName = authMethod.GetLocalizedFriendlyName(_localizationService, _workContext.WorkingLanguage.Id) }); } //custom customer attributes var customAttributes = PrepareCustomCustomerAttributes(customer, overrideCustomCustomerAttributesXml); customAttributes.ForEach(model.CustomerAttributes.Add); return(model); }
public JsonResult UpdateAbonentStatus(int cust_id, string dataval, int buyreason_status, int satisfied_status, string info) { if (!Utils.Utils.GetPermission("SET_VERIFYSTATUS_CARDS")) { return Json(0); } using (DataContext _db = new DataContext()) { using (DbContextTransaction tran = _db.Database.BeginTransaction(IsolationLevel.Snapshot)) { try { int user_id = ((User)Session["CurrentUser"]).Id; //int user_id = ((User)Session["CurrentUser"]).Id; Customer cust = _db.Customers.Where(c => c.Id == cust_id).FirstOrDefault(); if (cust != null) { switch(dataval) { case "buy_reason": { cust.BuyReason = (AbonentBuyReason)buyreason_status; cust.Info = info; _db.Entry(cust).State = EntityState.Modified; } break; case "is_satisfied": { cust.IsSatisfied = (AbonentSatisfiedStatus)satisfied_status; cust.Desc = info; _db.Entry(cust).State = EntityState.Modified; } break; } //card.VerifyStatus = (CardVerifyStatus)verify_status; //card.Info = info; //_db.Entry(card).State = EntityState.Modified; //_db.Loggings.Add(new Logging() //{ // Tdate = DateTime.Now, // UserId = user_id, // Type = LogType.Card, // Mode = LogMode.Verify, // TypeValue = card.CardNum, // TypeId = card.Id //}); _db.SaveChanges(); tran.Commit(); return Json(1); } } catch (Exception ex) { tran.Rollback(); return Json(0); } } } return Json(0); }
private async Task OnCheckoutMessageReceived(ProcessMessageEventArgs args) { var messageBody = Encoding.UTF8.GetString(args.Message.Body); var basketCheckoutMessage = JsonConvert.DeserializeObject <BasketCheckoutMessageDto>(messageBody); await using var _orderDbContext = new OrderDbContext(_options); var existingCustomer = await _orderDbContext.Customers.FindAsync(basketCheckoutMessage.UserId); if (existingCustomer == null) { var newCustomer = new Customer { Id = basketCheckoutMessage.UserId, FirstName = basketCheckoutMessage.FirstName, LastName = basketCheckoutMessage.LastName, Email = basketCheckoutMessage.Email, Address = basketCheckoutMessage.Address, ZipCode = basketCheckoutMessage.ZipCode, City = basketCheckoutMessage.City, Country = basketCheckoutMessage.Country }; await _orderDbContext.Customers.AddAsync(newCustomer); } Guid orderId = Guid.NewGuid(); var order = new Order { UserId = basketCheckoutMessage.UserId, Id = orderId, OrderPaid = false, OrderPlaced = DateTime.Now, OrderTotal = basketCheckoutMessage.BasketTotal }; order.OrderLines = new List <OrderLine>(); foreach (var bLine in basketCheckoutMessage.BasketLines) { var orderLine = new OrderLine { Id = Guid.NewGuid(), Price = bLine.Price, TicketAmount = bLine.TicketAmount, EventId = bLine.EventId, EventName = bLine.EventName, EventDate = bLine.EventDate, VenueName = bLine.VenueName, VenueCity = bLine.VenueCity, VenueCountry = bLine.VenueCountry }; order.OrderLines.Add(orderLine); } await _orderDbContext.Orders.AddAsync(order); var orderPaymentRequestMessage = new OrderPaymentRequestMessage { CardExpiration = basketCheckoutMessage.CardExpiration, CardName = basketCheckoutMessage.CardName, CardNumber = basketCheckoutMessage.CardNumber, OrderId = orderId, Total = basketCheckoutMessage.BasketTotal }; try { await _orderDbContext.SaveChangesAsync(); await _messageBus.PublishMessage(orderPaymentRequestMessage, _orderPaymentRequestMessageTopic); await args.CompleteMessageAsync(args.Message); } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Formats attributes /// </summary> /// <param name="attributesXml">Attributes in XML format</param> /// <param name="customer">Customer</param> /// <param name="separator">Separator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param> /// <returns>Attributes</returns> public virtual string FormatAttributes(string attributesXml, Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { var result = new StringBuilder(); var attributes = _checkoutAttributeParser.ParseCheckoutAttributes(attributesXml); for (var i = 0; i < attributes.Count; i++) { var attribute = attributes[i]; var valuesStr = _checkoutAttributeParser.ParseValues(attributesXml, attribute.Id); for (var j = 0; j < valuesStr.Count; j++) { var valueStr = valuesStr[j]; var formattedAttribute = ""; if (!attribute.ShouldHaveValues()) { //no values if (attribute.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox var attributeName = attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = $"{attributeName}: {HtmlHelper.FormatText(valueStr, false, true, false, false, false, false)}"; //we never encode multiline textbox input } else if (attribute.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid.TryParse(valueStr, out Guid downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download != null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string attributeText; var fileName = $"{download.Filename ?? download.DownloadGuid.ToString()}{download.Extension}"; //encode (if required) if (htmlEncode) { fileName = WebUtility.HtmlEncode(fileName); } if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = $"{_webHelper.GetStoreLocation(false)}download/getfileupload/?downloadId={download.DownloadGuid}"; attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>"; } else { //hyperlinks aren't allowed attributeText = fileName; } var attributeName = attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id); //encode (if required) if (htmlEncode) { attributeName = WebUtility.HtmlEncode(attributeName); } formattedAttribute = $"{attributeName}: {attributeText}"; } } else { //other attributes (textbox, datepicker) formattedAttribute = $"{attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)}: {valueStr}"; //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } else { if (int.TryParse(valueStr, out int attributeValueId)) { var attributeValue = _checkoutAttributeService.GetCheckoutAttributeValueById(attributeValueId); if (attributeValue != null) { formattedAttribute = $"{attribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)}: {attributeValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id)}"; if (renderPrices) { var priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(attributeValue, customer); var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { var priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment); formattedAttribute += $" [+{priceAdjustmentStr}]"; } } } //encode (if required) if (htmlEncode) { formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); } } } if (!string.IsNullOrEmpty(formattedAttribute)) { if (i != 0 || j != 0) { result.Append(separator); } result.Append(formattedAttribute); } } } return(result.ToString()); }
public ActionResult ExcelUpload() { var Message = "Success"; try { var file = Request.Form.Files[0]; var folderName = Path.Combine("Resources", "TempFile"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); if (file.Length > 0) { var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); var fullPath = Path.Combine(pathToSave, fileName); var dbPath = Path.Combine(folderName, fileName); IExcelDataReader reader = null; using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); //Copy to directory if (file.FileName.EndsWith(".xls")) { reader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (file.FileName.EndsWith(".xlsx")) { reader = ExcelReaderFactory.CreateOpenXmlReader(stream); } DataSet excelRecords = reader.AsDataSet(); reader.Close(); var finalRecords = excelRecords.Tables[0]; for (int i = 0; i < finalRecords.Rows.Count; i++) { Customer oCustomer = new Customer(); oCustomer.Name = finalRecords.Rows[i][0].ToString(); oCustomer.Profession = finalRecords.Rows[i][1].ToString(); oCustomer.MonthlyIncome = Convert.ToDouble(finalRecords.Rows[i][2].ToString()); oCustomer.EducatonLevel = EducationLavel(finalRecords.Rows[i][3].ToString()); EnumSection myStatus; Enum.TryParse(finalRecords.Rows[i][4].ToString(), out myStatus); //Convert string to enum oCustomer.Section = Convert.ToInt16(myStatus); //Convert enum to int oCustomer.Latitude = Convert.ToDouble(finalRecords.Rows[i][5]); oCustomer.Longitude = Convert.ToDouble(finalRecords.Rows[i][6]); _oCustomer = oCustomer.Save(oCustomer); } } return(Ok(new { Message })); } else { Message = "Sorry, There is No File"; return(Ok(new { Message })); } } catch (Exception e) { Message = e.Message; } return(Ok(new { Message })); }
/// <summary> /// Prepare the custom customer attribute models /// </summary> /// <param name="customer">Customer</param> /// <param name="overrideAttributesXml">Overridden customer attributes in XML format; pass null to use CustomCustomerAttributes of customer</param> /// <returns>List of the customer attribute model</returns> public virtual IList <CustomerAttributeModel> PrepareCustomCustomerAttributes(Customer customer, string overrideAttributesXml = "") { if (customer == null) { throw new ArgumentNullException("customer"); } var result = new List <CustomerAttributeModel>(); var customerAttributes = _customerAttributeService.GetAllCustomerAttributes(); foreach (var attribute in customerAttributes) { var attributeModel = new CustomerAttributeModel { Id = attribute.Id, Name = attribute.GetLocalized(x => x.Name), IsRequired = attribute.IsRequired, AttributeControlType = attribute.AttributeControlType, }; if (attribute.ShouldHaveValues()) { //values var attributeValues = _customerAttributeService.GetCustomerAttributeValues(attribute.Id); foreach (var attributeValue in attributeValues) { var valueModel = new CustomerAttributeValueModel { Id = attributeValue.Id, Name = attributeValue.GetLocalized(x => x.Name), IsPreSelected = attributeValue.IsPreSelected }; attributeModel.Values.Add(valueModel); } } //set already selected attributes var selectedAttributesXml = !String.IsNullOrEmpty(overrideAttributesXml) ? overrideAttributesXml : customer.GetAttribute <string>(SystemCustomerAttributeNames.CustomCustomerAttributes, _genericAttributeService); switch (attribute.AttributeControlType) { case AttributeControlType.DropdownList: case AttributeControlType.RadioList: case AttributeControlType.Checkboxes: { if (!String.IsNullOrEmpty(selectedAttributesXml)) { //clear default selection foreach (var item in attributeModel.Values) { item.IsPreSelected = false; } //select new values var selectedValues = _customerAttributeParser.ParseCustomerAttributeValues(selectedAttributesXml); foreach (var attributeValue in selectedValues) { foreach (var item in attributeModel.Values) { if (attributeValue.Id == item.Id) { item.IsPreSelected = true; } } } } } break; case AttributeControlType.ReadonlyCheckboxes: { //do nothing //values are already pre-set } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: { if (!String.IsNullOrEmpty(selectedAttributesXml)) { var enteredText = _customerAttributeParser.ParseValues(selectedAttributesXml, attribute.Id); if (enteredText.Any()) { attributeModel.DefaultValue = enteredText[0]; } } } break; case AttributeControlType.ColorSquares: case AttributeControlType.ImageSquares: case AttributeControlType.Datepicker: case AttributeControlType.FileUpload: default: //not supported attribute control types break; } result.Add(attributeModel); } return(result); }
public static void RunUi(IBookRepository bookRepository, ICustomerRepository customerRepository, XmlSerializer serializer) { Console.WriteLine("Book Store"); while (true) { Console.WriteLine(); Console.WriteLine("c:\tDisplay and manage customers."); Console.WriteLine("a:\tAdd new customers."); Console.WriteLine("b:\tDisplay or Manage books."); Console.WriteLine("s:\tSave data to disk."); Console.WriteLine(); Console.Write("Enter valid menu option, or \"q\" to quit: "); var input = Console.ReadLine(); if (input == "c") { var customers = customerRepository.GetCustomers().ToList(); Console.WriteLine(); if (customers.Count == 0) { Console.WriteLine("No customers."); } while (customers.Count > 0) { for (var i = 1; i <= customers.Count; i++) { Customer customer = customers[i - 1]; var customerString = $"{i}: \"{customer.FirstName}\""; if (customer.Addresses?.Count > 0) { Console.WriteLine(customerString); } } Console.WriteLine(); Console.Write("Enter valid menu option, or \"b\" to go back: "); input = Console.ReadLine(); if (int.TryParse(input, out var customerNum) && customerNum > 0 && customerNum <= customers.Count) { Customer customer = customers[customerNum - 1]; List <Address> addresses = customer.Addresses; while (true) { Console.WriteLine(); var customerString = $"\"{customer.FirstName}\""; if (customer.Addresses?.Count > 0) { Console.WriteLine(customerString); } if (addresses.Count > 0) { Console.WriteLine("c:\tDisplay addresses."); } Console.WriteLine("a:\tAdd review."); Console.WriteLine("e:\tEdit."); Console.WriteLine("d:\tDelete."); Console.WriteLine(); Console.Write("Enter valid menu option, or \"b\" to go back: "); input = Console.ReadLine(); if (input == "c" && addresses.Count > 0) { while (addresses.Count > 0) { Console.WriteLine(); for (var i = 1; i <= addresses.Count; i++) { Address address = addresses[i - 1]; Console.WriteLine($"{i}:" + $" From \"{address.City}\"" + $" In \"{address.States}\""); } Console.WriteLine(); Console.Write("Enter valid menu option," + " or \"b\" to go back: "); input = Console.ReadLine(); if (int.TryParse(input, out var addressNum) && addressNum > 0 && addressNum <= addresses.Count) { Console.WriteLine(); Console.WriteLine("e:\tEdit."); Console.WriteLine("d:\tDelete."); Console.WriteLine(); Console.Write("Enter valid menu option, " + "or \"b\" to go back: "); input = Console.ReadLine(); } else if (input == "b") { break; } else { Console.WriteLine(); Console.WriteLine($"Invalid input \"{input}\"."); } } } } } } } else if (input == "a") { var customer = new Customer(); while (customer.FirstName == null) { Console.WriteLine(); Console.Write("Enter the new customer name: "); input = Console.ReadLine(); try { customer.FirstName = input; } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } } customerRepository.AddCustomer(customer); customerRepository.Save(); } else if (input == "s") { Console.WriteLine(); var customers = customerRepository.GetCustomers().ToList(); try { using (var stream = new FileStream("../../../data.xml", FileMode.Create)) { serializer.Serialize(stream, customers); } Console.WriteLine("Success."); } catch (SecurityException ex) { Console.WriteLine($"Error while saving: {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"Error while saving: {ex.Message}"); } } else if (input == "l") { Console.WriteLine(); List <Customer> customers; try { using (var stream = new FileStream("../../../data.xml", FileMode.Open)) { customers = (List <Customer>)serializer.Deserialize(stream); } Console.WriteLine("Success."); foreach (Customer item in customerRepository.GetCustomers()) { customerRepository.DeleteCustomer(item.CustomerId); } foreach (Customer item in customers) { customerRepository.AddCustomer(item); } customerRepository.Save(); } catch (FileNotFoundException) { Console.WriteLine("No saved data found."); } catch (SecurityException ex) { Console.WriteLine($"Error while loading: {ex.Message}"); } catch (IOException ex) { Console.WriteLine($"Error while loading: {ex.Message}"); } } else if (input == "q") { break; } else { Console.WriteLine(); Console.WriteLine($"Invalid input \"{input}\"."); } } }
public BuyingState(float buyTime, Customer customer, CustomerEvents customerEvents) { _buyTime = buyTime; _customer = customer; _customerEvents = customerEvents; }
public ActionResult SetCustomer(int id, int value) { var entity = SalesOrder.Find(id); var item = Customer.TryFind(value); if (entity.IsCompleted || entity.IsCancelled) { Response.StatusCode = 400; return(Content(Resources.ItemAlreadyCompletedOrCancelled)); } if (item != null) { entity.Customer = item; entity.Contact = null; entity.ShipTo = null; entity.CustomerShipTo = null; entity.CustomerName = null; if (item.SalesPerson == null) { entity.SalesPerson = CurrentUser.Employee; } else { entity.SalesPerson = item.SalesPerson; } if (entity.Terms == PaymentTerms.NetD && !entity.Customer.HasCredit) { entity.Terms = PaymentTerms.Immediate; } switch (entity.Terms) { case PaymentTerms.Immediate: entity.DueDate = entity.Date; break; case PaymentTerms.NetD: entity.DueDate = entity.Date.AddDays(entity.Customer.CreditDays); break; } entity.Updater = CurrentUser.Employee; entity.ModificationTime = DateTime.Now; entity.Recipient = string.Empty; entity.RecipientName = string.Empty; entity.RecipientAddress = null; using (var scope = new TransactionScope()) { entity.UpdateAndFlush(); } } return(Json(new { id = id, value = entity.FormattedValueFor(x => x.Customer), terms = entity.Terms, termsText = entity.Terms.GetDisplayName(), dueDate = entity.FormattedValueFor(x => x.DueDate), salesPerson = entity.SalesPerson.Id, salesPersonName = entity.SalesPerson.Name })); }
public ActionResult Create(Customer customer) { _context.Customers.Add(customer); _context.SaveChanges(); return(RedirectToAction("Index", "Customers")); }
public void getName() { Customer customer = new Customer("Shyam"); Assert.AreEqual("Shyam", customer.GetName()); }
private string GetDisplayNameForCustomer(Customer customer) { return(customer.GetFullName().NullEmpty() ?? customer.Username ?? customer.FindEmail()); }