private async Task CheckOrRequestAddressBookPermission() { if (!await _addressBook.RequestPermission()) { _addressBook = null; } }
/// <summary> /// Iterates though all people in the AddressBook and prints info about them. /// </summary> static void Print(AddressBook addressBook) { foreach (Person person in addressBook.PersonList) { Console.WriteLine("Person ID: {0}", person.Id); Console.WriteLine(" Name: {0}", person.Name); if (person.HasEmail) { Console.WriteLine(" E-mail address: {0}", person.Email); } foreach (Person.Types.PhoneNumber phoneNumber in person.PhoneList) { switch (phoneNumber.Type) { case Person.Types.PhoneType.MOBILE: Console.Write(" Mobile phone #: "); break; case Person.Types.PhoneType.HOME: Console.Write(" Home phone #: "); break; case Person.Types.PhoneType.WORK: Console.Write(" Work phone #: "); break; } Console.WriteLine(phoneNumber.Number); } } }
/// <summary> /// Iterates though all people in the AddressBook and prints info about them. /// </summary> private static void Print(AddressBook addressBook) { foreach (Person person in addressBook.People) { Console.WriteLine("Person ID: {0}", person.Id); Console.WriteLine(" Name: {0}", person.Name); if (person.Email != "") { Console.WriteLine(" E-mail address: {0}", person.Email); } foreach (Person.Types.PhoneNumber phoneNumber in person.Phones) { switch (phoneNumber.Type) { case Person.Types.PhoneType.Mobile: Console.Write(" Mobile phone #: "); break; case Person.Types.PhoneType.Home: Console.Write(" Home phone #: "); break; case Person.Types.PhoneType.Work: Console.Write(" Work phone #: "); break; } Console.WriteLine(phoneNumber.Number); } } }
public MainWindow() { book = new AddressBook(); InitializeComponent(); DataContext = book; myData.DataContext = book.Groups.ElementAt(0); }
/// <summary> /// Entry point - loads an existing addressbook or creates a new one, /// then writes it back to the file. /// </summary> public static int Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE"); return -1; } AddressBook addressBook; if (File.Exists(args[0])) { using (Stream file = File.OpenRead(args[0])) { addressBook = AddressBook.Parser.ParseFrom(file); } } else { Console.WriteLine("{0}: File not found. Creating a new file.", args[0]); addressBook = new AddressBook(); } // Add an address. addressBook.People.Add(PromptForAddress(Console.In, Console.Out)); // Write the new address book back to disk. using (Stream output = File.OpenWrite(args[0])) { addressBook.WriteTo(output); } return 0; }
private static void Main() { byte[] bytes; // Create a new person Person person = new Person { Id = 1, Name = "Foo", Email = "foo@bar", Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } } }; using (MemoryStream stream = new MemoryStream()) { // Save the person to a stream person.WriteTo(stream); bytes = stream.ToArray(); } Person copy = Person.Parser.ParseFrom(bytes); AddressBook book = new AddressBook { People = { copy } }; bytes = book.ToByteArray(); // And read the address book back again AddressBook restored = AddressBook.Parser.ParseFrom(bytes); // The message performs a deep-comparison on equality: if (restored.People.Count != 1 || !person.Equals(restored.People[0])) { throw new Exception("There is a bad person in here!"); } }
public Customer(Guid id, AddressBook addresses, Orders orderHistory, PaymentDetails paymentDetails, LoyaltySummary loyalty) { this.Id = id; this.Addresses = addresses; this.OrderHistory = orderHistory; this.PaymentDetails = paymentDetails; this.Loyalty = loyalty; }
public async Task Update(AddressBook addressBook) { if (context.Entry(addressBook).State == EntityState.Detached) { context.AddressBooks.Add(addressBook); } await context.SaveChangesAsync(); }
/// <summary> /// Constructor /// </summary> /// <param name="catchAllConfig">The configuration.</param> /// <param name="addressBook">The address book to perform lookups.</param> public CatchAllAgent(CatchAllConfig catchAllConfig, AddressBook addressBook) { // Save the address book and configuration _addressBook = addressBook; _catchAllConfig = catchAllConfig; // Register an OnRcptCommand event handler OnRcptCommand += RcptToHandler; }
void HandlePersonSelection(AddressBook.ABPerson person) { Console.Error.WriteLine ("# select Person: {0}", person); toString.Text = person.ToString (); firstName.Text = person.FirstName; lastName.Text = person.LastName; property.Text = ""; identifier.Text = ""; }
public ContactsProvider(IAddressBook addressBook) { // TODO: Try/Catch this explicit cast or no big deal cause I control it? _addressBook = addressBook as AddressBook; // TODO: Original sample does NOT await here in ctor, because ctor is not async method // TODO: can HasPermissionToUseAddressBook() have bad info? and report null too early? // TODO: DO I even need that method on the interface? Hide it? CheckOrRequestAddressBookPermission(); }
public void AddContact_CorrectOrder() { var addressBook = new AddressBook(); addressBook.AddContact(new Contact() { FirstName = "Magnus", LastName = "Ahlberg" }); Assert.That(addressBook.GetContacts(), Has.Count.EqualTo(1)); }
//=============================================================== // Function: saveButton_Click //=============================================================== protected void saveButton_Click(object sender, EventArgs e) { int userID = int.Parse(Session["loggedInUserID"].ToString()); AddressBook addressBookEntry = new AddressBook(Session["loggedInUserFullName"].ToString()); addressBookEntry.userID = userID; addressBookEntry.firstName = firstNameTextBox.Text; addressBookEntry.lastName = lastNameTextBox.Text; addressBookEntry.emailAddress = emailAddress.Text; addressBookEntry.Add(); //Response.Redirect("editAddressBook.aspx?ABID=" + addressBookEntry.addressBookID.ToString()); Response.Redirect("addressBook.aspx"); }
//=============================================================== // Function: saveButton_Click //=============================================================== protected void saveButton_Click(object sender, EventArgs e) { int addressBookID = int.Parse(Request.QueryString["ABID"].ToString()); int userID = int.Parse(Session["loggedInUserID"].ToString()); AddressBook addressBookEntry = new AddressBook(Session["loggedInUserFullName"].ToString(), addressBookID); addressBookEntry.firstName = firstNameTextBox.Text; addressBookEntry.lastName = lastNameTextBox.Text; addressBookEntry.emailAddress = emailAddress.Text; addressBookEntry.Update(); Response.Redirect("addressBook.aspx"); }
//=============================================================== // Function: Page_Load //=============================================================== protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int addressBookID = int.Parse(Request.QueryString["ABID"].ToString()); AddressBook addressBookEntry = new AddressBook(Session["loggedInUserFullName"].ToString(), addressBookID); firstNameTextBox.Text = addressBookEntry.firstName; lastNameTextBox.Text = addressBookEntry.lastName; emailAddress.Text = addressBookEntry.emailAddress; } }
public CodeSamples() { #region AddressBook var builder = new StringBuilder(); var abook = new AddressBook(); foreach (Contact c in abook.Where (c => c.FirstName == "Eric" && c.Phones.Any())) { builder.AppendLine (c.DisplayName); foreach (Phone p in c.Phones) builder.AppendLine (String.Format ("{0}: {1}", p.Label, p.Number)); builder.AppendLine(); } #endregion }
public int Save(AddressBook addressBook) { int result = 0; using (var data = new SafeFolderEntities()) { data.AddressBooks.Add(addressBook); if (data.ChangeTracker.HasChanges()) { result = data.SaveChanges(); } } return result; }
void IAddressBookService.Create(AddressBook addressBook) { _repository.Add(addressBook); if (this._log.IsInfoEnabled) { var personalAddressBook = addressBook as PersonalAddressBook; if (personalAddressBook != null) { this._log.InfoFormat("新增私人通讯簿#{0}|{1}|{2}", addressBook.ID, addressBook.Name, personalAddressBook.OwnerAccountId); } else { this._log.InfoFormat("新增通讯簿#{0}|{1}", addressBook.ID, addressBook.Name); } } }
public void AddContact_GetContactsByLastName_CorrectOrder() { var addressBook = new AddressBook(); addressBook.AddContact(new Contact() { FirstName = "Hans", LastName = "Fjällmark" }); addressBook.AddContact(new Contact() { FirstName = "Magnus", LastName = "Ahlberg" }); var contacts = addressBook.GetContactsOrderedByLastName(); Assert.That(contacts, Has.Count.EqualTo(2)); Assert.That(contacts[0].FirstName, Is.EqualTo("Magnus")); Assert.That(contacts[1].FirstName, Is.EqualTo("Hans")); }
public ActionResult index(CheckoutViewModel checkoutViewModel) { try { if (checkoutViewModel.BillingDistrictID == 0) { checkoutViewModel.BillingDistrictID = null; } if (checkoutViewModel.BillingProvinceID == 0) { checkoutViewModel.BillingProvinceID = null; } if (checkoutViewModel.ShippingDistrictID == 0) { checkoutViewModel.ShippingDistrictID = null; } if (checkoutViewModel.ShippingProvinceID == 0) { checkoutViewModel.ShippingProvinceID = null; } TblCart cart = cartService.GetByCookieID(checkoutViewModel.CookieID); cart.CartItems = cartItemService.GetByCartID(cart.CartID); if (cart.CartItems != null && cart.CartItems.Count > 0) { foreach (var item in cart.CartItems) { item.Variant = variantService.GetByPrimaryKey(item.VariantID); if (item.Variant != null) { item.Variant.Product = productService.GetByPrimaryKey(item.Variant.ProductID); } } } checkoutViewModel.CartItems = cart.CartItems; checkoutViewModel.CartID = cart.CartID; // create or update customer Customer customer = customerService.GetByEmail(checkoutViewModel.CustomerEmail); if (customer == null) { customer = new Customer(); customer.CustomerFirstName = checkoutViewModel.BillingAddress.CustomerName; customer.CustomerEmail = checkoutViewModel.CustomerEmail; customer.TotalCount = 0; customer.TotalOrder = 1; customer.CreatedDateTime = SDateTime.GetYYYYMMddHmmSSNow(); customer.CustomerID = customerService.Insert(customer); } else { customer.TotalCount += checkoutViewModel.TotalPrice; customer.TotalOrder += 1; customer.ModifiedDateTime = SDateTime.GetYYYYMMddHmmSSNow(); customerService.Update(customer); } AddressBook addressBook = new AddressBook(); addressBook.AddressBookFirstName = checkoutViewModel.BillingAddress.CustomerName; addressBook.Phone = checkoutViewModel.BillingAddress.Phone; addressBook.HomeAddress = checkoutViewModel.BillingAddress.HomeAddress; addressBook.DistrictID = checkoutViewModel.BillingDistrictID; addressBook.ProvinceID = checkoutViewModel.BillingProvinceID; addressBook.ProvinceName = provinceService.GetProvinceName(checkoutViewModel.BillingProvinceID == null ? 0 : checkoutViewModel.BillingProvinceID.Value); addressBook.CountryID = Common.Country_VietNameID; addressBook.CustomerID = customer.CustomerID; addressBook.IsDefault = true; addressBookService.Insert(addressBook); if (checkoutViewModel.OtherShippingAddress) { addressBook.AddressBookFirstName = checkoutViewModel.ShippingAddress.CustomerName; addressBook.Phone = checkoutViewModel.ShippingAddress.Phone; addressBook.HomeAddress = checkoutViewModel.ShippingAddress.HomeAddress; addressBook.DistrictID = checkoutViewModel.ShippingDistrictID; addressBook.ProvinceID = checkoutViewModel.ShippingProvinceID; addressBook.ProvinceName = provinceService.GetProvinceName(checkoutViewModel.ShippingProvinceID == null ? 0 : checkoutViewModel.ShippingProvinceID.Value); addressBook.CountryID = Common.Country_VietNameID; addressBook.CustomerID = customer.CustomerID; addressBook.IsDefault = false; addressBookService.Insert(addressBook); } int billingAddressID = 0, shippingAddressID = 0; // contructor billing address checkoutViewModel.BillingAddress.ProvinceID = checkoutViewModel.BillingProvinceID; checkoutViewModel.BillingAddress.ProvinceName = provinceService.GetProvinceName(checkoutViewModel.BillingProvinceID == null ? 0 : checkoutViewModel.BillingProvinceID.Value); checkoutViewModel.BillingAddress.CountryID = 1; if (SNumber.ToNumber(checkoutViewModel.BillingDistrictID) > 0) { checkoutViewModel.BillingAddress.DistrictID = checkoutViewModel.BillingDistrictID; //checkoutViewModel.BillingAddress.DistrictName = districtService.get } else { checkoutViewModel.BillingAddress.DistrictID = null; } // contructor shipping address // shipping address different billing address if (checkoutViewModel.OtherShippingAddress) { checkoutViewModel.ShippingAddress.ProvinceID = checkoutViewModel.ShippingProvinceID; checkoutViewModel.ShippingAddress.ProvinceName = provinceService.GetProvinceName(checkoutViewModel.ShippingProvinceID == null ? 0 : checkoutViewModel.ShippingProvinceID.Value); checkoutViewModel.ShippingAddress.CountryID = 1; if (SNumber.ToNumber(checkoutViewModel.ShippingDistrictID) > 0) { checkoutViewModel.ShippingAddress.DistrictID = checkoutViewModel.ShippingDistrictID; } else { checkoutViewModel.ShippingAddress.DistrictID = null; } } // shipping address as billing address else { checkoutViewModel.ShippingAddress.CustomerName = checkoutViewModel.BillingAddress.CustomerName; checkoutViewModel.ShippingAddress.ProvinceID = checkoutViewModel.BillingProvinceID; checkoutViewModel.ShippingAddress.ProvinceName = provinceService.GetProvinceName(checkoutViewModel.BillingProvinceID == null ? 0 : checkoutViewModel.BillingProvinceID.Value); checkoutViewModel.ShippingAddress.CountryID = 1; if (SNumber.ToNumber(checkoutViewModel.BillingDistrictID) > 0) { checkoutViewModel.ShippingAddress.DistrictID = checkoutViewModel.BillingDistrictID; } else { checkoutViewModel.ShippingAddress.DistrictID = null; } } billingAddressID = billingAddressService.Insert(checkoutViewModel.BillingAddress); shippingAddressID = shippingAddressService.Insert(checkoutViewModel.ShippingAddress); // create order & line item TblOrder order = new TblOrder(); order.OrderStatus = Common.Active; order.CustomerID = customer.CustomerID; order.BillingStatus = Common.Pending; order.ShippingStatus = Common.Unfulfilled; order.OrderNote = checkoutViewModel.CheckoutNote; order.TotalCount = checkoutViewModel.TotalSubPrice; order.TotalShipping = checkoutViewModel.TotalShipping; order.CustomerEmail = checkoutViewModel.CustomerEmail; if (shippingAddressID == 0) { order.ShippingAddressID = null; } else { order.ShippingAddressID = shippingAddressID; } if (billingAddressID == 0) { order.BillingAddressID = null; } else { order.BillingAddressID = billingAddressID; } order.Number = orderService.GetLastNumber() + 1; order.CreatedDateTime = order.ModifiedDateTime = SDateTime.GetYYYYMMddHmmSSNow(); int orderID = orderService.Insert(order); if (SNumber.ToNumber(orderID) > 0) { if (checkoutViewModel.CartItems != null && checkoutViewModel.CartItems.Count > 0) { foreach (var item in checkoutViewModel.CartItems) { item.OrderID = orderID; LineItem lineItem = cartItemService.ToLineItem(item); lineItemService.Insert(lineItem); } } } // remove cart and cartItem if (cart != null) { cartItemService.DeleteByCartID(cart.CartID); } return(RedirectToAction("thankyou", "checkout", new { id = orderID })); } catch (Exception ex) { LogService.WriteException(ex); } return(RedirectToAction("index", "checkout", new { cookieID = checkoutViewModel.CookieID })); }
public static Action <object> ParseMessageToAction(Message message) { if (message.Type == MsgType.Reply) { throw new InvalidOperationException("Server received MsgType.Reply... those are meant to only flow the other way."); } if (message.Type == MsgType.Notify) { return(null); // Notify messages ONLY raise the OnReceiveMessage event and nothing else. } if (message.Type == MsgType.LaunchActivity) { var substrings = message.Content.Split(onNEXT); var type = Type.GetType(substrings[0]); var tdata = Type.GetType(substrings[1]); var serializedPassedInfo = substrings[2]; // Currently nothing is done with this, since it'll be a right pain in the arse to do. return((o) => { // Todo - embed the PassedInfo into somewhere (Res? try again for Bundle syntax?) before this. Application.Context.StartActivity(type); }); } if (message.Type == MsgType.PushSFX) { IEffect FX; if (!Res.SFX.Effects.TryGetValue($"RequestedFX{NEXT}{message.Content}", out FX)) { if (!int.TryParse(message.Content, out int ResourceID)) { ResourceID = typeof(Resource.Id).GetStaticProperty <int>(message.Content); } FX = Res.SFX.Register($"RequestedFX{NEXT}{message.Content}", ResourceID); } if (FX == null) { return(null); } return((o) => { FX.Activate(); FX.Play(); }); } if (message.Type == MsgType.PushSpeech) { return((o) => { Speech.Say(message.Content); }); } if (message.Type == MsgType.PushEffect) { var substrings = message.Content.Split(onNEXT, 2); var effectName = substrings[0]; var effectParams = substrings[1]; //if (!MasterSpellLibrary.CastingResults.ContainsKey(effectName)) //{ // Log.Warn(_tag, $"Unable to locate game effect '{effectName}'."); // return null; //} if (!GameEffect.Definition.ContainsKey(effectName)) { Log.Warn(_tag, $"Unable to locate effect '{effectName}'."); return(null); } //var doFunc = MasterSpellLibrary.CastingResults[effectName]; return((o) => { GameEffect .Definition[effectName]? .OnReceiving(TemporaryAddressBook_SingleEntry ?? new CommsContact(), effectParams); }); } if (message.Type == MsgType.PushEffect2) { var effectInstance = GameEffectInstance.FromStringForm(message.Content); //var doFunc = MasterSpellLibrary.CastingResults[effectName]; return((o) => { effectInstance? .SourceEffect? .OnReceiving2(effectInstance); }); } if (message.Type == MsgType.Query) { return((o) => { var target = AddressBook.Resolve(message.From); target.SendMessage(DataLibrarian.FetchRequestedData(message, o)); }); } if (message.Type == MsgType.SetScenarioVariable) { var substrings = message.Content.Split(onNEXT); Encounters.Scenario.Current.SetVariable(substrings[0], (Encounters.Scenario.State)Enum.Parse(typeof(Encounters.Scenario.State), substrings[1]), false); // False meaning don't rebroadcast it. } throw new NotImplementedException(); }
private AddressBook CreateAddressBook() { Person person = new Person { Id = 1, Name = "Foo", Email = "foo@bar", Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } } }; person.Id = 2; AddressBook book = new AddressBook { People = { person }, AddressBookName = "MyGreenAddressBook" }; return book; }
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { try { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var strOrderStatusID = ((RadComboBox)row.FindControl("ddlOrderStatus")).SelectedValue; if (e.CommandName == "PerformInsert") { OdsOrder.InsertParameters["OrderStatusID"].DefaultValue = strOrderStatusID; OdsOrder.InsertParameters["UserID"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString(); } else { OdsOrder.UpdateParameters["OrderStatusID"].DefaultValue = strOrderStatusID; OdsOrder.UpdateParameters["UserID"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString(); } } catch (Exception ex) { lblError.Text = ex.Message; } } else if (e.CommandName == "QuickUpdate") { //var lnkbQuickUpdate = (RadComboBox)RadGrid1.FindControl("lnkbQuickUpdate"); foreach (GridDataItem item in RadGrid1.SelectedItems) { string OrderID = item["OrderID"].Text; string UserName = item["UserName"].Text; string Email = (item.FindControl("hdnEmail") as HiddenField).Value; string FullName = (item.FindControl("hdnFullName") as HiddenField).Value; string OrderStatusID = (item.FindControl("ddlOrderStatus") as RadComboBox).SelectedValue; string ShippingStatusID = (item.FindControl("ddlShippingStatus") as RadComboBox).SelectedValue; string PaymentMethodID = (item.FindControl("ddlPaymentMethod") as RadComboBox).SelectedValue; string PayStatusID = (item.FindControl("ddlPayStatus") as RadComboBox).SelectedValue; string BillingAddressID = item["BillingAddressID"].Text; string ShippingAddressID = item["ShippingAddressID"].Text; string Notes = (item.FindControl("txtNotes") as RadTextBox).Text; var oOrders = new Orders(); //var oAddressBook = new AddressBook(); oOrders.OrdersQuickUpdate1( OrderID, UserName, OrderStatusID, ShippingStatusID, PaymentMethodID, BillingAddressID, ShippingAddressID, Notes, PayStatusID ); if (OrderStatusID == "3" && ShippingStatusID == "2" && PayStatusID == "1") { //var dvAddressBook = oAddressBook.AddressBookSelectAll("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "").DefaultView; //var dvOrder = (DataView)OdsOrder.Select(); var To = Email; var CC = "*****@*****.**"; var Subject = "Hoàn tất đơn hàng"; var YourName = FullName; //var OrderCode = OrderID; string Host = "118.69.193.238"; int Port = 25; string From = "*****@*****.**"; string Password = "******"; string Body = "<div style='width: 100%; font-size: 11px; font-family: Arial;'>"; Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>"; Body += "Đơn hàng đã được hoàn tất"; Body += "</h3>"; Body += "<div style='font-family: Verdana; font-size: 11px; margin-bottom: 20px;'>"; Body += "<p>Xin chào " + YourName + ",</p>"; Body += "<p>Đơn hàng bạn đặt trên website của chúng tôi đã giao tới người nhận bạn đã chỉ định.</p>"; Body += "<p>Trạng thái của đơn hàng số <strong>" + OrderID + "</strong> hiện tại là <b>Đã hoàn thành</b>.</p>"; Body += "<p>Xin vui lòng <a href='http://www.pandemos.vn/lien-he.aspx'>gọi điện</a> tới Pandemos nếu thông tin nói trên không chính xác.</p>"; Body += "<p>Cảm ơn Quý khách đã ủng hộ <strong>Pandemos</strong> và xin hân hạnh được tiếp tục phục vụ Quý khách trong thời gian tới.</p>"; Body += "</div>"; Body += "<div style='font-family:Verdana;font-size:12px;margin-top:10px;'>"; Body += "<div style='font-size:16px;font-weight:bold;'>=================</div>"; Body += "<h4 style='font-size:14px;font-family:Verdana;margin:0;padding:0;'>Pandemos</h4>"; Body += "<div style='font-size:11px;font-family:Verdana;margin-top:5px;padding:0;margin:0;'>"; Body += "<p>Add: 403, Hai Bà Trưng, Phường 8, Quận 3, Tp HCM.</p>"; Body += "<p>Tel: (08)3 820 8577 - Hotline: 0902 563 577</p>"; Body += "<p>W: <a href='http://www.pandemos.vn'>www.pandemos.vn</a></p>"; Body += "<p>E: <a href='mailto:[email protected]'>[email protected]</a></p>"; Body += "</div>"; Body += "</div>"; Body += "</div>"; Common.SendMail(Host, Port, From, Password, To, CC, Subject, Body, false); //string Body = "<div style='width: 100%; font-size: 11px; font-family: Arial;'>"; //Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>"; //Body += "Đơn hàng đã được hoàn tất/Order Delivered"; //Body += "</h3>"; //Body += "<div style='font-family: Verdana; font-size: 11px; margin-bottom: 20px;'>"; //Body += "<p>Xin chào " + YourName + "/Hi " + YourName + ",</p>"; //Body += "<p>Đơn hàng bạn đặt trên website của chúng tôi đã giao tới người nhận bạn đã chỉ định/An order you recently placed on our website has delivered to nominated recipient.</p>"; //Body += "<p>Trạng thái của đơn hàng số <strong>" + OrderID + "</strong> hiện tại là <b>Đã hoàn thành</b>/The status of order " + OrderID + " is now <b>Completed</b>.</p>"; //Body += "<p>Xin vui lòng <a href='http://www.pandemos.vn/lien-he.aspx'>gọi điện</a> tới Pandemos nếu thông tin nói trên không chính xác/ Please <a href='http://www.pandemos.vn/lien-he.aspx'>call</a> <strong>Pandemos</strong> if above information is not correct.</p>"; //Body += "<p>Cảm ơn Quý khách đã ủng hộ <strong>Pandemos</strong> và xin hân hạnh được tiếp tục phục vụ Quý khách trong thời gian tới.</p>"; //Body += "</div>"; //Body += "<div style='font-family:Verdana;font-size:12px;margin-top:10px;'>"; //Body += "<div style='font-size:16px;font-weight:bold;'>=================</div>"; //Body += "<h4 style='font-size:14px;font-family:Verdana;margin:0;padding:0;'>Pandemos</h4>"; //Body += "<div style='font-size:11px;font-family:Verdana;margin-top:5px;padding:0;margin:0;'>"; //Body += "<p>Add: 403, Hai Bà Trưng, Phường 8, Quận 3, Tp HCM.</p>"; //Body += "<p>Tel: (08)3 820 8577 - Hotline: 0902 563 577</p>"; //Body += "<p>W: <a href='http://www.pandemos.vn'>www.pandemos.vn</a></p>"; //Body += "<p>E: <a href='mailto:[email protected]'>[email protected]</a></p>"; //Body += "</div>"; //Body += "</div>"; //Body += "</div>"; //if (bSendEmail) //{ //Common.ShowAlert("Bạn đã gửi mail thành công"); //ScriptManager.RegisterClientScriptBlock(lnkbQuickUpdate, lnkbQuickUpdate.GetType(), "runtime", "alert('Bạn đã gửi mail thành công')", true); //} } } } else if (e.CommandName == "DeleteSelected") { foreach (GridDataItem item in RadGrid1.SelectedItems) { string ShippingAddressID = item["ShippingAddressID"].Text; if (ShippingAddressID != "" && ShippingAddressID != " ") { var oAddressBook = new AddressBook(); oAddressBook.AddressBookDelete(ShippingAddressID); } } } }
/* * 1. Add the required classes to make the following code compile. * HINT: Use a Dictionary in the AddressBook class to store Contacts. The key should be the contact's email address. * * 2. Run the program and observe the exception. * * 3. Add try/catch blocks in the appropriate locations to prevent the program from crashing * Print meaningful error messages in the catch blocks. */ static void Main(string[] args) { // Create a few contacts Contact bob = new Contact() { FirstName = "Bob", LastName = "Smith", Email = "*****@*****.**", Address = "100 Some Ln, Testville, TN 11111" }; Contact sue = new Contact() { FirstName = "Sue", LastName = "Jones", Email = "*****@*****.**", Address = "322 Hard Way, Testville, TN 11111" }; Contact juan = new Contact() { FirstName = "Juan", LastName = "Lopez", Email = "*****@*****.**", Address = "888 Easy St, Testville, TN 11111" }; // Create an AddressBook and add some contacts to it AddressBook addressBook = new AddressBook(); addressBook.AddContact(bob); addressBook.AddContact(sue); addressBook.AddContact(juan); // Try to add a contact a second time try { addressBook.AddContact(sue); } catch (ArgumentException) { Console.WriteLine("A contact has already been added using this email."); } // Create a list of emails that match our Contacts List <string> emails = new List <string>() { "*****@*****.**", "*****@*****.**", "*****@*****.**", }; // Insert an email that does NOT match a Contact emails.Insert(1, "*****@*****.**"); // Search the AddressBook by email and print the information about each Contact foreach (string email in emails) { try { Contact contact = addressBook.GetByEmail(email); Console.WriteLine("----------------------------"); Console.WriteLine($"Name: {contact.FullName}"); Console.WriteLine($"Email: {contact.Email}"); Console.WriteLine($"Address: {contact.Address}"); } catch (NullReferenceException) { Console.WriteLine($"The email {email} was not found in the address book."); } } }
private static async Task handleAddersBook(Session session, AddressBook ab) { Interlocked.Increment(ref count); await session.sendProtobuf(ab); /* echo */ }
public async Task <SupplierView> CreateSupplierByAddressBook(AddressBook addressBook, LocationAddress locationAddress, Email email) { SupplierView supplierView = null; try { UDC udc = await base.GetUdc("AB_Type", "Supplier"); if (udc != null) { addressBook.PeopleXrefId = udc.XRefId; } UDC udcLocationAddressType = await base.GetUdc("LOCATIONADDRESS_TYPE", "BillTo"); if (udcLocationAddressType != null) { locationAddress.TypeXRefId = udcLocationAddressType.XRefId; } AddressBook query = await(from e in _dbContext.AddressBooks join f in _dbContext.Emails on e.AddressId equals f.AddressId where f.Email1 == email.Email1 select e).FirstOrDefaultAsync <AddressBook>(); if (query == null) { _dbContext.Set <AddressBook>().Add(addressBook); _dbContext.SaveChanges(); locationAddress.AddressId = addressBook.AddressId; _dbContext.Set <LocationAddress>().Add(locationAddress); _dbContext.SaveChanges(); email.AddressId = addressBook.AddressId; _dbContext.Set <Email>().Add(email); _dbContext.SaveChanges(); } else { addressBook.AddressId = query.AddressId; } Supplier supplier = await(from e in _dbContext.Suppliers where e.AddressId == addressBook.AddressId select e).FirstOrDefaultAsync <Supplier>(); if (supplier == null) { Supplier newSupplier = new Supplier(); newSupplier.AddressId = addressBook.AddressId; newSupplier.Identification = email.Email1; _dbContext.Set <Supplier>().Add(newSupplier); _dbContext.SaveChanges(); supplierView = applicationViewFactory.MapSupplierView(newSupplier); } else { supplierView = applicationViewFactory.MapSupplierView(supplier); } return(supplierView); } catch (Exception ex) { throw new Exception(GetMyMethodName(), ex); } }
public void DelContact() { AddressBook.DeleteItemMenu(SaveModel.Email); EventAggregationProvider.EventAggregator.Publish(AddressBook.ListAllMenu()); TryClose(); }
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { try { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var strOrderStatusID = ((RadComboBox)row.FindControl("ddlOrderStatus")).SelectedValue; if (e.CommandName == "PerformInsert") { OdsOrder.InsertParameters["OrderStatusID"].DefaultValue = strOrderStatusID; OdsOrder.InsertParameters["UserID"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString(); } else { OdsOrder.UpdateParameters["OrderStatusID"].DefaultValue = strOrderStatusID; OdsOrder.UpdateParameters["UserID"].DefaultValue = Membership.GetUser().ProviderUserKey.ToString(); } } catch (Exception ex) { lblError.Text = ex.Message; } } else if (e.CommandName == "QuickUpdate") { //var lnkbQuickUpdate = (RadComboBox)RadGrid1.FindControl("lnkbQuickUpdate"); foreach (GridDataItem item in RadGrid1.SelectedItems) { string OrderID = item["OrderID"].Text; string UserName = item["UserName"].Text; string Email = (item.FindControl("hdnEmail") as HiddenField).Value; string FullName = (item.FindControl("hdnFullName") as HiddenField).Value; string OrderStatusID = (item.FindControl("ddlOrderStatus") as RadComboBox).SelectedValue; string ShippingStatusID = (item.FindControl("ddlShippingStatus") as RadComboBox).SelectedValue; string PaymentMethodID = (item.FindControl("ddlPaymentMethod") as RadComboBox).SelectedValue; string PayStatusID = (item.FindControl("ddlPayStatus") as RadComboBox).SelectedValue; string BillingAddressID = item["BillingAddressID"].Text; string ShippingAddressID = item["ShippingAddressID"].Text; string Notes = (item.FindControl("txtNotes") as RadTextBox).Text; var oOrders = new Orders(); //var oAddressBook = new AddressBook(); oOrders.OrdersQuickUpdate1( OrderID, UserName, OrderStatusID, ShippingStatusID, PaymentMethodID, BillingAddressID, ShippingAddressID, Notes, PayStatusID ); if (OrderStatusID == "3" && ShippingStatusID == "2" && PayStatusID == "1") { //var dvAddressBook = oAddressBook.AddressBookSelectAll("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "").DefaultView; //var dvOrder = (DataView)OdsOrder.Select(); var To = Email; var CC = "*****@*****.**"; var Subject = "Hoàn tất đơn hàng"; var YourName = FullName; //var OrderCode = OrderID; string Host = "118.69.193.238"; int Port = 25; string From = "*****@*****.**"; string Password = "******"; string Body = "<div style='width: 100%; font-size: 11px; font-family: Arial;'>"; Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>"; Body += "Đơn hàng đã được hoàn tất"; Body += "</h3>"; Body += "<div style='font-family: Verdana; font-size: 11px; margin-bottom: 20px;'>"; Body += "<p>Xin chào " + YourName + ",</p>"; Body += "<p>Đơn hàng bạn đặt trên website của chúng tôi đã giao tới người nhận bạn đã chỉ định.</p>"; Body += "<p>Trạng thái của đơn hàng số <strong>" + OrderID + "</strong> hiện tại là <b>Đã hoàn thành</b>.</p>"; Body += "<p>Xin vui lòng <a href='http://www.pandemos.vn/lien-he.aspx'>gọi điện</a> tới Pandemos nếu thông tin nói trên không chính xác.</p>"; Body += "<p>Cảm ơn Quý khách đã ủng hộ <strong>Pandemos</strong> và xin hân hạnh được tiếp tục phục vụ Quý khách trong thời gian tới.</p>"; Body += "</div>"; Body += "<div style='font-family:Verdana;font-size:12px;margin-top:10px;'>"; Body += "<div style='font-size:16px;font-weight:bold;'>=================</div>"; Body += "<h4 style='font-size:14px;font-family:Verdana;margin:0;padding:0;'>Pandemos</h4>"; Body += "<div style='font-size:11px;font-family:Verdana;margin-top:5px;padding:0;margin:0;'>"; Body += "<p>Add: 403, Hai Bà Trưng, Phường 8, Quận 3, Tp HCM.</p>"; Body += "<p>Tel: (08)3 820 8577 - Hotline: 0902 563 577</p>"; Body += "<p>W: <a href='http://www.pandemos.vn'>www.pandemos.vn</a></p>"; Body += "<p>E: <a href='mailto:[email protected]'>[email protected]</a></p>"; Body += "</div>"; Body += "</div>"; Body += "</div>"; Common.SendMail(Host, Port, From, Password, To, CC, Subject, Body, false); //string Body = "<div style='width: 100%; font-size: 11px; font-family: Arial;'>"; //Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>"; //Body += "Đơn hàng đã được hoàn tất/Order Delivered"; //Body += "</h3>"; //Body += "<div style='font-family: Verdana; font-size: 11px; margin-bottom: 20px;'>"; //Body += "<p>Xin chào " + YourName + "/Hi " + YourName + ",</p>"; //Body += "<p>Đơn hàng bạn đặt trên website của chúng tôi đã giao tới người nhận bạn đã chỉ định/An order you recently placed on our website has delivered to nominated recipient.</p>"; //Body += "<p>Trạng thái của đơn hàng số <strong>" + OrderID + "</strong> hiện tại là <b>Đã hoàn thành</b>/The status of order " + OrderID + " is now <b>Completed</b>.</p>"; //Body += "<p>Xin vui lòng <a href='http://www.pandemos.vn/lien-he.aspx'>gọi điện</a> tới Pandemos nếu thông tin nói trên không chính xác/ Please <a href='http://www.pandemos.vn/lien-he.aspx'>call</a> <strong>Pandemos</strong> if above information is not correct.</p>"; //Body += "<p>Cảm ơn Quý khách đã ủng hộ <strong>Pandemos</strong> và xin hân hạnh được tiếp tục phục vụ Quý khách trong thời gian tới.</p>"; //Body += "</div>"; //Body += "<div style='font-family:Verdana;font-size:12px;margin-top:10px;'>"; //Body += "<div style='font-size:16px;font-weight:bold;'>=================</div>"; //Body += "<h4 style='font-size:14px;font-family:Verdana;margin:0;padding:0;'>Pandemos</h4>"; //Body += "<div style='font-size:11px;font-family:Verdana;margin-top:5px;padding:0;margin:0;'>"; //Body += "<p>Add: 403, Hai Bà Trưng, Phường 8, Quận 3, Tp HCM.</p>"; //Body += "<p>Tel: (08)3 820 8577 - Hotline: 0902 563 577</p>"; //Body += "<p>W: <a href='http://www.pandemos.vn'>www.pandemos.vn</a></p>"; //Body += "<p>E: <a href='mailto:[email protected]'>[email protected]</a></p>"; //Body += "</div>"; //Body += "</div>"; //Body += "</div>"; //if (bSendEmail) //{ //Common.ShowAlert("Bạn đã gửi mail thành công"); //ScriptManager.RegisterClientScriptBlock(lnkbQuickUpdate, lnkbQuickUpdate.GetType(), "runtime", "alert('Bạn đã gửi mail thành công')", true); //} } } } else if (e.CommandName == "DeleteSelected") { foreach (GridDataItem item in RadGrid1.SelectedItems) { string ShippingAddressID = item["ShippingAddressID"].Text; var oAddressBook = new AddressBook(); oAddressBook.AddressBookDelete(ShippingAddressID); } } }
public AddressBookInformation(Context context) { this.book = new AddressBook(context); }
public void InitializeConsumerTable_WithNonEmptyConsumers_ShouldInvokeCallbackWithCorrectArgument() { // Arrange. var callback = new Mock <Action <ConsumerDescriptor> >(); var person = new Person(); var addressBook = new AddressBook(); var personConsuming = new TaskCompletionSource <bool>(); var addressBookConsuming = new TaskCompletionSource <bool>(); this.consumer.StubbedConsumeAddressBookAsync .Setup(f => f(It.IsAny <AddressBook>(), It.IsAny <CancellationToken>())) .Returns(new ValueTask(addressBookConsuming.Task)); this.consumer.StubbedConsumePersonAsync .Setup(f => f(It.IsAny <Person>(), It.IsAny <CancellationToken>())) .Returns(new ValueTask(personConsuming.Task)); // Act. this.subject.InitializeConsumerTable(new[] { this.consumer }, callback.Object); // Assert. callback.Verify( f => f(It.Is <ConsumerDescriptor>(a => ReferenceEquals(a.Instance, this.consumer))), Times.Exactly(2)); var personConsumer = callback.Invocations .Select(i => (ConsumerDescriptor)i.Arguments[0]) .Single(d => d.EventDescriptor.ClrType == typeof(Person)); var addressBookConsumer = callback.Invocations .Select(i => (ConsumerDescriptor)i.Arguments[0]) .Single(d => d.EventDescriptor.ClrType == typeof(AddressBook)); Assert.Same(Person.Descriptor, personConsumer.EventDescriptor); Assert.Same(Person.Parser, personConsumer.EventParser); Assert.Same(AddressBook.Descriptor, addressBookConsumer.EventDescriptor); Assert.Same(AddressBook.Parser, addressBookConsumer.EventParser); this.consumer.ClearStubbedInvocations(); using (var cancellation = new CancellationTokenSource()) { var result = personConsumer.ConsumeExecutor(person, cancellation.Token); this.consumer.StubbedConsumePersonAsync.Verify( f => f(person, cancellation.Token), Times.Once()); this.consumer.StubbedConsumeAddressBookAsync.Verify( f => f(It.IsAny <AddressBook>(), It.IsAny <CancellationToken>()), Times.Never()); Assert.Same(result.AsTask(), personConsuming.Task); } this.consumer.ClearStubbedInvocations(); using (var cancellation = new CancellationTokenSource()) { var result = addressBookConsumer.ConsumeExecutor(addressBook, cancellation.Token); this.consumer.StubbedConsumePersonAsync.Verify( f => f(It.IsAny <Person>(), It.IsAny <CancellationToken>()), Times.Never()); this.consumer.StubbedConsumeAddressBookAsync.Verify( f => f(addressBook, cancellation.Token), Times.Once()); Assert.Same(result.AsTask(), addressBookConsuming.Task); } }
public void DeleteAddress() { var mgr = CreateManager(); var client = CreateNew(); var key = client.GetKey(); // создаём инстанс вложенной сущности var address = new AddressBook(); try { #region . Create . var oldLength = 0; // считываем коллекцию вложенных сущностей var addressLst = client.AsDynamic().ADDRESS as IList <AddressBook>; if (addressLst == null) { addressLst = new WMSBusinessCollection <AddressBook>(); client.SetProperty("ADDRESS", addressLst); } else { oldLength = addressLst.Count; } // заполняем ссылки и обязательные поля вложенной сущности address.AsDynamic().ADDRESSBOOKINDEX = TestDecimal; address.AsDynamic().ADDRESSBOOKTYPECODE = "ADR_LEGAL"; // добавляем связь с вложенной сущностью, сохраняем addressLst.Add(address); mgr.Update(client); // читаем из БД по ключу client = mgr.Get(key); var addressLstNew = client.AsDynamic().ADDRESS as IList <AddressBook>; // проверка создания addressLstNew.Should().NotBeNull("Должны были получить хотя бы 1 элемент"); addressLstNew.Count.ShouldBeEquivalentTo(oldLength + 1, "Manager должен создавать вложенные сущности"); #endregion #region . Delete . // удалем связь с вложенной сущностью, сохраняем addressLst = client.AsDynamic().ADDRESS as IList <AddressBook>; address = addressLst[addressLst.Count - 1]; addressLst.Remove(address); mgr.Update(client); // убеждаемся, что корректно удалили client = mgr.Get(key); addressLstNew = client.AsDynamic().ADDRESS as IList <AddressBook>; if (addressLstNew == null) { oldLength.Equals(0); } else { addressLstNew.Count.ShouldBeEquivalentTo(oldLength, "Manager должен удалять вложенные сущности"); } #endregion } catch (Exception ex) { throw new Exception(ex.Message + " УДАЛИТЕ СТРОКУ ИЗ ТАБЛИЦЫ WMSADDRESSBOOK с ADDRESSBOOKINDEX = " + TestDecimal); } finally { ClearForSelf(); } }
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "alpha" || e.CommandName == "NoFilter") { String value = null; switch (e.CommandName) { case ("alpha"): { value = string.Format("{0}%", e.CommandArgument); break; } case ("NoFilter"): { value = "%"; break; } } ObjectDataSource1.SelectParameters["LastName"].DefaultValue = value; ObjectDataSource1.DataBind(); RadGrid1.Rebind(); } else if (e.CommandName == "QuickUpdate") { string UserName, Role; var oUser = new User(); foreach (GridDataItem item in RadGrid1.Items) { UserName = item.GetDataKeyValue("UserName").ToString(); Role = ((RadComboBox)item.FindControl("ddlRole")).SelectedValue; oUser.ChangeRole(UserName, Role); } } else if (e.CommandName == "DeleteSelected") { var oAddressBook = new AddressBook(); var oUser = new User(); string errorList = "", UserName = ""; foreach (GridDataItem item in RadGrid1.SelectedItems) { try { var AddressBookID = item.GetDataKeyValue("AddressBookID").ToString(); UserName = item["UserName"].Text; oAddressBook.AddressBookDelete(AddressBookID); oUser.UserDelete(UserName); } catch (Exception ex) { lblError.Text = ex.Message; if (ex.Message == ((int)ErrorNumber.ConstraintConflicted).ToString()) errorList += ", " + UserName; } } if (!string.IsNullOrEmpty(errorList)) { e.Canceled = true; string strAlertMessage = "Tài khoản <b>\"" + errorList.Remove(0, 1).Trim() + " \"</b> đang có đơn hàng .<br /> Xin xóa đơn hàng hoặc sử dụng chức năng khoá tài khoản."; lblError.Text = strAlertMessage; } RadGrid1.Rebind(); } else if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { try { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var DistrictID = ((RadComboBox)row.FindControl("ddlDistrict")).SelectedValue; var ProvinceID = ((RadComboBox)row.FindControl("ddlProvince")).SelectedValue; var RoleName = ((RadComboBox)row.FindControl("ddlRole")).SelectedValue; var UserName = ((RadTextBox)row.FindControl("txtUserName")).Text; var IsPrimary = "True"; var CountryID = "1"; var oUser = new User(); if (e.CommandName == "PerformInsert") { var insertParams = ObjectDataSource1.InsertParameters; insertParams["CountryID"].DefaultValue = CountryID; insertParams["ProvinceID"].DefaultValue = ProvinceID; insertParams["DistrictID"].DefaultValue = DistrictID; insertParams["RoleName"].DefaultValue = RoleName; insertParams["IsPrimary"].DefaultValue = IsPrimary; oUser.ChangeRole(UserName, RoleName); } else { var updateParams = ObjectDataSource1.UpdateParameters; updateParams["CountryID"].DefaultValue = CountryID; updateParams["ProvinceID"].DefaultValue = ProvinceID; updateParams["DistrictID"].DefaultValue = DistrictID; updateParams["RoleName"].DefaultValue = RoleName; updateParams["IsPrimary"].DefaultValue = IsPrimary; oUser.ChangeRole(UserName, RoleName); } } catch (Exception ex) { lblError.Text = ex.Message; } } }
private bool OpenAddressBook() { this.cAddressBook = null; if (this.bookList != null && this.bookList.Count != 0) { string bookName = null; try { IEnumerator cEnum = bookList.GetEnumerator(); if (cEnum.MoveNext()) { bookName = (string) cEnum.Current; if (verbose == true) { Console.WriteLine("Opening address book: " + bookName); } this.cAddressBook = abManager.GetAddressBookByName(bookName); } } catch { if (verbose == true) { Console.WriteLine("OpenAddressBook failed"); if (bookName != null) { Console.WriteLine("Address Book: {0} does not exist.", bookName); } } } } else { DisplayUsage(); this.cAddressBook = null; } if (this.cAddressBook == null) { return(false); } return(true); }
/// <summary> /// Initial set up for the application. We read the config file and create the instance of Oauth and addressbook object. /// If it's post back from getting Auth code then perform operations. /// </summary> protected void Page_Load(object sender, EventArgs e) { ReadConfigFile(); oauth = new OAuth(endPoint, scope, apiKey, secretKey, authorizeRedirectUri, refreshTokenExpiresIn, bypassSSL); this.serializer = new JavaScriptSerializer(); if (Session["cs_rest_AccessToken"] != null && this.addressbook == null) { this.addressbook = new AddressBook(this.endPoint, Session["cs_rest_AccessToken"].ToString()); } if ((string)Session["cs_rest_appState"] == "GetToken" && Request["Code"] != null) { this.oauth.authCode = Request["code"].ToString(); if (oauth.GetAccessToken(OAuth.AccessTokenType.Authorization_Code) == true) { StoreAccessTokenToSession(oauth.access_token_json); this.addressbook = new AddressBook(this.endPoint, this.accessToken); Operation operation = (Operation)Session["cs_rest_ServiceRequest"]; switch (operation) { case Operation.CreateContactOperation: if (!addressbook.createContact(Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.create_contact = new Success(); this.create_contact.location = this.addressbook.location; } break; case Operation.UpdateContactOperation: if (!addressbook.updateContact(Session["contactid"].ToString(), Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteContactOperation: if (!addressbook.deleteContact(Session["contactid"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactsOperation: if (!addressbook.getContacts(Session["querystring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { try { this.qContactResult = serializer.Deserialize <QuickContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.contact_error = ex.Message; } } break; case Operation.UpdateMyInfoOperation: if (!addressbook.updateMyInfo(Session["JSONstring"].ToString())) { this.myinfo_error = this.addressbook.errorResponse; } else { this.update_myinfo = new Success(); this.update_myinfo.last_modified = this.addressbook.last_mod; } break; case Operation.GetMyInfoOperation: if (!addressbook.getMyInfo()) { this.myinfo_error = this.addressbook.errorResponse; } else { try { this.myInfoResult = serializer.Deserialize <ContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.myinfo_error = ex.Message; } } break; case Operation.CreateGroupOperation: if (!addressbook.createGroup(Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.create_group = new Success(); this.create_group.location = this.addressbook.location; } break; case Operation.UpdateGroupOperation: if (!addressbook.updateGroup(Session["groupid"].ToString(), Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteGroupOperation: if (!addressbook.deleteGroup(Session["groupid"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.GetGroupsOperation: if (!addressbook.getGroups(Session["querystring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { try { this.groupResult = serializer.Deserialize <GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.group_error = ex.Message; } } break; case Operation.GetGroupContactsOperation: if (!addressbook.getGroupContacts(Session["groupid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactIdResult = serializer.Deserialize <ContactIdJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; case Operation.AddContctsToGroupOperation: if (!addressbook.addContactToGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.RemoveContactsFromGroupOperation: if (!addressbook.removeContactsFromGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactGroupsOperation: if (addressbook.getContactGroups(Session["contactid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactGroupResult = serializer.Deserialize <GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; } ResetRequestSessionVariables(operation); } else { if (oauth.getAuthCodeError != null) { this.oauth_error = "GetAuthCodeError: " + oauth.getAuthCodeError; } if (oauth.GetAccessTokenError != null) { this.oauth_error = "GetAccessTokenError: " + oauth.GetAccessTokenError; } this.ResetTokenSessionVariables(); return; } } }
public FriendTarget(AddressBook item) : base(10, false, TargetFlags.None) { m_Book = item; }
public TelAdres() { book = new AddressBook(); }
public MobileAccount() { AddressBook = new AddressBook(); }
public async Task TestAddUpdatDelete() { AccountReceivableDetailModule AccountReceivableDetailMod = new AccountReceivableDetailModule(); Invoice invoice = await AccountReceivableDetailMod.Invoice.Query().GetEntityById(18); Customer customer = await AccountReceivableDetailMod.Customer.Query().GetEntityById(9); AddressBook addressBookCustomer = await AccountReceivableDetailMod.AddressBook.Query().GetEntityById(customer?.AddressId); PurchaseOrder purchaseOrder = await AccountReceivableDetailMod.PurchaseOrder.Query().GetEntityById(20); Udc udc = await AccountReceivableDetailMod.Udc.Query().GetEntityById(66); ChartOfAccount chartOfAccount = await AccountReceivableDetailMod.ChartOfAccount.Query().GetEntityById(3); AccountReceivableView acctRecView = new AccountReceivableView() { DiscountDueDate = DateTime.Parse("2/8/2020"), Gldate = DateTime.Parse("7/16/2018"), InvoiceId = invoice.InvoiceId, CreateDate = DateTime.Parse("7/16/2018"), DocNumber = (await AccountReceivableDetailMod.AccountReceivable.Query().GetDocNumber()).NextNumberValue, Remark = "VNW Fixed Asset project", PaymentTerms = "Net 30", CustomerId = customer?.CustomerId ?? 0, PurchaseOrderId = purchaseOrder?.PurchaseOrderId ?? 0, Description = "Fixed Asset Project", AcctRecDocTypeXrefId = udc.XrefId, AccountId = chartOfAccount.AccountId, Amount = 1500M, DebitAmount = 189.6300M, CreditAmount = 1500, OpenAmount = 1335.37M, DiscountPercent = 0, DiscountAmount = 0, AcctRecDocType = "INV", InterestPaid = 0, LateFee = 25.0000M, AccountReceivableNumber = (await AccountReceivableDetailMod.AccountReceivable.Query().GetNextNumber()).NextNumberValue, CustomerPurchaseOrder = "PO-321", Tax = 0, InvoiceDocument = invoice.InvoiceDocument, CustomerName = addressBookCustomer?.Name, DocType = udc.KeyCode }; AccountReceivable newAccountReceivable = await AccountReceivableDetailMod.AccountReceivable.Query().MapToEntity(acctRecView); AccountReceivableDetailMod.AccountReceivable.AddAccountReceivable(newAccountReceivable).Apply(); AccountReceivable lookupAccountReceivable = await AccountReceivableDetailMod.AccountReceivable.Query().GetEntityByNumber(newAccountReceivable.AccountReceivableNumber); InvoiceDetail invoiceDetail = await AccountReceivableDetailMod.InvoiceDetail.Query().GetEntityById(6); PurchaseOrderDetail purchaseOrderDetail = await AccountReceivableDetailMod.PurchaseOrderDetail.Query().GetEntityById(33); ItemMaster itemMaster = await AccountReceivableDetailMod.ItemMaster.Query().GetEntityById(4); AccountReceivableDetailView acctRecDetailView = new AccountReceivableDetailView() { InvoiceId = invoice.InvoiceId, InvoiceDetailId = invoiceDetail.InvoiceDetailId, AccountReceivableId = lookupAccountReceivable.AccountReceivableId, UnitPrice = invoiceDetail.UnitPrice, Quantity = invoiceDetail.Quantity, UnitOfMeasure = invoiceDetail.UnitOfMeasure, Amount = invoiceDetail.Amount, AmountReceived = 189.6300M, PurchaseOrderDetailId = purchaseOrderDetail.PurchaseOrderDetailId, ItemId = itemMaster.ItemId, AccountReceivableDetailNumber = (await AccountReceivableDetailMod.AccountReceivableDetail.Query().GetNextNumber()).NextNumberValue, PurchaseOrderId = purchaseOrder.PurchaseOrderId, CustomerId = customer.CustomerId, QuantityDelivered = invoiceDetail.Quantity, Comment = "possible write off", TypeOfPayment = "Partial" }; AccountReceivableDetail accountReceivableDetail = await AccountReceivableDetailMod.AccountReceivableDetail.Query().MapToEntity(acctRecDetailView); AccountReceivableDetailMod.AccountReceivableDetail.AddAccountReceivableDetail(accountReceivableDetail).Apply(); AccountReceivableDetail newAccountReceivableDetail = await AccountReceivableDetailMod.AccountReceivableDetail.Query().GetEntityByNumber(acctRecDetailView.AccountReceivableDetailNumber); Assert.NotNull(newAccountReceivableDetail); newAccountReceivableDetail.Comment = "AccountReceivableDetail Test Update"; AccountReceivableDetailMod.AccountReceivableDetail.UpdateAccountReceivableDetail(newAccountReceivableDetail).Apply(); AccountReceivableDetailView updateView = await AccountReceivableDetailMod.AccountReceivableDetail.Query().GetViewById(newAccountReceivableDetail.AccountReceivableDetailId); Assert.Same(updateView.Comment, "AccountReceivableDetail Test Update"); AccountReceivableDetailMod.AccountReceivableDetail.DeleteAccountReceivableDetail(newAccountReceivableDetail).Apply(); AccountReceivableDetail lookupAccountReceivableDetail = await AccountReceivableDetailMod.AccountReceivableDetail.Query().GetEntityById(acctRecDetailView.AccountReceivableDetailId); Assert.Null(lookupAccountReceivableDetail); AccountReceivableDetailMod.AccountReceivable.DeleteAccountReceivable(lookupAccountReceivable).Apply(); AccountReceivable lookupAccountReceivable2 = await AccountReceivableDetailMod.AccountReceivable.Query().GetEntityByNumber(newAccountReceivable.AccountReceivableNumber); Assert.Null(lookupAccountReceivable2); }
IEnumerable<Contact> IContactService.GetContacts(AddressBook addressBook) { return _repository.FindBy(addressBook); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // // Get the contact ID that is passed in // from the main activity // String contactID = String.Empty; if (bundle != null) { contactID = bundle.GetString("contactID"); } else { contactID = Intent.GetStringExtra("contactID"); } // // Get the address book // var book = new AddressBook(this); // // Important: PreferContactAggregation must be set to the // the same value as when the ID was generated (from the // previous activity) // book.PreferContactAggregation = true; Contact contact = book.Load(contactID); // // If the contact is empty, we'll // display a 'not found' error // String displayName = "Contact Not Found"; String mobilePhone = String.Empty; // // Set the displayName variable to the contact's // DisplayName property // if (contact != null) { displayName = contact.DisplayName; var phone = contact.Phones.FirstOrDefault(p => p.Type == PhoneType.Mobile); if (phone != null) { mobilePhone = phone.Number; } } // // Show the contacts display name and mobile phone // SetContentView(Resource.Layout.contact_view); var fullNameTextView = FindViewById <TextView> (Resource.Id.full_name); fullNameTextView.Text = displayName; var mobilePhoneTextView = FindViewById <TextView> (Resource.Id.mobile_phone); mobilePhoneTextView.Text = mobilePhone; }
/// <summary> /// Initializes a new instance of the <see cref="AddressBookViewModel"/> class. /// </summary> /// <param name="addressBook"></param> public AddressBookViewModel(AddressBook addressBook) { AddressBookEditWrapper = addressBook; EnableLiveShaping(); }
internal static void AssertAreEqual(AddressBookBuilder expected, AddressBook actual) { AssertAreEqual(expected, actual, ""); }
protected void btnRegister_Click(object sender, EventArgs e) { if (Page.IsValid && RadCaptcha1.IsValid) { var oAddressBook = new AddressBook(); var FirstName = txtFullNameRegister.Text.Trim(); var Email = txtEmailRegister.Text.Trim(); var UserName = txtEmailRegister.Text.Trim(); var Password = txtPasswordRegister.Text.Trim(); var IsPrimary = "True"; var IsPrimaryBilling = "True"; var IsPrimaryShipping = "True"; var RoleName = "member"; var Gender = rdbGender.SelectedValue; //DateTime strDateOfBirth = new DateTime(Convert.ToInt32(ddlYear.SelectedItem.Text), Convert.ToInt32(ddlMonth.SelectedItem.Text), Convert.ToInt32(ddlDay.SelectedItem.Text)); string Birthday = hdnBirthDay.Value;// strDateOfBirth.ToString("MM/dd/yyyy"); //var Gender = rdbGender.SelectedValue; //DateTime strDateOfBirth = new DateTime(Convert.ToInt32(ddlYear.SelectedItem.Text), Convert.ToInt32(ddlMonth.SelectedItem.Text), Convert.ToInt32(ddlDay.SelectedItem.Text)); //string Birthday = strDateOfBirth.ToString("MM/dd/yyyy"); bool bError = false; if (!string.IsNullOrEmpty(UserName)) { if (Membership.GetUser(UserName) != null) { CustomValidator2.ErrorMessage = "<b>+ Tên truy cập " + UserName + " đã được đăng ký sử dụng, vui lòng chọn tên khác</b>"; CustomValidator2.IsValid = false; bError = true; } else { CustomValidator2.IsValid = true; } } if (!bError) { Membership.CreateUser(UserName, Password, Email); Roles.AddUserToRole(UserName, RoleName); //var oUser = new User(); //oUser.UserInsert(UserName, Password, Email, Role); oAddressBook.AddressBookInsert( FirstName, "", Email, txtPhone.Text.Trim(), txtPhone.Text.Trim(), "", //ReceiveEmail, UserName, "", txtAddress.Text.Trim(), "", "", "", "", "", "", IsPrimary, IsPrimaryBilling, IsPrimaryShipping, RoleName, Gender, Birthday ); //if (ckbNewsletter.Checked) //{ // var oNewletter = new Newsletter(); // oNewletter.NewsletterInsert(Email); //} FormsAuthentication.SetAuthCookie(UserName, true); //pnlSuccess.Visible = true; Session["UserName"] = UserName; //var CC = "*****@*****.**"; var Subject = "Đăng ký tài khoản thành công/Thanks for Registering"; //var OrderCode = OrderID; string Host = "smtp.gmail.com"; int Port = 587; string From = "*****@*****.**"; string mPassword = "******"; string Body = "<div style='width: 100%; font-size: 11px; font-family: Arial;'>"; Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>"; Body += "Cảm ơn bạn đã đăng ký tài khoản/Thanks for Registering"; Body += "</h3>"; Body += "<div style='font-family: Verdana; font-size: 11px; margin-bottom: 20px;'>"; Body += "<p>Xin chào " + FirstName + "/Hi " + FirstName + ",</p>"; Body += "<p>Cảm ơn bạn đã đăng ký tài khoản tại EZStore/ Many thanks for registering at EZStore</p>"; Body += "<p>Thông tin đăng nhập của bạn như sau/ Your login detail is as follow:</p>"; Body += "<p>Email: <b>" + Email + "</b></p>"; Body += "<p>Mật khẩu/Password: <b>" + Password + "</b></p>"; Body += "<p>Mọi thắc mắc, xin vui lòng liên hệ với chúng tôi qua email: <a href='mailto:[email protected]'>[email protected]</a> /If you have any enquiries, please email us on <a href='mailto:[email protected]'>[email protected]</a></p>"; Body += "<p>Chúc bạn có những thời khắc ngọt ngào với Lady fashion/ We hope you have great expericences with Lady fashion</p>"; Body += "</div>"; Body += "<div style='font-family:Verdana;font-size:12px;margin-top:10px;'>"; Body += "<div style='font-size:16px;font-weight:bold;'>=================</div>"; Body += "<h4 style='font-size:14px;font-family:Verdana;margin:0;padding:0;'>Lady fashion</h4>"; Body += "<div style='font-size:11px;font-family:Verdana;margin-top:5px;padding:0;margin:0;'>"; Body += "<p>Add: 1278 Quang Trung, Phường 14, Quận Gò Vấp, TP.HCM</p>"; Body += "<p>Tel: 08 386 569 - 0906 211 611</p>"; //Body += "<p>M: +84 908 xxx xxx>"; //Body += "<p>W: <a href='http://www.pandemos.vn'>www.pandemos.vn</a></p>"; //Body += "<p>E: <a href='mailto:[email protected]'>[email protected]</a></p>"; Body += "</div>"; Body += "</div>"; Body += "</div>"; TLLib.Common.SendMail(Host, Port, From, mPassword, Email, "", Subject, Body, false); //txtUserNameRegister.Text = txtEmailRegister.Text = ""; txtPasswordRegister.Text = ""; txtVerifyCode.Text = ""; //txtConfirmPassWordRegister.Text = ""; //ddlYear.SelectedIndex = ddlDay.SelectedIndex = ddlMonth.SelectedIndex = -1; lblEmailMessage.Text = ""; //ckbSuccess.Checked = false; //ckbNewsletter.Checked = false; //ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "runtime", "alert('Bạn đã đăng ký thành công!')", true); Response.Redirect("~/Default.aspx"); } } //else //{ // ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "runtime", " $(document).ready(function () {$('.dk').trigger('click');});", true); //} }
async Task TestCreateAccountReceivableFromPO() { AddressBook addressBook = null; AddressBook buyerAddressBook = null; PurchaseOrderModule PurchaseOrderMod = new PurchaseOrderModule(); ChartOfAccount account = await PurchaseOrderMod.ChartOfAccount.Query().GetEntityById(17); Supplier supplier = await PurchaseOrderMod.Supplier.Query().GetEntityById(3); if (supplier != null) { addressBook = await PurchaseOrderMod.AddressBook.Query().GetEntityById(supplier.AddressId); } Contract contract = await PurchaseOrderMod.Contract.Query().GetEntityById(1); Poquote poquote = await PurchaseOrderMod.POQuote.Query().GetEntityById(2); Buyer buyer = await PurchaseOrderMod.Buyer.Query().GetEntityById(1); if (buyer != null) { buyerAddressBook = await PurchaseOrderMod.AddressBook.Query().GetEntityById(buyer.AddressId); } TaxRatesByCode taxRatesByCode = await PurchaseOrderMod.TaxRatesByCode.Query().GetEntityById(1); PurchaseOrderView view = new PurchaseOrderView() { DocType = "STD", PaymentTerms = "Net 30", Amount = 286.11M, AmountPaid = 0, Remark = "PO Remark", Gldate = DateTime.Parse("11/29/2019"), AccountId = account.AccountId, Location = account.Location, BusUnit = account.BusUnit, Subsidiary = account.Subsidiary, SubSub = account.SubSub, Account = account.Account, AccountDescription = account.Description, SupplierId = supplier.SupplierId, CustomerId = contract?.CustomerId, SupplierName = addressBook.Name, ContractId = contract?.ContractId, PoquoteId = poquote?.PoquoteId, QuoteAmount = poquote?.QuoteAmount, Description = "PO Description", Ponumber = "PO-123", TakenBy = "David Nishimoto", ShippedToName = " shipped name", ShippedToAddress1 = "shipped to address1", ShippedToAddress2 = "shipped to address2", ShippedToCity = "shipped city", ShippedToState = "ID", ShippedToZipcode = "83709", BuyerId = buyer.BuyerId, BuyerName = buyerAddressBook?.Name, RequestedDate = DateTime.Parse("11/29/2019"), PromisedDeliveredDate = DateTime.Parse("11/29/2019"), Tax = 0M, TransactionDate = DateTime.Parse("11/29/2019"), TaxCode1 = taxRatesByCode.TaxCode, TaxCode2 = "", TaxRate = taxRatesByCode.TaxRate ?? 0, PurchaseOrderNumber = (await PurchaseOrderMod.PurchaseOrder.Query().GetNextNumber()).NextNumberValue }; PurchaseOrder purchaseOrder = await PurchaseOrderMod.PurchaseOrder.Query().MapToEntity(view); PurchaseOrderMod.PurchaseOrder.AddPurchaseOrder(purchaseOrder).Apply(); Udc udcAccountReceivableType = await PurchaseOrderMod.Udc.Query().GetEntityById(66); ChartOfAccount coaAccountReceivable = await PurchaseOrderMod.ChartOfAccount.Query().GetEntityById(4); AccountReceivable accountReceivable = await PurchaseOrderMod.AccountReceivable.Query().MapEntityFromPurchaseOrder(purchaseOrder, udcAccountReceivableType, coaAccountReceivable); PurchaseOrderMod.AccountReceivable.AddAccountReceivable(accountReceivable).Apply(); }
/// <summary> /// Initializes a new instance of the <see cref="AddressBookInformation"/> class. /// </summary> public AddressBookInformation() { this.book = new AddressBook(Forms.Context.ApplicationContext); }
protected void btnBook_Click(object sender, EventArgs e) { if (IsValid) { var dtCart = Session["Cart"] as DataTable; var oAddressBook = new AddressBook(); var dtAddressBook = oAddressBook.AddressBookSelectAll("", "", "", "", "", "", "", Session["UserName"].ToString(), "", "", "", "", "", "", "", "", "", "", "", "").DefaultView; var txtFullName = dtAddressBook[0]["FirstName"].ToString(); var txtEmail = dtAddressBook[0]["Email"].ToString(); var txtAddress = dtAddressBook[0]["Address1"].ToString(); var txtPhuongXa = dtAddressBook[0]["Address2"].ToString(); var txtPhone = dtAddressBook[0]["HomePhone"].ToString(); var ddlProvince = dtAddressBook[0]["ProvinceName"].ToString(); var ddlDistrict = dtAddressBook[0]["DistrictName"].ToString(); if (dtCart != null) { Session["HoanThanh"] = "true"; string CreateBy = "admin"; string OrderNumber = DateTime.Now.ToString("ddMMyy") + Guid.NewGuid().GetHashCode().ToString("X").Substring(0, 4); //Session["OrderNumber"] = OrderNumber; string Email = ""; string FirstName = ""; string Address = ""; string PhoneNumber = ""; double TotalPrice = 0; double SumTotalPrice = 0; string PaymentMethods = ""; string OrderQuantity = "0"; string OrderStatusID = ""; Session["OrderNumber"] = OrderNumber; Email = txtEmail; FirstName = txtFullName; Address = txtAddress + " ," + txtPhuongXa + " ," + ddlProvince + " ," + ddlDistrict; // City = txtTinh.Text.Trim().ToString(); PhoneNumber = txtPhone; //TotalPrice = Session["tongtien"].ToString(); //OrderQuantity = Session["Quantity"].ToString(); OrderStatusID = "1"; PaymentMethods = "Thanh Toán Trực Tiếp"; string Price = "0"; // them don hang var oOrders = new Orders2(); oOrders.Orders2Insert( OrderNumber, CreateBy, DateTime.Now.ToString("MM/dd/yyyy"), PaymentMethods, FirstName, Address, PhoneNumber, "", Email, OrderStatusID); // don hang chi tiet var oOrderDetail = new OrderDetail2(); foreach (DataRow dr in dtCart.Rows) { string ProductID = dr["ProductID"].ToString(); var Quantity = Convert.ToInt32(dr["Quantity"]); if (dr["ProductPrice"] != null) { Price = (Convert.ToInt32(dr["Quantity"]) * (Convert.ToDouble(string.IsNullOrEmpty(dr["ProductPrice"].ToString()) ? 0 : dr["ProductPrice"]))).ToString(); } if (Session["UserName"] != null) { CreateBy = Session["UserName"].ToString(); } oOrderDetail.OrderDetail2Insert( OrderNumber, ProductID, Quantity.ToString(), Price, CreateBy ); } // hinh thuc thanh toan if (rbtMoney.Checked == true) { string FullName = FirstName; Session["FullName"] = FullName; Session["Address"] = Address; PaymentMethods = "Thanh Toán Trực Tiếp"; // noi dung mail xac nhan string Body = "<div style='width: 100%; font-size: 14px; font-family: Arial;'>"; Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>Cảm ơn bạn đã đặt hàng/Thanks for Your Order!</h3>"; Body += "<div style='padding: 10px; background-color: rgb(255,244,234); font-family: Verdana;font-size: 11px; margin-bottom: 20px;'>"; Body += "<p>Mã số đơn hàng của bạn là <b>" + Session["OrderNumber"] + "</b>. Chi tiết đơn hàng được liệt kê ở phía dưới. </p>"; Body += "</div>"; Body += "<p><b>Người nhận</b></p>"; Body += "<p>Họ và tên: " + txtFullName + "</p>"; Body += "<p>Email: " + txtEmail + "</p>"; Body += "<p>Điện thoại: " + txtPhone + "</p>"; Body += "<p>Địa chỉ: " + txtAddress + "</p>"; //Body += "<p>Loại địa chỉ: " + dropLoaiDiaChi.SelectedItem.Text + "</p>"; Body += "<p>Tỉnh/Thành phố: " + ddlProvince + "</p>"; Body += "<p>Quận/Huyện: " + ddlDistrict + "</p>"; Body += "<p>Ghi chú: " + txtGhiChu.Text + "</p>"; Body += "</div>"; Body += "<p><b>* Phương thức thanh toán</b>: " + PaymentMethods + "</p>"; Body += "<table style='font-size: 11px; font-family: Verdana; padding: 10px; border: 1px solid #C7D7DB; width: 100%;border-collapse: collapse;' cellpadding='0' cellspacing='0'>"; //Body += "<tr><th align='left' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Sản phẩm/Cart Items</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Cỡ/Size</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Số lượng/Qty</th><th align='center' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Giá/Item Price</th><th align='right' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Thành tiền/Item Total</th></tr>"; Body += "<tr><th align='left' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Sản phẩm/Cart Items</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Số lượng/Qty</th><th align='center' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Giá/Item Price</th><th align='right' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Thành tiền/Item Total</th></tr>"; foreach (DataRow dr in dtCart.Rows) { //string ProductCode = dr["Tag"].ToString(); string ProductID = dr["ProductID"].ToString(); string ProductName = dr["ProductName"].ToString(); string Quantity = dr["Quantity"].ToString(); Price = dr["ProductPrice"].ToString(); //string ProductOptionCategoryName = dr["ProductOptionCategoryName"].ToString(); // string ProductLengthName = dr["ProductLengthName"].ToString(); double tPrice = Convert.ToDouble(Price) * Convert.ToDouble(Quantity); var itemPrice = string.Format("{0:##,###.##}", tPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ"; var sPrice = string.Format("{0:##,###.##}", dr["ProductPrice"]).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ"; //Amount += Convert.ToDouble(Price) * Convert.ToDouble(Quantity); Body += "<tr>"; Body += "<td style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductName + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductCode + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductLengthName + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'><div style='background: " + ProductOptionCategoryName + "; width: 30px; height: 30px;'></div></td>"; Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + Quantity + "</td>"; Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + sPrice + "</td>"; Body += "<td align='right' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + itemPrice + "</td>"; Body += "</tr>"; TotalPrice += tPrice; } if (!string.IsNullOrEmpty(hdnSavePrice.Value)) { SumTotalPrice = TotalPrice - Convert.ToDouble(hdnSavePrice.Value); } else { SumTotalPrice = TotalPrice; } Body += "</table>"; Body += "<div style='clear: both;'></div>"; Body += "<table style='font-size: 13px; font-family: Verdana; text-align: right; margin: 10px 0; width: 100%; float: right;' cellpadding='0' cellspacing='0'>"; Body += "<tr><td style='width:85%;'>Thành tiền:</td><td style='width:15%;'>" + string.Format("{0:##,###.##}", TotalPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</td></tr>"; Body += "<tr><td>Giảm:</td><td>" + string.Format("{0:##,###.##}", Convert.ToDouble(hdnSavePrice.Value)).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</td></tr>"; Body += "<tr><td><b>Tổng tiền:</b></td><td><b>" + string.Format("{0:##,###.##}", SumTotalPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</b></td></tr>"; Body += "</table>"; Body += "<div style='clear: both;'></div>"; Common.SendMail("smtp.gmail.com", 587, "*****@*****.**", "web123master", txtEmail, "*****@*****.**", "Đặt Hàng PALACIO PERFUME", Body, true); ///////////////////////////////////////////////////////////////////////////////// //txtFullName.Text = ""; //txtPhone.Text = ""; //txtEmail.Text = ""; //txtAddress.Text = ""; txtGhiChu.Text = ""; lblSavePrice.Text = ""; hdnSavePrice.Value = ""; var oShoppingCart = new ShoppingCart(); oShoppingCart.DeleteAllItem(); Session["Cart"] = null; Session["SavePrice"] = null; ListView2.DataBind(); Response.Redirect("dat-hang-thanh-cong.aspx"); } else if (rbtEmail.Checked == true) { string FullName = FirstName; Session["FullName"] = FullName; Session["Address"] = Address; PaymentMethods = "Thanh Toán Chuyển Khoản"; oOrders.Orders2Update( OrderNumber, CreateBy, DateTime.Now.ToString("MM/dd/yyyy"), PaymentMethods, FirstName, Address, PhoneNumber, "", Email, OrderStatusID); // noi dung mail xac nhan string Body = "<div style='width: 100%; font-size: 14px; font-family: Arial;'>"; Body += "<h3 style='color: rgb(204,102,0); font-size: 22px; border-bottom-color: gray; border-bottom-width: 1px;border-bottom-style: dashed; margin-bottom: 20px; font-family: Times New Roman;'>Cảm ơn bạn đã đặt hàng/Thanks for Your Order!</h3>"; Body += "<div style='padding: 10px; background-color: rgb(255,244,234); font-family: Verdana;font-size: 11px; margin-bottom: 20px;'>"; Body += "<p>Mã số đơn hàng của bạn là <b>" + Session["OrderNumber"] + "</b>. Chi tiết đơn hàng được liệt kê ở phía dưới. </p>"; Body += "</div>"; Body += "<p><b>Người nhận</b></p>"; Body += "<p>Họ và tên: " + txtFullName + "</p>"; Body += "<p>Email: " + txtEmail + "</p>"; Body += "<p>Điện thoại: " + txtPhone + "</p>"; Body += "<p>Địa chỉ: " + txtAddress + "</p>"; //Body += "<p>Loại địa chỉ: " + dropLoaiDiaChi.SelectedItem.Text + "</p>"; Body += "<p>Tỉnh/Thành phố: " + ddlProvince + "</p>"; Body += "<p>Quận/Huyện: " + ddlDistrict + "</p>"; Body += "<p>Ghi chú: " + txtGhiChu.Text + "</p>"; Body += "</div>"; Body += "<p><b>* Phương thức thanh toán</b>: " + PaymentMethods + "</p>"; Body += "<table style='font-size: 11px; font-family: Verdana; padding: 10px; border: 1px solid #C7D7DB; width: 100%;border-collapse: collapse;' cellpadding='0' cellspacing='0'>"; //Body += "<tr><th align='left' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Sản phẩm/Cart Items</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Cỡ/Size</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Số lượng/Qty</th><th align='center' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Giá/Item Price</th><th align='right' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Thành tiền/Item Total</th></tr>"; Body += "<tr><th align='left' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Sản phẩm/Cart Items</th><th style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Số lượng/Qty</th><th align='center' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Giá/Item Price</th><th align='right' style='padding: 8px 5px; border-collapse: collapse; background-color: rgb(2,11,111);color: #fff;'>Thành tiền/Item Total</th></tr>"; foreach (DataRow dr in dtCart.Rows) { //string ProductCode = dr["Tag"].ToString(); string ProductID = dr["ProductID"].ToString(); string ProductName = dr["ProductName"].ToString(); string Quantity = dr["Quantity"].ToString(); Price = dr["Price"].ToString(); //string ProductOptionCategoryName = dr["ProductOptionCategoryName"].ToString(); //string ProductLengthName = dr["ProductLengthName"].ToString(); double tPrice = Convert.ToDouble(Price) * Convert.ToDouble(Quantity); var itemPrice = string.Format("{0:##,###.##}", tPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VND"; var sPrice = string.Format("{0:##,###.##}", dr["ProductPrice"]).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VND"; //Amount += Convert.ToDouble(Price) * Convert.ToDouble(Quantity); Body += "<tr>"; Body += "<td style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductName + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductCode + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + ProductLengthName + "</td>"; //Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'><div style='background: " + ProductOptionCategoryName + "; width: 30px; height: 30px;'></div></td>"; Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + Quantity + "</td>"; Body += "<td align='center' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + sPrice + "</td>"; Body += "<td align='right' style='padding: 5px; border-collapse: collapse; border-bottom: 1px solid #C7D7DB;'>" + itemPrice + "</td>"; Body += "</tr>"; TotalPrice += tPrice; } if (!string.IsNullOrEmpty(hdnSavePrice.Value)) { SumTotalPrice = TotalPrice - Convert.ToDouble(hdnSavePrice.Value); } else { SumTotalPrice = TotalPrice; } Body += "</table>"; Body += "<div style='clear: both;'></div>"; Body += "<table style='font-size: 13px; font-family: Verdana; text-align: right; margin: 10px 0; width: 100%; float: right;' cellpadding='0' cellspacing='0'>"; Body += "<tr><td style='width:85%;'>Thành tiền:</td><td style='width:15%;'>" + string.Format("{0:##,###.##}", TotalPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</td></tr>"; Body += "<tr><td>Giảm:</td><td>" + string.Format("{0:##,###.##}", Convert.ToDouble(hdnSavePrice.Value)).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</td></tr>"; Body += "<tr><td><b>Tổng tiền:</b></td><td><b>" + string.Format("{0:##,###.##}", SumTotalPrice).Replace('.', '*').Replace(',', '.').Replace('*', ',') + " VNĐ" + "</b></td></tr>"; Body += "</table>"; Body += "<div style='clear: both;'></div>"; Common.SendMail("smtp.gmail.com", 587, "*****@*****.**", "web123master", txtEmail, "*****@*****.**", "Đặt Hàng PALACIO PERFUME", Body, true); ///////////////////////////////////////////////////////////////////////////////// //txtFullName.Text = ""; //txtPhone.Text = ""; //txtEmail.Text = ""; //txtAddress.Text = ""; lblSavePrice.Text = ""; hdnSavePrice.Value = ""; txtGhiChu.Text = ""; var oShoppingCart = new ShoppingCart2(); oShoppingCart.DeleteAllItem(); Session["Cart"] = null; Session["SavePrice"] = null; ListView2.DataBind(); Response.Redirect("dat-hang-thanh-cong.aspx"); } } } }
/// <summary> /// Initial set up for the application. We read the config file and create the instance of Oauth and addressbook object. /// If it's post back from getting Auth code then perform operations. /// </summary> protected void Page_Load(object sender, EventArgs e) { ReadConfigFile(); oauth = new OAuth(endPoint, scope, apiKey, secretKey, authorizeRedirectUri, refreshTokenExpiresIn, bypassSSL); this.serializer = new JavaScriptSerializer(); if (Session["cs_rest_AccessToken"] != null && this.addressbook == null) { this.addressbook = new AddressBook(this.endPoint, Session["cs_rest_AccessToken"].ToString()); } if ((string)Session["cs_rest_appState"] == "GetToken" && Request["Code"] != null) { this.oauth.authCode = Request["code"].ToString(); if (oauth.GetAccessToken(OAuth.AccessTokenType.Authorization_Code) == true) { StoreAccessTokenToSession(oauth.access_token_json); this.addressbook = new AddressBook(this.endPoint, this.accessToken); Operation operation = (Operation)Session["cs_rest_ServiceRequest"]; switch (operation) { case Operation.CreateContactOperation: if (!addressbook.createContact(Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.create_contact = new Success(); this.create_contact.location = this.addressbook.location; } break; case Operation.UpdateContactOperation: if (!addressbook.updateContact(Session["contactid"].ToString(), Session["JSONstring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteContactOperation: if (!addressbook.deleteContact(Session["contactid"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { this.success_contact = new Success(); this.success_contact.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactsOperation: if (!addressbook.getContacts(Session["querystring"].ToString())) { this.contact_error = this.addressbook.errorResponse; } else { try { this.qContactResult = serializer.Deserialize<QuickContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.contact_error = ex.Message; } } break; case Operation.UpdateMyInfoOperation: if (!addressbook.updateMyInfo(Session["JSONstring"].ToString())) { this.myinfo_error = this.addressbook.errorResponse; } else { this.update_myinfo = new Success(); this.update_myinfo.last_modified = this.addressbook.last_mod; } break; case Operation.GetMyInfoOperation: if (!addressbook.getMyInfo()) { this.myinfo_error = this.addressbook.errorResponse; } else { try { this.myInfoResult = serializer.Deserialize<ContactJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.myinfo_error = ex.Message; } } break; case Operation.CreateGroupOperation: if (!addressbook.createGroup(Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.create_group = new Success(); this.create_group.location = this.addressbook.location; } break; case Operation.UpdateGroupOperation: if (!addressbook.updateGroup(Session["groupid"].ToString(), Session["JSONstring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.DeleteGroupOperation: if (!addressbook.deleteGroup(Session["groupid"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { this.success_group = new Success(); this.success_group.last_modified = this.addressbook.last_mod; } break; case Operation.GetGroupsOperation: if (!addressbook.getGroups(Session["querystring"].ToString())) { this.group_error = this.addressbook.errorResponse; } else { try { this.groupResult = serializer.Deserialize<GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.group_error = ex.Message; } } break; case Operation.GetGroupContactsOperation: if (!addressbook.getGroupContacts(Session["groupid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactIdResult = serializer.Deserialize<ContactIdJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; case Operation.AddContctsToGroupOperation: if(!addressbook.addContactToGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.RemoveContactsFromGroupOperation: if (!addressbook.removeContactsFromGroup(Session["groupid"].ToString(), Session["contactids"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { this.manage_groups = new Success(); this.manage_groups.last_modified = this.addressbook.last_mod; } break; case Operation.GetContactGroupsOperation: if (addressbook.getContactGroups(Session["contactid"].ToString())) { this.manage_groups_error = this.addressbook.errorResponse; } else { try { this.contactGroupResult = serializer.Deserialize<GroupJSON.RootObject>(addressbook.JSONstring); } catch (Exception ex) { this.manage_groups_error = ex.Message; } } break; } ResetRequestSessionVariables(operation); } else { if (oauth.getAuthCodeError != null) { this.oauth_error = "GetAuthCodeError: " + oauth.getAuthCodeError; } if (oauth.GetAccessTokenError != null) { this.oauth_error = "GetAccessTokenError: " + oauth.GetAccessTokenError; } this.ResetTokenSessionVariables(); return; } } }
public async Task TestAddUpdatDelete() { CustomerModule CustomerMod = new CustomerModule(); AddressBook addressBook = await CustomerMod.AddressBook.Query().GetEntityById(1); LocationAddress shipToLocationAddress = await CustomerMod.LocationAddress.Query().GetEntityById(3); LocationAddress mailingLocationAddress = await CustomerMod.LocationAddress.Query().GetEntityById(3); LocationAddress billingLocationAddress = await CustomerMod.LocationAddress.Query().GetEntityById(3); PhoneEntity phone = await CustomerMod.Phone.Query().GetEntityById(1); EmailEntity emailEntity = await CustomerMod.Email.Query().GetEntityById(1); CustomerView view = new CustomerView() { AddressId = addressBook.AddressId, CustomerName = addressBook.Name, FirstName = addressBook.FirstName, LastName = addressBook.LastName, PrimaryEmailId = emailEntity?.EmailId, AccountEmail = emailEntity?.Email, AccountEmailLogin = emailEntity?.LoginEmail ?? false, PrimaryShippedToLocationAddressId = shipToLocationAddress?.LocationAddressId, ShipToAddressLine1 = shipToLocationAddress?.AddressLine1, ShipToAddressLine2 = shipToLocationAddress?.AddressLine2, ShipToCity = shipToLocationAddress?.City, ShipToZipcode = shipToLocationAddress?.Zipcode, MailingLocationAddressId = mailingLocationAddress?.LocationAddressId, MailingAddressLine1 = mailingLocationAddress?.AddressLine1, MailingAddressLine2 = mailingLocationAddress?.AddressLine2, MailingCity = mailingLocationAddress?.City, MailingZipcode = mailingLocationAddress?.Zipcode, PrimaryBillingLocationAddressId = billingLocationAddress?.LocationAddressId, BillingAddressLine1 = billingLocationAddress?.AddressLine1, BillingAddressLine2 = billingLocationAddress?.AddressLine2, BillingCity = billingLocationAddress?.City, BillingZipcode = billingLocationAddress?.Zipcode, PrimaryPhoneId = phone.PhoneId, PhoneNumber = phone.PhoneNumber, TaxIdentification = "tax id" }; NextNumber nnNextNumber = await CustomerMod.Customer.Query().GetNextNumber(); view.CustomerNumber = nnNextNumber.NextNumberValue; Customer customer = await CustomerMod.Customer.Query().MapToEntity(view); CustomerMod.Customer.AddCustomer(customer).Apply(); Customer newCustomer = await CustomerMod.Customer.Query().GetEntityByNumber(view.CustomerNumber); Assert.NotNull(newCustomer); newCustomer.AddressId = 17; CustomerMod.Customer.UpdateCustomer(newCustomer).Apply(); CustomerView updateView = await CustomerMod.Customer.Query().GetViewById(newCustomer.CustomerId); if (updateView.AddressId != 17) { Assert.True(true); } CustomerMod.Customer.DeleteCustomer(newCustomer).Apply(); Customer lookupCustomer = await CustomerMod.Customer.Query().GetEntityById(view.CustomerId); Assert.Null(lookupCustomer); }
public PreFormActionResponse Execute(OwaContext owaContext, out ApplicationElement applicationElement, out string type, out string state, out string action) { if (owaContext == null) { throw new ArgumentNullException("owaContext"); } UserContext userContext = owaContext.UserContext; HttpRequest request = owaContext.HttpContext.Request; string[] array = null; applicationElement = ApplicationElement.Item; type = string.Empty; action = string.Empty; state = string.Empty; if (!Utilities.IsPostRequest(request)) { return(userContext.LastClientViewState.ToPreFormActionResponse()); } PreFormActionResponse preFormActionResponse = new PreFormActionResponse(); string formParameter = Utilities.GetFormParameter(request, "hidAB"); int num = 0; StoreObjectId storeObjectId = null; string changeKey = null; string[] array2 = formParameter.Split(new char[] { ';' }); if (array2 != null && array2.Length > 0) { if (string.CompareOrdinal(array2[0], "Ad") == 0) { num = 1; } else { if (string.CompareOrdinal(array2[0], "Con") != 0) { throw new OwaInvalidRequestException("Invalid search location for addressbook"); } num = 2; } } string action2 = owaContext.FormsRegistryContext.Action; if (action2 == null) { throw new OwaInvalidRequestException("Action query string parameter is missing"); } object obj = AddressBookPreFormAction.actionParser.Parse(action2); AddressBookPreFormAction.Action action3 = (AddressBookPreFormAction.Action)obj; string text = request.Form["chkRcpt"]; if (!string.IsNullOrEmpty(text)) { array = text.Split(new char[] { ',' }); } AddressBook.Mode mode = AddressBookHelper.TryReadAddressBookMode(request, AddressBook.Mode.None); if (AddressBook.IsEditingMode(mode)) { string formParameter2 = Utilities.GetFormParameter(request, "hidid", false); changeKey = Utilities.GetFormParameter(request, "hidchk", false); if (!string.IsNullOrEmpty(formParameter2)) { storeObjectId = Utilities.CreateStoreObjectId(userContext.MailboxSession, formParameter2); if (storeObjectId == null) { throw new OwaInvalidRequestException("ItemId cannot be null"); } } } switch (action3) { case AddressBookPreFormAction.Action.Done: if (AddressBook.IsEditingMode(mode)) { using (Item item = AddressBookHelper.GetItem(userContext, mode, storeObjectId, changeKey)) { if (array != null && array.Length > 0) { RecipientItemType type2 = RecipientItemType.To; string formParameter3 = Utilities.GetFormParameter(request, "hidrw"); if (!string.IsNullOrEmpty(formParameter3)) { int num2; if (!int.TryParse(formParameter3, out num2) || num2 < 1 || num2 > 3) { type2 = RecipientItemType.To; } else { type2 = (RecipientItemType)num2; } } if (num == 1) { AddressBookHelper.AddRecipientsToDraft(array, item, type2, userContext); } else if (num == 2) { AddressBookHelper.AddContactsToDraft(item, type2, userContext, array); } } preFormActionResponse = AddressBookHelper.RedirectToEdit(userContext, item, mode); break; } } throw new OwaInvalidRequestException("This action must be in editing mode"); case AddressBookPreFormAction.Action.Mail: if (array != null && array.Length > 0) { using (Item item2 = MessageItem.Create(userContext.MailboxSession, userContext.DraftsFolderId)) { item2[ItemSchema.ConversationIndexTracking] = true; if (num == 1) { AddressBookHelper.AddRecipientsToDraft(array, item2, RecipientItemType.To, userContext); } else if (num == 2) { AddressBookHelper.AddContactsToDraft(item2, RecipientItemType.To, userContext, array); } preFormActionResponse.ApplicationElement = ApplicationElement.Item; preFormActionResponse.Type = "IPM.Note"; preFormActionResponse.Action = "Open"; preFormActionResponse.State = "Draft"; preFormActionResponse.AddParameter("id", item2.Id.ObjectId.ToBase64String()); break; } } preFormActionResponse.ApplicationElement = ApplicationElement.Item; preFormActionResponse.Type = "IPM.Note"; preFormActionResponse.Action = "New"; break; case AddressBookPreFormAction.Action.MeetingRequest: preFormActionResponse.ApplicationElement = ApplicationElement.Item; preFormActionResponse.Type = "IPM.Appointment"; if (array != null && array.Length > 0) { using (CalendarItemBase calendarItemBase = EditCalendarItemHelper.CreateDraft(userContext, userContext.CalendarFolderId)) { calendarItemBase.IsMeeting = true; if (num == 1) { AddressBookHelper.AddRecipientsToDraft(array, calendarItemBase, RecipientItemType.To, userContext); } else if (num == 2) { AddressBookHelper.AddContactsToDraft(calendarItemBase, RecipientItemType.To, userContext, array); } preFormActionResponse.Action = "Open"; EditCalendarItemHelper.CreateUserContextData(userContext, calendarItemBase); break; } } preFormActionResponse.AddParameter("mr", "1"); preFormActionResponse.Action = "New"; break; case AddressBookPreFormAction.Action.Close: if (AddressBook.IsEditingMode(mode)) { using (Item item3 = AddressBookHelper.GetItem(userContext, mode, storeObjectId, changeKey)) { preFormActionResponse = AddressBookHelper.RedirectToEdit(userContext, item3, mode); break; } } throw new OwaInvalidRequestException("This action must be in editing mode"); case AddressBookPreFormAction.Action.AddToContacts: { string type3 = "IPM.Contact"; string text2 = null; if (array == null || array.Length != 1) { throw new OwaInvalidRequestException("User must select some recipient to add and can only add one recipient to contacts at one time"); } ADObjectId adobjectId = DirectoryAssistance.ParseADObjectId(array[0]); if (adobjectId == null) { throw new OwaADObjectNotFoundException(); } IRecipientSession recipientSession = Utilities.CreateADRecipientSession(Culture.GetUserCulture().LCID, true, ConsistencyMode.FullyConsistent, true, userContext); ADRecipient adrecipient = recipientSession.Read(adobjectId); if (adrecipient == null) { throw new OwaADObjectNotFoundException(); } using (ContactBase contactBase = ContactUtilities.AddADRecipientToContacts(userContext, adrecipient)) { if (contactBase != null) { contactBase.Load(); text2 = contactBase.Id.ObjectId.ToBase64String(); type3 = contactBase.ClassName; } } preFormActionResponse.ApplicationElement = ApplicationElement.Item; preFormActionResponse.Type = type3; if (text2 != null) { preFormActionResponse.Action = "Open"; preFormActionResponse.State = "Draft"; preFormActionResponse.AddParameter("id", text2); } else { preFormActionResponse.Action = "New"; } break; } default: throw new OwaInvalidRequestException("Invalid request for addressbook preformaction"); } return(preFormActionResponse); }
//=============================================================== // Function: Page_Load //=============================================================== protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int userID = int.Parse(Session["loggedInUserID"].ToString()); string action = ""; if (Request.QueryString["A"] != null) { action = Request.QueryString["A"].ToString(); int addressBookID = -1; if (Request.QueryString["ABID"] != null) { addressBookID = int.Parse(Request.QueryString["ABID"]); } int addressBookUserID = -1; if (Request.QueryString["UID"] != null) { addressBookUserID = int.Parse(Request.QueryString["UID"]); } if (action == "Delete") { try { AddressBook addressBook = new AddressBook(Session["loggedInUserFullName"].ToString(), addressBookID); addressBook.Delete(); } catch (Exception ex) { Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert(\"Error: " + ex.Message + "\");", true); } } if (action == "Add") { SedogoUser newAddressBookUser = new SedogoUser(Session["loggedInUserFullName"].ToString(), addressBookUserID); AddressBook addressBookEntry = new AddressBook(Session["loggedInUserFullName"].ToString()); addressBookEntry.userID = userID; addressBookEntry.firstName = newAddressBookUser.firstName; addressBookEntry.lastName = newAddressBookUser.lastName; addressBookEntry.emailAddress = newAddressBookUser.emailAddress; addressBookEntry.Add(); } } SedogoUser user = new SedogoUser(Session["loggedInUserFullName"].ToString(), userID); sidebarControl.userID = userID; sidebarControl.user = user; bannerAddFindControl.userID = userID; PopulateAddressBook(userID); } }
internal static HandleRef getCPtr(AddressBook obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; }
public GetAppointmentsQueryHandler(AppointmentRepository appointmentRepository, AppointmentRequestRepository appointmentRequestRepository, AddressBook addressBook) { this.appointmentRepository = appointmentRepository; this.appointmentRequestRepository = appointmentRequestRepository; this.addressBook = addressBook; }
public AddressBookGump(Mobile owner, int listPage, ArrayList list, int[] count, AddressBook hiya) : base(140, 80) { m_Book = hiya; owner.CloseGump(typeof(AddressBookGump)); m_List = BuildThisList(list); //m_List=list; if (m_List == null) { m_List = new ArrayList(); } m_ListPage = listPage; m_CountList = count; m_Owner = owner; Closable = true; Disposable = true; Dragable = true; Resizable = false; AddPage(0); AddImage(3, 18, 2200);//book AddButton(139, 27, 0x8B0, 0x8B0, 91000, GumpButtonType.Reply, 0); AddLabel(42, 20, 0, "Add Contact"); AddLabel(229, 20, 0, "Entries:"); //Added code for working pages if ((m_CountList == null) && (m_List.Count > 6)) { m_CountList = new int[(int)(m_List.Count / 6)]; } if (listPage > 0) { AddButton(23, 23, 2205, 2205, 90000, GumpButtonType.Reply, 0); } if ((listPage + 1) * 6 < m_List.Count) { AddButton(297, 23, 2206, 2206, 90001, GumpButtonType.Reply, 0); //Next page } if (m_List.Count == 0) { AddLabel(35, 82, 0x25, "No Entries"); } int k = 0; if (listPage > 0) { for (int z = 0; z < (listPage - 1); ++z) { k = k + Convert.ToInt32(m_CountList[z]); } } for (int i = 0, j = 0, index = ((listPage * 6) + k); i < 6 && index >= 0 && index < m_List.Count && j >= 0; ++i, ++j, ++index) { int offset = 75 + (i * 15); AdresseeEntry entry = (AdresseeEntry)m_List[index]; if (entry.Adressee != null && !entry.Adressee.Deleted) { AddButton(186, offset, 0x845, 0x846, (index + 1), GumpButtonType.Reply, 0); AddLabel(204, offset, GetHueFor(entry.Adressee), entry.Adressee.Name.ToString()); } else { AddLabel(204, offset, 0, entry.Adressee.Name.ToString() + " [Void]"); } if (i == 6) { m_CountList[listPage] = (j - 6); } } }
/// <summary> /// Constructor /// </summary> /// <param name="catchAllConfig">The configuration.</param> /// <param name="addressBook">The address book to perform lookups.</param> public CatchAllAgent(CatchAllConfig catchAllConfig, AddressBook addressBook) { // Save the address book and configuration this.addressBook = addressBook; this.catchAllConfig = catchAllConfig; // Register an OnRcptCommand event handler this.OnRcptCommand += new RcptCommandEventHandler(this.RcptToHandler); }
public override void AddAddress(string code, Addresses addresses) { AddressBook.AddOrUpdate(code, addresses, (s, oldAddress) => addresses); }
/// <summary> /// Constructor /// </summary> /// <param name="catchAllConfig">The configuration.</param> /// <param name="addressBook">The address book to perform lookups.</param> public CatchAllAgent(AddressBook addressBook) { // Save the address book and configuration this.addressBook = addressBook; this.origToMapping = new Dictionary <string, string[]>(); DomainSection domains = CatchAllFactory.GetCustomConfig <DomainSection>("domainSection"); if (domains == null) { Logger.LogError("domainSection not found in configuration."); return; } domainList = new List <DomainElement>(); if (domains.Domains.Count == 0) { Logger.LogWarning("No domains configured for CatchAll. I've nothing to do..."); } else { string domainStr = ""; foreach (DomainElement d in domains.Domains) { if (!d.Regex && !RoutingAddress.IsValidAddress(d.Address)) { Logger.LogError("Invalid address for domain: " + d.Name + ". '" + d.Address); continue; } else if (d.Regex && !d.compileRegex()) { Logger.LogError("Invalid regex for domain: " + d.Name + ". '" + d.Address); continue; } domainList.Add(d); if (domainStr.Length > 0) { domainStr += ", "; } domainStr += d.Name; } Logger.LogInformation("Following domains configured for CatchAll: " + domainStr, 50); } Database settings = CatchAllFactory.GetCustomConfig <Database>("customSection/database"); if (settings == null) { Logger.LogWarning("No database settings found. Not using database connection."); return; } if (settings.Enabled) { switch (settings.Type.ToLower()) { case "mysql": databaseConnector = new MysqlConnector(settings.ConnectionStrings); break; case "mssql": databaseConnector = new MssqlConnector(settings.ConnectionStrings); break; //case "oracle": // databaseConnector = new OracleConnector(settings.ConnectionStrings); // break; //case "db2": // databaseConnector = new Db2Connector(settings.ConnectionStrings); // break; default: Logger.LogError("Configuration: Database has invalid type setting: " + settings.Type + "\nMust be 'mysql' or 'mssql'."); break; } } else { Logger.LogInformation("Database connection disabled in config file.", 60); } this.OnEndOfData += new EndOfDataEventHandler(this.OnEndOfDataHandler); this.OnRcptCommand += new RcptCommandEventHandler(this.RcptToHandler); }
static void Main(string[] args) { // Serialize and parse it. Make sure to parse from an InputStream, not // directly from a ByteString, so that CodedInputStream uses buffered // reading. AddressBook l1 = new AddressBook(); l1.People.Add(new Person() { Id = 1, Name = "ABC", Email = "*****@*****.**" }); uint tagLengthDelimited = WireFormat.MakeTag(AddressBook.PeopleFieldNumber, WireFormat.WireType.LengthDelimited); //// Hand-craft the stream to contain a single entry with just a value. //using (var memoryStream = new MemoryStream()) //using (var output = new CodedOutputStream(memoryStream)) //{ // output.WriteTag(AddressBook.PeopleFieldNumber, WireFormat.WireType.LengthDelimited); // // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) // output.WriteLength(2 + l1.CalculateSize()); // output.WriteTag(2, WireFormat.WireType.LengthDelimited); // output.WriteMessage(l1); // output.Flush(); // byte[] bf = memoryStream.ToArray(); // var parsed = AddressBook.Parser.ParseFrom(bf); //} var clone = l1.Clone(); byte[] bytes = l1.ToByteArray(); string json1 = l1.ToString(); string json2 = JsonFormatter.Default.Format(l1); var writer = new StringWriter(); JsonFormatter.Default.Format(l1, writer); string json3 = writer.ToString(); var empty = Empty.Parser.ParseFrom(bytes); // this works - json below JsonFormatter jsf = new JsonFormatter(new JsonFormatter.Settings(true)); string jsonString = jsf.Format(l1); // this throws error - see exception details below var lsJson = JsonParser.Default.Parse <AddressBook>(jsonString); var lsJson2 = JsonParser.Default.Parse(jsonString, AddressBook.Descriptor); // MessageDescriptor -> //string jsonMessageDescriptor = JsonConvert.SerializeObject(AddressBook.Descriptor); byte[] buf = null; using (var ms = new MemoryStream()) using (var output = new CodedOutputStream(ms)) { //////uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); //////output.WriteRawVarint32(tag); //////output.WriteRawVarint32(0x7FFFFFFF); //////output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. //////output.Flush(); //////ms.Position = 0; ////output.WriteTag(1, WireFormat.WireType.Varint); //output.WriteInt32(99); ////output.WriteTag(2, WireFormat.WireType.Varint); //output.WriteInt32(123); //output.WriteFixed32(0); //output.WriteFixed32(34567); //output.WriteRawVarint32(0); //output.WriteRawVarint32(34567); //output.WriteLength(7); output.WriteRawVarint32(99); output.WriteFixed32(34567); l1.WriteTo(output); output.Flush(); buf = ms.ToArray(); } byte type = 0; uint tag = 0; AddressBook l2 = null; string log; if (buf != null && buf.Length > 0) { //using (var input = new CodedInputStream(buf)) //{ // //tag = input.ReadInt32(); // tag = input.ReadFixed32(); // try // { // l2 = AddressBook.Parser.ParseFrom(input); // } // catch (Exception ex) // { // log = ex.Message; // } //} type = buf[0]; tag = BitConverter.ToUInt32(buf, 1); using (CodedInputStream input = new CodedInputStream(buf, 5, buf.Length - 5)) { try { l2 = AddressBook.Parser.ParseFrom(input); } catch (Exception ex) { log = ex.Message; } } } //////////////////////////////////////////////// Console.WriteLine("Enter to exit ..."); Console.ReadLine(); }
private static void TestPerformance() { AddressBook ab = new AddressBook (); ab.List = new List<Person>(); //Generating structures for (int n = 0; n < 1000; n++) { Person p = new Person (); p.Name = "Alice" + n; p.Id = 17532; p.Email = "*****@*****.**"; p.Phone = new List<Person.PhoneNumber> (); for (int m = 0; m < 1000; m++) { Person.PhoneNumber pn = new Person.PhoneNumber (); pn.Type = Person.PhoneType.MOBILE; pn.Number = m.ToString (); p.Phone.Add (pn); } ab.List.Add (p); } //Serialize DateTime start = DateTime.Now; byte[] buffer = AddressBook.SerializeToBytes (ab); TimeSpan serialize = DateTime.Now - start; Console.WriteLine ("Speed test: Serialize in " + serialize); //Deserialize start = DateTime.Now; AddressBook.Deserialize (buffer); TimeSpan deserialize = DateTime.Now - start; Console.WriteLine ("Speed test: Deserialize in " + deserialize); }
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e) { if (e.CommandName == "alpha" || e.CommandName == "NoFilter") { String value = null; switch (e.CommandName) { case ("alpha"): { value = string.Format("{0}%", e.CommandArgument); break; } case ("NoFilter"): { value = "%"; break; } } ObjectDataSource1.SelectParameters["UserName"].DefaultValue = value; ObjectDataSource1.DataBind(); RadGrid1.Rebind(); } else if (e.CommandName == "QuickUpdate") { string UserName, Role; var oUser = new User(); foreach (GridDataItem item in RadGrid1.Items) { UserName = item["UserName"].Text; Role = ((RadComboBox)item.FindControl("ddlRole")).SelectedValue; oUser.ChangeRole(UserName, Role); } } else if (e.CommandName == "PerformInsert" || e.CommandName == "Update") { try { var command = e.CommandName; var row = command == "PerformInsert" ? (GridEditFormInsertItem)e.Item : (GridEditFormItem)e.Item; var FileAvatarImage = (RadUpload)row.FindControl("FileAvatarImage"); string strAvatarImage = FileAvatarImage.UploadedFiles.Count > 0 ? FileAvatarImage.UploadedFiles[0].FileName : ""; var strUserID = ((HiddenField)row.FindControl("hdnUserID")).Value; //var oUser = new User(); var AddressBookID = ((HiddenField)row.FindControl("hdnAddressBookID")).Value.ToString().Trim(); var hdnUserName = ((HiddenField)row.FindControl("hdnUserName")).Value.ToString().Trim(); var hdnEmail = ((HiddenField)row.FindControl("hdnEmail")).Value.ToString().Trim(); var strUserName = ((TextBox)row.FindControl("txtEmail")).Text; if (strUserName == "") strUserName = hdnUserName; string ConvertedFirstName = Common.ConvertTitle(strUserName); var strEmail = ((TextBox)row.FindControl("txtEmail")).Text; if (strEmail == "") strEmail = hdnEmail; var strPassword = ((TextBox)row.FindControl("txtPassword")).Text; var strCompanyName = ((TextBox)row.FindControl("txtCompanyName")).Text; var strAddress1 = ((TextBox)row.FindControl("txtAddress")).Text; var strFullName = ((TextBox)row.FindControl("txtFullName")).Text; var strCellPhone = ((TextBox)row.FindControl("txtCellPhone")).Text; string strOldImageName = ((HiddenField)row.FindControl("hdnOldImageName")).Value; if (e.CommandName == "PerformInsert") { var ListViewRoles = (ListView)row.FindControl("lvListViewRoles"); string[] dsRoles = Roles.GetRolesForUser(strUserName); Membership.CreateUser(strUserName, strPassword, strEmail); if (string.IsNullOrEmpty(strUserID)) strUserID = Membership.GetUser(strUserName).ProviderUserKey.ToString(); foreach (ListViewItem item in ListViewRoles.Items) { var check = (CheckBox)item.FindControl("chkRoles"); if (check.Checked == true) { Roles.AddUserToRole(strUserName, check.Text); } else { Roles.AddUserToRole(strUserName, "customer"); break; } } var oUserProfile = new AddressBook(); oUserProfile.AddressBookInsert2( strFullName, "", strEmail, strCellPhone, "", "", strUserName, strCompanyName, strAddress1, "", "", "", "", "", "", "", "", "", "", "", "" ); //var oUserProfile = new UserProfile(); //oUserProfile.UserProfileInsert(strUserID, strCompanyName, strFullName, "", "", strCellPhone, "", "", "true"); } else { var UserName = ((HiddenField)row.FindControl("hdnUserName")).Value.ToString().Trim(); var ListViewRoles = (ListView)row.FindControl("lvListViewRoles"); string[] dsRoles = Roles.GetRolesForUser(UserName); Roles.RemoveUserFromRoles(UserName, dsRoles); foreach (ListViewItem item in ListViewRoles.Items) { var check = (CheckBox)item.FindControl("chkRoles"); if (check.Checked == true) { Roles.AddUserToRole(UserName, check.Text); } else { Roles.AddUserToRole(strUserName, "customer"); break; } } var oUserProfile = new AddressBook(); oUserProfile.AddressBookUpdate2( AddressBookID, strFullName, "", strEmail, strCellPhone, "", "", strUserName, strCompanyName, strAddress1, "", "", "", "", "", "", "", "", "", "", "", "" ); //var oUserProfile = new UserProfile(); //oUserProfile.UserProfileUpdate( // strUserID, // strCompanyName, // strFullName, // "", // "", // strCellPhone, // "", // strAvatarImage, // "true" // ); } var strOldImagePath = Server.MapPath("~/res/userprofile/" + strOldImageName); if (!string.IsNullOrEmpty(strAvatarImage)) { if (File.Exists(strOldImagePath)) File.Delete(strOldImagePath); string strFullPath = "~/res/userprofile/" + (string.IsNullOrEmpty(ConvertedFirstName) ? "" : ConvertedFirstName) + strAvatarImage.Substring(strAvatarImage.LastIndexOf('.')); FileAvatarImage.UploadedFiles[0].SaveAs(Server.MapPath(strFullPath)); ResizeCropImage.ResizeByCondition(strFullPath, 100, 100); } RadGrid1.Rebind(); } catch (Exception ex) { lblError.Text = ex.Message; } } else if (e.CommandName == "DeleteSelected") { string OldAvatarImage; var oUserProfile = new AddressBook(); var oUser = new User(); string errorList = "", UserName = ""; foreach (GridDataItem item in RadGrid1.SelectedItems) { try { var UserID = item.GetDataKeyValue("UserID").ToString(); UserName = item["UserName"].Text; oUserProfile.AddressBookDeleteByUserName(UserName); oUser.UserDelete(UserName); OldAvatarImage = ((HiddenField)item.FindControl("hdnAvatarImage")).Value; DeleteImage(OldAvatarImage); } catch (Exception ex) { lblError.Text = ex.Message; if (ex.Message == ((int)ErrorNumber.ConstraintConflicted).ToString()) errorList += ", " + UserName; } } if (!string.IsNullOrEmpty(errorList)) { e.Canceled = true; string strAlertMessage = "Tài khoản <b>\"" + errorList.Remove(0, 1).Trim() + " \"</b> đang có tin đăng BĐS .<br /> Xin xóa tin đăng hoặc sử dụng chức năng khoá tài khoản."; lblError.Text = strAlertMessage; } RadGrid1.Rebind(); } }
static void Main(string[] args) { /* * Task.Run(() => * { * IntPtr loop = Libuv.CreateLoop(); * * Libuv.uv_loop_init(loop); * * IntPtr timer = Libuv.Allocate(Libuv.uv_handle_type.UV_TIMER); * Libuv.uv_timer_init(loop, timer); * Libuv.uv_timer_start(timer, work_cb, 1000, 1000); * * Libuv.uv_run(loop, Libuv.uv_run_mode.UV_RUN_DEFAULT); * }); */ //AreaServer as Console.WriteLine("Hello World!"); AddressBook addrbook = new AddressBook(); addrbook.People.Add(new Person() { Name = "abc", Id = 10, Email = "*****@*****.**" }); addrbook.People.Add(new Person() { Name = "abcd", Id = 11, Email = "*****@*****.**" }); byte[] buffs = new byte[1024]; var gstream = new CodedOutputStream(buffs); addrbook.WriteTo(gstream); int i = addrbook.CalculateSize(); Console.WriteLine($"c size:{i},buf:{gstream.Position}"); var istream = new CodedInputStream(buffs, 0, i); AddressBook book2 = new AddressBook(); book2.MergeFrom(istream); Console.WriteLine($"{book2.People[0].Name}"); //book2. //AreaServer area = new AreaServer(); AreaServer.instance.Start(); //Server s = new Server(11240); //s.Start(); /* * * * IntPtr loop = Libuv.CreateLoop(); * * Libuv.uv_loop_init(loop); * * IntPtr timer = Libuv.Allocate(Libuv.uv_handle_type.UV_TIMER); * Libuv.uv_timer_init(loop, timer); * Libuv.uv_timer_start(timer, work_cb, 1000, 1000); * * Libuv.uv_run(loop, Libuv.uv_run_mode.UV_RUN_DEFAULT); */ }