Пример #1
0
        public void Doit()
        {
            var c = new Customer
                        {
                            CustomerId = 3,
                            FirstName = "fn",
                            SecondName = "sn",
                            CustomerCountries =
                                new[] { new CustomerCountry { CountryId = 1 }, new CustomerCountry { CountryId = 2 } }
                        };

            var countries = new[]
                                {
                                    new Country {CountryId = 1, Name = "Moldova"},
                                    new Country {CountryId = 2, Name = "Japan"}
                                };

            var d = new CustomerDto();
            d.InjectFrom(c);
            Assert.AreEqual(c.CustomerId, d.CustomerId);
            Assert.AreEqual(c.FirstName, d.FirstName);
            Assert.AreEqual(c.SecondName, d.SecondName);

            d.InjectFrom(new My(countries), c);

            Assert.AreEqual(c.CustomerCountries.Count(), d.Countries.Count());
            Assert.AreEqual(countries.First().Name, d.Countries.First().Name);
        }
        public bool Savecustomer(CustomerDto customer)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                conn.Open();
                var query = "insert into pc_customers(firstname,lastname,address,city,state,country,phoneno,carddetails,username,password) values(@firstname,@lastname,@address,@city,@state,@country,@phoneno,@carddetails,@username,@password)";
                // var query = "insert into pc_customers(firstname,lastname,address,city,state,country,phoneno,carddetails,username,password) values(@firstname,@lastname,@address,@city,@state,@country,@phoneno,@carddetails,@username,@password)";
                //SqlCommand comm = new SqlCommand(query, conn);
                //comm.Parameters.AddWithValue("@firstname", customer.Firstname);
                //comm.Parameters.AddWithValue("@lastname", customer.Lastname);
                //comm.Parameters.AddWithValue("@address", customer.Address);
                //comm.Parameters.AddWithValue("@city", customer.City);
                //comm.Parameters.AddWithValue("@state", customer.State);
                //comm.Parameters.AddWithValue("@country", customer.Country);
                //comm.Parameters.AddWithValue("@phoneno", customer.Phoneno);
                //comm.Parameters.AddWithValue("@carddetails", customer.Carddetails);
                //comm.Parameters.AddWithValue("@username", customer.Username);
                //comm.Parameters.AddWithValue("@password", customer.Password);
                var result = conn.Query<CustomerDto>(query,customer);

                if (result != null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
Пример #3
0
 public NewUser(string username, string password, string repeatedPassword, CustomerDto customer)
 {
     this.username = username;
     this.password = password;
     this.repeatedPassword = repeatedPassword;
     this.customer = customer;
 }
Пример #4
0
        internal CustomerDto MapTo(Customer source, CustomerDto target)
        {
            target.Id = source.Id;
            target.FirstName = source.FirstName;
            target.LastName = source.LastName;

            return target;
        }
Пример #5
0
 public CustomerViewModel(CustomerDto customerDto)
 {
     CustomerId = customerDto.CustomerId;
     _firstName = customerDto.FirstName;
     _lastName = customerDto.LastName;
     _originalValue = (CustomerViewModel)MemberwiseClone();
     _orderServiceManager = ServiceProvider.Instance.Get<IOrderServiceManager>();
     _customerServiceManager = ServiceProvider.Instance.Get<ICustomerServiceManager>();
 }
Пример #6
0
        public CustomerDto GetCustomer(string sessionKey, string customerId)
        {
            CustomerDto retVal = new CustomerDto();

             long id = 0;
             long.TryParse(customerId, out id);
             retVal.Id = id;
             retVal.Name = "Rush Inuit";

             return retVal;
        }
Пример #7
0
        private string Authorize(string enteredLogin, string enteredPassword)
        {
            var customerDto = new CustomerDto()
            {
                Login = enteredLogin,
                Password = enteredPassword
            };

            RegistrationRequest request = new RegistrationRequest()
            {
                NewCustomerData = customerDto
            };

            return client.RegisterNewCustomer(request).Message;
        }
Пример #8
0
        public void Example()
        {
            Mapper.CreateMap<Person, CustomerDto>()
                .ForMember(dest => dest.Name,
                           opt => opt.MapFrom(src => String.Format("{0} {1}", src.FirstName, src.LastName)));
            Mapper.CreateMap<Customer, CustomerDto>();

            var person = new Person {FirstName = "John", Id = 1, LastName = "Smith"};
            var customer = new Customer {Language = "English", LoyaltyNumber = 1};
            var expected = new CustomerDto {Name = "John Smith", Language = "English"};
            //Chain together mappings to create an aggregate mapped object
            var actual = Mapper.Map(customer, Mapper.Map<Person, CustomerDto>(person));

            actual.Name.ShouldEqual(expected.Name);
            actual.Language.ShouldEqual(expected.Language);
        }
        public CustomerDto Create()
        {
            //CREATE THE DTO
              CustomerDto dto = new CustomerDto() { Id = Guid.NewGuid(), Name = Properties.Resources.DefaultCustomerName };

              //INSERT INTO THE DB
              var connStr = Properties.Resources.ConnectionString;
              #region Odbc Connection Learning Process/NOTES
              //connStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=HireMe;User Id=;Password=;";  //can't find datasource
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMe;Uid=User;Pwd=;"; //better, now login failed
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMe;Uid=User;";//try without pwd=.....
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMe;Trusted_Connection=yes;";//nope...try trusted connection.
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMe;Trusted_Connection=yes;";//nope...try trusted connection.
              //connStr = @"Data Source=C:\Users\User\Documents\Visual Studio 2010\Projects\HireMe\HireMe.WcfService\HireMe.DataAccess.OdbcProvider\HireMe.sdf";
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\Users\User\Documents\Visual Studio 2010\Projects\HireMe\HireMe.WcfService\HireMe.DataAccess.OdbcProvider\DataSource\HireMeDatabase.mdf"";Integrated Security=True;User Instance=True";
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;AttachDbFilename=""C:\Users\User\Documents\Visual Studio 2010\Projects\HireMe\HireMe.WcfService\HireMe.DataAccess.OdbcProvider\DataSource\HireMeDatabase.mdf"";Integrated Security=True;User Instance=True";
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMeDatabase;C:\Users\User\Documents\Visual Studio 2010\Projects\HireMe\HireMe.WcfService\HireMe.DataAccess.OdbcProvider\DataSource\HireMeDatabase.mdf"";Integrated Security=True;User Instance=True";
              //connStr = @"Driver={SQL Server};Server=.\SQLEXPRESS;Database=HireMeDatabase.mdf;Integrated Security=True;User Instance=True";
              //connStr = @"FILEDSN=C:\Users\User\Documents\Visual Studio 2010\Projects\HireMe\HireMe.WcfService\HireMe.DataAccess.OdbcProvider\DataSource\HireMeOdbc.dsn;";
              //connStr = @"DSN=HireMeOdbc; Trusted_Connection=yes;Database=HireMe;AttachDbFilename=""C:\HireMe\HireMe.DataSource\HireMe.DataSource\HireMe.mdf""";
              //connStr = @"DSN=HireMeOdbc; Trusted_Connection=yes;"; //does work, so good enough!
              //connStr = @"FILEDSN=C:\HireMe\OdbcDataSource\HireMeOdbc.dsn; Trusted_Connection=yes;";
              //The lessons here are:
              //The AttachDbFilename has to be in a location where the sql server can access it.
              //TODO: Need to test if you can copy mdf file to other location than where it was created.  It seems like this should be possible.
              //Trusted_Connection=yes indicates no user/pass
              //Driver,Server,Database can be included in the DSN config.
              //In DSN config, you must set both the Name to the database name, and the path to the attached file (where it can be accessed).
              //If you even come close to modifying the mdf file, you will have to reconfig the dsn file.
              #endregion
              using (OdbcConnection connection = new OdbcConnection(connStr))
              {
            connection.Open();
            string queryStr = string.Format(@"INSERT INTO {0} " +
                                        @"({1}, {2}, {3}) " +
                                        @"VALUES('{4}','{5}', '{6}');",
                                        Properties.Resources.CustomerTable,
                                        Properties.Resources.CustomerIdColumn, Properties.Resources.NameColumn, Properties.Resources.EmailAddressColumn,
                                        dto.Id, dto.Name, dto.EmailAddress);
            var cmd = connection.CreateCommand();
            cmd.CommandText = queryStr;
            var numRowsAffected = cmd.ExecuteNonQuery();
              }

              //RETURN OUR INSERTED DTO
              return dto;
        }
Пример #10
0
        public static void DirectMapping()
        {
            var customer = new Customer
              {
            ID = 1,
            FirstName = "First",
            LastName = "Last",
            Orders = new List<Order>
            {
              new Order
              {
            ID = 1,
            Amount = 10,
              },
              new Order
              {
            ID = 2,
            Amount = 20
              }
            }
              };

              var mapper = new MemberMapper();

              // Explicit source and destination type, just pass a source type instance
              var dto = mapper.Map<Customer, CustomerDto>(customer);

              // Just specify what ThisMember should map to, pass in any type that you think can be mapped
              dto = mapper.Map<CustomerDto>(customer);

              // Update the existing Customer, just set a new FirstName for him
              dto = new CustomerDto
              {
            FirstName = "NewName"
              };

              // For that we have to set an option that null-values from the source are ignored, so that LastName does not get set to null
              mapper.Options.Conventions.IgnoreMembersWithNullValueOnSource = true;

              // Setting an option that affects map generation has no effect on maps that have already been generated. Normally there'd be little
              // need to set this option on the fly, you would just have a seperate mapper for doing these mappings. But for this sample, it works fine.
              mapper.ClearMapCache(); // We could also have called mapper.CreateMap<CustomerDto, Customer>(), which always recreates the map.

              // Only FirstName will have changed now on customer, because the null (or null-equivalent in case of nullable value types) values were ignored.
              mapper.Map(dto, customer);
        }
 public ActionResult Create(FormCollection form)
 {
     CustomerDto customer = new CustomerDto();
     customer.Address = form["address"];
     customer.Carddetails = form["carddetais"];
     customer.City = form["city"];
     customer.Country = form["country"];
     customer.Firstname = form["firstname"];
     customer.Lastname = form["lastname"];
     customer.Phoneno = form["phonenumber"];
     customer.State = form["state"];
     customer.Username = form["username"];
     customer.Password = form["password"];
     CustomerServices cs = new CustomerServices();
     cs.Savecustomer(customer);
     return View();
 }
Пример #12
0
        public void TestLoadAccounts()
        {
            //Given
            CustomerViewModel vm = new CustomerViewModel();
            WCFAccountService accountService = _mocks.StrictMock<WCFAccountService>();

            vm.AccountService = accountService;

            //create the individualcustomer
            CustomerDto customer = new CustomerDto() { Id = 1 };
            vm.Customer = customer;

            //When
            vm.LoadAccounts();

            //Then
            Assert.IsTrue(vm.InProgress);
        }
Пример #13
0
 public void UpdateCustomer(CustomerDto customerDto)
 {
     CustomerServiceClient customerServiceClient = new CustomerServiceClient();
     try
     {
         customerServiceClient.UpdateCustomer(new UpdateCustomerRequest
                                                  {
                                                      CustomerDto = customerDto
                                                  });
     }
     catch (Exception exception)
     {
         string message = string.Format("An error occured while in type :{0} , method :{1} ", "CustomerServiceManager", MethodBase.GetCurrentMethod().Name);
         CommonLogManager.Log.Error(message, exception);
         throw;
     }
     finally
     {
         customerServiceClient.Close();
     }
 }
 ///<summary>
 /// Converts Customer DTO to Customer
 /// <remarks>
 /// The fields IsEviivoAgreementAccepted, IsProviderAgreementAccepted, IsOtherAgreementAccepted
 /// are being set here as a default for the mobile app. They will only be persisted during the customer 
 /// creation through the mobile app. During the update through the mobile app those three fields will be 
 /// ignored and whichever changes made on them won't be reflected.
 /// </remarks>
 ///</summary>
 ///<param name="customerDto">Customer DTO</param>
 ///<returns>Converted Customer</returns>
 public static Customer ConvertCustomerDtoToCustomer(CustomerDto customerDto)
 {
     return new Customer
                {
                    Id = customerDto.Id,
                    BusinessId = customerDto.BusinessId,
                    ContactNumber1 = customerDto.ContactNumber1,
                    ContactNumber2 = customerDto.ContactNumber2,
                    Email = customerDto.Email,
                    Forename = customerDto.Forename,
                    Notes = customerDto.Notes,
                    AddressLine1 = customerDto.AddressLine1,
                    AddressLine2 = customerDto.AddressLine2,
                    AddressLine3 = customerDto.AddressLine3,
                    City = customerDto.City,
                    StateProvinceId = customerDto.StateProvinceId,
                    PostCode = customerDto.PostCode,
                    CountryId = customerDto.CountryId,
                    Surname = customerDto.Surname,
                    TitleId = customerDto.TitleId,
                    IsEviivoAgreementAccepted = true,
                    IsProviderAgreementAccepted = true,
                    IsOtherAgreementAccepted = false
                };
 }
 public bool SaveCustomer(CustomerDto customer)
 {
     var response = _customerServices.Savecustomer(customer);
     return response;
 }
Пример #16
0
 public void Update(CustomerDto customer)
 {
     _customerRepository.Update(customer.Id, _mapper.Map <Customer>(customer));
     _customerRepository.SaveChanges();
 }
        public async Task Insert_GetAll_Update_GetByCityCode_Should_Return_Expected_Result(string postUrl, string getUrl)
        {
            #region Insert
            var expectedResult     = string.Empty;
            var expectedStatusCode = HttpStatusCode.OK;

            // Arrange-1
            var request = new CustomerDto
            {
                FullName  = "Caner Tosuner",
                CityCode  = "Ist",
                BirthDate = new DateTime(1990, 1, 1)
            };
            var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");

            _client.DefaultRequestHeaders.Add("audity-user", "admin-abraham lincoln");
            // Act-1
            var response = await _client.PostAsync(postUrl, content);

            var actualStatusCode = response.StatusCode;
            var actualResult     = await response.Content.ReadAsStringAsync();

            // Assert-1
            Assert.Equal(expectedResult, actualResult);
            Assert.Equal(expectedStatusCode, actualStatusCode);
            #endregion



            #region GetAll
            // Act-2
            var responseGet = await _client.GetAsync(getUrl);

            responseGet.EnsureSuccessStatusCode();

            var actualGetResult = await responseGet.Content.ReadAsStringAsync();

            var getResultList = JsonConvert.DeserializeObject <List <CustomerDto> >(actualGetResult);

            var insertedCustomerExist = getResultList.Any(c => c.CityCode == request.CityCode);

            // Assert-2
            Assert.NotEmpty(getResultList);
            Assert.True(insertedCustomerExist);
            Assert.Equal("admin-abraham lincoln", getResultList.Single(c => c.CityCode == request.CityCode).CreatedBy);
            #endregion



            #region Update
            // Arrange-3
            var insertedCustomer = getResultList.Single(c => c.CityCode == request.CityCode);
            var requestUpdate    = new CustomerDto
            {
                FullName  = "Ali Tosuner",
                CityCode  = "Ist",
                BirthDate = new DateTime(1994, 1, 1),
                Id        = insertedCustomer.Id
            };
            var contentUpdate = new StringContent(JsonConvert.SerializeObject(requestUpdate), Encoding.UTF8, "application/json");
            _client.DefaultRequestHeaders.Clear();
            _client.DefaultRequestHeaders.Add("audity-user", "super-admin nicola tesla");

            // Act-3
            var responseUpdate = await _client.PutAsync(postUrl, contentUpdate);

            responseUpdate.EnsureSuccessStatusCode();
            var updateActualResult = await responseUpdate.Content.ReadAsStringAsync();

            var obj = await JsonConvert.DeserializeObjectAsync <CustomerDto>(updateActualResult);

            // Assert-3
            Assert.Equal(obj.FullName, requestUpdate.FullName);
            Assert.Equal("super-admin nicola tesla", obj.ModifiedBy);
            #endregion



            #region GetByCityCode
            // Act-2
            var responseGetByCityCode = await _client.GetAsync("/api/customer/getbycitycode/" + requestUpdate.CityCode);

            responseGetByCityCode.EnsureSuccessStatusCode();

            var actualGetByCityCodeResult = await responseGetByCityCode.Content.ReadAsStringAsync();

            var getByCityCodeResultList = JsonConvert.DeserializeObject <List <CustomerDto> >(actualGetByCityCodeResult);

            var updatedCustomerExist = getByCityCodeResultList.Any(c => c.CityCode == request.CityCode);

            // Assert-2
            Assert.NotEmpty(getByCityCodeResultList);
            Assert.True(updatedCustomerExist);
            Assert.Equal("super-admin nicola tesla", getByCityCodeResultList.Single(c => c.CityCode == request.CityCode).ModifiedBy);
            #endregion
        }
        public static void CreateDummyData(DbContext context, bool execute = false)
        {
            if (!execute)
            {
                return;
            }

            using (context)
            {
                for (int i = 0; i < 8; i++)
                {
                    var country = new CountryDto()
                    {
                        Name = $"Sri Lanka {i}",
                    };
                    var ethnicity = new EthnicityDto()
                    {
                        Name = "Zoroastrian",
                    };
                    var watchBrand = new WatchBrandDto()
                    {
                        Name = "Panerai",
                    };

                    var hiking = new SpecificActivityDto()
                    {
                        Name = "Hiking"
                    };
                    var cycling = new SpecificActivityDto()
                    {
                        Name = "Cycling"
                    };
                    var jerking = new SpecificActivityDto()
                    {
                        Name = "Jerking"
                    };

                    var activity = new ActivityDto()
                    {
                        Activities = new List <SpecificActivityDto>()
                        {
                            hiking, cycling, jerking,
                        },
                    };
                    var customer = new CustomerDto()
                    {
                        BirthDate      = DateTime.Now.AddYears(-54 + i),
                        CustomerNumber = $"HY398{i}K07K",
                        Tags           = new List <TagDto>()
                        {
                            ethnicity, country, watchBrand, activity
                        }
                    };

                    context.Entry(ethnicity).State = EntityState.Added;
                    context.Entry(country).State   = EntityState.Added;

                    context.Entry(activity).State = EntityState.Added;

                    context.Entry(hiking).State  = EntityState.Added;
                    context.Entry(cycling).State = EntityState.Added;
                    context.Entry(jerking).State = EntityState.Added;

                    context.Entry(watchBrand).State = EntityState.Added;
                    context.Entry(customer).State   = EntityState.Added;
                }

                context.SaveChanges();
            }
        }
Пример #19
0
        /// <summary>
        /// GetFakeCustomerAccountDto - returns fake CustomerAccountDto object
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="subscriberID"></param>
        /// <param name="fakeBillingAccountIdDto"></param>
        /// <param name="fakeCustomerAccountIdDto"></param>
        /// <returns></returns>
        public CustomerAccountDto GetFakeCustomerAccountDto(string firstName, string lastName, string subscriberID, BillingAccountIdDto fakeBillingAccountIdDto, CustomerAccountIdDto fakeCustomerAccountIdDto)
        {
            var fakeIndividualName = new IndividualNameDto()
            {
                GivenNames = firstName,
                FamilyNames = lastName
            };

            var fakeIndividualDto = new IndividualDto()
            {
                IndividualName = fakeIndividualName
            };

            var fakeCustomerDto = new CustomerDto()
            {
                Individual = fakeIndividualDto
            };

            var fakeCustomerAccountDto = new CustomerAccountDto()
            {
                AccountID = subscriberID,
                BillingAccountId = fakeBillingAccountIdDto,
                CustomerAccountId = fakeCustomerAccountIdDto,
                Customer = fakeCustomerDto
            };

            return fakeCustomerAccountDto;
        }
Пример #20
0
            public void ModifyBookingWithMisMatchBusinessThrowsException()
            {
                // Arrange
                const long BUSINESS_ID = 2;
                const long MISMATCHED_BUSINESS_ID = 5;

                // Stub the BusinessCache to have the businesses to be used by our service method
                CacheHelper.StubBusinessCacheMultipleBusiness(new List<long> { MISMATCHED_BUSINESS_ID, BUSINESS_ID });

                // invalidate the cache so we make sure both our businesses are loaded into the cache
                Cache.Business.Invalidate();

                //Set up a customer for the booking
                var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" };

                var bookingDto = new BookingDto
                {
                    BusinessId = BUSINESS_ID,
                    StartDateUTC = DateTime.Now,
                    EndDateUTC = DateTime.Now.AddDays(1),
                    Customer = customer,
                    RoomId = 1
                };

                try
                {
                    // Act
                    limitedMobileService.ModifyBooking(MISMATCHED_BUSINESS_ID, false, bookingDto);

                    // Assert
                    Assert.Fail("An exception SRVEX30000 of type ValidationException should have been thrown");
                }
                catch (ValidationException ex)
                {
                    // Assert
                    Assert.AreEqual("SRVEX30000", ex.Code, "The Validation exception is not returning the right error code");
                }
                finally
                {
                    // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method
                    CacheHelper.ReAssignBusinessDaoToBusinessCache();

                }
            }
Пример #21
0
 public static Customer ToEntity(this CustomerDto model)
 {
     return(model.MapTo <CustomerDto, Customer>());
 }
 public record Request(CustomerDto Customer) : IRequest <Response>;
Пример #23
0
        public void CreateCustomer(CustomerDto customerDto)
        {
            var customer = customerDto.MappingCustomer();

            customerRepository.Add(customer);
        }
        public CustomerDto GetCustomerById(int id, bool showDeleted = false)
        {
            if (id == 0)
            {
                return(null);
            }

            // Here we expect to get two records, one for the first name and one for the last name.
            var customerAttributeMappings = (from customer in _customerRepository.Table          //NoTracking
                                             join attribute in _genericAttributeRepository.Table //NoTracking
                                             on customer.Id equals attribute.EntityId
                                             where customer.Id == id &&
                                             attribute.KeyGroup == "Customer"
                                             select new CustomerAttributeMappingDto
            {
                Attribute = attribute,
                Customer = customer
            }).ToList();

            CustomerDto customerDto = null;

            // This is in case we have first and last names set for the customer.
            if (customerAttributeMappings.Count > 0)
            {
                var customer = customerAttributeMappings.First().Customer;
                // The customer object is the same in all mappings.
                customerDto = customer.ToDto();

                var defaultStoreLanguageId = GetDefaultStoreLangaugeId();

                // If there is no Language Id generic attribute create one with the default language id.
                if (!customerAttributeMappings.Any(cam => cam?.Attribute != null &&
                                                   cam.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase)))
                {
                    var languageId = new GenericAttribute
                    {
                        Key   = LanguageId,
                        Value = defaultStoreLanguageId.ToString()
                    };

                    var customerAttributeMappingDto = new CustomerAttributeMappingDto
                    {
                        Customer  = customer,
                        Attribute = languageId
                    };

                    customerAttributeMappings.Add(customerAttributeMappingDto);
                }

                foreach (var mapping in customerAttributeMappings)
                {
                    if (!showDeleted && mapping.Customer.Deleted)
                    {
                        continue;
                    }

                    if (mapping.Attribute != null)
                    {
                        if (mapping.Attribute.Key.Equals(FirstName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.FirstName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LastName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LastName = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(LanguageId, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.LanguageId = mapping.Attribute.Value;
                        }
                        else if (mapping.Attribute.Key.Equals(DateOfBirth, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.DateOfBirth = string.IsNullOrEmpty(mapping.Attribute.Value)
                                                          ? (DateTime?)null
                                                          : DateTime.Parse(mapping.Attribute.Value);
                        }
                        else if (mapping.Attribute.Key.Equals(Gender, StringComparison.InvariantCultureIgnoreCase))
                        {
                            customerDto.Gender = mapping.Attribute.Value;
                        }
                    }
                }
            }
            else
            {
                // This is when we do not have first and last name set.
                var currentCustomer = _customerRepository.Table.FirstOrDefault(customer => customer.Id == id);

                if (currentCustomer != null)
                {
                    if (showDeleted || !currentCustomer.Deleted)
                    {
                        customerDto = currentCustomer.ToDto();
                    }
                }
            }

            SetNewsletterSubscribtionStatus(customerDto);

            return(customerDto);
        }
Пример #25
0
 public CustomerModel(CustomerDto customerDto)
 {
     Id    = customerDto.Id;
     Name  = customerDto.Name;
     Email = customerDto.Email;
 }
Пример #26
0
 public static async Task DeleteCustomerAddress(AddressDto address, CustomerDto customer)
 {
     await customer.DeleteAddress(address.Id).GetValueAsync();
 }
Пример #27
0
 public static async Task AssignAddressToCustomer(AddressDto address, CustomerDto customer)
 {
     await customer.AddAddress("", address.City, address.Email, address.Company, address.Address1, address.Address2, address.LastName,
                               address.CountryId, address.FaxNumber, address.FirstName, address.VatNumber, address.PhoneNumber,
                               address.CustomAttributes, address.CreatedOnUtc, address.ZipPostalCode, address.StateProvinceId).GetValueAsync();
 }
Пример #28
0
        public void Index_ProvisioningLocation_withAddresses_withRateCenter_withNetworkLocCode()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                // service account
                var serviceAccount = new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI",
                };
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => serviceAccount;

                // Expected provisioning locaton
                var provLocation = new LocationDto
                {
                    ID = "12345666666444",
                    AddressLine1 = "ADDRESS1",
                    AddressLine2 = "ADDRESS2",
                    CityName = "CITY",
                    StateName = "STATE WA",
                    ZipCode = "12345",
                    HeadendCode = "01",
                    NetworkLocationCode = "1234567",
                    RateCenterName = "123456",
                };

                // CurrentSubscriber location
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => provLocation.ID;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => provLocation.AddressLine1;
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => provLocation.AddressLine2;
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => provLocation.CityName;
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => provLocation.StateName;
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => provLocation.ZipCode;
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => provLocation.HeadendCode;
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => provLocation.RateCenterName;
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet =
                    (myTestParam) => provLocation.NetworkLocationCode;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                // account controller
                var accountsController = DependencyResolver.Current.GetService<AccountsController>();

                // call Index action method
                var result = accountsController.Index();

                // results is no null
                Assert.IsNotNull(result);

                var accountTuple = (AccountTuple) result.Model;

                // validate billing info
                Assert.IsTrue(accountTuple.BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(accountTuple.BillingAccount.TN.Equals("TestBillingNumber"));

                // validate service address
                Assert.AreEqual(serviceAccount.Address.Address1, accountTuple.ServiceAccount.Addresses.ServiceAddress.AddressLine1, "Service Address1 does not match");
                Assert.IsTrue(accountTuple.ServiceAccount.TN.Equals("TestServiceNumber"));

                // validate provisioning location;
                var actualProvLocaton = accountTuple.ServiceAccount.Addresses.ProvisioningAddress.Location;
                Assert.AreEqual(provLocation.ID, actualProvLocaton.LocationID, "Location ID does not match");
                Assert.AreEqual(provLocation.AddressLine1, actualProvLocaton.Address1, "Address1 does not match");
                Assert.AreEqual(provLocation.AddressLine2, actualProvLocaton.Address2, "Address2 does not match");
                Assert.AreEqual(provLocation.HeadendCode, actualProvLocaton.Headend, "Headend does not match");
                Assert.AreEqual(provLocation.CityName, actualProvLocaton.City, "City does not match");
                Assert.AreEqual(provLocation.StateName, actualProvLocaton.State, "State does not match");
                Assert.AreEqual(provLocation.RateCenterName, actualProvLocaton.RateCenter, "RateCenter does not match");
                Assert.AreEqual(provLocation.NetworkLocationCode, actualProvLocaton.NetworkLocationCode, "NetworkLocationCode does not match");
            }
        }
Пример #29
0
            public void ModifyBookingWithExpectedResult()
            {
                // Arrange
                const long BUSINESS_ID = 1;

                //Set up a customer for the booking
                var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" };
                
                var bookingDto = new BookingDto
                {
                    BusinessId = BUSINESS_ID,
                    StartDateUTC = DateTime.Now,
                    EndDateUTC = DateTime.Now.AddDays(1),
                    Customer = customer,
                    RoomId = 1
                };

                var stubBookingManager = MockRepository.GenerateMock<IBookingManager>();
                
                limitedMobileService.BookingManager = stubBookingManager;

                stubBookingManager.Expect(c => c.ModifyBooking(Arg<bool>.Is.Equal(false), Arg<Booking>.Is.Anything)).Return(true);

                // Stub the BusinessCache to be used by our service method
                CacheHelper.StubBusinessCacheSingleBusiness(BUSINESS_ID);

                // invalidate the cache so we make sure our business is loaded into the cache
                Cache.Business.Invalidate();

                // Act
                bool modifyBookingResult = limitedMobileService.ModifyBooking(BUSINESS_ID, false, bookingDto);

                // Assert
                Assert.IsTrue(modifyBookingResult, "booking was not modified successfully");
                stubBookingManager.VerifyAllExpectations();

                // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method
                CacheHelper.ReAssignBusinessDaoToBusinessCache();
            }
Пример #30
0
 public static Customer ToEntity(this CustomerDto model, Customer destination)
 {
     return(model.MapTo(destination));
 }
Пример #31
0
            public void EditCustomerWithInvalidBusinessThrowsException()
            {
                // Arrange
                // business that we know will never exist in the cache
                const long INVALID_BUSINESS = -100;

                var customerDto = new CustomerDto
                {
                    Id = 1,
                    BusinessId = INVALID_BUSINESS,
                    Surname = "Test",
                    Email = "*****@*****.**"
                };

                try
                {
                    // Act
                    limitedMobileService.EditCustomer(INVALID_BUSINESS, customerDto);

                    // Assert
                    Assert.Fail("An exception SRVEX30001 of type ValidationException should have been thrown");
                }
                catch (ValidationException ex)
                {
                    // Assert
                    Assert.AreEqual("SRVEX30001", ex.Code, "The Validation exception is not returning the right error code");
                }
            }
Пример #32
0
 public CustomerViewModel(CustomerDto dto) : this()
 {
     Customer = dto;
 }
Пример #33
0
        public static void Benchmark()
        {
            var mapper = new MemberMapper();

              var map = mapper.CreateAndFinalizeMap<Customer, CustomerDto>(customMapping: src => new
              {
            FullName = src.FirstName + " " + src.LastName,
            OrderCount = src.Orders.Count,
            OrderAmount = src.Orders.Sum(o => o.Amount)
              });

              var mappingFunc = map.MappingFunction;

              var customer = new Customer
              {
            CustomerID = 1,
            FirstName = "John",
            LastName = "Doe",
            Orders = new List<Order>
            {
              new Order
              {
            Amount = 100m
              },
              new Order
              {
            Amount = 15m
              },
              new Order
              {
            Amount = 150m
              }
            }
              };

              var sw = Stopwatch.StartNew();

              for (var i = 0; i < 1000000; i++)
              {
            Dto = new CustomerDto();

            Dto.FirstName = customer.FirstName;
            Dto.LastName = customer.LastName;
            Dto.FullName = customer.FirstName + " " + customer.LastName;
            Dto.OrderCount = customer.Orders.Count;
            Dto.OrderAmount = customer.Orders.Sum(o => o.Amount);
              }

              sw.Stop();

              Console.WriteLine("Manual: " + sw.Elapsed);

              sw.Restart();

              for (var i = 0; i < 1000000; i++)
              {
            Dto = mapper.Map<Customer, CustomerDto>(customer);
              }

              sw.Stop();

              Console.WriteLine("ThisMember slow: " + sw.Elapsed);

              sw.Restart();

              for (var i = 0; i < 1000000; i++)
              {
            Dto = mappingFunc(customer, new CustomerDto());
              }

              sw.Stop();

              Console.WriteLine("ThisMember fast: " + sw.Elapsed);
        }
Пример #34
0
 public CustomerDto CreateCustomer(CustomerDto dto)
 {
     return(new CustomerLogic().Create(dto));
 }
Пример #35
0
 public CustomerDto InsertCustomer(CustomerDto customer)
 {
     return(_customersApplicationService.InsertCustomer(customer));
 }
Пример #36
0
 public CustomerDto SaveCustomer(CustomerDto dto)
 {
     return(new CustomerLogic().Save(dto));
 }
Пример #37
0
 public void Create(CustomerDto customer)
 {
     _customerRepository.Create(_mapper.Map <Customer>(customer));
     _customerRepository.SaveChanges();
 }
Пример #38
0
 public CustomerDto InsertCustomer(CustomerDto customer) => null;
Пример #39
0
        private void UpdateCustomer(CustomerDto customerDto)
        {
            var customerInDb = _context.Customers.First(c => c.Id == customerDto.Id);

            Mapper.Map(customerDto, customerInDb);
        }
Пример #40
0
 public CustomerDto UpdateCustomer(CustomerDto customer) => null;
Пример #41
0
        private static void Registration()
        {
            Console.WriteLine("Podaj Login:"******"Podaj Hasło:");
            string password = Console.ReadLine();
            var customerDto = new CustomerDto()
                {
                    Login = login,
                    Password = password
                };

            RegistrationRequest request = new RegistrationRequest()
                {
                    NewCustomerData = customerDto
                };

            Console.WriteLine(client.RegisterNewCustomer(request).Message);
        }
Пример #42
0
 public void DeleteCustomer(CustomerDto customer)
 {
 }
Пример #43
0
        public void Index_HasAddressConflict_True()
        {
            using (ShimsContext.Create())
            {

                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                const string subId = "123456789";
                const string headend = "04";
                const string locId = "123456789";
                var address1 = "2345 TEST ADDRESS1";
                var address2 = "APT 2";
                var city = "REDMOND";
                var state = "WA";
                var zip = "98052";

                // Service Address
                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto
                    {
                        Address1 = address1,
                        Address2 = address2,
                        Locality = city,
                        StateOrProvince = state,
                        Postcode = zip
                    },
                };

                // Provisioning Service Address
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => headend;
                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => locId;
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => subId;
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => address1 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.Address2Get = (myTestParam) => address2 + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.CityGet = (myTestParam) => city + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => state + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => zip + " DIFFERENT";
                ShimCurrentSubscriber.AllInstances.RateCenterGet = (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsNotNull(result);

                // Validate the HasAddressConflict flag
                var hasAddressConflict = ((AccountTuple) result.Model).ServiceAccount.Addresses.ProvisioningAddress.Location.HasAddressConflict;
                Assert.IsTrue(hasAddressConflict, "HasAddressConflict should be false");
            }
        }
        public IList<CustomerDto> GetAll()
        {
            List<CustomerDto> allDtos = new List<CustomerDto>();

              var connStr = Properties.Resources.ConnectionString;
              using (OdbcConnection connection = new OdbcConnection(connStr))
              {
            connection.Open();
            string queryStr = string.Format(@"SELECT * " +
                                        @"FROM {0}",
                                        Properties.Resources.CustomerTable);

            OdbcCommand cmd = new OdbcCommand(queryStr, connection);

            var reader = cmd.ExecuteReader();
            while (reader.Read())
            {
              var dto = new CustomerDto();
              dto.Id = reader.GetGuid(reader.GetOrdinal(Properties.Resources.CustomerIdColumn));
              dto.Name = reader.GetString(reader.GetOrdinal(Properties.Resources.NameColumn));
              dto.EmailAddress = reader.GetString(reader.GetOrdinal(Properties.Resources.EmailAddressColumn));
              allDtos.Add(dto);
            }
              }

              return allDtos;
        }
Пример #45
0
        public void Index_HappyPath()
        {
            using (ShimsContext.Create())
            {
                // Fake the session state for HttpContext
                var session = new ShimHttpSessionState
                {
                    ItemGetString = s =>
                    {
                        if (s == "")
                            return null;
                        return null;
                    }
                };

                // Fake the HttpContext
                var context = new ShimHttpContext();
                ShimHttpContext.CurrentGet = () => context;

                // When the Fake HttpContext is called, provide the fake session state
                ShimHttpContext.AllInstances.SessionGet = (o) => session;
                var customer = new CustomerDto();
                customer.CitizensPostalAddress.AddressTexts.Add(new AddressTextDto() { Address = "TestBillingAddress", SequenceNumber = 0 });
                var billingAccountId = new BillingAccountIdDto();
                billingAccountId.PhoneNumberAsId.TelephoneNumber.Number = "TestBillingNumber";
                ShimCurrentSubscriber.AllInstances.CurrentBillingAccountGet = (myTest) => new CustomerAccountDto()
                {

                    Customer = customer,
                    BillingAccountId = billingAccountId

                };

                ShimCurrentSubscriber.AllInstances.CurrentServiceAccountGet = (myTest) => new ServiceAccountDto
                {
                    Address = new ServiceAddressDto{ Address1 = "TestServiceAddress"},
                    IsBTN = false,
                    SubscriberName = "TestServiceName",
                    TN = "TestServiceNumber",
                    USI = "TestServiceUSI"
                };

                ShimCurrentSubscriber.AllInstances.LocationIdGet = (myTestParam) => "123456789";
                ShimCurrentSubscriber.AllInstances.AddressGet = (myTestParam) => "TestAddressLine1";
                ShimCurrentSubscriber.AllInstances.Address2Get= (myTestParam) => "TestAddressLine2";
                ShimCurrentSubscriber.AllInstances.CityGet= (myTestParam) => "TestCity";
                ShimCurrentSubscriber.AllInstances.StateGet = (myTestParam) => "TestState";
                ShimCurrentSubscriber.AllInstances.ZipGet = (myTestParam) => "TestZip";
                ShimCurrentSubscriber.AllInstances.HeadendCodeGet = (myTestParam) => "TestHeadend";
                ShimCurrentSubscriber.AllInstances.RateCenterGet= (myTestParam) => "TestRateCenter";
                ShimCurrentSubscriber.AllInstances.NetworkLocationCodeGet = (myTestParam) => "TestNetworkCode";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";
                ShimCurrentSubscriber.AllInstances.SubIdGet = (myTestParam) => "TestSub";

                var accountsController = DependencyResolver.Current.GetService<AccountsController>();
                var result = accountsController.Index();
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.Address.AddressLine1.Equals("TestBillingAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).BillingAccount.TN.Equals("TestBillingNumber"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.Addresses.ServiceAddress.AddressLine1.Equals("TestServiceAddress"));
                Assert.IsTrue(((AccountTuple)result.Model).ServiceAccount.TN.Equals("TestServiceNumber"));

            }
        }
Пример #46
0
        public CustomerDto GetCustomerInforTurnOut(string ticketId)
        {
            using (SqlConnection connection = new SqlConnection(Config.ConnectionString))
            {
                try
                {
                    connection.Open();
                    SqlCommand cmd =
                        new SqlCommand("usp_get_customer_infor", connection)
                    {
                        CommandType = CommandType.StoredProcedure
                    };
                    cmd.Parameters.Add(new SqlParameter("@ticketId", ticketId));
                    cmd.Parameters.Add(new SqlParameter("@mode", true));
                    var returnParam = cmd.Parameters.Add("@count", SqlDbType.Int);
                    returnParam.Direction = ParameterDirection.ReturnValue;


                    cmd.ExecuteNonQuery();
                    int result = (int)returnParam.Value;

                    if (result == 1)
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            CustomerDto customer = new CustomerDto()
                            {
                                LicensePlate = (reader["BKS"] == DBNull.Value) ? "" : (string)reader["BKS"],
                                VehicleType  = (int)reader["LoaiXe"],
                                AreaID       = (int)reader["KhuVuc"],
                                Fee          = new PriceDto()
                                {
                                    ID = (int)reader["MaMP"], Price = (decimal)reader["MucPhi"]
                                }
                            };
                            return(customer);
                        }
                    }

                    if (result == 2)
                    {
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            reader.Read();
                            CustomerDto customer = new CustomerDto()
                            {
                                LicensePlate = (reader["BKS"] == DBNull.Value) ? "" : (string)reader["BKS"],
                                Name         = (string)reader["TenKH"],
                                IDCard       = (string)reader["CMND"],
                                PhoneNumber  = (string)reader["SDT"],
                                Block        = (string)reader["ToaNha"],
                                VehicleType  = (int)reader["MaLoai"],
                                AreaID       = (int)reader["MaKhu"]
                            };

                            reader.NextResult();
                            reader.Read();
                            customer.Status = (bool)reader["TrangThai"];

                            reader.NextResult();
                            reader.Read();
                            customer.Fee = new PriceDto()
                            {
                                ID = (int)reader["MaMP"], Price = (decimal)reader["MucPhi"]
                            };
                            return(customer);
                        }
                    }

                    return(null);
                }
                catch (Exception e)
                {
                    return(null);
                }
            }
        }
Пример #47
0
            public void ModifyBookingWithInvalidBusinessThrowsException()
            {
                // Arrange
                const long BUSINESS_ID = 123456;

                //Set up a customer for the booking
                var customer = new CustomerDto { Id = 23, BusinessId = BUSINESS_ID, Surname = "Doe" };

                var bookingDto = new BookingDto
                {
                    BusinessId = BUSINESS_ID,
                    StartDateUTC = DateTime.Now,
                    EndDateUTC = DateTime.Now.AddDays(1),
                    Customer = customer,
                    RoomId = 1
                };

                try
                {
                    // Act
                    limitedMobileService.ModifyBooking(BUSINESS_ID, false, bookingDto);

                    // Assert
                    Assert.Fail("An exception SRVEX30001 of type ValidationException should have been thrown");
                }
                catch (ValidationException ex)
                {
                    // Assert
                    Assert.AreEqual("SRVEX30001", ex.Code, "The Validation exception is not returning the right error code");
                }
            }
Пример #48
0
 public CustomerController(CustomerDto db)
 {
     this.context = db;
     // context= HttpContext.RequestServices.GetService(typeof(DemoContext)) as DemoContext;
 }
Пример #49
0
            public void EditCustomerWithExpectedResult()
            {
                // Arrange
                const long BUSINESS_ID = 1;

                var customerDto = new CustomerDto
                {
                    Id = 1,
                    BusinessId = BUSINESS_ID,
                    Surname = "Test",
                    Email = "*****@*****.**"
                };

                var stubCustomerManager = MockRepository.GenerateMock<ICustomerManager>();
                limitedMobileService.CustomerManager = stubCustomerManager;

                stubCustomerManager.Expect(c => c.ModifyLimited(Arg<Customer>.Is.Anything));

                // Stub the BusinessCache to be used by our service method
                CacheHelper.StubBusinessCacheSingleBusiness(BUSINESS_ID);

                // invalidate the cache so we make sure our business is loaded into the cache
                Cache.Business.Invalidate();

                // Act
                limitedMobileService.EditCustomer(BUSINESS_ID, customerDto);

                // Assert
                stubCustomerManager.VerifyAllExpectations();

                // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method
                CacheHelper.ReAssignBusinessDaoToBusinessCache();
            }
Пример #50
0
        /// <summary>
        /// Genera el json en la solapa resultado a partir de los datos ingresados en el resto de las solapas.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GenerarJson_Click(object sender, EventArgs e)
        {
            OrderDto orderDto = new OrderDto();

            try
            {
                orderDto.CancelOrder = Convert.ToBoolean(principalCancelOrder.Text.ToLower());
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

            CustomerDto customerDto = new CustomerDto();

            customerDto.Apartment       = customerApartment.Text;
            customerDto.BusinessAddress = customerBusinessAddress.Text;
            customerDto.BusinessName    = customerBusinessName.Text;
            customerDto.City            = customerCity.Text;
            customerDto.Comments        = customerComments.Text;
            try
            {
                customerDto.CustomerID = Convert.ToInt64(customerCustomerID.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

            customerDto.DocumentNumber    = customerDocumentNumber.Text;
            customerDto.DocumentType      = customerDocumentType.Text;
            customerDto.Email             = customerEmail.Text;
            customerDto.FirstName         = customerFirstName.Text;
            customerDto.Floor             = customerFloor.Text;
            customerDto.HouseNumber       = customerHouseNumber.Text;
            customerDto.IVACategoryCode   = customerIVACategoryCode.Text;
            customerDto.LastName          = customerLastName.Text;
            customerDto.MobilePhoneNumber = customerMobilePhoneNumber.Text;
            customerDto.PhoneNumber1      = customerPhoneNumber1.Text;
            customerDto.PhoneNumber2      = customerPhoneNumber2.Text;
            customerDto.PostalCode        = customerPostalCode.Text;
            customerDto.ProvinceCode      = customerProvinceCode.Text;
            customerDto.Street            = customerStreet.Text;
            customerDto.User = customerUser.Text;

            orderDto.Customer = customerDto;
            try
            {
                orderDto.Date               = Convert.ToDateTime(principalDate.Text);
                orderDto.PaidTotal          = Convert.ToDecimal(principalPaidTotal.Text);
                orderDto.FinancialSurcharge = Convert.ToDecimal(principalFinancialSurcharge.Text);
                orderDto.WarehouseCode      = Convert.ToString(principalWarehouseCode.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

            orderDto.OrderID     = principalOrderID.Text;
            orderDto.OrderItems  = ListaOrderItems;
            orderDto.OrderNumber = principalOrderNumber.Text;
            orderDto.Payments    = ListaPayments;
            orderDto.ValidateTotalWithPaidTotal = checkValidateTotalWithPaidTotal.Checked;

            CashPaymentDto cashPayment = new CashPaymentDto();

            try
            {
                cashPayment.PaymentTotal = Convert.ToDecimal(cashPaymentTotal.Text);
                cashPayment.PaymentID    = Convert.ToInt64(cashPaymentId.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            cashPayment.PaymentMethod = cashPaymentMethod.Text;

            if (checkGenerarCashPayment.Checked)
            {
                orderDto.CashPayment = cashPayment;
            }

            ShippingDto shipping = new ShippingDto();

            shipping.Apartment         = shippingApartment.Text;
            shipping.City              = shippingCity.Text;
            shipping.DeliversMonday    = shippingDeliversMonday.Text;
            shipping.DeliversTuesday   = shippingDeliversTuesday.Text;
            shipping.DeliversWednesday = shippingDeliversWednesday.Text;
            shipping.DeliversThursday  = shippingDeliversThursday.Text;
            shipping.DeliversFriday    = shippingDeliversFriday.Text;
            shipping.DeliversSaturday  = shippingDeliversSaturday.Text;
            shipping.DeliversSunday    = shippingDeliversSunday.Text;
            shipping.DeliveryHours     = shippingDeliveryHours.Text;
            shipping.Floor             = shippingFloor.Text;
            shipping.HouseNumber       = shippingHouseNumber.Text;
            shipping.PhoneNumber1      = shippingPhoneNumber1.Text;
            shipping.PhoneNumber2      = shippingPhoneNumber2.Text;
            shipping.PostalCode        = shippingPostalCode.Text;
            shipping.ProvinceCode      = shippingProvinceCode.Text;
            shipping.Street            = shippingStreet.Text;

            shipping.ShippingCost = 0;
            if (!String.IsNullOrWhiteSpace(shippingShippingCost.Text))
            {
                shipping.ShippingCost = Convert.ToDecimal(shippingShippingCost.Text);
            }

            shipping.ShippingID = 0;
            if (!String.IsNullOrWhiteSpace(shippingShippingID.Text))
            {
                shipping.ShippingID = Convert.ToInt64(shippingShippingID.Text);
            }

            if (checkGenerarShipping.Checked)
            {
                orderDto.Shipping = shipping;
            }

            try
            {
                orderDto.Total         = Convert.ToDecimal(principalTotal.Text);
                orderDto.TotalDiscount = Convert.ToDecimal(principalTotalDiscount.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }

            string json = JsonConvert.SerializeObject(orderDto, Formatting.Indented);

            resultadoSerializado.Text = json;
            tabControl1.SelectTab("tabResultado");
        }
Пример #51
0
            public void EditCustomerWithMismatchBusinessThrowsException()
            {
                // Arrange
                const long MISMATCHED_BUSINESS_ID = 5;

                // Stub the BusinessCache to be used by our service method
                CacheHelper.StubBusinessCacheSingleBusiness(MISMATCHED_BUSINESS_ID);

                // invalidate the cache so we make sure our business is loaded into the cache
                Cache.Business.Invalidate();

                var customerDto = new CustomerDto
                {
                    Id = 1,
                    BusinessId = 2,
                    Surname = "Test",
                    Email = "*****@*****.**"
                };

                try
                {
                    // Act
                    limitedMobileService.EditCustomer(MISMATCHED_BUSINESS_ID, customerDto);

                    // Assert
                    Assert.Fail("An exception SRVEX30000 of type ValidationException should have been thrown");
                }
                catch (ValidationException ex)
                {
                    // Assert
                    Assert.AreEqual("SRVEX30000", ex.Code, "The Validation exception is not returning the right error code");
                }
                finally
                {
                    // Reassign the Dao on the cache to discard the stub assigned on the StubBusinessCacheSingleBusiness method
                    CacheHelper.ReAssignBusinessDaoToBusinessCache();
                }
            }
Пример #52
0
 // POST: api/Customer
 public void Post([FromBody] CustomerDto model)
 {
     _customerService.Create(model);
 }
Пример #53
0
 // PUT: api/Customer/5
 public void Put(int id, [FromBody] CustomerDto model)
 {
     _customerService.Update(model);
 }
Пример #54
0
 public Customer FromCustomerDtoToCustomer(CustomerDto customerDto)
 {
     return(_mapper.Map <CustomerDto, Customer>(customerDto));
 }
 public CustomerDto CreateNewCustomer(CustomerDto dto)
 {
     return(ExecuteCommand(locator => CreateNewCustomerCommand(locator, dto)));
 }
Пример #56
0
 public static void Merge(this Customer entity, CustomerDto dto)
 {
     entity.FirstName = dto.FirstName;
     entity.LastName  = dto.LastName;
     entity.Updated   = DateTime.UtcNow;
 }
        public CustomerDto Update(CustomerDto dto)
        {
            var connStr = Properties.Resources.ConnectionString;
              using (OdbcConnection connection = new OdbcConnection(connStr))
              {
            connection.Open();
            string queryStr = string.Format(@"UPDATE {0} " +               //Update Customers table
                                        @"SET {1} = '{2}', " +          //Set Name = dto.Name
                                            @"{3} = '{4}' " +          //Set EmailAddress = dto.EmailAddress
                                        @"WHERE {5} = '{6}'",          //Where Id = 'id'
                                        Properties.Resources.CustomerTable,
                                        Properties.Resources.NameColumn, dto.Name,
                                        Properties.Resources.EmailAddressColumn, dto.EmailAddress,
                                        Properties.Resources.CustomerIdColumn, dto.Id.ToString());

            OdbcCommand cmd = new OdbcCommand(queryStr, connection);

            var numRowsAffected = cmd.ExecuteNonQuery();
              }

              return dto;
        }
        private CustomerDto CreateNewCustomerCommand(IRepositoryLocator locator, CustomerDto dto)
        {
            var customer = Customer.Create(locator, dto);

            return(Customer_to_Dto(customer));
        }
        public CustomerDto Get(Guid id)
        {
            CustomerDto dto = new CustomerDto();
              var connStr = Properties.Resources.ConnectionString;
              using (OdbcConnection connection = new OdbcConnection(connStr))
              {
            connection.Open();
            string queryStr = string.Format(@"SELECT * " +
                                        @"FROM {0} " +
                                        @"WHERE {1} = '{2}'",
                                        Properties.Resources.CustomerTable,
                                        Properties.Resources.CustomerIdColumn, id.ToString());

            OdbcCommand cmd = new OdbcCommand(queryStr, connection);

            var reader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleResult);
            if (reader.Read())
            {
              dto.Id = reader.GetGuid(reader.GetOrdinal(Properties.Resources.CustomerIdColumn));
              dto.Name = reader.GetString(reader.GetOrdinal(Properties.Resources.NameColumn));
              dto.EmailAddress = reader.GetString(reader.GetOrdinal(Properties.Resources.EmailAddressColumn));
            }
            else
              throw new CustomerDataException();
              }

              return dto;
        }
 public CustomerDto UpdateCustomer(CustomerDto dto)
 {
     return(ExecuteCommand(locator => UpdateCustomerCommand(locator, dto)));
 }