public CustomerUpdateData(CustomerResponse data) { this.ID = data.CustomerID; this.Name = data.Name; this.Website = data.Website; foreach (LocationResponse l in data.Locations) { if (l.IsPrimary) { this.Address = l.Address; this.City = l.City; this.StateProvince = l.StateProvince; this.Country = l.Country; this.ZipPostalCode = l.ZipPostalCode; break; } } this.PrimaryContact = data.getPrimaryContact(); this.Fields = data.Fields; }
public async Task CanCreateRecurringPaymentAndRetrieveIt() { // If: we create a new recurring payment MandateResponse mandate = await this.GetFirstValidMandate(); CustomerResponse customer = await this._customerClient.GetCustomerAsync(mandate.Links.Customer); PaymentRequest paymentRequest = new PaymentRequest() { Amount = new Amount(Currency.EUR, "100.00"), Description = "Description", RedirectUrl = this.DefaultRedirectUrl, SequenceType = SequenceType.First, CustomerId = customer.Id }; // When: We send the payment request to Mollie and attempt to retrieve it PaymentResponse paymentResponse = await this._paymentClient.CreatePaymentAsync(paymentRequest); PaymentResponse result = await this._paymentClient.GetPaymentAsync(paymentResponse.Id); // Then: Make sure the recurringtype parameter is entered Assert.AreEqual(SequenceType.First, result.SequenceType); }
public async Task <bool> UpdateCustomerAsync(CustomerResponse customerViewModel, CancellationToken ct = default) { var customer = await _customerRepository.GetByIdAsync(customerViewModel.CustomerId, ct); if (customer == null) { return(false); } customer.FirstName = customerViewModel.FirstName; customer.LastName = customerViewModel.LastName; customer.Company = customerViewModel.Company; customer.Address = customerViewModel.Address; customer.City = customerViewModel.City; customer.State = customerViewModel.State; customer.Country = customerViewModel.Country; customer.PostalCode = customerViewModel.PostalCode; customer.Phone = customerViewModel.Phone; customer.Fax = customerViewModel.Fax; customer.Email = customerViewModel.Email; customer.SupportRepId = customerViewModel.SupportRepId; return(await _customerRepository.UpdateAsync(customer, ct)); }
public async Task <CustomerResponse> AddCustomerAsync(CustomerResponse newCustomerViewModel, CancellationToken ct = default) { var customer = new Customer { FirstName = newCustomerViewModel.FirstName, LastName = newCustomerViewModel.LastName, Company = newCustomerViewModel.Company, Address = newCustomerViewModel.Address, City = newCustomerViewModel.City, State = newCustomerViewModel.State, Country = newCustomerViewModel.Country, PostalCode = newCustomerViewModel.PostalCode, Phone = newCustomerViewModel.Phone, Fax = newCustomerViewModel.Fax, Email = newCustomerViewModel.Email, SupportRepId = newCustomerViewModel.SupportRepId }; customer = await _customerRepository.AddAsync(customer, ct); newCustomerViewModel.CustomerId = customer.CustomerId; return(newCustomerViewModel); }
public async Task <CustomerResponse> AuthencateUser1(string email) { sw.Start(); CustomerResponse output = null; try { LoggingClass.LogServiceInfo("service called", "AuthencateUser1"); var uri = new Uri(ServiceURL + "AuthenticateUser1/" + email); var response = await client.GetStringAsync(uri).ConfigureAwait(false); output = JsonConvert.DeserializeObject <CustomerResponse>(response); LoggingClass.LogServiceInfo("service response" + email, "AuthencateUser1"); } catch (Exception exe) { LoggingClass.LogError(exe.Message, screenid, exe.StackTrace.ToString()); } sw.Stop(); LoggingClass.LogTime("The total time to start and end the service AuthencateUser1", "The timer ran for " + sw.Elapsed.TotalSeconds); return(output); }
public IActionResult Post(Customers custs) { var inputCustomer = new Customer { full_name = custs.data.attributes.full_name, username = custs.data.attributes.username, birthdate = custs.data.attributes.birthdate, password = custs.data.attributes.password, gender = custs.data.attributes.gender, email = custs.data.attributes.email, phone_number = custs.data.attributes.phone_number }; _context.CustomersAcc.Add(inputCustomer); var time = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds; inputCustomer.created_at = (long)time; inputCustomer.updated_at = (long)time; _context.SaveChanges(); var customer = new CustomerResponse { id = inputCustomer.id, full_name = custs.data.attributes.full_name, username = custs.data.attributes.username, birthdate = custs.data.attributes.birthdate, password = custs.data.attributes.password, gender = custs.data.attributes.gender.ToString(), email = custs.data.attributes.email, phone_number = custs.data.attributes.phone_number, created_at = inputCustomer.created_at, updated_at = inputCustomer.updated_at }; return(Ok(new { message = "success retrieve data", status = true, data = customer })); }
public async Task <CustomerResponse> InsertUpdateGuest(string token) { sw.Start(); CustomerResponse output = null; try { var uri = new Uri(ServiceURL + "InsertUpdateguests/" + token + "/token/1"); var content = JsonConvert.SerializeObject(token); var cont = new StringContent(content, System.Text.Encoding.UTF8, "application/json"); var response = await client.GetStringAsync(uri).ConfigureAwait(false); output = JsonConvert.DeserializeObject <CustomerResponse>(response); CurrentUser.PutGuestId(output.customer.CustomerID.ToString()); } catch (Exception ex) { LoggingClass.LogError(ex.ToString(), screen, ex.StackTrace); } sw.Stop(); LoggingClass.LogServiceInfo("Service " + sw.Elapsed.TotalSeconds, "Guest Service"); //Console.WriteLine("Guest service Time Elapsed"+sw.Elapsed.TotalSeconds); return(output); }
public CustomerResponse GetCustomerData() { var cr = new CustomerResponse { Code = "1797", Name = "testCust" }; cr.Addresses.General = new PostalAddress { Address1 = "testaddress", City = "veenendaal", Country = { Code = "NL", Name = "Nederland" }, ZipCode = "3905GG" }; cr.Bank.Name = "testbank"; cr.Bank.AccountHolder = "1002"; cr.Bank.AccountNumber = "12345"; return(cr); }
public async void Preinfo(string CardNumber) { AndHUD.Shared.Show(this, "Please Wait...", Convert.ToInt32(MaskType.Clear)); try { BtnLogin.Visibility = ViewStates.Gone; BtnResend.Visibility = ViewStates.Gone; try { //CurrentUser. EmailVerification(false); } catch (Exception ex) { LoggingClass.LogError(ex.Message, screenid, ex.StackTrace); } AuthServ = await svc.AuthencateUser("test", CardNumber, CurrentUser.GetDeviceID()); CurrentUser.SaveInternalCustometID(AuthServ.customer.CustomerID.ToString()); LoggingClass.LogInfo("User Tried to login with " + CardNumber, screenid); if (CardNumber != null) { CurrentUser.SaveCardNumber(CardNumber); } if (AuthServ != null) { CurrentUser.SaveUserName(AuthServ.customer.FirstName + AuthServ.customer.LastName, AuthServ.customer.CustomerID.ToString()); CurrentUser.SavePrefered(AuthServ.customer.PreferredStore); if (AuthServ.customer.Email != "" && AuthServ.customer.Email != null) { SendRegistrationToAppServer(CurrentUser.getDeviceToken()); if (AuthServ.ErrorDescription != null || AuthServ.ErrorDescription == "") { TxtScanresult.Text = AuthServ.ErrorDescription; } else { TxtScanresult.Text = " Hi " + AuthServ.customer.FirstName + AuthServ.customer.LastName + ",\nWe are sending a verification email to " + AuthServ.customer.Email + "..To proceed press continue. To change your emailAddress click on Update."; } TxtScanresult.SetTextColor(Android.Graphics.Color.Black); BtnContinue.Visibility = ViewStates.Visible; BtnUpdateEmail.Visibility = ViewStates.Invisible; update.Visibility = ViewStates.Visible; BtnContinue.Click += async delegate { { AndHUD.Shared.Show(this, " Please Wait...", Convert.ToInt32(MaskType.Clear)); AuthServ = await svc.ContinueService(AuthServ); ShowInfo(AuthServ); AndHUD.Shared.Dismiss(); } }; update.Click += delegate { TxtScanresult.Text = ""; BtnContinue.Visibility = ViewStates.Gone; update.Visibility = ViewStates.Gone; txtmail.Visibility = ViewStates.Visible; Txtem.Visibility = ViewStates.Visible; BtnUpdateEmail.Visibility = ViewStates.Visible; }; BtnUpdateEmail.Click += delegate { { BtnUpdateEmail_Click("please enter your new e-mail id."); } }; } else { if (AuthServ.ErrorDescription != null || AuthServ.ErrorDescription == "") { TxtScanresult.Text = AuthServ.ErrorDescription; } else { TxtScanresult.Text = "Hi " + AuthServ.customer.FirstName + AuthServ.customer.LastName + ", \nIt seems we do not have your email address! Please update it so we can send you a verification link that will activate your account."; } TxtScanresult.SetTextColor(Android.Graphics.Color.Red); BtnContinue.Visibility = ViewStates.Gone; BtnUpdateEmail.Visibility = ViewStates.Visible; txtmail.Visibility = ViewStates.Visible; Txtem.Visibility = ViewStates.Visible; BtnUpdateEmail.Click += delegate { BtnUpdateEmail_Click("please enter your new e-mail id."); }; } } else { TxtScanresult.Text = "Sorry. Your Card number is not matching our records.\n Please re-scan Or Try app as Guest Log In."; BtnResend.Visibility = ViewStates.Invisible; BtnLogin.Visibility = ViewStates.Invisible; TxtScanresult.SetTextColor(Android.Graphics.Color.Red); AndHUD.Shared.Dismiss(); } AndHUD.Shared.Dismiss(); } catch (Exception exe) { } }
public async void ShowInfo(CustomerResponse cr, Boolean Continue) { BTProgressHUD.Show("Please wait..."); CGSize sTemp = new CGSize(View.Frame.Width, 100); try { if (CardNumber != null) { CurrentUser.PutCardNumber(CardNumber); } if (cr != null) { if (cr.customer.Email != "" && cr.customer.Email != null) { if ((cr.ErrorDescription == null && cr.ErrorDescription == "") || cr.customer.CustomerID != 0) { lblInfo.Text = "Hi " + cr.customer.FirstName + " " + cr.customer.LastName + ",\nWe have sent you a verification link to " + cr.customer.Email + ". Please click on the activation link to activate the account."; } else { lblInfo.Text = cr.ErrorDescription; } lblInfo.LineBreakMode = UILineBreakMode.WordWrap; lblInfo.Lines = 0; sTemp = lblInfo.SizeThatFits(sTemp); //Console.WriteLine("Show info "+y); lblInfo.Frame = new CGRect(10, y, View.Frame.Width - 10, sTemp.Height); lblInfo.TextAlignment = UITextAlignment.Left; lblInfo.TextColor = UIColor.Black; CurrentUser.StoreId(cr.customer.CustomerID.ToString()); try { BtnTest1.Hidden = true; BtnTest2.Hidden = true; btnLogin.Hidden = false; btnResend.Hidden = false; } catch (Exception exe) { //Console.WriteLine(exe.Message); } start = 0; start = y + lblInfo.Frame.Height + 10; btnLogin.Frame = new CGRect(180, start, 120, 30); btnResend.Frame = new CGRect(30, start, 120, 30); btnResend.TouchUpInside += async (send, eve) => { BTProgressHUD.Show("Sending verification email to " + cr.customer.Email); if (CardNumber != null) { await svc.ResendEMail(CardNumber); } else { await svc.ResendEMail(CurrentUser.GetCardNumber()); } BTProgressHUD.ShowSuccessWithStatus("Sent"); }; btnLogin.TouchUpInside += (sen, ev) => { try { BTProgressHUD.Show("Checking email verification"); EmailVerification(false); } catch (Exception ex) { //LoggingClass.LogError(ex.Message, screenid, ex.StackTrace.ToString()); } }; BTProgressHUD.Dismiss(); } else { lblInfo.Text = cr.ErrorDescription; //lblInfo.TextAlignment = UITextAlignment.Center; lblInfo.TextColor = UIColor.Red; try { btnLogin.Hidden = true; btnResend.Hidden = true; } catch (Exception exe) { //LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } sTemp = lblInfo.SizeThatFits(sTemp); lblInfo.Frame = new CGRect(0, start, View.Frame.Width - 10, sTemp.Height); BTProgressHUD.Dismiss(); } } else { lblInfo.Text = "Sorry. Your Card number is not matching our records.\n Please re-scan Or Try app as Guest Log In."; lblInfo.TextColor = UIColor.Red; lblInfo.TextAlignment = UITextAlignment.Center; sTemp = lblInfo.SizeThatFits(sTemp); lblInfo.Frame = new CGRect(0, start, View.Frame.Width - 10, sTemp.Height); try { if (btnLogin != null || btnResend != null) { btnLogin.SetTitleColor(UIColor.White, UIControlState.Normal); btnResend.SetTitleColor(UIColor.White, UIControlState.Normal); btnLogin.BackgroundColor = UIColor.White; btnResend.BackgroundColor = UIColor.White; } } catch (Exception ex) { //LoggingClass.LogError(ex.Message, screenid, ex.StackTrace); } BTProgressHUD.Dismiss(); } BTProgressHUD.Dismiss(); } catch (Exception exe) { lblInfo.Text = "Something went wrong.We're on it."; lblInfo.TextColor = UIColor.Red; sTemp = lblInfo.SizeThatFits(sTemp); lblInfo.Frame = new CGRect(0, start, View.Frame.Width - 10, sTemp.Height); LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } BTProgressHUD.Dismiss(); }
public ResultResponse <CustomerResponse> getOrderByCustomerId(BDHomeFoodContext _context, int costumerid) { try { ResultResponse <CustomerResponse> response = new ResultResponse <CustomerResponse>(); var firstresult = _context.Customer.Any(c => c.CustomerId == costumerid); if (firstresult) { var result = _context.Customer.FirstOrDefault(c => c.CustomerId == costumerid); CustomerResponse customerResponse = new CustomerResponse { CustomerId = result.CustomerId, Names = result.Names, LastNames = result.LastNames, DocumentoIdentity = result.DocumentoIdentity, Email = result.Email, Phone = result.Phone, Birthdate = result.Birthdate, Username = result.Username, State = result.State, CreateDate = result.CreateDate, UpdateDate = result.UpdateDate, Order = _context.Order.Where(x => x.CustomerId == result.CustomerId).Select( x => new OrderResponse { OrderId = x.OrderId, TotalCost = x.TotalCost, TotalCostOrder = x.TotalCostOrder, TotalCostDriver = x.TotalCostDriver, PaymentDate = x.PaymentDate, State = x.State, CollaboratorDriverId = x.CollaboratorDriverId, Collected = x.Collected, OnMyWay = x.OnMyWay, Deliverred = x.Deliverred, Received = x.Received, PayTypeId = x.PayTypeId, CustomerCodePromotionId = x.CustomerCodePromotionId, CustomerId = x.CustomerId, Collaborator = _context.Collaborator.Where(y => y.CollaboratorId == x.CollaboratorId).Select( y => new CollaboratorResponse { CollaboratorId = y.CollaboratorId, Names = y.Names, LastNames = y.LastNames, DocumentIdentity = y.DocumentIdentity, Email = y.Email, Phone = y.Phone, BirthDate = y.BirthDate, Username = y.Username, Latitude = y.Latitude, Longitude = y.Longitude, UrlPhoto = y.UrlPhoto, State = y.State, StateActivity = y.StateActivity, CollaboratorType = _context.CollaboratorType.Where(z => z.CollaboratorTypeId == y.CollaboratorTypeId).Select( z => new CollaboratorTypeResponse { CollaboratorTypeId = z.CollaboratorTypeId, Name = z.Name, Description = z.Description }).ToList() }).ToList() }).ToList() }; response.Data = customerResponse; response.Error = false; response.Message = "Datos encontrados"; } else { response.Data = null; response.Error = true; response.Message = "No se encontraron datos"; } return(response); } catch (Exception ex) { throw new Exception(ex.Message); } }
static async Task RunAsync() { string username = "******"; string password = "******"; string authKey = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password)); // Update port # in the following line. //client.BaseAddress = new Uri("http://*****:*****@test.com", "Goran Engstrom"); //var respCustomer = await CreateCustomerAsync(nyCustomer); //Console.WriteLine(respCustomer); //Get Billogram BillogramResponse billogramResp = new BillogramResponse(); myurl = "api/v2/billogram/"; billogramResp = await GetBillogramAsync(myurl + "wdu4gsU"); ShowBillogram(billogramResp); Console.WriteLine($"GetBillogram is done!!"); //POST Billogram BillogramCreate billogramCreate = new BillogramCreate(); //billogram.Invoice_date = DateTime.Now; //billogram.Due_date = DateTime.Now.AddDays(30); CustomerMini smallCustomer = new CustomerMini(); smallCustomer.customer_no = 12370; billogramCreate.customer = smallCustomer; // Skapa ett item ItemMini item = new ItemMini(); item.item_no = "4"; // Deltagaravg Rätt focus SME item.title = "Produkt försäljning"; item.count = 1; item.vat = 20; item.price = 125; ItemMini item2 = new ItemMini(); item2.title = "Detta kan vara en textrad"; ItemMini item3 = new ItemMini(); item3.title = "Administattionskostnad"; item3.count = 1; item3.price = 45; item3.vat = 12; ItemMini[] items = new ItemMini[3] { item, item2, item3 }; billogramCreate.items = items; //Skapa ett Info Info info = new Info(); info.message = "Skapat via ConsoleAPI_Test"; billogramCreate.info = info; On_success on_Success = new On_success(); on_Success.command = "send"; on_Success.method = "Email"; billogramCreate.on_success = on_Success; // Create Billogram billogramResp = await CreateBillogramAsync(billogramCreate); if (billogramResp != null) { ShowBillogram(billogramResp); } //----------------------------------------------- //// Create a new product //Product product = new Product //{ // Name = "Gizmo", // Price = 100, // Category = "Widgets" //}; //var url = await CreateProductAsync(product); //Console.WriteLine($"Created at {url}"); //// Get the product //product = await GetProductAsync(url.PathAndQuery); //ShowProduct(product); //// Update the product //Console.WriteLine("Updating price..."); //product.Price = 80; //await UpdateProductAsync(product); //// Get the updated product //product = await GetProductAsync(url.PathAndQuery); //ShowProduct(product); //// Delete the product //var statusCode = await DeleteProductAsync(product.Id); //Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})"); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); }
public override void ViewDidLoad() { try { //this.NavCtrl.NavigationBar.BarStyle = UIBarStyle.BlackTranslucent; //UINavigationBar.Appearance.BackgroundColor = UIColor.Clear; //NavCtrl.NavigationBar.BackgroundColor = UIColor.Clear; nfloat ScreenHeight = UIScreen.MainScreen.Bounds.Height; ScreenHeight = (ScreenHeight - 100) / 3; Boolean internetStatus = Reachability.IsHostReachable("https://www.google.com"); if (internetStatus == false) { UIAlertView alert = new UIAlertView() { Title = "Sorry", Message = "Not connected to internet.Please connect and retry." }; alert.AddButton("OK"); alert.Show(); } BTProgressHUD.Dismiss(); UIImageView backgroud = new UIImageView(); backgroud.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, ScreenHeight - 20); backgroud.Image = new UIImage("proback.png"); backgroud.UserInteractionEnabled = false; btnBack.UserInteractionEnabled = false; //imgProfile.Frame = new CGRect((View.Frame.Width / 2) - 72, 3 * (backgroud.Frame.Height / 3), 144, 152); //UITapGestureRecognizer singleTap = new UITapGestureRecognizer(); //singleTap.CancelsTouchesInView = false; //Scroll.AddGestureRecognizer(singleTap); //DismissKeyboardOnBackgroundTap(); NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyBoardDownNotification); NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyBoardUpNotification); LoggingClass.LogInfo("Entered into Profile View", screenid); pickerDataModel = new StatePickerDataModel(); pickerDataModel.Items.Add("---Select your state---"); pickerDataModel.Items.Add("AL"); pickerDataModel.Items.Add("AK"); pickerDataModel.Items.Add("AZ"); pickerDataModel.Items.Add("AR"); pickerDataModel.Items.Add("CA"); pickerDataModel.Items.Add("CO"); pickerDataModel.Items.Add("CT"); pickerDataModel.Items.Add("DE"); pickerDataModel.Items.Add("FL"); pickerDataModel.Items.Add("GA"); pickerDataModel.Items.Add("HI"); pickerDataModel.Items.Add("ID"); pickerDataModel.Items.Add("IL"); pickerDataModel.Items.Add("IN"); pickerDataModel.Items.Add("IA"); pickerDataModel.Items.Add("KS"); pickerDataModel.Items.Add("KY"); pickerDataModel.Items.Add("LA"); pickerDataModel.Items.Add("ME"); pickerDataModel.Items.Add("MD"); pickerDataModel.Items.Add("MA"); pickerDataModel.Items.Add("MI"); pickerDataModel.Items.Add("MN"); pickerDataModel.Items.Add("MS"); pickerDataModel.Items.Add("MO"); pickerDataModel.Items.Add("MT"); pickerDataModel.Items.Add("NE"); pickerDataModel.Items.Add("NV"); pickerDataModel.Items.Add("NH"); pickerDataModel.Items.Add("NJ"); pickerDataModel.Items.Add("NM"); pickerDataModel.Items.Add("NY"); pickerDataModel.Items.Add("NC"); pickerDataModel.Items.Add("ND"); pickerDataModel.Items.Add("OH"); pickerDataModel.Items.Add("OK"); pickerDataModel.Items.Add("OR"); pickerDataModel.Items.Add("PA"); pickerDataModel.Items.Add("RI"); pickerDataModel.Items.Add("SC"); pickerDataModel.Items.Add("SD"); pickerDataModel.Items.Add("TN"); pickerDataModel.Items.Add("TX"); pickerDataModel.Items.Add("UT"); pickerDataModel.Items.Add("VT"); pickerDataModel.Items.Add("VA"); pickerDataModel.Items.Add("WA"); pickerDataModel.Items.Add("WV"); pickerDataModel.Items.Add("WI"); pickerDataModel.Items.Add("WY"); statePicker.Model = pickerDataModel; //statePicker.BackgroundColor = UIColor.Red; //statePicker = new UIPickerView(new CGRect(01,01,UIScreen.MainScreen.Bounds.Width,UIScreen.MainScreen.Bounds.Height)); // //UIScreen.MainScreen.Bounds.X-UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height, UIScreen.MainScreen.Bounds.Width, 180)); StoreDataModel = new StorePickerDataModel(); StoreDataModel.Items.Add("---Select preffered store---"); StoreDataModel.Items.Add("Wall"); StoreDataModel.Items.Add("Pt. Pleasant Beach"); StoreDataModel.Items.Add("All"); storePicker.Model = StoreDataModel; //statePicker.Select(5, 0, true); //LoggingClass.UploadErrorLogs(); if (CurrentUser.RetreiveUserId() == 0) { DownloadAsync(); UIAlertView alert = new UIAlertView() { Title = "This feature is allowed only for VIP Card holders", //Message = "Coming Soon..." }; alert.AddButton("OK"); alert.AddButton("Log in"); alert.AddButton("Know more"); alert.Clicked += (senderalert, buttonArgs) => { if (buttonArgs.ButtonIndex == 1) { CurrentUser.Clear(); LoginViewController yourController = new LoginViewController(); yourController.nav = NavCtrl; yourController.RootTabs = CurrentUser.RootTabs; NavCtrl.PushViewController(yourController, false); //NavCtrl.PopViewController(false); //NavCtrl.PopViewController(false); } }; alert.Clicked += (senderalert, buttonArgs) => { if (buttonArgs.ButtonIndex == 2) { UIApplication.SharedApplication.OpenUrl(new NSUrl("https://hangoutz.azurewebsites.net/index.html")); } }; alert.Show(); btnUpdate.UserInteractionEnabled = false; txtLastName.UserInteractionEnabled = false; txtPhone.UserInteractionEnabled = false; txtAddress.UserInteractionEnabled = false; txtZipCode.UserInteractionEnabled = false; txtEmail.UserInteractionEnabled = false; statePicker.UserInteractionEnabled = false; storePicker.UserInteractionEnabled = false; imgProfile.UserInteractionEnabled = false; btnPicEdit.UserInteractionEnabled = false; } else { DownloadAsync(); cRes = svc.GetCustomerDetails(CurrentUser.RetreiveUserId()).Result; //txtFirstName.Text = cRes.customer.FirstName; name = cRes.customer.FirstName + " " + cRes.customer.LastName; name = name.Trim(); txtLastName.Text = name; //cRes.customer.FirstName+" "+cRes.customer.LastName; //txtCity.Text = cRes.customer.City; txtEmail.Text = cRes.customer.Email; if (cRes.customer.PhoneNumber.Length != 10) { //cRes.customer.PhoneNumber txtPhone.Text = cRes.customer.PhoneNumber; } txtCardnumber.Text = cRes.customer.CardNumber; txtExpirydate.Text = cRes.customer.ExpireDate.ToString("MM-dd-yyyy"); txtZipCode.Text = cRes.customer.Zip; string state = cRes.customer.State; if (pickerDataModel.Items.Contains(state)) { int i = pickerDataModel.Items.FindIndex(x => x == state); statePicker.Select(i, 0, false); } int prefStore = cRes.customer.PreferredStore; storePicker.Select(prefStore, 0, false); txtAddress.Text = cRes.customer.Address1 + cRes.customer.Address2 + cRes.customer.City; //txtFirstName.ShouldReturn += (TextField) => // { // ((UITextField)TextField).ResignFirstResponder(); // return true; // }; txtLastName.ShouldReturn += (TextField) => { ((UITextField)TextField).ResignFirstResponder(); return(true); }; txtEmail.ShouldReturn += (TextField) => { ((UITextField)TextField).ResignFirstResponder(); return(true); }; txtPhone.ShouldReturn += (TextField) => { ((UITextField)TextField).ResignFirstResponder(); return(true); }; txtAddress.ShouldReturn += (TextField) => { ((UITextField)TextField).ResignFirstResponder(); return(true); }; txtZipCode.ShouldReturn += (TextField) => { ((UITextField)TextField).ResignFirstResponder(); return(true); }; txtZipCode.AccessibilityScroll(UIAccessibilityScrollDirection.Up); btnUpdate.SetTitleColor(UIColor.Purple, UIControlState.Normal); //btnEdit.SetTitleColor(UIColor.Purple, UIControlState.Normal); //btnUpdate.TouchDown += (sender, e) => //{ // BTProgressHUD.Show("Updating profile..."); //show spinner + text //}; //btnUpdate.TouchUpInside += async (sender, e) => //{ // if (txtPhone.Text.Length > 10 || txtPhone.Text.Length < 10) // { // BTProgressHUD.ShowErrorWithStatus("Phone number is invalid"); // } // else if ((txtEmail.Text.Contains("@")) == false || (txtEmail.Text.Contains(".")) == false) // { // BTProgressHUD.ShowErrorWithStatus("Email is invalid"); // } // else if ((txtZipCode.Text.Length!=5)) // { // BTProgressHUD.ShowErrorWithStatus("Zipcode is invalid"); // } // else // { // LoggingClass.LogInfo("Update button into Profile View", screenid); // Customer cust = new Customer(); // cust.CustomerID = CurrentUser.RetreiveUserId(); // cust.Address1 = txtAddress.Text; // name = txtLastName.Text; // name = name.Trim(); // try // { // string[] str1 = name.Split(' '); // if (str1.Length == 2) // { // cust.FirstName = str1[0]; // cust.LastName = str1[1]; // } // else // { // cust.FirstName = str1[0] + str1[1]; // cust.LastName = str1[2]; // } // } // catch (Exception exe) // { // LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); // } // cust.Email = txtEmail.Text; // cust.PhoneNumber = txtPhone.Text; // cust.State = pickerDataModel.SelectedItem; // cust.Zip = txtZipCode.Text; // cust.PreferredStore = StoreDataModel.SelectedItem; // CurrentUser.PutStore(StoreDataModel.SelectedItem); // await svc.UpdateCustomer(cust); // BTProgressHUD.ShowSuccessWithStatus("Profile Updated."); // //try // //{ // // NavCtrl.PopViewController(true); // // //NavCtrl.PushViewController(new FirstViewController(handle), false); // //} // //catch (Exception exe) // //{ // // LoggingClass.LogError(exe.Message, screenid, exe.StackTrace.ToString()); // //} // } //}; btnUpdate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; UIImage imgbtnCam = UIImage.FromFile("cam.png"); imgbtnCam = ResizeImage(imgbtnCam, 25, 25); btnPicEdit.SetImage(imgbtnCam, UIControlState.Normal); btnBack.UserInteractionEnabled = false; //btnPicEdit.SetTitle("Edit", UIControlState.Normal); //try //{ btnPicEdit.TouchUpInside += (sender, e) => { try { UIAlertView alert = new UIAlertView() { Title = "Please choose an option to upload profile picture", //Message = "Coming Soon..." }; alert.AddButton("Cancel"); alert.AddButton("Camera"); alert.AddButton("Gallery"); alert.Clicked += (senderalert, buttonArgs) => { if (buttonArgs.ButtonIndex == 1) { try { IsCameraAuthorized(); TweetStation.Camera.TakePicture(this, (obj) => { var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage; var meta = obj.ValueForKey(new NSString("UIImagePickerControllerMediaMetadata")) as NSDictionary; UploadProfilePic(photo); //ALAssetsLibrary library = new ALAssetsLibrary(); //library.WriteImageToSavedPhotosAlbum(photo.CGImage, meta, (assetUrl, error) => //{ // UploadProfilePic(assetUrl.ToString()); // Console.WriteLine("assetUrl:" + assetUrl); //}); //var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); }); } catch (Exception exe) { LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } } }; alert.Clicked += (senderalert, buttonArgs) => { if (buttonArgs.ButtonIndex == 2) { imagePicker = new UIImagePickerController(); imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary); imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia; imagePicker.Canceled += Handle_Canceled; NavCtrl.PresentModalViewController(imagePicker, true); } }; alert.Show(); //imagePicker = new UIImagePickerController(); //imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; //imagePicker.MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary); //imagePicker.FinishedPickingMedia += Handle_FinishedPickingMedia; //imagePicker.Canceled += Handle_Canceled; //NavCtrl.PresentModalViewController(imagePicker, true); } catch (Exception exe) { LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } }; } //imgEmail.Image = new UIImage("mail.png"); //imgAddr.Image = new UIImage("add.png"); //imgPhone.Image = new UIImage("phone1.png"); Scroll = new UIScrollView { Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height), ContentSize = new CGSize(View.Frame.Width, View.Frame.Height), BackgroundColor = UIColor.White, AutoresizingMask = UIViewAutoresizing.FlexibleHeight, }; UIToolbar toolbar = new UIToolbar(new RectangleF(0.0f, 0.0f, Convert.ToSingle(this.View.Frame.Size.Width), 44.0f)); toolbar.TintColor = UIColor.White; toolbar.BarStyle = UIBarStyle.Default; toolbar.Translucent = true; UITapGestureRecognizer taps = new UITapGestureRecognizer(); taps.CancelsTouchesInView = false; taps.AddTarget(() => Scroll.EndEditing(true)); Scroll.AddGestureRecognizer(taps); UIImage imgbtnUpdate = UIImage.FromFile("tick.png"); imgbtnUpdate = ResizeImage(imgbtnUpdate, 25, 25); //var topBtn = new UIBarButtonItem(imgbtnUpdate, UIBarButtonItemStyle.Plain, async delegate //{ btnUpdate.TouchUpInside += async delegate { //if (txtPhone.Text.Length!=12) //{ // BTProgressHUD.ShowErrorWithStatus("Phone number is invalid"); //} if ((txtEmail.Text.Contains("@")) == false || (txtEmail.Text.Contains(".")) == false) { BTProgressHUD.ShowErrorWithStatus("Email is invalid"); } else if ((txtZipCode.Text.Length != 5)) { BTProgressHUD.ShowErrorWithStatus("Zipcode is invalid"); } else { BTProgressHUD.Show("Updating Profile..."); LoggingClass.LogInfo("Update button into Profile View", screenid); Customer cust = new Customer(); cust.CustomerID = CurrentUser.RetreiveUserId(); cust.Address1 = txtAddress.Text; //cust.FirstName = txtFirstName.Text; name = txtLastName.Text; name = name.Trim(); try { string[] str1 = name.Split(' '); if (str1.Length == 2) { cust.FirstName = str1[0]; cust.LastName = str1[1]; } else { cust.FirstName = str1[0] + str1[1]; cust.LastName = str1[2]; } } catch (Exception exe) { LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } cust.Email = txtEmail.Text; cust.PhoneNumber = txtPhone.Text; if (pickerDataModel.SelectedItem == "---Select your state---") { if (pickerDataModel.Items.Contains(cRes.customer.State)) { int i = pickerDataModel.Items.FindIndex(x => x == cRes.customer.State); statePicker.Select(i, 0, false); } cust.State = cRes.customer.State; } else { cust.State = pickerDataModel.SelectedItem; } cust.Zip = txtZipCode.Text; if (StoreDataModel.SelectedItem == 0) { cust.PreferredStore = cRes.customer.PreferredStore; storePicker.Select(cRes.customer.PreferredStore, 0, false); CurrentUser.PutStore(cust.PreferredStore); } else { cust.PreferredStore = StoreDataModel.SelectedItem; CurrentUser.PutStore(cust.PreferredStore); } await svc.UpdateCustomer(cust); BTProgressHUD.ShowSuccessWithStatus("Profile Updated."); } }; imgProfile.ClipsToBounds = true; imgProfile.BackgroundColor = UIColor.White; //NavigationController.NavigationBar.TopItem.SetRightBarButtonItem(topBtn, true); btnBack.BackgroundColor = UIColor.FromRGB(93, 93, 93); Scroll.AddSubview(backgroud); Scroll.AddSubview(btnBack); //Scroll.AddSubview(imgAddr); //Scroll.AddSubview(imgPhone); //Scroll.AddSubview(imgEmail); Scroll.AddSubview(txtEmail); Scroll.AddSubview(statePicker); Scroll.AddSubview(storePicker); Scroll.AddSubview(txtPhone); Scroll.AddSubview(txtZipCode); //Scroll.AddSubview(txtFirstName); Scroll.AddSubview(txtLastName); Scroll.AddSubview(txtAddress); Scroll.AddSubview(imgProfile); Scroll.AddSubview(btnPicEdit); Scroll.AddSubview(lblEmail); Scroll.AddSubview(lblState); Scroll.AddSubview(lblMobile); Scroll.AddSubview(lblAddress); Scroll.AddSubview(lblZipcode); //Scroll.AddSubview(lblFirstname); Scroll.AddSubview(lblLastname); Scroll.AddSubview(btnUpdate); Scroll.AddSubview(lblStorePi); Scroll.AddSubview(lblExpiryDate); Scroll.AddSubview(txtExpirydate); Scroll.AddSubview(lblcardnumber); Scroll.AddSubview(txtCardnumber); //View.AddSubview(Scroll); for (int i = 0; i < Scroll.Subviews.Length; i++) { nfloat n = Scroll.Subviews[i].Frame.Size.Height; h = h + n; } //Console.WriteLine(h); Scroll.ContentSize = new CGSize(UIScreen.MainScreen.Bounds.Width, h - 200); View = (Scroll); } catch (Exception ex) { LoggingClass.LogError(ex.ToString(), screenid, ex.StackTrace); } }
public override async Task <CustomerResponse> GetCustomerUnary(CustomerRequest request, ServerCallContext context) { CustomerResponse customerResponce = customerList.FirstOrDefault(customer => customer.Id == request.CustomerId); return(await Task.FromResult(customerResponce)); }
public void TestCustomerAdd() { Client client = getApiClient(); CustomerResponse newCustomerData = new CustomerResponse(); newCustomerData.Name = "Tester"; CustomerResponse response = client.CustomerAdd(newCustomerData); newCustomerData.Added = response.Added; newCustomerData.Modified = response.Modified; newCustomerData.CustomerID = response.CustomerID; newCustomerData.Fields = response.Fields; Assert.IsTrue(newCustomerData.Equals(response)); }
public void SincronizaContatos() { var customers = _customerService.GetAllCustomers(); var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext); CustomerResponse[] GetCustomerResponse = null; CustomerResponse CustomerResponse = null; var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope); var number = string.Empty; var complement = string.Empty; var cpfCnpj = string.Empty; foreach (var item in customers) { var customer = new CustomerMessage(); new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null, out number, out complement, out cpfCnpj); customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null; customer.companyName = item.BillingAddress != null ? item.BillingAddress.Company : null; customer.email = item.Email; customer.personType = "NATURAL"; customer.mobilePhone = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null; customer.address.city.name = item.BillingAddress != null ? item.BillingAddress.City : null; customer.address.state.name = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null; // customer.address.zipCode = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null; customer.address.street = item.BillingAddress != null ? item.BillingAddress.Address1 : null; customer.address.complement = complement; customer.address.number = number; customer.document = cpfCnpj; try { var filtro = "?search=" + cpfCnpj; using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox)) GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult(); //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco if (GetCustomerResponse != null) { var customerPayPalPlus = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]); //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul if (customerPayPalPlus == null) { using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); if (CustomerResponse != null) { var customerContaAzul = new CustomerContaAzul(); customerContaAzul.ContaAzulId = CustomerResponse.id; customerContaAzul.CustomerId = item.Id; customerContaAzul.DataCriacao = DateTime.Now; _contaAzulCustomerService.InsertCustomer(customerContaAzul); } } else { //se ele já existe na tabela, só faz o update no conta azul using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerPayPalPlus.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); } } else {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); if (CustomerResponse != null) { var customerContaAzul = new CustomerContaAzul(); customerContaAzul.ContaAzulId = CustomerResponse.id; customerContaAzul.CustomerId = item.Id; customerContaAzul.DataCriacao = DateTime.Now; _contaAzulCustomerService.InsertCustomer(customerContaAzul); } } } catch (Exception ex) { try { var retorno = JsonConvert.DeserializeObject <MiscExecutitionResponse>(ex.Message, ConverterPaymentExecution.Settings); if (retorno.StatusCode == "401") { RefreshToken(); _logger.Error("Token expirado " + ContaAzulMiscSettings.access_token, ex); } else { _logger.Error(ex.Message, ex); } } catch (Exception erro) { _logger.Error(erro.Message, erro); throw; } // ErrorNotification("O Customer com id " + item.Id + " não foi encontrado" ); } } }
public JsonResult CreateBooking(string sendInfo) { string userId = User.Identity.GetUserId(); //string date_from; //string date_to; string car_id; string latitude; string longitude; double distance = 0.0; double price = 0.0; List <LocationModel> location = new List <LocationModel>(); String[] spearator = { "," }; String[] result = sendInfo.Split(spearator, StringSplitOptions.RemoveEmptyEntries); foreach (String s in result) { Console.WriteLine(result); } DateTime date_from = Convert.ToDateTime(result[0].Trim('\t', '[', '"')); DateTime date_to = Convert.ToDateTime(result[1].Trim('\t', '[', '"')); var date_from_converted = date_from.ToString("yyyy-MM-dd"); var date_to_converted = date_to.ToString("yyyy-MM-dd"); DateTime date_from_date = Convert.ToDateTime(date_from_converted); DateTime date_to_date = Convert.ToDateTime(date_to_converted); car_id = result[2].Trim('\t', '[', '"'); var abc = result[3].Trim('\t', '[', '"'); distance = Convert.ToDouble(abc); var vehicle_id = Int32.Parse(car_id); price = distance * 3; try { using (var context = new Entities3()) { // this SQL command is executed to insert the booking into the database context.Database.ExecuteSqlCommand("insert into " + "[dbo].[CustomerBooking]([userId],[vehicle_id]," + "[isAccepted],[to_date],[from_date],[pickup_location],[dropoff_location],[distance],[price]) " + "values('" + userId + "', '" + car_id + "', 'false', '" + date_to_converted + "'," + "'" + date_from_converted + "','location1','location2', '" + distance + "', '" + price + "')"); var lastId = (from c in context.CustomerBookings where c.userId == userId && c.vehicle_id == vehicle_id select c.customer_booking_id).ToArray(); for (int i = 4; i <= result.Length - 2; i = i + 2) { latitude = result[i].Trim('[', ']'); int j = i; longitude = result[j + 1].Trim('[', ']'); context.Database.ExecuteSqlCommand("insert into " + "[dbo].[CustomerBookingLocation](customer_booking_id,latitude,longitude)" + "values('" + lastId[0] + "', '" + latitude + "', '" + longitude + "')"); } } } catch (Exception e) { return(Json("error", JsonRequestBehavior.AllowGet)); } CustomerResponse cs = new CustomerResponse(); cs.response = "success"; cs.distance = distance; cs.price = price; cs.message = "Thank you for using our services. Our staff will be in contact with you soon."; JavaScriptSerializer js = new JavaScriptSerializer(); var json = js.Serialize(cs); return(Json(json, JsonRequestBehavior.AllowGet)); }
public async Task <CustomerResponse> GetAsync(string filters, string sorts, int page, int pageSize, string fields) { try { DotNetCoreSieveModel sieveModel = new DotNetCoreSieveModel { Filters = filters, Sorts = sorts, Fields = fields }; List <string> filterStrings = new List <string>(), sortStrings = new List <string>(); string filtering = string.Empty, sorting = string.Empty; if (sieveModel.GetFiltersParsed() != null) { foreach (var filter in sieveModel.GetFiltersParsed()) { filterStrings.Add(string.Format("{0}{1}{2}{3}", filter.Names[0], filter.Operator == "==" ? filter.Operator + "\"" : filter.Operator, filter.Value, filter.Operator == "==" ? "\"" : "")); } filtering = String.Join(" && ", filterStrings.ToArray()); } if (sieveModel.GetSortsParsed() != null) { foreach (var sort in sieveModel.GetSortsParsed()) { sortStrings.Add(string.Format("{0} {1}", sort.Name.Replace("-", ""), sort.Descending ? "DESC" : "ASC")); } } else { sortStrings.Add("id ASC"); } sorting = String.Join(", ", sortStrings.ToArray()); using (IDbConnection conn = _connection) { DynamicParameters parameters = new DynamicParameters(); parameters.Add("@filters", filtering); parameters.Add("@sorts", sorting); parameters.Add("@page", page); parameters.Add("@pageSize", pageSize); parameters.Add("@fields", fields); conn.Open(); var reader = await conn.QueryMultipleAsync("CustomersGet", parameters, commandType : CommandType.StoredProcedure); int totalRows = (await reader.ReadAsync <int>()).FirstOrDefault(); var result = (await reader.ReadAsync <Customer>()).ToList(); if (result.Count == 0) { throw new DotNetCoreRefDapperException(); } var response = new CustomerResponse() { Page = page, PageSize = pageSize, TotalItems = totalRows, Entities = result }; conn.Close(); return(await Task.Run(() => response)); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Sets the customers. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> public CustomerResponse SetCustomers(CustomerRequest request) { var response = new CustomerResponse(); var customerEntity = request.Customer; if (request.Action != PersistType.Delete) { if (!customerEntity.Validate()) { foreach (string error in customerEntity.ValidationErrors) { response.Message += error + Environment.NewLine; } response.Acknowledge = AcknowledgeType.Failure; return(response); } } try { if (request.Action == PersistType.Delete) { var customerForDelete = CustomerDao.GetCustomerById(request.CustomerId); response.Message = CustomerDao.DeleteCustomer(customerForDelete); } else { var customer = CustomerDao.GetCustomerByCode(customerEntity.CustomerCode); if (request.Action == PersistType.Insert) { if (customer != null) { response.Acknowledge = AcknowledgeType.Failure; response.Message = @"Mã khách hàng " + customer.CustomerCode + @" đã tồn tại !"; return(response); } customerEntity.CustomerId = CustomerDao.InsertCustomer(customerEntity); if (customerEntity.CustomerId != 0) { AutoNumberListDao.UpdateIncreateAutoNumberListByValue("Customer"); } response.Message = null; } if (request.Action == PersistType.Update) { if (customer != null) { if (customer.CustomerId != customerEntity.CustomerId) { response.Acknowledge = AcknowledgeType.Failure; response.Message = @"Mã khách hàng " + customer.CustomerCode + @" đã tồn tại !"; return(response); } } response.Message = CustomerDao.UpdateCustomer(customerEntity); } } } catch (Exception ex) { response.Acknowledge = AcknowledgeType.Failure; response.Message = ex.Message; return(response); } response.CustomerId = customerEntity != null ? customerEntity.CustomerId : 0; response.Acknowledge = response.Message != null ? AcknowledgeType.Failure : AcknowledgeType.Success; return(response); }
public OrderResponse(IOrderDto orderDto) { OrderUid = orderDto.OrderUid; Customer = new CustomerResponse(orderDto.Customer); Positions = orderDto.Positions.Select(_ => new OrderPositionResponse(_)).ToList(); }
public void Execute() { _contaAzulService.RefreshToken(); var customers = _customerService.GetAllCustomers(); // var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext); CustomerResponse[] GetCustomerResponse = null; CustomerResponse CustomerResponse = null; var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>(); var number = string.Empty; var complement = string.Empty; var cpfCnpj = string.Empty; foreach (var item in customers) { var customer = new CustomerMessage(); new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null, out number, out complement, out cpfCnpj); customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null; customer.companyName = item.BillingAddress != null ? item.BillingAddress.Company : null; customer.email = item.Email; customer.personType = "NATURAL"; customer.stateRegistrationType = "NO_CONTRIBUTOR"; customer.mobilePhone = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null; customer.address.city.name = item.BillingAddress != null ? item.BillingAddress.City : null; customer.address.state.name = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null; customer.address.zipCode = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null; customer.address.street = item.BillingAddress != null ? item.BillingAddress.Address1 : null; customer.address.complement = complement; customer.address.number = number; customer.document = cpfCnpj == "" ? null : cpfCnpj; try { var filtro = "?search="; if (cpfCnpj == string.Empty) { filtro = filtro + item.Email; } else { filtro = filtro + cpfCnpj; } using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox)) GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult(); //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco if (GetCustomerResponse.Count() > 0) { var customerTable = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]); //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul if (customerTable == null) { var customerContaAzul = new CustomerContaAzul(); customerContaAzul.ContaAzulId = GetCustomerResponse[0].id; customerContaAzul.CustomerId = item.Id; customerContaAzul.DataCriacao = DateTime.Now; _contaAzulCustomerService.InsertCustomer(customerContaAzul); customer.id = customerTable.ContaAzulId.ToString(); customer.address.city.name = null; var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]); var data2 = JsonConvert.SerializeObject(customer); // var data = data2.Equals(data1); if (!data1.Equals(data2)) { //se ele já existe na tabela, só faz o update no conta azul using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); } } else { customer.id = customerTable.ContaAzulId.ToString(); customer.address.city.name = null; var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]); var data2 = JsonConvert.SerializeObject(customer); var data = data2.Equals(data1); if (!data1.Equals(data2)) { //se ele já existe na tabela, só faz o update no conta azul using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerTable.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); } } } else {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados var data2 = JsonConvert.SerializeObject(customer); using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox)) CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult(); if (CustomerResponse != null) { var customerContaAzul = new CustomerContaAzul(); customerContaAzul.ContaAzulId = CustomerResponse.id; customerContaAzul.CustomerId = item.Id; customerContaAzul.DataCriacao = DateTime.Now; _contaAzulCustomerService.InsertCustomer(customerContaAzul); } } } catch (Exception ex) { _logger.Error(ex.Message, ex); } } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.OtpReceiverLayout); string Sentotp = Intent.GetStringExtra("otp"); string username = Intent.GetStringExtra("username"); EditText receivedOtp = FindViewById <EditText>(Resource.Id.txtOtp); Button btnVerification = FindViewById <Button>(Resource.Id.btnVerify); btnVerification.Click += delegate { if (Sentotp == receivedOtp.Text) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Successfully your logged in"); alert.SetMessage("Thank You"); alert.SetNegativeButton("Ok", delegate { }); Dialog dialog = alert.Create(); dialog.Show(); CustomerResponse authen = new CustomerResponse(); ServiceWrapper svc = new ServiceWrapper(); try { authen = svc.AuthencateUser(username).Result; if (authen.customer != null && authen.customer.CustomerID != 0) { CurrentUser.SaveUserName(username, authen.customer.CustomerID.ToString()); Intent intent = new Intent(this, typeof(TabActivity)); StartActivity(intent); } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("You entered wrong "); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog1 = aler.Create(); dialog1.Show(); }; } catch (Exception exception) { if (exception.Message.ToString() == "One or more errors occurred.") { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("Please check your internet connection"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog2 = aler.Create(); dialog2.Show(); } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("We're under maintanence"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog3 = aler.Create(); dialog3.Show(); } } } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Incorrect Otp"); aler.SetMessage("Please Check Again"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog = aler.Create(); dialog.Show(); } }; }
public RegisterResponse(CustomerResponse customer, AccountResponse account) { Customer = customer; Account = account; }
public async Task <ActionResult> Detail(string id) { CustomerResponse payment = await this._customerClient.GetCustomerAsync(id); return(View(payment)); }
static void ShowCustomer(CustomerResponse customer) { Console.WriteLine($"Status: {customer.status} \tName: {customer.data.name} \tEmail: {customer.data.contact.email}" + $"\tAdress: {customer.data.address.street_address} \tNotes: {customer.data.notes} " ); }
public async Task <CustomerResponse <List <CustomerStatus> > > Import(IFormFile formFile, CancellationToken cancellationToken) { if (formFile == null || formFile.Length <= 0) { return(CustomerResponse <List <CustomerStatus> > .GetResult(-1, "File này đang rỗng!", 0, 0, null)); } if (!Path.GetExtension(formFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { return(CustomerResponse <List <CustomerStatus> > .GetResult(-1, "Loại file này không được hỗ trợ!", 0, 0, null)); } var filename = formFile.FileName; var list = new List <CustomerStatus>(); using (var stream = new MemoryStream()) { await formFile.CopyToAsync(stream, cancellationToken); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; var rowCount = worksheet.Dimension.Rows; for (int row = 3; row <= rowCount; row++) { Customer customer = new Customer(); customer.CustomerCode = worksheet.Cells[row, 1].Value == null ? "" : worksheet.Cells[row, 1].Value.ToString().Trim(); customer.CustomerName = worksheet.Cells[row, 2].Value == null ? "" : worksheet.Cells[row, 2].Value.ToString().Trim(); customer.CustomerMemberId = worksheet.Cells[row, 3].Value == null ? "" : worksheet.Cells[row, 3].Value.ToString().Trim(); customer.CustomerGroupName = worksheet.Cells[row, 4].Value == null ? "" : worksheet.Cells[row, 4].Value.ToString().Trim(); customer.PhoneNumber = worksheet.Cells[row, 5].Value == null ? "" : worksheet.Cells[row, 5].Value.ToString().Trim(); customer.CompanyName = worksheet.Cells[row, 7].Value == null ? "" : worksheet.Cells[row, 7].Value.ToString().Trim(); customer.TaxCode = worksheet.Cells[row, 8].Value == null ? "" : worksheet.Cells[row, 8].Value.ToString().Trim(); customer.Email = worksheet.Cells[row, 9].Value == null ? "" : worksheet.Cells[row, 9].Value.ToString().Trim(); customer.Address = worksheet.Cells[row, 10].Value == null ? "" : worksheet.Cells[row, 10].Value.ToString().Trim(); customer.Note = worksheet.Cells[row, 11].Value == null ? "" : worksheet.Cells[row, 11].Value.ToString().Trim(); //customer.DateOfBirth = DateTime.Parse(worksheet.Cells[row, 6].Value.ToString().Trim()); CustomerStatus customerStatus = new CustomerStatus(); customerStatus.Customer = customer; customerStatus.StatusDetail = StatusData(list, customer); if (customerStatus.StatusDetail != "Hợp lệ") { customerStatus.DataIsValid = true; } else { customerStatus.DataIsValid = false; } list.Add(customerStatus); //list.Add(new CustomerStatus //{ // CustomerCode = worksheet.Cells[row, 1].Value.ToString().Trim(), // CustomerName = worksheet.Cells[row, 2].Value.ToString().Trim(), // CustomerMemberId = worksheet.Cells[row, 3].Value.ToString().Trim(), // CustomerGroupName = worksheet.Cells[row, 4].Value.ToString().Trim(), // PhoneNumber = worksheet.Cells[row, 5].Value.ToString().Trim(), // //tempDate = worksheet.Cells[row, 6].Value.ToString().Trim(), // DateOfBirth = DateTime.Parse(worksheet.Cells[row, 6].Value.ToString().Trim()), // CompanyName = worksheet.Cells[row, 7].Value.ToString().Trim(), // TaxCode = worksheet.Cells[row, 8].Value.ToString().Trim(), // Email = worksheet.Cells[row, 9].Value == null ? "" : worksheet.Cells[row, 9].Value.ToString().Trim(), // Address = worksheet.Cells[row, 10].Value == null ? "" : worksheet.Cells[row, 10].Value.ToString().Trim(), //}); } } } // add list to db .. // here just read and return return(CustomerResponse <List <CustomerStatus> > .GetResult(0, "OK", 0, 0, list)); }
public async void PreInfo(string CardNumber) { CGSize sTemp = new CGSize(View.Frame.Width, 100); try { if (btnLogin != null && btnResend != null) { btnLogin.Hidden = true; btnResend.Hidden = true; } BTProgressHUD.Show(LoggingClass.txtpleasewait); try { EmailVerification(true); } catch (Exception exe) { //Console.WriteLine(exe.Message, exe.StackTrace); } cr = await svc.AuthencateUser("email", CardNumber, uid_device); if (CardNumber != null) { CurrentUser.PutCardNumber(CardNumber); } if (cr != null) { //Updating device token in different thread var TaskA = new System.Threading.Tasks.Task(() => { updatetoken(cr); }); TaskA.Start(); //Storing customerid and updating the device tokens CurrentUser.StoreId(cr.customer.CustomerID.ToString()); if (cr.customer.Email != null && cr.customer.Email != "") { if ((cr.ErrorDescription == null && cr.ErrorDescription == "") && cr.customer.CustomerID != 0) { //Console.WriteLine("Error Description is not there"); lblInfo.Text = "Hi " + cr.customer.FirstName + " " + cr.customer.LastName + ", \nWe are sending a verification email to " + cr.customer.Email + " . To proceed press continue.\nTo change your emailAddress click on Update."; } else { lblInfo.Text = cr.ErrorDescription; } lblInfo.LineBreakMode = UILineBreakMode.WordWrap; lblInfo.TextAlignment = UITextAlignment.Justified; lblInfo.Lines = 0; sTemp = lblInfo.SizeThatFits(sTemp); if (screenheight <= 568) { y = y - 80; lblInfo.Frame = new CGRect(10, y, View.Frame.Width - 10, sTemp.Height); } else { lblInfo.Frame = new CGRect(10, y, View.Frame.Width - 10, sTemp.Height); } lblInfo.TextAlignment = UITextAlignment.Left; lblInfo.TextColor = UIColor.Black; lblInfo.Font = UIFont.FromName("HelveticaNeue", 15f); CurrentUser.StoreId(cr.customer.CustomerID.ToString()); start = 0; start = y + lblInfo.Frame.Height + 10; //Console.WriteLine("Error " + cr.ErrorDescription); BtnTest1.Frame = new CGRect(180, start, 120, 30); BtnTest2.Frame = new CGRect(30, start, 140, 30); try { BtnTest1.Hidden = false; BtnTest2.Hidden = false; } catch (Exception ex) { //LoggingClass.LogError(ex.Message, screenid, ex.StackTrace); } BtnTest1.TouchUpInside += async delegate { BTProgressHUD.Show(LoggingClass.txtloading); cr = await svc.ContinueService(cr); ShowInfo(cr, false); //btnCardScanner.Hidden = true; }; BtnTest2.TouchUpInside += delegate { BTProgressHUD.Show(LoggingClass.txtloading); UpdateEmail("Please enter your new E-mail Id"); //btnCardScanner.Hidden = true; }; } else { emailnotpresent = true; //Console.WriteLine("Error Discription before if " + cr.ErrorDescription); if ((cr.ErrorDescription == null && cr.ErrorDescription == "") || cr.customer.CustomerID != 0) { //Console.WriteLine("Error Discription in if " + cr.ErrorDescription); UpdateEmail("Hi " + cr.customer.FirstName + cr.customer.LastName + ", \nIt seems we do not have your email address! Please update it so we can send you a verification link that will activate your account."); } else { UpdateEmail(cr.ErrorDescription); } } BTProgressHUD.Dismiss(); } else { try { BtnTest2.Hidden = true; BtnTest1.Hidden = true; btnLogin.Hidden = true; btnResend.Hidden = true; } catch (Exception ex) { //Console.WriteLine(ex.Message); } lblInfo.Text = "Sorry. Your Card number is not matching our records.\n Please re-scan Or Try app as Guest Log In."; lblInfo.TextColor = UIColor.Red; lblInfo.TextAlignment = UITextAlignment.Center; sTemp = lblInfo.SizeThatFits(sTemp); lblInfo.Frame = new CGRect(0, y, View.Frame.Width - 10, sTemp.Height); BTProgressHUD.Dismiss(); } } catch (Exception ex) { //Console.WriteLine(ex.Message); } }
public void OtpVerification(string sentOtp, string receivedOtp, string username) { //starting of otp verification code if (sentOtp == receivedOtp) { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("Successfully your logged in"); alert.SetMessage("Thank You"); alert.SetNegativeButton("Ok", delegate { }); Dialog dialog = alert.Create(); dialog.Show(); CustomerResponse authen = new CustomerResponse(); ServiceWrapper svc = new ServiceWrapper(); try { /// authen = svc.AuthencateUser(username).Result; if (authen.customer != null && authen.customer.CustomerID != 0) { CurrentUser.SaveUserName(username, authen.customer.CustomerID.ToString()); Intent intent = new Intent(this, typeof(TabActivity)); StartActivity(intent); } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("You entered wrong "); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog1 = aler.Create(); dialog1.Show(); }; } catch (Exception exception) { if (exception.Message.ToString() == "One or more errors occurred.") { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("Please check your internet connection"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog2 = aler.Create(); dialog2.Show(); } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Sorry"); aler.SetMessage("We're under maintanence"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog3 = aler.Create(); dialog3.Show(); } } } else { AlertDialog.Builder aler = new AlertDialog.Builder(this); aler.SetTitle("Incorrect Otp"); aler.SetMessage("Please Check Again"); aler.SetNegativeButton("Ok", delegate { }); Dialog dialog = aler.Create(); dialog.Show(); } //Ending of otp verification code }
public async void EmailVerification(Boolean start) { try { DeviceToken Dt = new DeviceToken(); if (CurrentUser.GetId() != null) { Dt = await svc.VerifyMail(CurrentUser.GetId()); try { if (cr.customer == null) { cr = await svc.GetCustomerDetails(Convert.ToInt32(CurrentUser.GetId())); } } catch (Exception exe) { //LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } } if (Dt.VerificationStatus == 1) { CurrentUser.Store(cr.customer.CustomerID.ToString(), cr.customer.FirstName + cr.customer.LastName); CurrentUser.PutStore(cr.customer.PreferredStore); if (RootTabs == null || _window == null) { RootTabs = CurrentUser.RootTabs; _window = CurrentUser.window; nav = new UINavigationController(RootTabs); AddNavigationButtons(nav); _window.RootViewController = nav; LoggingClass.LogInfo("The User logged in with user id: " + CurrentUser.RetreiveUserId(), screenid); } else { nav = new UINavigationController(RootTabs); AddNavigationButtons(nav); _window.RootViewController = nav; LoggingClass.LogInfo("The User logged in with user id: " + CurrentUser.RetreiveUserId(), screenid); } BTProgressHUD.Dismiss(); } else { if (start == false) { try { BTProgressHUD.ShowErrorWithStatus("Your email is not verified plesase check email and verify.", 5000); View.AddSubview(btnResend); } catch (Exception ex) { //LoggingClass.LogError(ex.Message, screenid, ex.StackTrace); } } } } catch (Exception Exe) { //UIAlertView alert = new UIAlertView() //{ //Title = Exe.Message+"\n"+Exe.StackTrace, // //Message = "Coming Soon..." //}; //alert.AddButton("OK"); //alert.Show(); LoggingClass.LogError(Exe.Message, screenid, Exe.StackTrace); } }
public async Task <CustomerResponse <List <Customer> > > Import(IFormFile formFile, CancellationToken cancellationToken) { //kiểm tra file null if (formFile == null || formFile.Length <= 0) { return(CustomerResponse <List <Customer> > .GetResult(-1, "formfile is empty")); } // kiểm tra định dạng file if (!Path.GetExtension(formFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { return(CustomerResponse <List <Customer> > .GetResult(-1, "Not support file extension")); } //thực hiện get dữ liệu từ file var list = new List <Customer>(); using (var stream = new MemoryStream()) { await formFile.CopyToAsync(stream, cancellationToken); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; var rowCount = worksheet.Dimension.Rows; for (int row = 3; row < rowCount; row++) { //get ngày tháng //khởi tạo biến dateTime = ngày hiện tại DateTime dateTime = DateTime.Today; // kiểm tra null if (worksheet.Cells[row, 6].Value == null) { // nếu null gán = ngày hiện tại dateTime = DateTime.UtcNow; } else { // lấy dữ liệu dateTime trong file excel và parse về kiểu Datetime string sDate = worksheet.Cells[row, 6].Value.ToString(); //dateTime = DateTime.ParseExact(sDate, "dd/MM/yyyy", CultureInfo.InvariantCulture); //validate datetime //- Nếu chỉ nhập năm thì ngày sinh hiển thị sẽ là 01/01/[năm] //- Nếu nhập tháng/ năm thì sẽ lấy ngày là ngày 01: 01/[tháng]/[năm] dateTime = (DateTime)validDateOfBirth(sDate); } // get email //khởi tạo email = "" var email = ""; // kiểm tra giá trị null khi lấy từ trong file excel if (worksheet.Cells[row, 9].Value == null) { // gán email = null nếu giá trị = null email = null; } else {// gán giá trị email = giá trị trong file excel email = worksheet.Cells[row, 9].Value.ToString().Trim(); } //thêm dữ liệu và list list.Add(new Customer { CustomerCode = (worksheet.Cells[row, 1].Value == null) ? "" : worksheet.Cells[row, 1].Value.ToString().Trim(), FullName = (worksheet.Cells[row, 2].Value == null) ? "" : worksheet.Cells[row, 2].Value.ToString().Trim(), MemberCardCode = (worksheet.Cells[row, 3].Value == null) ? "" : worksheet.Cells[row, 3].Value.ToString().Trim(), CustomerGroupName = (worksheet.Cells[row, 4].Value == null) ? "" : worksheet.Cells[row, 4].Value.ToString().Trim(), PhoneNumber = (worksheet.Cells[row, 5].Value == null) ? "" : worksheet.Cells[row, 5].Value.ToString().Trim(), //DateOfBirth = DateTime.Parse( worksheet.Cells[row, 6].Value.ToString()), DateOfBirth = dateTime, CompanyName = (worksheet.Cells[row, 7].Value == null) ? "" : worksheet.Cells[row, 7].Value.ToString().Trim(), CompanyTaxCode = (worksheet.Cells[row, 8].Value == null) ? "" : worksheet.Cells[row, 8].Value.ToString().Trim(), Email = email, Address = (worksheet.Cells[row, 10].Value == null) ? "" : worksheet.Cells[row, 10].Value.ToString().Trim(), Note = (worksheet.Cells[row, 11].Value == null) ? "" : worksheet.Cells[row, 11].Value.ToString().Trim() }); } } } //kiểm tra các trường mã khách hàng, tên nhóm khách hàng, số điện thoại có bị trùng lặp trong file hoặc đã tồn tại trên hệ thống for (var k = 0; k < list.Count; k++) { list[k].Status = null; //kiểm tra trùng lặp trong file // khởi tạo biến check Mã khách hàng: // false - không có trong file // true - có trong file bool checkCustomerCode = false; // khởi tạo biến check số điện thoại: // false - không có trong file // true - có trong file bool checkPhoneNumber = false; for (int i = k + 1; i < list.Count; i++) { // kiểm tra trùng mã khách hàng if (list[k].CustomerCode == list[i].CustomerCode) { checkCustomerCode = true; } //Kiểm tra trùng số điện thoại if (list[k].PhoneNumber == list[i].PhoneNumber) { checkPhoneNumber = true; } } //add status if (checkCustomerCode) { list[k].Status += "Mã khách hàng đã trùng với mã khách hàng khách trong tệp nhập khẩu. \n"; } if (checkPhoneNumber) { list[k].Status += "Số điện thoại " + list[k].PhoneNumber + " đã trùng với số điện thoại của khách hàng khác trong tệp nhập khẩu.\n"; } //kiểm tra trùng trong cơ sở dữ liệu. check(list[k]); } // thêm vào db var rowAffect = Insert(list); return(CustomerResponse <List <Customer> > .GetResult(0, "OK", list)); }
protected override void OnCreate(Bundle savedInstanceState) { CheckInternetConnection(); Stopwatch st = new Stopwatch(); st.Start(); //for direct login //CurrentUser.SaveUserName("Sumanth","3"); //Preinfo("8902519310330"); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.LoginView); var TaskA = new System.Threading.Tasks.Task(() => { BlobWrapper.DownloadImages(Convert.ToInt32(CurrentUser.getUserId())); }); TaskA.Start(); //checking user id's exist or not. if ((CurrentUser.getUserId() != null || CurrentUser.getUserId() != "0") && (CurrentUser.getUserId() != null)) { IntoApp(); } else if (CurrentUser.GetGuestId() != null || CurrentUser.getUserId() == "0") { IntoApp(); } else { //if (CurrentUser.GetCardNumber() != null) //{ // Preinfo(CurrentUser.GetCardNumber()); //} ImageButton BtnScanner = FindViewById <ImageButton>(Resource.Id.btnScanner); Button BtnGuestLogin = FindViewById <Button>(Resource.Id.btnGuestLogin); LoggingClass.LogInfo("Opened the app", screenid); BtnScanner.Click += async delegate { try { MobileBarcodeScanner.Initialize(Application); var scanner = new ZXing.Mobile.MobileBarcodeScanner(); scanner.UseCustomOverlay = false; var result = await scanner.Scan();// "8902519310330";// "900497354894";//await scanner.Scan(); if (result != null) { LoggingClass.LogInfo("User Tried to login with " + result, screenid); Preinfo(result.Text); CurrentUser.SaveCardNumber(result.Text); txtmail.Visibility = ViewStates.Gone; Txtem.Visibility = ViewStates.Gone; } } catch (Exception exe) { LoggingClass.LogError(exe.Message, screenid, exe.StackTrace); } }; BtnGuestLogin.Click += async delegate { Intent intent = new Intent(this, typeof(Login)); ProgressIndicator.Show(this); LoggingClass.LogInfo("User Tried to login with Guest Login ", screenid); StartActivity(intent); CustomerResponse csr = new CustomerResponse(); csr = await svc.InsertUpdateGuest("Didn't get the token"); CurrentUser.SaveGuestId(csr.customer.CustomerID.ToString()); }; TxtScanresult = FindViewById <TextView>(Resource.Id.txtScanresult); Txtem = FindViewById <TextView>(Resource.Id.textV); BtnLogin = FindViewById <Button>(Resource.Id.btnLogin); txtmail = FindViewById <EditText>(Resource.Id.txtmail); BtnResend = FindViewById <Button>(Resource.Id.btnResend); update = FindViewById <Button>(Resource.Id.btnUpdateEmailclick); BtnContinue = FindViewById <Button>(Resource.Id.btnContinue); BtnUpdateEmail = FindViewById <Button>(Resource.Id.btnUpdateEmail); BtnResend.Visibility = ViewStates.Gone; update.Visibility = ViewStates.Gone; BtnLogin.Visibility = ViewStates.Gone; BtnContinue.Visibility = ViewStates.Gone; BtnUpdateEmail.Visibility = ViewStates.Gone; txtmail.Visibility = ViewStates.Gone; Txtem.Visibility = ViewStates.Gone; if (IsPlayServicesAvailable()) { var TaskB = new System.Threading.Tasks.Task(() => { var intent = new Intent(this, typeof(RegistrationIntentService)); StartService(intent); }); TaskB.Start(); } var telephonyDeviceID = string.Empty; var telephonySIMSerialNumber = string.Empty; TelephonyManager telephonyManager = (TelephonyManager)this.ApplicationContext.GetSystemService(Context.TelephonyService); if (telephonyManager != null) { if (!string.IsNullOrEmpty(telephonyManager.DeviceId)) { telephonyDeviceID = telephonyManager.DeviceId; } if (!string.IsNullOrEmpty(telephonyManager.SimSerialNumber)) { telephonySIMSerialNumber = telephonyManager.SimSerialNumber; } } var androidID = Android.Provider.Settings.Secure.GetString(this.ApplicationContext.ContentResolver, Android.Provider.Settings.Secure.AndroidId); var deviceUuid = new UUID(androidID.GetHashCode(), ((long)telephonyDeviceID.GetHashCode() << 32) | telephonySIMSerialNumber.GetHashCode()); var DeviceID = deviceUuid.ToString(); CurrentUser.SaveDeviceID(DeviceID); BtnScanner.Dispose(); } }
static async Task Main(string[] args) { //Güvenilir olmayan/geçersiz sertifikayla gRPC hizmetini çağırma HttpClientHandler httpHandler = new HttpClientHandler(); httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; //Güvenilir olmayan/geçersiz sertifikayla gRPC hizmetini çağırma GrpcChannel channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions { HttpHandler = httpHandler }); CustomerClient client = new CustomerClient(channel); #region Unary CustomerRequest request = new CustomerRequest { CustomerId = 1 }; var callUnary = await client.GetCustomerUnaryAsync(request); Console.WriteLine($"{callUnary.Name} ,{callUnary.Email},{callUnary.Adress},{callUnary.Age}"); #endregion #region Server Streaming CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); using (var callServerStream = client.GetCustomerServerStream(new Empty())) { while (await callServerStream.ResponseStream.MoveNext(cancellationTokenSource.Token)) { //herhangi bir yerde iptal tokene gönderebiliriz //cancellationTokenSource.Cancel(); CustomerResponse currentCustomer = callServerStream.ResponseStream.Current; Console.WriteLine($"{currentCustomer.Name} ,{currentCustomer.Email},{currentCustomer.Adress},{currentCustomer.Age}"); } } #endregion #region Client Streaming using (var callClientStream = client.GetCustomersClientStream()) { for (int i = 1; i <= 3; i++) { await callClientStream.RequestStream.WriteAsync(new CustomerRequest { CustomerId = i }); } await callClientStream.RequestStream.CompleteAsync();// steam'i bitirdik CustomersResponse response = await callClientStream; foreach (var customer in response.Customer) { Console.WriteLine($"{customer.Name} ,{customer.Email},{customer.Adress},{customer.Age}"); } } #endregion #region Bi-Directional Streaming CancellationTokenSource cancellationTokenSource2 = new CancellationTokenSource(); using (var callBiDirectionalStream = client.GetCustomersBiDirectionalStream()) { Console.WriteLine("Başla"); var readTask = Task.Run(async() => { while (await callBiDirectionalStream.ResponseStream.MoveNext(cancellationTokenSource.Token)) { Console.WriteLine(callBiDirectionalStream.ResponseStream.Current); } }); for (int i = 1; i <= 3; i++) { await callBiDirectionalStream.RequestStream.WriteAsync(new CustomerRequest { CustomerId = i }); await Task.Delay(TimeSpan.FromSeconds(2)); } await callBiDirectionalStream.RequestStream.CompleteAsync(); await readTask; Console.WriteLine("Bitir"); } #endregion Console.ReadLine(); }