public Point FindPoint(br.com.maplink.services.Address address, AddressOptions addressOptions)
        {
            var findResponse = _addressFinder.findAddress(address, addressOptions, _token);

            return((findResponse.addressLocation != null && findResponse.addressLocation.Length > 0)
                ? findResponse.addressLocation[0].point : null);
        }
        public IActionResult UserContactDetails(UserContactDetailsViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            AddressOptions addressOptions = _accountProvider.GetAddressOptions(AddressOption.Billing);

            if (addressOptions.HasFlag(AddressOptions.TelephoneMandatory) && String.IsNullOrEmpty(model.Telephone))
            {
                ModelState.AddModelError($"{nameof(model.Telephone)}", Languages.LanguageStrings.InvalidTelephoneNumber);
            }

            if (ModelState.IsValid)
            {
                if (_accountProvider.SetUserAccountDetails(UserId(), model.FirstName, model.LastName, model.Email, model.Telephone))
                {
                    GrowlAdd(Languages.LanguageStrings.ContactDetailsUpdated);
                    return(RedirectToAction(nameof(Index), "Account"));
                }

                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.FailedToUpdateAccount);
            }

            model.Breadcrumbs = GetBreadcrumbs();
            model.CartSummary = GetCartSummary();

            return(View(model));
        }
        public IActionResult UserContactDetails(UserContactDetailsViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            AddressOptions addressOptions = _accountProvider.GetAddressOptions();

            if (addressOptions.HasFlag(AddressOptions.TelephoneMandatory) && String.IsNullOrEmpty(model.Telephone))
            {
                ModelState.AddModelError($"{nameof(model.Telephone)}", "Please enter a valid telephone number");
            }

            if (ModelState.IsValid)
            {
                if (_accountProvider.SetUserAccountDetails(UserId(), model.FirstName, model.LastName, model.Email, model.Telephone))
                {
                    GrowlAdd("Contact details successfully updated");
                    return(RedirectToAction("Index", "Account"));
                }

                ModelState.AddModelError(String.Empty, "Failed to update user account");
            }

            return(View(model));
        }
Example #4
0
 public SendTransferRequest(Ed25519Seed seed, TransferOutput output, int accountIndex = 0,
                            AddressOptions addressOptions = null,
                            string indexationKey          = "", string data = "") : this(seed, new List <TransferOutput> {
     output
 }, accountIndex,
                                                                                         addressOptions, indexationKey, data)
 {
 }
        public async Task ShouldUpdateAddress()
        {
            RestRequest savedRequest = null;

            var tcs = new TaskCompletionSource <Address>();

            tcs.SetResult(new Address());

            mockClient.Setup(trc => trc.Execute <Address>(It.IsAny <RestRequest>()))
            .Callback <RestRequest>((request) => savedRequest = request)
            .Returns(tcs.Task);

            var client  = mockClient.Object;
            var options = new AddressOptions();

            options.City         = "Springfield";
            options.CustomerName = "Homer Simpson";
            options.FriendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName();
            options.PostalCode   = "65801";
            options.Region       = "MO";
            options.Street       = "742 Evergreen Terrace";

            await client.UpdateAddressAsync(ADDRESS_SID, options);

            mockClient.Verify(trc => trc.Execute <Address>(It.IsAny <RestRequest>()), Times.Once);
            Assert.IsNotNull(savedRequest);
            Assert.AreEqual("Accounts/{AccountSid}/Addresses/{AddressSid}.json", savedRequest.Resource);
            Assert.AreEqual("POST", savedRequest.Method);
            Assert.AreEqual(7, savedRequest.Parameters.Count);
            var addressSidParam = savedRequest.Parameters.Find(x => x.Name == "AddressSid");

            Assert.IsNotNull(addressSidParam);
            Assert.AreEqual(ADDRESS_SID, addressSidParam.Value);
            var cityParam = savedRequest.Parameters.Find(x => x.Name == "City");

            Assert.IsNotNull(cityParam);
            Assert.AreEqual(options.City, cityParam.Value);
            var customerNameParam = savedRequest.Parameters.Find(x => x.Name == "CustomerName");

            Assert.IsNotNull(customerNameParam);
            Assert.AreEqual(options.CustomerName, customerNameParam.Value);
            var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");

            Assert.IsNotNull(friendlyNameParam);
            Assert.AreEqual(options.FriendlyName, friendlyNameParam.Value);
            var postalCodeParam = savedRequest.Parameters.Find(x => x.Name == "PostalCode");

            Assert.IsNotNull(postalCodeParam);
            Assert.AreEqual(options.PostalCode, postalCodeParam.Value);
            var regionParam = savedRequest.Parameters.Find(x => x.Name == "Region");

            Assert.IsNotNull(regionParam);
            Assert.AreEqual(options.Region, regionParam.Value);
            var streetParam = savedRequest.Parameters.Find(x => x.Name == "Street");

            Assert.IsNotNull(streetParam);
            Assert.AreEqual(options.Street, streetParam.Value);
        }
Example #6
0
 public SendTransferRequest(Ed25519Seed seed, List <TransferOutput> outputs, int accountIndex = 0,
                            AddressOptions addressOptions = null,
                            string indexationKey          = "", string data = "") : base(indexationKey, data)
 {
     Seed           = seed;
     AccountIndex   = accountIndex;
     Outputs        = outputs;
     AddressOptions = addressOptions ?? new AddressOptions();
 }
Example #7
0
        public void ShouldUpdateAddressAsynchronously()
        {
            IRestRequest savedRequest = null;

            mockClient.Setup(trc => trc.ExecuteAsync <Address>(It.IsAny <IRestRequest>(), It.IsAny <Action <Address> >()))
            .Callback <IRestRequest, Action <Address> >((request, action) => savedRequest = request);
            var client = mockClient.Object;

            manualResetEvent = new ManualResetEvent(false);
            var options = new AddressOptions();

            options.City         = "Springfield";
            options.CustomerName = "Homer Simpson";
            options.FriendlyName = Utilities.MakeRandomFriendlyName();
            options.PostalCode   = "65801";
            options.Region       = "MO";
            options.Street       = "742 Evergreen Terrace";

            client.UpdateAddress(ADDRESS_SID, options, address => {
                manualResetEvent.Set();
            });
            manualResetEvent.WaitOne(1);

            mockClient.Verify(trc => trc.ExecuteAsync <Address>(It.IsAny <IRestRequest>(), It.IsAny <Action <Address> >()), Times.Once);
            Assert.IsNotNull(savedRequest);
            Assert.AreEqual("Accounts/{AccountSid}/Addresses/{AddressSid}.json", savedRequest.Resource);
            Assert.AreEqual(Method.POST, savedRequest.Method);
            Assert.AreEqual(7, savedRequest.Parameters.Count);
            var addressSidParam = savedRequest.Parameters.Find(x => x.Name == "AddressSid");

            Assert.IsNotNull(addressSidParam);
            Assert.AreEqual(ADDRESS_SID, addressSidParam.Value);
            var cityParam = savedRequest.Parameters.Find(x => x.Name == "City");

            Assert.IsNotNull(cityParam);
            Assert.AreEqual(options.City, cityParam.Value);
            var customerNameParam = savedRequest.Parameters.Find(x => x.Name == "CustomerName");

            Assert.IsNotNull(customerNameParam);
            Assert.AreEqual(options.CustomerName, customerNameParam.Value);
            var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");

            Assert.IsNotNull(friendlyNameParam);
            Assert.AreEqual(options.FriendlyName, friendlyNameParam.Value);
            var postalCodeParam = savedRequest.Parameters.Find(x => x.Name == "PostalCode");

            Assert.IsNotNull(postalCodeParam);
            Assert.AreEqual(options.PostalCode, postalCodeParam.Value);
            var regionParam = savedRequest.Parameters.Find(x => x.Name == "Region");

            Assert.IsNotNull(regionParam);
            Assert.AreEqual(options.Region, regionParam.Value);
            var streetParam = savedRequest.Parameters.Find(x => x.Name == "Street");

            Assert.IsNotNull(streetParam);
            Assert.AreEqual(options.Street, streetParam.Value);
        }
 public AddressAdapter()
 {
     this.findAddressOptions = new AddressOptions
     {
         usePhonetic = true,
         searchType = 2,
         resultRange = new ResultRange { pageIndex = 1, recordsPerPage = 10 }
     };
     this.lastLocations = new List<AddressLocation>();
 }
Example #9
0
 public SendTransferRequest(Ed25519Seed seed, string receiverBech32Address, long amount, string indexationKey,
                            string data) : base(indexationKey, data)
 {
     Seed         = seed;
     AccountIndex = 0;
     Outputs      = new List <TransferOutput>
     {
         new TransferOutput(new Bech32Address(receiverBech32Address), amount)
     };
     AddressOptions = new AddressOptions();
 }
Example #10
0
        public static Address CreateAddress(AddressOptions addressOptions)
        {
            var random = new Random((int)(DateTime.Now.Ticks % Int32.MaxValue));

            return new Address
            {
                Type = addressOptions,
                AddressDesc = random.Next(1000, 10000) + " " + RandomStreet(random.Next()) + ", " + RandomCity(random.Next()) + ", QC",
                PostalCode = RandomPostalCode(random),
                Country = "Canada"
            };
        }
Example #11
0
        public static void CreateCustomer(IAsyncDocumentSession session, string name, AddressOptions addressOptions)
        {
            var entity = new Customer { Name = name };

            if (addressOptions == AddressOptions.Home || addressOptions == AddressOptions.HomeAndBusines)
                entity.Addresses.Add(CreateAddress(AddressOptions.Home));

            if (addressOptions == AddressOptions.Business || addressOptions == AddressOptions.HomeAndBusines)
                entity.Addresses.Add(CreateAddress(AddressOptions.Business));

            session.Store(entity);
        }
        private AddressOptions GetAddressOptions()
        {
            var addressOptions = new AddressOptions
            {
                usePhonetic = true,
                searchType  = 2,
                resultRange = new ResultRange {
                    pageIndex = 1, recordsPerPage = 10
                }
            };

            return(addressOptions);
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/user/account
        string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        string AuthToken  = "your_auth_token";
        var    twilio     = new TwilioRestClient(AccountSid, AuthToken);

        var options = new AddressOptions();

        options.CustomerName = "Customer 456";
        options.Street       = "2 Hasselhoff Lane";

        twilio.UpdateAddress("AD2a0747eba6abf96b7e3c3ff0b4530f6e", options);
    }
Example #14
0
        public void FindAddress()
        {
            var address = new Address
            {
                street      = "Avenida Paulista",
                houseNumber = "1000",
                city        = new City {
                    name = "São Paulo", state = "SP"
                }
            };

            var addressOptions = new AddressOptions
            {
                usePhonetic = true,
                searchType  = 2,
                resultRange = new ResultRange {
                    pageIndex = 1, recordsPerPage = 10
                }
            };

            using (var addressFinderSoapClient = new AddressFinderSoapClient())
            {
                var findAddressResponse = addressFinderSoapClient.findAddress(address, addressOptions, _token);

                Console.WriteLine("----- AddressFinder - FindAddress -----");
                Console.WriteLine("Page Count: {0}, Record Count: {1}", findAddressResponse.pageCount, findAddressResponse.recordCount);

                findAddressResponse.addressLocation
                .ToList()
                .ForEach(addressLocation =>
                         Console.WriteLine
                         (
                             "Key: {0}, " +
                             "Street name: {1}, Street number: {2}, Zip code: {3}, District: {4}, " +
                             "City: {5}, State: {6}, " +
                             "Left zip code: {7}, Right zip code: {8}, Car access: {9}, " +
                             "Data Source: {10}, Latitude: {11}, Longitude: {12}",
                             addressLocation.key,
                             addressLocation.address.street, addressLocation.address.houseNumber,
                             addressLocation.address.zip, addressLocation.address.district,
                             addressLocation.address.city.name,
                             addressLocation.address.city.state,
                             addressLocation.zipL, addressLocation.zipR,
                             addressLocation.carAccess, addressLocation.dataSource,
                             addressLocation.point.y, addressLocation.point.x
                         ));
            }
        }
    static void Main(string[] args)
    {
        // Find your Account Sid and Auth Token at twilio.com/user/account
        string AccountSid = "{{ account_sid }}";
        string AuthToken  = "{{ auth_token }}";
        var    twilio     = new TwilioRestClient(AccountSid, AuthToken);

        var options = new AddressOptions();

        options.CustomerName = "Customer 456";
        options.Street       = "2 Hasselhoff Lane";

        var address = twilio.AddAddress("Billing - Customer 123", "Customer 123", "2 Hasselhoff Lane", "Berlin", "Berlin", "10785", "DE");

        Console.WriteLine(address.Sid);
    }
Example #16
0
        public ActionResult EditAddress(Twilio.Address _address)
        {
            var twilio  = new TwilioRestClient(AccountSid, AuthToken);
            var options = new AddressOptions();

            options.City         = _address.City;
            options.CustomerName = _address.CustomerName;
            options.FriendlyName = _address.FriendlyName;
            options.PostalCode   = _address.PostalCode;
            options.Region       = _address.Region;
            options.Street       = _address.Street;

            var response = twilio.UpdateAddress(_address.Sid, options);

            return(RedirectToAction("ListAddress"));
        }
Example #17
0
 public SovrinTokenConfigurationService(
     IApplicationLifetime applicationLifetime,
     IPaymentService paymentService,
     IProvisioningService provisioningService,
     IAgentProvider agentProvider,
     IWalletRecordService recordService,
     IOptions <AddressOptions> addressOptions,
     ILogger <SovrinTokenConfigurationService> logger)
 {
     applicationLifetime.ApplicationStarted.Register(CreateDefaultPaymentAddress);
     this.paymentService      = paymentService;
     this.provisioningService = provisioningService;
     this.agentProvider       = agentProvider;
     this.recordService       = recordService;
     this.addressOptions      = addressOptions.Value;
     this.logger = logger;
 }
Example #18
0
        private TAddress UpdateAddressDetail(TAddressRequest address)
        {
            AddressOptions addressOptions = new AddressOptions()
            {
                City         = address.City,
                CustomerName = address.CustomerName,
                FriendlyName = address.FriendlyName,
                PostalCode   = address.PostalCode,
                Region       = address.Region,
                Street       = address.Street
            };
            Address detail = TwilioClient.UpdateAddress(address.AddressSid, addressOptions);

            if (detail.RestException != null)
            {
                throw new Exception(detail.RestException.Message);
            }
            return(Mapper.Map <TAddress>(detail));
        }
Example #19
0
        public ActionResult Update(string Sid, string FriendlyName, string CustomerName, string Street, string City, string Region, string PostalCode)
        {
            var accountSid = ConfigurationManager.AppSettings["TwilioAccountSid"];
            var authToken  = ConfigurationManager.AppSettings["TwilioAuthToken"];
            var twilio     = new TwilioRestClient(accountSid, authToken);

            var options = new AddressOptions {
                FriendlyName = FriendlyName, CustomerName = CustomerName, Street = Street, City = City, Region = Region, PostalCode = PostalCode
            };
            var address = twilio.UpdateAddress(Sid, options);

            if (address.RestException != null)
            {
                return(new HttpStatusCodeResult(500, address.RestException.Message));
            }

            ViewBag.address = address;
            return(View(viewName: "~/Views/Home/Details.cshtml"));
        }
        private void PrepareCreateAccountModel(ref CreateAccountViewModel model)
        {
            AddressOptions addressOptions = _accountProvider.GetAddressOptions();

            model.ShowAddressLine1 = addressOptions.HasFlag(AddressOptions.AddressLine1Show);
            model.ShowAddressLine2 = addressOptions.HasFlag(AddressOptions.AddressLine2Show);
            model.ShowAddressLine3 = addressOptions.HasFlag(AddressOptions.AddressLine3Show);
            model.ShowBusinessName = addressOptions.HasFlag(AddressOptions.BusinessNameShow);
            model.ShowCity         = addressOptions.HasFlag(AddressOptions.CityShow);
            model.ShowCounty       = addressOptions.HasFlag(AddressOptions.CountyShow);
            model.ShowPostcode     = addressOptions.HasFlag(AddressOptions.PostCodeShow);
            model.ShowTelephone    = addressOptions.HasFlag(AddressOptions.TelephoneShow);

            model.ShowCaptchaImage = true;

            CreateAccountCacheItem createAccountCacheItem = GetCachedCreateAccountAttempt(true);

            createAccountCacheItem.CaptchaText = GetRandomWord(6, CaptchaCharacters);
        }
Example #21
0
        private void ValidateBillingAddressModel(ref BillingAddressViewModel model)
        {
            AddressOptions addressOptions = _accountProvider.GetAddressOptions(AddressOption.Delivery);

            if (addressOptions.HasFlag(AddressOptions.AddressLine1Mandatory) && String.IsNullOrEmpty(model.AddressLine1))
            {
                ModelState.AddModelError(nameof(model.AddressLine1), Languages.LanguageStrings.AddressLine1Required);
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine2Mandatory) && String.IsNullOrEmpty(model.AddressLine2))
            {
                ModelState.AddModelError(nameof(model.AddressLine2), Languages.LanguageStrings.AddressLine2Required);
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine3Mandatory) && String.IsNullOrEmpty(model.AddressLine3))
            {
                ModelState.AddModelError(nameof(model.AddressLine3), Languages.LanguageStrings.AddressLine3Required);
            }

            if (addressOptions.HasFlag(AddressOptions.CityMandatory) && String.IsNullOrEmpty(model.City))
            {
                ModelState.AddModelError(nameof(model.City), Languages.LanguageStrings.CityRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.CountyMandatory) && String.IsNullOrEmpty(model.County))
            {
                ModelState.AddModelError(nameof(model.County), Languages.LanguageStrings.CountyRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.PostCodeMandatory) && String.IsNullOrEmpty(model.Postcode))
            {
                ModelState.AddModelError(nameof(model.Postcode), Languages.LanguageStrings.PostcodeRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.BusinessNameMandatory) && String.IsNullOrEmpty(model.BusinessName))
            {
                ModelState.AddModelError(nameof(model.BusinessName), Languages.LanguageStrings.BusinessNameRequired);
            }
        }
        private void ValidateBillingAddressModel(ref BillingAddressViewModel model)
        {
            AddressOptions addressOptions = _accountProvider.GetAddressOptions();

            if (addressOptions.HasFlag(AddressOptions.AddressLine1Mandatory) && String.IsNullOrEmpty(model.AddressLine1))
            {
                ModelState.AddModelError(nameof(model.AddressLine1), "Address line 1 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine2Mandatory) && String.IsNullOrEmpty(model.AddressLine2))
            {
                ModelState.AddModelError(nameof(model.AddressLine2), "Address line 2 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine3Mandatory) && String.IsNullOrEmpty(model.AddressLine3))
            {
                ModelState.AddModelError(nameof(model.AddressLine3), "Address line 3 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.CityMandatory) && String.IsNullOrEmpty(model.City))
            {
                ModelState.AddModelError(nameof(model.City), "City is required");
            }

            if (addressOptions.HasFlag(AddressOptions.CountyMandatory) && String.IsNullOrEmpty(model.County))
            {
                ModelState.AddModelError(nameof(model.County), "County is required");
            }

            if (addressOptions.HasFlag(AddressOptions.PostCodeMandatory) && String.IsNullOrEmpty(model.Postcode))
            {
                ModelState.AddModelError(nameof(model.Postcode), "Postcode is required");
            }

            if (addressOptions.HasFlag(AddressOptions.BusinessNameMandatory) && String.IsNullOrEmpty(model.BusinessName))
            {
                ModelState.AddModelError(nameof(model.BusinessName), "Business Name is required");
            }
        }
Example #23
0
        /// <summary>
        /// Creates a new address for a contact from the sevDesk API.
        /// </summary>
        /// <param name="id">The ID of the contact.</param>
        /// <param name="options">The options that contain the information about the address.</param>
        /// <exception cref="InvalidOperationException">If the API could not be reached or the token is not valid, an <see cref="InvalidOperationException" /> is thrown.</exception>
        /// <returns>Returns the ID of the created address.</returns>
        public async Task <string> CreateAddressAsync(string id, AddressOptions options)
        {
            try
            {
                // Initializes the key value pairs
                List <KeyValuePair <string, string> > values = new List <KeyValuePair <string, string> >();
                if (!string.IsNullOrWhiteSpace(options.Street))
                {
                    values.Add(new KeyValuePair <string, string>("street", options.Street));
                }
                if (!string.IsNullOrWhiteSpace(options.ZipCode))
                {
                    values.Add(new KeyValuePair <string, string>("zip", options.ZipCode));
                }
                if (!string.IsNullOrWhiteSpace(options.City))
                {
                    values.Add(new KeyValuePair <string, string>("city", options.City));
                }
                if (!string.IsNullOrWhiteSpace(options.CountryId))
                {
                    values.Add(new KeyValuePair <string, string>("country", options.CountryId));
                }
                if (!string.IsNullOrWhiteSpace(options.CategoryId))
                {
                    values.Add(new KeyValuePair <string, string>("category", options.CategoryId));
                }

                // Sends an HTTP request to endpoint
                HttpResponseMessage response = await httpClient.PostAsync($"{this.apiUri}/Contact/{id}/addAddress?token={this.Token}", new FormUrlEncodedContent(values));

                // Returns the result
                return(JsonConvert.DeserializeObject <Result <Models.Addresses.Address> >(await response.Content.ReadAsStringAsync()).objects.id);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
Example #24
0
        /// <summary>
        /// Updates an existing address for a contact from the sevDesk API.
        /// </summary>
        /// <param name="id">The ID of the address.</param>
        /// <param name="options">The options that contain the information about the address.</param>
        /// <exception cref="InvalidOperationException">If the API could not be reached or the token is not valid, an <see cref="InvalidOperationException" /> is thrown.</exception>
        public async Task UpdateAddressAsync(string id, AddressOptions options)
        {
            try
            {
                // Initializes the key value pairs
                List <KeyValuePair <string, string> > values = new List <KeyValuePair <string, string> >();
                if (!string.IsNullOrWhiteSpace(options.Street))
                {
                    values.Add(new KeyValuePair <string, string>("street", options.Street));
                }
                if (!string.IsNullOrWhiteSpace(options.ZipCode))
                {
                    values.Add(new KeyValuePair <string, string>("zip", options.ZipCode));
                }
                if (!string.IsNullOrWhiteSpace(options.City))
                {
                    values.Add(new KeyValuePair <string, string>("city", options.City));
                }
                if (!string.IsNullOrWhiteSpace(options.CountryId))
                {
                    values.Add(new KeyValuePair <string, string>("country[id]", options.CountryId));
                    values.Add(new KeyValuePair <string, string>("country[objectName]", "StaticCountry"));
                }
                if (!string.IsNullOrWhiteSpace(options.CategoryId))
                {
                    values.Add(new KeyValuePair <string, string>("category[id]", options.CategoryId));
                    values.Add(new KeyValuePair <string, string>("category[objectName]", "Category"));
                }

                // Sends an HTTP request to endpoint
                HttpResponseMessage response = await httpClient.PutAsync($"{this.apiUri}/ContactAddress/{id}?token={this.Token}", new FormUrlEncodedContent(values));
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
        /// <summary>
        /// Método para retorno de informações e valores sobre a rota
        /// </summary>
        /// <param name="token">Chave para autenticação</param>
        /// <param name="enderecoPartida">Endereco com número de partida, ex: Av Paulista, 1000</param>
        /// <param name="cidadeUfPartida">Cidade e estado de partida, ex: São Paulo,SP</param>
        /// <param name="enderecoDestino">Endereco com número de destino, ex: Av Paulista, 1000</param>
        /// <param name="cidadeUfDestino">Cidade e estado de destino, ex: São Paulo,SP</param>
        /// <param name="veiculo">Infomar: CapacidadeTanque,ConsumoMedio,ValorCombustivel,VelocidadeMedia,CategoriaVeiculo(1-Moto,2-Carro,5-Onibus,7-Caminhao)</param>
        /// <param name="tipoRota">0 = Rota padrão mais rápida, 1 = Rota evitando o trânsito. (Somente utilizando base urbana)</param>
        /// <returns>Tempo total da rota;Distância total;Custo de combustível;Custo total considerando pedágio</returns>
        public ResponseInformacoesRota GetInformacoesRota(string token, string enderecoPartida, string cidadeUfPartida, string enderecoDestino, string cidadeUfDestino, Veiculo veiculo, int tipoRota = 0)
        {
            try
            {
                if (string.IsNullOrEmpty(enderecoPartida) || enderecoPartida.Split(',').Length != 2)
                {
                    return new ResponseInformacoesRota {
                               Exception = "O endereço de partida deve ser preenchido corretamente: ex: Av Paulista, 1000"
                    }
                }
                ;
                if (string.IsNullOrEmpty(cidadeUfPartida) || cidadeUfPartida.Split(',').Length != 2)
                {
                    return new ResponseInformacoesRota {
                               Exception = "A cidade e UF de partida deve ser preenchida corretamente, ex: São Paulo, SP"
                    }
                }
                ;
                if (string.IsNullOrEmpty(enderecoDestino) || enderecoDestino.Split(',').Length != 2)
                {
                    return new ResponseInformacoesRota {
                               Exception = "O endereço de destino deve ser preenchido corretamente: ex: Av Paulista, 2000"
                    }
                }
                ;
                if (string.IsNullOrEmpty(cidadeUfDestino) || cidadeUfDestino.Split(',').Length != 2)
                {
                    return new ResponseInformacoesRota {
                               Exception = "A cidade de destino deve ser preenchida corretamente, ex: São Paulo, SP"
                    }
                }
                ;
                if (veiculo == null)
                {
                    return new ResponseInformacoesRota {
                               Exception = "As informações do veículo devem ser preenchidas"
                    }
                }
                ;
                if (veiculo.CapacidadeTanque <= 0)
                {
                    return new ResponseInformacoesRota {
                               Exception = "A capacidade do tanque deve ser informada"
                    }
                }
                ;
                if (veiculo.CategoriaVeiculo <= 0)
                {
                    return new ResponseInformacoesRota {
                               Exception = "A categoria do veículo deve ser informada"
                    }
                }
                ;
                if (veiculo.ConsumoMedio <= 0)
                {
                    return new ResponseInformacoesRota {
                               Exception = "O consumo médio do veículo deve ser informado"
                    }
                }
                ;
                if (veiculo.ValorCombustivel <= 0)
                {
                    return new ResponseInformacoesRota {
                               Exception = "O valor do combustível deve ser informado"
                    }
                }
                ;
                //ToDo: Verificar se existe método no webservice que calcula velocidade média da viagem
                if (veiculo.VelocidadeMedia <= 0)
                {
                    return new ResponseInformacoesRota {
                               Exception = "A velocidade média a ser empregada na viagem deve ser informada"
                    }
                }
                ;

                var addressStart = new Address
                {
                    street      = enderecoPartida.Split(',')[0].Trim(),
                    houseNumber = enderecoPartida.Split(',')[1].Trim(),
                    city        = new ServiceAddress.City {
                        name = cidadeUfPartida.Split(',')[0].Trim(), state = cidadeUfPartida.Split(',')[1].Trim()
                    }
                };

                var addressEnd = new Address
                {
                    street      = enderecoDestino.Split(',')[0].Trim(),
                    houseNumber = enderecoDestino.Split(',')[1].Trim(),
                    city        = new ServiceAddress.City {
                        name = cidadeUfDestino.Split(',')[0].Trim(), state = cidadeUfDestino.Split(',')[1].Trim()
                    }
                };

                var addressOptions = new AddressOptions
                {
                    usePhonetic = true,
                    searchType  = 2,
                    resultRange = new ResultRange {
                        pageIndex = 1, recordsPerPage = 1
                    }
                };

                double xPartida = 0;
                double yPartida = 0;
                using (var addressFinderSoapClient = new AddressFinderSoapClient())
                {
                    var findAddressResponse = addressFinderSoapClient.findAddress(addressStart, addressOptions, token);

                    if (findAddressResponse.addressLocation.Count() == 0)
                    {
                        return new ResponseInformacoesRota {
                                   Exception = "O endereço de partida não foi localizado, verifique"
                        }
                    }
                    ;

                    xPartida = findAddressResponse.addressLocation.First().point.x;
                    yPartida = findAddressResponse.addressLocation.First().point.y;
                }

                double xDestino = 0;
                double yDestino = 0;
                using (var addressFinderSoapClient = new AddressFinderSoapClient())
                {
                    var findAddressResponse = addressFinderSoapClient.findAddress(addressEnd, addressOptions, token);
                    if (findAddressResponse.addressLocation.Count() == 0)
                    {
                        return new ResponseInformacoesRota {
                                   Exception = "O endereço de chegada não foi localizado, verifique"
                        }
                    }
                    ;

                    xDestino = findAddressResponse.addressLocation.First().point.x;
                    yDestino = findAddressResponse.addressLocation.First().point.y;
                }

                var originRoute = new ServiceRouteMapLink.RouteStop
                {
                    description = addressStart.street,
                    point       = new ServiceRouteMapLink.Point {
                        x = xPartida, y = yPartida
                    }
                };

                var destinationRoute = new ServiceRouteMapLink.RouteStop
                {
                    description = addressEnd.street,
                    point       = new ServiceRouteMapLink.Point {
                        x = xDestino, y = yDestino
                    }
                };

                var routes = new[] { originRoute, destinationRoute };

                var opcaoRota = DescriptionType.RotaUrbana;
                tipoRota = (int)RouteType.PadraoRapida;
                //Se a cidade for diferente troca o descriptionType para rota rodoviária
                if (!cidadeUfPartida.Trim().Equals(cidadeUfDestino.Trim()))
                {
                    opcaoRota = DescriptionType.RotaRodoviaria;
                }

                var routeOptions = new RouteOptions
                {
                    language     = "portugues",
                    routeDetails = new RouteDetails {
                        descriptionType = (int)opcaoRota, routeType = tipoRota, optimizeRoute = true
                    },
                    vehicle = new Vehicle
                    {
                        tankCapacity       = veiculo.CapacidadeTanque,
                        averageConsumption = veiculo.ConsumoMedio,
                        fuelPrice          = veiculo.ValorCombustivel,
                        averageSpeed       = veiculo.VelocidadeMedia,
                        tollFeeCat         = veiculo.CategoriaVeiculo
                    }
                };

                using (var routeSoapClient = new RouteSoapClient())
                {
                    var getRouteResponse = routeSoapClient.getRoute(routes, routeOptions, token);

                    var result = new ResponseInformacoesRota
                    {
                        TempoTotal              = getRouteResponse.routeTotals.totalTime,
                        DistanciaTotal          = getRouteResponse.routeTotals.totalDistance,
                        CustoCombustivel        = getRouteResponse.routeTotals.totalfuelCost,
                        CustoPedagioCombustivel = getRouteResponse.routeTotals.totalCost
                    };
                    return(result);
                }
            }
            catch (Exception)
            {
                return(new ResponseInformacoesRota {
                    Exception = "Não foi possível processar sua solicitação"
                });
            }
        }
        /// <inheritdoc />
        public async Task <PaymentAddressRecord> CreatePaymentAddressAsync(IAgentContext agentContext, AddressOptions configuration = null)
        {
            var address = await IndyPayments.CreatePaymentAddressAsync(agentContext.Wallet, TokenConfiguration.MethodName,
                                                                       new { seed = configuration?.Seed }.ToJson());

            var addressRecord = new PaymentAddressRecord
            {
                Id              = Guid.NewGuid().ToString("N"),
                Method          = TokenConfiguration.MethodName,
                Address         = address,
                SourcesSyncedAt = DateTime.MinValue
            };

            await recordService.AddAsync(agentContext.Wallet, addressRecord);

            return(addressRecord);
        }
        private void ValidateCreateAccountModel(ref CreateAccountViewModel model)
        {
            CreateAccountCacheItem createAccountCacheItem = GetCachedCreateAccountAttempt(true);

            if (!String.IsNullOrEmpty(createAccountCacheItem.CaptchaText))
            {
                if (!createAccountCacheItem.CaptchaText.Equals(model.CaptchaText))
                {
                    ModelState.AddModelError(String.Empty, "Invalid Validation Code");
                }
            }

            createAccountCacheItem.CreateAttempts++;

            if (createAccountCacheItem.CreateAttempts > 10)
            {
                ModelState.AddModelError(String.Empty, "Too many attempts, please wait 30 minutes and try again");
            }

            AddressOptions addressOptions = _accountProvider.GetAddressOptions();

            if (!ValidatePasswordComplexity(model.Password))
            {
                ModelState.AddModelError(String.Empty, "Password does not match complexity rules.");
            }

            if (!model.Password.Equals(model.ConfirmPassword))
            {
                ModelState.AddModelError("", "Confirm password must match Password");
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine1Mandatory) && String.IsNullOrEmpty(model.AddressLine1))
            {
                ModelState.AddModelError(nameof(model.AddressLine1), "Address line 1 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine2Mandatory) && String.IsNullOrEmpty(model.AddressLine2))
            {
                ModelState.AddModelError(nameof(model.AddressLine2), "Address line 2 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine3Mandatory) && String.IsNullOrEmpty(model.AddressLine3))
            {
                ModelState.AddModelError(nameof(model.AddressLine3), "Address line 3 is required");
            }

            if (addressOptions.HasFlag(AddressOptions.CityMandatory) && String.IsNullOrEmpty(model.City))
            {
                ModelState.AddModelError(nameof(model.City), "City is required");
            }

            if (addressOptions.HasFlag(AddressOptions.CountyMandatory) && String.IsNullOrEmpty(model.County))
            {
                ModelState.AddModelError(nameof(model.County), "County is required");
            }

            if (addressOptions.HasFlag(AddressOptions.PostCodeMandatory) && String.IsNullOrEmpty(model.Postcode))
            {
                ModelState.AddModelError(nameof(model.Postcode), "Postcode is required");
            }

            if (addressOptions.HasFlag(AddressOptions.BusinessNameMandatory) && String.IsNullOrEmpty(model.BusinessName))
            {
                ModelState.AddModelError(nameof(model.BusinessName), "Business Name is required");
            }

            if (addressOptions.HasFlag(AddressOptions.TelephoneMandatory) && String.IsNullOrEmpty(model.Telephone))
            {
                ModelState.AddModelError(nameof(model.Telephone), "Telephone is required");
            }

            createAccountCacheItem.CaptchaText = GetRandomWord(6, CaptchaCharacters);
            model.CaptchaText = String.Empty;
        }
        public async Task CreateCustomerAsync(string nativePaymentMethodId, TKey subscriptionId)
        {
            var subscription = await _subscriptionManager.FindByIdAsync(subscriptionId);

            var tenant = await _tenantManager.FindByIdAsync(subscription.TenantId);

            var addresses = await _addressProfileManager.FindByTenantIdAsync(tenant.Id);

            TAddressProfile address = null;

            foreach (var addr in addresses)
            {
                var userAddress = addr.UserAddresses.FirstOrDefault();

                if (userAddress.AddressType == DaAddressType.Billing)
                {
                    address = addr;
                    break;
                }
            }

            if (address == null)
            {
                address = addresses.FirstOrDefault();
            }

            if (address == null)
            {
                throw new InvalidOperationException("No address found.");
            }

            var country = await _countryManager.FindByIdAsync(tenant.CountryId);

            var addressOption = new AddressOptions()
            {
                Line1      = address.Address1,
                Line2      = address.Address2,
                Country    = country.Name,
                PostalCode = address.ZipCode,
                State      = address.State,
                City       = address.City
            };

            var options = new CustomerCreateOptions
            {
                PaymentMethod = nativePaymentMethodId,
                Email         = tenant.BillingEmail,
                Name          = tenant.Name,
                Address       = addressOption
            };

            var service  = new CustomerService();
            var customer = await service.CreateAsync(options);

            var tenantAttribute = tenant.Attributes.Where(m => m.AttributeName == "StripeCustomerId").SingleOrDefault();

            bool newAttribute = false;

            if (tenantAttribute == null)
            {
                tenantAttribute = new TTenantAttribute()
                {
                    Tenant         = tenant,
                    AttributeName  = "StripeCustomerId",
                    CreatedDateUtc = DateTime.UtcNow
                };

                newAttribute = true;
            }

            tenantAttribute.AttributeValue     = customer.Id;
            tenantAttribute.LastUpdatedDateUtc = DateTime.UtcNow;

            if (newAttribute)
            {
                if (tenant.Attributes == null)
                {
                    tenant.Attributes = new List <TTenantAttribute>();
                }

                tenant.Attributes.Add(tenantAttribute);
            }

            await _tenantManager.UpdateAsync(tenant);
        }
Example #29
0
        public void ShouldUpdateAddress()
        {
            RestRequest savedRequest = null;
            mockClient.Setup(trc => trc.Execute<Address>(It.IsAny<RestRequest>()))
                .Callback<RestRequest>((request) => savedRequest = request)
                .Returns(new Address());
            var client = mockClient.Object;
            var options = new AddressOptions();
            options.City = "Springfield";
            options.CustomerName = "Homer Simpson";
            options.FriendlyName = Twilio.Api.Tests.Utilities.MakeRandomFriendlyName ();
            options.PostalCode = "65801";
            options.Region = "MO";
            options.Street = "742 Evergreen Terrace";

            client.UpdateAddress(ADDRESS_SID, options);

            mockClient.Verify(trc => trc.Execute<Address>(It.IsAny<RestRequest>()), Times.Once);
            Assert.IsNotNull(savedRequest);
            Assert.AreEqual("Accounts/{AccountSid}/Addresses/{AddressSid}.json", savedRequest.Resource);
            Assert.AreEqual("POST", savedRequest.Method);
            Assert.AreEqual(7, savedRequest.Parameters.Count);
            var addressSidParam = savedRequest.Parameters.Find(x => x.Name == "AddressSid");
            Assert.IsNotNull(addressSidParam);
            Assert.AreEqual(ADDRESS_SID, addressSidParam.Value);
            var cityParam = savedRequest.Parameters.Find(x => x.Name == "City");
            Assert.IsNotNull(cityParam);
            Assert.AreEqual(options.City, cityParam.Value);
            var customerNameParam = savedRequest.Parameters.Find(x => x.Name == "CustomerName");
            Assert.IsNotNull(customerNameParam);
            Assert.AreEqual(options.CustomerName, customerNameParam.Value);
            var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");
            Assert.IsNotNull(friendlyNameParam);
            Assert.AreEqual(options.FriendlyName, friendlyNameParam.Value);
            var postalCodeParam = savedRequest.Parameters.Find(x => x.Name == "PostalCode");
            Assert.IsNotNull(postalCodeParam);
            Assert.AreEqual(options.PostalCode, postalCodeParam.Value);
            var regionParam = savedRequest.Parameters.Find(x => x.Name == "Region");
            Assert.IsNotNull(regionParam);
            Assert.AreEqual(options.Region, regionParam.Value);
            var streetParam = savedRequest.Parameters.Find(x => x.Name == "Street");
            Assert.IsNotNull(streetParam);
            Assert.AreEqual(options.Street, streetParam.Value);
        }
Example #30
0
 /// <inheritdoc />
 public Task <PaymentAddressRecord> CreatePaymentAddressAsync(IAgentContext agentContext, AddressOptions configuration = null)
 {
     throw new NotSupportedException();
 }
Example #31
0
 public GetUnspentAddressesRequest(Ed25519Seed seed, int accountIndex = 0, AddressOptions addressOptions = null)
 {
     Seed           = seed;
     AccountIndex   = accountIndex;
     AddressOptions = addressOptions ?? new AddressOptions();
 }
Example #32
0
        public void ShouldUpdateAddressAsynchronously()
        {
            IRestRequest savedRequest = null;
            mockClient.Setup(trc => trc.ExecuteAsync<Address>(It.IsAny<IRestRequest>(), It.IsAny<Action<Address>>()))
                .Callback<IRestRequest, Action<Address>>((request, action) => savedRequest = request);
            var client = mockClient.Object;
            manualResetEvent = new ManualResetEvent(false);
            var options = new AddressOptions();
            options.City = "Springfield";
            options.CustomerName = "Homer Simpson";
            options.FriendlyName = Utilities.MakeRandomFriendlyName ();
            options.PostalCode = "65801";
            options.Region = "MO";
            options.Street = "742 Evergreen Terrace";

            client.UpdateAddress(ADDRESS_SID, options, address => {
                manualResetEvent.Set();
            });
            manualResetEvent.WaitOne(1);

            mockClient.Verify(trc => trc.ExecuteAsync<Address>(It.IsAny<IRestRequest>(), It.IsAny<Action<Address>>()), Times.Once);
            Assert.IsNotNull(savedRequest);
            Assert.AreEqual("Accounts/{AccountSid}/Addresses/{AddressSid}.json", savedRequest.Resource);
            Assert.AreEqual(Method.POST, savedRequest.Method);
            Assert.AreEqual(7, savedRequest.Parameters.Count);
            var addressSidParam = savedRequest.Parameters.Find(x => x.Name == "AddressSid");
            Assert.IsNotNull(addressSidParam);
            Assert.AreEqual(ADDRESS_SID, addressSidParam.Value);
            var cityParam = savedRequest.Parameters.Find(x => x.Name == "City");
            Assert.IsNotNull(cityParam);
            Assert.AreEqual(options.City, cityParam.Value);
            var customerNameParam = savedRequest.Parameters.Find(x => x.Name == "CustomerName");
            Assert.IsNotNull(customerNameParam);
            Assert.AreEqual(options.CustomerName, customerNameParam.Value);
            var friendlyNameParam = savedRequest.Parameters.Find(x => x.Name == "FriendlyName");
            Assert.IsNotNull(friendlyNameParam);
            Assert.AreEqual(options.FriendlyName, friendlyNameParam.Value);
            var postalCodeParam = savedRequest.Parameters.Find(x => x.Name == "PostalCode");
            Assert.IsNotNull(postalCodeParam);
            Assert.AreEqual(options.PostalCode, postalCodeParam.Value);
            var regionParam = savedRequest.Parameters.Find(x => x.Name == "Region");
            Assert.IsNotNull(regionParam);
            Assert.AreEqual(options.Region, regionParam.Value);
            var streetParam = savedRequest.Parameters.Find(x => x.Name == "Street");
            Assert.IsNotNull(streetParam);
            Assert.AreEqual(options.Street, streetParam.Value);
        }
Example #33
0
        private void ValidateCreateAccountModel(ref CreateAccountViewModel model)
        {
            CreateAccountCacheItem createAccountCacheItem = GetCachedCreateAccountAttempt(true);

            if (!String.IsNullOrEmpty(createAccountCacheItem.CaptchaText))
            {
                if (!createAccountCacheItem.CaptchaText.Equals(model.CaptchaText))
                {
                    ModelState.AddModelError(String.Empty, Languages.LanguageStrings.CodeNotValid);
                }
            }

            createAccountCacheItem.CreateAttempts++;

            if (createAccountCacheItem.CreateAttempts > 10)
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.TooManyAttempts);
            }

            AddressOptions addressOptions = _accountProvider.GetAddressOptions(AddressOption.Billing);

            if (!ValidatePasswordComplexity(model.Password))
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.PasswordComplexityFailed);
            }

            if (!model.Password.Equals(model.ConfirmPassword))
            {
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.PasswordDoesNotMatch);
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine1Mandatory) && String.IsNullOrEmpty(model.AddressLine1))
            {
                ModelState.AddModelError(nameof(model.AddressLine1), Languages.LanguageStrings.AddressLine1Required);
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine2Mandatory) && String.IsNullOrEmpty(model.AddressLine2))
            {
                ModelState.AddModelError(nameof(model.AddressLine2), Languages.LanguageStrings.AddressLine2Required);
            }

            if (addressOptions.HasFlag(AddressOptions.AddressLine3Mandatory) && String.IsNullOrEmpty(model.AddressLine3))
            {
                ModelState.AddModelError(nameof(model.AddressLine3), Languages.LanguageStrings.AddressLine3Required);
            }

            if (addressOptions.HasFlag(AddressOptions.CityMandatory) && String.IsNullOrEmpty(model.City))
            {
                ModelState.AddModelError(nameof(model.City), Languages.LanguageStrings.CityRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.CountyMandatory) && String.IsNullOrEmpty(model.County))
            {
                ModelState.AddModelError(nameof(model.County), Languages.LanguageStrings.CountyRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.PostCodeMandatory) && String.IsNullOrEmpty(model.Postcode))
            {
                ModelState.AddModelError(nameof(model.Postcode), Languages.LanguageStrings.PostcodeRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.BusinessNameMandatory) && String.IsNullOrEmpty(model.BusinessName))
            {
                ModelState.AddModelError(nameof(model.BusinessName), Languages.LanguageStrings.BusinessNameRequired);
            }

            if (addressOptions.HasFlag(AddressOptions.TelephoneMandatory) && String.IsNullOrEmpty(model.Telephone))
            {
                ModelState.AddModelError(nameof(model.Telephone), Languages.LanguageStrings.TelephoneRequired);
            }

            createAccountCacheItem.CaptchaText = GetRandomWord(6, CaptchaCharacters);
            model.CaptchaText = String.Empty;
        }