// accepts new customer object
 public void AddCustomer(CustomerEntity customer)
 {
     customer.CustomerId = (int)(from b in customerData.Descendants("customer") orderby (int)b.Element("id") descending select (int)b.Element("id")).FirstOrDefault() + 1;
     customerData.Root.Add(new XElement("customer", new XElement("id", customer.CustomerId),
                             new XElement("name", customer.CustomerName),
                             new XElement("address", customer.CustomerAddress)));
     customerData.Save(filePath);
 }
        // accepts modified customer object
        public void EditCustomer(CustomerEntity customer)
        {
            XElement customerExisting = customerData.Root.Elements("customer").Where(i => (int)i.Element("id") == customer.CustomerId).FirstOrDefault();

            customerExisting.SetElementValue("name", customer.CustomerName);
            customerExisting.SetElementValue("address", customer.CustomerAddress);

            customerData.Save(filePath);
        }
Exemplo n.º 3
0
 private Customer Map(CustomerEntity entity)
 {
     var model = new Customer
     {
         Id = entity.Id,
         DisplayName = entity.DisplayName
     };
     return model;
 }
        public void StoreData()
        {
            var storage = new AzureTableStorageProvider();

            const string tableName = "people";
            storage.CreateTable(tableName);

            // Create a new customer entity
            var customer1 = new CustomerEntity("Harp", "Walter")
                                {
                                    Email = "*****@*****.**",
                                    PhoneNumber = "425-555-0101"
                                };

            // Add the new customer to the people table
            storage.AddObject(tableName, customer1);

            // Commit the operation to the table service
            storage.Commit();

            //storage.GetObject();
        }
        static void Main(string[] args)
        {
            // Retrieve the storage account from the connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=aayazokulu;AccountKey=vcGOIzfmMjrj+lEBE+MADWNHYlR8MyFHChD2/0OSqmWDUzvaYt1G1CIBz9BhM9azTxftEH4KalvUpbgwn1IF8w==");

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference("people");

            // Create a new customer entity.
            CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
            customer1.Email = "*****@*****.**";
            customer1.PhoneNumber = "425-555-0101";

            // Create the TableOperation that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(customer1);

            // Execute the insert operation.
            table.Execute(insertOperation);
        }
Exemplo n.º 6
0
        public static bool InsertEntityToAzureTable(string tableName, CustomerEntity entity)
        {
            System.Diagnostics.Trace.TraceInformation(string.Format("Date = {0}, AzureTableOperation.InsertEntityToAzureTable is Called", DateTime.Now));
            // Retrieve the storage account from the connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(GetStorageConnectionString());

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            // Create the CloudTable object that represents the "people" table.
            CloudTable table = tableClient.GetTableReference(tableName);

            // Create the TableOperation object that inserts the customer entity.
            TableOperation insertOperation = TableOperation.Insert(entity);

            // Execute the insert operation.
            TableResult result = table.Execute(insertOperation);
            System.Diagnostics.Trace.TraceInformation(string.Format("Date = {0}, AzureTableOperation.InsertEntityToAzureTable insert entity to {1}: {2}", DateTime.Now, tableName, result.ToString()));

            //TODO: how to determine whether the operation is successful
            return true;
        }
 public CustomerRegisteredEvent(CustomerEntity entity, float initialCredit)
 {
     Customer      = entity;
     InitialCredit = initialCredit;
 }
Exemplo n.º 8
0
 public async Task Save(CustomerEntity customer)
 {
     await Task.Run(() => _customerDatabase.InsertOne(customer));
 }
Exemplo n.º 9
0
 public static CustomerModel CTM(this CustomerEntity source) => new CustomerModel
 {
     Address = new AddressModel()
 };
Exemplo n.º 10
0
 public CustomerGroupLinkEntity(CustomerEntity customer, GroupEntity group)
 {
     Customer = customer;
     Group    = group;
 }
 private void selectButton_Click(object sender, System.EventArgs e)
 {
     _cancelClicked    = false;
     _selectedCustomer = (CustomerEntity)_allCustomers[customersDataGrid.CurrentRowIndex];
     this.Close();
 }
Exemplo n.º 12
0
		/// <summary>Konvertira entitet u business object.</summary>
		protected Customer(CustomerEntity entity)
			: base(entity)
		{
		}
Exemplo n.º 13
0
 private void NewItem()
 {
     current = CustomerEntity.Empty;
     ShowItem(current);
 }
        /// <summary>
        /// Delete an entity
        /// </summary>
        /// <param name="table">Sample table name</param>
        /// <param name="deleteEntity">Entity to delete</param>
        /// <returns>A Task object</returns>
        private static async Task DeleteEntityAsync(CloudTable table, CustomerEntity deleteEntity)
        {
            try
            {
                if (deleteEntity == null)
                {
                    throw new ArgumentNullException("deleteEntity");
                }

                TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
                await table.ExecuteAsync(deleteOperation);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
        /// <summary>
        /// The Table Service supports two main types of insert operations. 
        ///  1. Insert - insert a new entity. If an entity already exists with the same PK + RK an exception will be thrown.
        ///  2. Replace - replace an existing entity. Replace an existing entity with a new entity. 
        ///  3. Insert or Replace - insert the entity if the entity does not exist, or if the entity exists, replace the existing one.
        ///  4. Insert or Merge - insert the entity if the entity does not exist or, if the entity exists, merges the provided entity properties with the already existing ones.
        /// </summary>
        /// <param name="table">The sample table name</param>
        /// <param name="entity">The entity to insert or merge</param>
        /// <returns>A Task object</returns>
        private static async Task<CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
                CustomerEntity insertedCustomer = result.Result as CustomerEntity;

                return insertedCustomer;
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
        /// <summary>
        /// Demonstrates basic CRUD operations using a SAS for authentication.
        /// </summary>
        /// <param name="table">The table.</param>
        /// <returns>A Task object</returns>
        private static async Task BasicDataOperationsWithSasAsync(CloudTable table)
        {
            string sharedAccessPolicyName = "sample-policy-" + DateTime.Now.Ticks.ToString();

            // Create a shared access policy on the table.
            // The access policy may be optionally used to provide constraints for
            // shared access signatures on the table.
            await CreateSharedAccessPolicy(table, sharedAccessPolicyName);

            // Generate an ad-hoc SAS on the table, then test the SAS. It permits all CRUD operations on the table.
            string adHocTableSAS = GetTableSasUri(table);

            // Create an instance of a customer entity.
            CustomerEntity customer1 = new CustomerEntity("Johnson", "Mary")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0105"
            };
            await TestTableSAS(adHocTableSAS, customer1);

            // Generate a SAS URI for the table, using the stored access policy to set constraints on the SAS.
            // Then test the SAS. All CRUD operations should succeed.
            string sharedPolicyTableSAS = GetTableSasUri(table, sharedAccessPolicyName);
            
            // Create an instance of a customer entity.
            CustomerEntity customer2 = new CustomerEntity("Wilson", "Joe")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0106"
            };
            await TestTableSAS(sharedPolicyTableSAS, customer2);
        }
        /// <summary>
        /// Demonstrate basic Table CRUD operations.
        /// </summary>
        /// <param name="table">The sample table</param>
        /// <returns>A Task object</returns>
        private static async Task BasicDataOperationsAsync(CloudTable table)
        {
            // Create an instance of a customer entity. See the Model\CustomerEntity.cs for a description of the entity.
            CustomerEntity customer = new CustomerEntity("Harp", "Walter")
            {
                Email = "*****@*****.**",
                PhoneNumber = "425-555-0101"
            };

            // Demonstrate how to Update the entity by changing the phone number
            Console.WriteLine("2. Update an existing Entity using the InsertOrMerge Upsert Operation.");
            customer.PhoneNumber = "425-555-0105";
            customer = await InsertOrMergeEntityAsync(table, customer);
            Console.WriteLine();

            // Demonstrate how to Read the updated entity using a point query 
            Console.WriteLine("3. Reading the updated Entity.");
            customer = await RetrieveEntityUsingPointQueryAsync(table, "Harp", "Walter");
            Console.WriteLine();

            // Demonstrate how to Delete an entity
            Console.WriteLine("4. Delete the entity. ");
            await DeleteEntityAsync(table, customer);
            Console.WriteLine();
        }
Exemplo n.º 18
0
 public void update(CustomerEntity customerEntity)
 {
     _customerDataSource.update(customerEntity);
 }
Exemplo n.º 19
0
 public void save(CustomerEntity customerEntity)
 {
     _customerDataSource.save(customerEntity);
 }
Exemplo n.º 20
0
 public void Update(CustomerEntity entity)
 {
     repository.Update(entity);
 }
Exemplo n.º 21
0
        public static void Initialize(Context context)
        {
            context.Database.EnsureCreated();
            HostContentPath = $"{Environment.CurrentDirectory}\\Images";
            if (!context.Customers.Any())
            {
                var customers = new CustomerEntity[]
                {
                    new CustomerEntity {
                        Name    = "Иван Иванов",
                        Address = "Проспект Мира д.24",
                        Code    = "0000-2021",
                        Account = new AccountEntity
                        {
                            Email    = "*****@*****.**",
                            Password = "******",
                            Role     = Role.Admin
                        }
                    },
                    new CustomerEntity {
                        Name    = "Вячеслав Петров",
                        Address = "ул. Академика Янгеля д.5",
                        Code    = "0001-2021",
                        Account = new AccountEntity
                        {
                            Email    = "*****@*****.**",
                            Password = "******",
                            Role     = Role.User
                        },
                        Discount = 10
                    },
                    new CustomerEntity
                    {
                        Name    = "Александр Ветров",
                        Address = "ул. Планерная д.31",
                        Code    = "0002-2021",
                        Account = new AccountEntity
                        {
                            Email    = "*****@*****.**",
                            Password = "******",
                            Role     = Role.User
                        },
                        Discount = 10
                    }
                };
                context.Customers.AddRange(customers);
                context.SaveChanges();
            }

            if (!context.Products.Any())
            {
                var products = new ProductEntity[]
                {
                    new ProductEntity {
                        Name = "Молоко", Category = "молочная продукция", Price = 60, ImgPath = $"{HostContentPath}\\milkProducts\\milk.jpg"
                    },
                    new ProductEntity {
                        Name = "Творог", Category = "молочная продукция", Price = 90, ImgPath = $"{HostContentPath}\\milkProducts\\cottageCheese.jpg"
                    },
                    new ProductEntity {
                        Name = "Сметана", Category = "молочная продукция", Price = 78, ImgPath = $"{HostContentPath}\\milkProducts\\sourCream.jpg"
                    },
                    new ProductEntity {
                        Name = "Йогурт", Category = "молочная продукция", Price = 97, ImgPath = $"{HostContentPath}\\milkProducts\\yogurt.jpg"
                    },
                    new ProductEntity {
                        Name = "Масло", Category = "молочная продукция", Price = 110, ImgPath = $"{HostContentPath}\\milkProducts\\butter.jpg"
                    },
                    new ProductEntity {
                        Name = "Чизкэйк", Category = "молочная продукция", Price = 250, ImgPath = $"{HostContentPath}\\milkProducts\\cheeseCacke.jpg"
                    },

                    new ProductEntity {
                        Name = "Хлеб", Category = "хлебная продукция", Price = 50, ImgPath = $"{HostContentPath}\\breadProducts\\bread.jpg"
                    },
                    new ProductEntity {
                        Name = "Булочка с маком", Category = "хлебная продукция", Price = 63, ImgPath = $"{HostContentPath}\\breadProducts\\bun.jpg"
                    },
                    new ProductEntity {
                        Name = "Чиабата", Category = "хлебная продукция", Price = 102, ImgPath = $"{HostContentPath}\\breadProducts\\ciabatta.jpg"
                    },
                    new ProductEntity {
                        Name = "Батон", Category = "хлебная продукция", Price = 57, ImgPath = $"{HostContentPath}\\breadProducts\\loaf.jpg"
                    },
                    new ProductEntity {
                        Name = "Батон нарезной", Category = "хлебная продукция", Price = 60, ImgPath = $"{HostContentPath}\\breadProducts\\slicedLoaf.jpg"
                    },
                    new ProductEntity {
                        Name = "Кулич", Category = "хлебная продукция", Price = 220, ImgPath = $"{HostContentPath}\\breadProducts\\kulich.jpg"
                    },

                    new ProductEntity {
                        Name = "Банан", Category = "фрукты", Price = 61, ImgPath = $"{HostContentPath}\\fruits\\banana.jpg"
                    },
                    new ProductEntity {
                        Name = "Ананас", Category = "фрукты", Price = 150, ImgPath = $"{HostContentPath}\\fruits\\pineapple.jpg"
                    },
                    new ProductEntity {
                        Name = "Киви", Category = "фрукты", Price = 130, ImgPath = $"{HostContentPath}\\fruits\\qiwi.jpg"
                    },
                    new ProductEntity {
                        Name = "Яблоко", Category = "фрукты", Price = 78, ImgPath = $"{HostContentPath}\\fruits\\apple.jpg"
                    },
                    new ProductEntity {
                        Name = "Груша", Category = "фрукты", Price = 115, ImgPath = $"{HostContentPath}\\fruits\\pear.jpg"
                    },
                    new ProductEntity {
                        Name = "Виноград", Category = "фрукты", Price = 190, ImgPath = $"{HostContentPath}\\fruits\\grapes.jpg"
                    },

                    new ProductEntity {
                        Name = "Картофель", Category = "овощи", Price = 20, ImgPath = $"{HostContentPath}\\vegetables\\potato.jpg"
                    },
                    new ProductEntity {
                        Name = "Лук", Category = "овощи", Price = 15, ImgPath = $"{HostContentPath}\\vegetables\\onion.jpg"
                    },
                    new ProductEntity {
                        Name = "Морковь", Category = "овощи", Price = 18, ImgPath = $"{HostContentPath}\\vegetables\\carrot.jpg"
                    },
                    new ProductEntity {
                        Name = "Огурец", Category = "овощи", Price = 41, ImgPath = $"{HostContentPath}\\vegetables\\cucumber.jpg"
                    },
                    new ProductEntity {
                        Name = "Перец болгарский", Category = "овощи", Price = 68, ImgPath = $"{HostContentPath}\\vegetables\\bolgarPepper.jpg"
                    },
                    new ProductEntity {
                        Name = "Капута", Category = "овощи", Price = 22, ImgPath = $"{HostContentPath}\\vegetables\\cabbage.jpg"
                    },

                    new ProductEntity {
                        Name = "Спагети", Category = "макаронные изделия", Price = 30, ImgPath = $"{HostContentPath}\\pastaProducts\\spagetti.jpg"
                    },
                    new ProductEntity {
                        Name = "Рожки", Category = "макаронные изделия", Price = 31, ImgPath = $"{HostContentPath}\\pastaProducts\\macaroni-2.jpg"
                    },
                    new ProductEntity {
                        Name = "Вермишель", Category = "макаронные изделия", Price = 45, ImgPath = $"{HostContentPath}\\pastaProducts\\vermicelli.jpg"
                    },
                    new ProductEntity {
                        Name = "Лапша домашняя", Category = "макаронные изделия", Price = 60, ImgPath = $"{HostContentPath}\\pastaProducts\\homeNoodles.jpg"
                    },
                    new ProductEntity {
                        Name = "Ролтон", Category = "макаронные изделия", Price = 11, ImgPath = $"{HostContentPath}\\pastaProducts\\macaroni-3.jpg"
                    },
                    new ProductEntity {
                        Name = "Перья", Category = "макаронные изделия", Price = 34, ImgPath = $"{HostContentPath}\\pastaProducts\\macaroni-1.jpg"
                    },

                    new ProductEntity {
                        Name = "Мыло", Category = "бытовая химия", Price = 37, ImgPath = $"{HostContentPath}\\householdChemicals\\soap.jpg"
                    },
                    new ProductEntity {
                        Name = "Гель для посуды", Category = "бытовая химия", Price = 98, ImgPath = $"{HostContentPath}\\householdChemicals\\dishesGel.jpg"
                    },
                    new ProductEntity {
                        Name = "Порошок стиральный", Category = "бытовая химия", Price = 115, ImgPath = $"{HostContentPath}\\householdChemicals\\miss.jpg"
                    },
                    new ProductEntity {
                        Name = "Порошок чистящий", Category = "бытовая химия", Price = 42, ImgPath = $"{HostContentPath}\\householdChemicals\\miss-2.jpg"
                    },
                    new ProductEntity {
                        Name = "Шампунь", Category = "бытовая химия", Price = 113, ImgPath = $"{HostContentPath}\\householdChemicals\\shampoo.jpg"
                    },
                    new ProductEntity {
                        Name = "кондиционер для белья", Category = "бытовая химия", Price = 118, ImgPath = $"{HostContentPath}\\householdChemicals\\linenconditioner.jpg"
                    },
                };
                context.Products.AddRange(products);
                context.SaveChanges();
            }
        }
Exemplo n.º 22
0
 public void Add(CustomerEntity entity)
 {
     repository.Add(entity);
 }
        /// <summary>
        /// Tests a table SAS to determine which operations it allows.
        /// </summary>
        /// <param name="sasUri">A string containing a URI with a SAS appended.</param>
        /// <param name="customer">The customer entity.</param>
        /// <returns>A Task object</returns>
        private static async Task TestTableSAS(string sasUri, CustomerEntity customer)
        {
            // Try performing table operations with the SAS provided.
            // Note that the storage account credentials are not required here; the SAS provides the necessary
            // authentication information on the URI.

            // Return a reference to the table using the SAS URI.
            CloudTable table = new CloudTable(new Uri(sasUri));

            // Upsert (add/update) operations: insert an entity.
            // This operation requires both add and update permissions on the SAS.
            try
            {
                // Insert the new entity.
                customer = await InsertOrMergeEntityAsync(table, customer);

                Console.WriteLine("Add operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Add operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Read operation: query an entity.
            // This operation requires read permissions on the SAS.
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(customer.PartitionKey, customer.RowKey);
                TableResult result = await table.ExecuteAsync(retrieveOperation);
                CustomerEntity customerRead = result.Result as CustomerEntity;
                if (customerRead != null)
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", customerRead.PartitionKey, customerRead.RowKey, customerRead.Email, customerRead.PhoneNumber);
                }

                Console.WriteLine("Read operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Read operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            // Delete operation: delete an entity.
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(customer.PartitionKey, customer.RowKey);
                TableResult result = await table.ExecuteAsync(retrieveOperation);
                CustomerEntity customerDelete = result.Result as CustomerEntity;
                if (customerDelete != null)
                {
                    await DeleteEntityAsync(table, customerDelete);
                }

                Console.WriteLine("Delete operation succeeded for SAS {0}", sasUri);
                Console.WriteLine();
            }
            catch (StorageException e)
            {
                if (e.RequestInformation.HttpStatusCode == 403)
                {
                    Console.WriteLine("Delete operation failed for SAS {0}", sasUri);
                    Console.WriteLine("Additional error information: " + e.Message);
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                    throw;
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 24
0
        public bool InsertEntityToAzureTable(string tableName, CustomerEntity entity)
        {
            System.Diagnostics.Trace.TraceInformation(string.Format("WebRoleService.InsertEntityToAzureTable is called."));

            //validation
            if (tableName.Trim() == "")
            {
                System.Diagnostics.Trace.TraceError(string.Format("Error: Table name is empty when call InsertEntityToAzureTable"));
                return false;
            }

            //call worker
            bool response = false;
            try
            {
                IWorkerService myClient = GetClient();
                response = myClient.InsertEntityToAzureTable(tableName, entity);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.TraceError(string.Format("Error in WebRoleService.InsertEntityToAzureTable: {0}", ex.Message));
            }

            return response;
        }
Exemplo n.º 25
0
        /// <summary>
        /// The Table Service supports two main types of insert operations.
        ///  1. Insert - insert a new entity. If an entity already exists with the same PK + RK an exception will be thrown.
        ///  2. Replace - replace an existing entity. Replace an existing entity with a new entity.
        ///  3. Insert or Replace - insert the entity if the entity does not exist, or if the entity exists, replace the existing one.
        ///  4. Insert or Merge - insert the entity if the entity does not exist or, if the entity exists, merges the provided entity properties with the already existing ones.
        /// </summary>
        /// <param name="table">The sample table name</param>
        /// <param name="entity">The entity to insert or merge</param>
        /// <returns></returns>
        private static async Task <CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // Create the InsertOrReplace  TableOperation
            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

            // Execute the operation.
            TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

            CustomerEntity insertedCustomer = result.Result as CustomerEntity;

            return(insertedCustomer);
        }
 public ActionResult SaveForm(string keyValue, CustomerEntity entity)
 {
     customerbll.SaveForm(keyValue, entity);
     return(Success("操作成功。"));
 }
 private void selectButton_Click(object sender, System.EventArgs e)
 {
     this.DialogResult = System.Windows.Forms.DialogResult.OK;
     _selectedCustomer = (CustomerEntity)_allCustomers[customersDataGrid.CurrentRowIndex];
     this.Close();
 }
Exemplo n.º 28
0
        /// <summary>
        /// Performs simple validation and setting property values so on any changes
        /// they are updated immediately.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _customerView_ListChanged(object sender, ListChangedEventArgs e)
        {
            if (e.PropertyDescriptor != null)
            {
                //
                // Get current customer in current DataGridView row
                //
                CustomerEntity currentCustomer = _customerView.CurrentCustomer(_customerBindingSource.Position);
                Console.WriteLine($" -> {e.ListChangedType.ToString()}");
                //
                // Assert if there are changes to the current row in the DataGridView
                //
                if (e.ListChangedType == ListChangedType.ItemChanged)
                {
                    //
                    // Get data residing in the database table
                    //
                    Customers customerItem = CustomersTestOperations
                                             .Context
                                             .Customers
                                             .FirstOrDefault((customer) => customer.CustomerIdentifier == currentCustomer.CustomerIdentifier);

                    if (customerItem != null)
                    {
                        /*
                         * Did contact first or last name change?
                         * If so we need to update the contact.
                         */
                        if (e.PropertyDescriptor.DisplayName == "FirstName" || e.PropertyDescriptor.DisplayName == "LastName")
                        {
                            customerItem.Contact.FirstName = currentCustomer.FirstName;
                            customerItem.Contact.LastName  = currentCustomer.LastName;
                        }

                        var test1 = currentCustomer.CompanyName;

                        EntityEntry <Customers> customerEntry = CustomersTestOperations.Context.Entry(customerItem);
                        customerEntry.CurrentValues.SetValues(currentCustomer);

                        //
                        // Setup validation on current row data
                        //
                        var validation = ValidationHelper.ValidateEntity(currentCustomer);

                        //
                        // If there are validation error present them to the user
                        //
                        if (validation.HasError)
                        {
                            var errorItems = string.Join(Environment.NewLine,
                                                         validation.Errors.Select((containerItem) => containerItem.ErrorMessage).ToArray());

                            MessageBox.Show(errorItems + Environment.NewLine + @"Customer has been reset!!!", @"Corrections needed");

                            //
                            // Read current values from database
                            //
                            Customers originalCustomer = CustomersTestOperations.CustomerFirstOrDefault(customerItem.CustomerIdentifier);

                            //
                            // reset current item both in Customer object and CustomerEntity object
                            // (there are other ways to deal with this but are dependent on business logic)
                            //
                            customerEntry.CurrentValues.SetValues(originalCustomer);
                            _customerView[_customerBindingSource.Position] = CustomersTestOperations.CustomerByIdentifier(originalCustomer.CustomerIdentifier);
                            _hasValidationErrors = true;
                        }
                        else
                        {
                            _hasValidationErrors = false;
                            CustomersTestOperations.Context.SaveChanges();
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
 public async Task NewCustomer(CustomerEntity cust)
 {
     await _repo.AddCustomer(cust);
 }
 public static void Add(CustomerEntity customer)
 {
     CustomerDetails.Add(customer);
 }
Exemplo n.º 31
0
 public bool SaveCustomer(CustomerEntity customerEntity)
 {
     _customerDataAccess = new CustomerDataAccess(_context);
     return(_customerDataAccess.SaveCustomer(customerEntity));
 }
Exemplo n.º 32
0
 public CustomerEntityExtend(CustomerEntity item)
 {
     Tools.CopyModel(this, item);
 }
Exemplo n.º 33
0
 public string _CustomerList()
 {
     string sql = "select * from [custom_info] order by pname ;select count(id) from custom_info";
     DataSet ds = DataFactory.SqlHelper.ExecuteDataset(DataBll.conString.constr, System.Data.CommandType.Text, sql);
     System.Data.DataTable dt = ds.Tables[0];
     int rows = Convert.ToInt32(Convert.IsDBNull(ds.Tables[1].Rows[0][0]) ? 0 : ds.Tables[1].Rows[0][0]); //获得总数
     List<CustomerEntity> wdList = new List<CustomerEntity>();
     for (int i = 0; i < dt.Rows.Count; i++)
     {
         CustomerEntity wd = new CustomerEntity();
         wd.id = Convert.ToInt32(dt.Rows[i]["id"] ?? 0);
         wd.pname = Convert.IsDBNull(dt.Rows[i]["pname"]) ? "" : dt.Rows[i]["pname"].ToString();
         wd.psize = Convert.IsDBNull(dt.Rows[i]["psize"]) ? "" : dt.Rows[i]["psize"].ToString();
         wd.clicevip = Convert.IsDBNull(dt.Rows[i]["clicevip"]) ? "" : dt.Rows[i]["clicevip"].ToString();
         wd.puser = Convert.IsDBNull(dt.Rows[i]["puser"]) ? "" : dt.Rows[i]["puser"].ToString();
         wd.userpho = Convert.IsDBNull(dt.Rows[i]["userpho"]) ? "" : dt.Rows[i]["userpho"].ToString();
         wd.cstatus = Convert.IsDBNull(dt.Rows[i]["cstatus"]) ? "" : dt.Rows[i]["cstatus"].ToString();
         wdList.Add(wd);
     }
     string output = JsonConvert.SerializeObject(wdList);
     string json = @"{""Rows"":" + output + @",""Total"":""" + rows + @"""}";
     return json;
 }
Exemplo n.º 34
0
 public async Task Update(string id, CustomerEntity customer)
 {
     await Task.Run(() => _customerDatabase.ReplaceOne(c => c.Id == id, customer));
 }
Exemplo n.º 35
0
        public void SaveFormApi(string keyValue, OrderEntity orderEntity, List <OrderEntryEntity> orderEntryList, List <ReceivableEntity> receivableentityList, string userid, string username)
        {
            IRepository db = new RepositoryFactory().BaseRepository().BeginTrans();

            try
            {
                decimal realsize = 0;
                if (!string.IsNullOrEmpty(orderEntity.PhotoPath))
                {
                    if (orderEntity.PhotoPath.ToString().Substring(orderEntity.PhotoPath.Length - 1, 1) == ",")
                    {
                        orderEntity.PhotoPath = orderEntity.PhotoPath.Substring(0, orderEntity.PhotoPath.Length - 1);
                    }
                }
                if (!string.IsNullOrEmpty(keyValue))
                {
                    decimal recA = 0;
                    ////主表
                    // orderEntity.Modify(keyValue);
                    orderEntity.OrderId = keyValue;
                    if (receivableentityList != null)
                    {
                        //收款
                        db.Delete <ReceivableEntity>(t => t.OrderId.Equals(keyValue));
                        foreach (ReceivableEntity receivableEntity in receivableentityList)
                        {
                            System.Threading.Thread.Sleep(10);
                            receivableEntity.PaymentTime    = receivableEntity.PaymentTime == null ? DateTime.Now : receivableEntity.PaymentTime;
                            receivableEntity.CreateDate     = receivableEntity.CreateDate == null ? DateTime.Now : receivableEntity.CreateDate;
                            receivableEntity.CreateUserId   = receivableEntity.CreateUserId == null ? userid : receivableEntity.CreateUserId;
                            receivableEntity.CreateUserName = receivableEntity.CreateUserName == null ? username : receivableEntity.CreateUserName;


                            recA = recA + Convert.ToDecimal(receivableEntity.PaymentPrice) - Convert.ToDecimal(receivableEntity.DrawbackPrice);
                            receivableEntity.ReceivableId = Guid.NewGuid().ToString();
                            receivableEntity.OrderId      = orderEntity.OrderId;
                            //添加收款
                            db.Insert(receivableEntity);
                        }
                    }

                    if (orderEntryList != null)
                    {
                        //明细
                        db.Delete <OrderEntryEntity>(t => t.OrderId.Equals(keyValue));
                        foreach (OrderEntryEntity orderEntryEntity in orderEntryList)
                        {
                            System.Threading.Thread.Sleep(10);
                            orderEntryEntity.RealSize   = orderEntryEntity.RealSize == null ? 0 : orderEntryEntity.RealSize;
                            orderEntryEntity.RealAmount = orderEntryEntity.RealAmount == null ? 0 : orderEntryEntity.RealAmount;
                            realsize = realsize + Convert.ToDecimal(orderEntryEntity.RealSize == null ? 0 : orderEntryEntity.RealSize);
                            orderEntryEntity.EstimateSize   = 0;
                            orderEntryEntity.EstimateAmount = 0;
                            orderEntryEntity.OrderEntryId   = Guid.NewGuid().ToString();
                            orderEntryEntity.OrderId        = orderEntity.OrderId;
                            db.Insert(orderEntryEntity);
                        }
                    }

                    if (orderEntity.OrderStatusName.Contains("已"))
                    {
                        orderEntity.OrderStatusId = "3";
                        if (string.IsNullOrEmpty(Convert.ToString(orderEntity.FinishDate)))
                        {
                            orderEntity.FinishDate = DateTime.Today;
                        }
                    }
                    else
                    {
                        orderEntity.OrderStatusId = "1";
                    }

                    //if (Convert.ToString(orderEntity.OrderStatusId) != "3")
                    //{
                    //    orderEntity.FinishDate = null;
                    //}

                    if (recA > 0)
                    {
                        //更改订单状态
                        if (GetEntity(keyValue).Accounts >= recA)
                        {
                            orderEntity.PaymentState = 3;
                        }
                        else
                        {
                            orderEntity.PaymentState = 2;
                        }

                        if (orderEntity.PayeeModeId == null)
                        {
                            orderEntity.PayeeModeId   = "1";
                            orderEntity.PayeeModeName = "现金";
                        }
                    }

                    db.Update(orderEntity);

                    orderEntity.SellerId       = null;
                    orderEntity.SellerName     = null;
                    orderEntity.ModifyDate     = DateTime.Now;
                    orderEntity.ModifyUserId   = userid;
                    orderEntity.ModifyUserName = username;
                    orderEntity.ReceivedAmount = recA;
                    orderEntity.RealSize       = realsize; //施工面积
                    db.Update(orderEntity);

                    if (GetEntity(keyValue).Description != orderEntity.Description && !string.IsNullOrEmpty(orderEntity.Description))
                    {//备注和之前不同时,插入备注列表
                        Client_OrderDescriptionEntity orderDescriptionEntity = new Client_OrderDescriptionEntity();

                        orderDescriptionEntity.CreateDate         = DateTime.Now;
                        orderDescriptionEntity.CreateUserId       = userid;
                        orderDescriptionEntity.CreateUserName     = username;
                        orderDescriptionEntity.DescriptionId      = Guid.NewGuid().ToString();
                        orderDescriptionEntity.OrderId            = orderEntity.OrderId;
                        orderDescriptionEntity.DescriptionContent = orderEntity.Description;
                        db.Insert(orderDescriptionEntity);
                    }
                }
                else
                {
                    CustomerService customerService = new CustomerService();

                    if (customerService.GetEntityByCondation(orderEntity.CustomerName, orderEntity.ContecterTel).Count() == 0)
                    {
                        CustomerEntity customerEntity = new CustomerEntity();
                        customerEntity.FullName = orderEntity.CustomerName;
                        customerEntity.Tel      = orderEntity.ContecterTel;
                        customerEntity.Mobile   = orderEntity.ContecterTel;

                        customerService.SaveFormApi("", customerEntity);
                        orderEntity.CustomerId = customerService.GetEntityByCondation(orderEntity.CustomerName, orderEntity.ContecterTel).ToList()[0].CustomerId;
                    }

                    //主表
                    orderEntity.SellerId   = userid;
                    orderEntity.SellerName = username;
                    if (orderEntity.OrderDate == null)
                    {
                        orderEntity.OrderDate = DateTime.Now;
                    }
                    //orderEntity.OrderDate = DateTime.Now;

                    orderEntity.CreateUserId   = userid;
                    orderEntity.CreateUserName = username;
                    orderEntity.OrderId        = Guid.NewGuid().ToString();
                    orderEntity.CreateDate     = DateTime.Now;
                    orderEntity.OrderCode      = coderuleService.SetBillCodeApi(userid, "", ((int)CodeRuleEnum.Customer_OrderCode).ToString());
                    coderuleService.UseRuleSeed(orderEntity.CreateUserId, "", ((int)CodeRuleEnum.Customer_OrderCode).ToString(), db);//占用单据号

                    decimal recA = 0;
                    if (receivableentityList != null)
                    {
                        //收款
                        // db.Delete<ReceivableEntity>(t => t.OrderId.Equals(keyValue));
                        foreach (ReceivableEntity receivableEntity in receivableentityList)
                        {
                            System.Threading.Thread.Sleep(10);
                            receivableEntity.CreateDate     = DateTime.Now;
                            receivableEntity.PaymentTime    = receivableEntity.PaymentTime == null ? DateTime.Now : receivableEntity.PaymentTime;
                            receivableEntity.CreateUserId   = userid;
                            receivableEntity.CreateUserName = username;
                            recA = recA + Convert.ToDecimal(receivableEntity.PaymentPrice) - Convert.ToDecimal(receivableEntity.DrawbackPrice);
                            receivableEntity.ReceivableId = Guid.NewGuid().ToString();
                            receivableEntity.OrderId      = orderEntity.OrderId;
                            //添加收款
                            db.Insert(receivableEntity);
                        }
                    }


                    if (orderEntryList != null)
                    {
                        //明细
                        foreach (OrderEntryEntity orderEntryEntity in orderEntryList)
                        {
                            System.Threading.Thread.Sleep(10);
                            orderEntryEntity.RealSize   = orderEntryEntity.RealSize == null ? 0 : orderEntryEntity.RealSize;
                            orderEntryEntity.RealAmount = orderEntryEntity.RealAmount == null ? 0 : orderEntryEntity.RealAmount;
                            realsize = realsize + Convert.ToDecimal(orderEntryEntity.RealSize == null ? 0 : orderEntryEntity.RealSize);
                            orderEntryEntity.EstimateSize   = 0;
                            orderEntryEntity.EstimateAmount = 0;
                            orderEntryEntity.OrderEntryId   = Guid.NewGuid().ToString();
                            orderEntryEntity.OrderId        = orderEntity.OrderId;
                            db.Insert(orderEntryEntity);
                        }
                    }
                    if (orderEntity.OrderStatusName.Contains("已"))
                    {
                        orderEntity.OrderStatusId = "3";
                        if (string.IsNullOrEmpty(Convert.ToString(orderEntity.FinishDate)))
                        {
                            orderEntity.FinishDate = DateTime.Today;
                        }
                    }
                    else
                    {
                        orderEntity.OrderStatusId = "1";
                    }
                    if (recA > 0)
                    {
                        //更改订单状态
                        if (orderEntity.Accounts >= recA)
                        {
                            orderEntity.PaymentState = 3;
                        }
                        else
                        {
                            orderEntity.PaymentState = 2;
                        }
                        if (orderEntity.PayeeModeId == null)
                        {
                            orderEntity.PayeeModeId   = "1";
                            orderEntity.PayeeModeName = "现金";
                        }
                    }


                    orderEntity.RealSize       = realsize; //施工面积
                    orderEntity.ReceivedAmount = recA;
                    db.Insert(orderEntity);
                    if (!string.IsNullOrEmpty(orderEntity.Description))
                    {
                        Client_OrderDescriptionEntity orderDescriptionEntity = new Client_OrderDescriptionEntity();

                        orderDescriptionEntity.CreateDate         = DateTime.Now;
                        orderDescriptionEntity.CreateUserId       = userid;
                        orderDescriptionEntity.CreateUserName     = username;
                        orderDescriptionEntity.DescriptionId      = Guid.NewGuid().ToString();
                        orderDescriptionEntity.OrderId            = orderEntity.OrderId;
                        orderDescriptionEntity.DescriptionContent = orderEntity.Description;
                        db.Insert(orderDescriptionEntity);
                    }
                }
                db.Commit();
            }
            catch
            {
                db.Rollback();

                throw;
            }
        }
Exemplo n.º 36
0
        public void receive_from_table()
        {
            lock (this)
            {

                string ipaddress = null;
                string[] arr = new string[100];
                arr = rd1.Split('-');
                Console.WriteLine("IP Address : " + arr[0]);
                Console.WriteLine("Custmer Name : " + arr[1]);
                Console.WriteLine("Time of day : " + arr[2]);
                ipaddress = arr[0];
                string tableName = arr[1] + arr[2];
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                CloudTableClient tableClient1 = storageAccount.CreateCloudTableClient();
                CloudTable table1 = null;
                try
                {
                    table1 = tableClient1.GetTableReference(tableName);
                    TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.NotEqual, "xyz"));
                    List<CustomerEntity> AddressList = new List<CustomerEntity>();

                    foreach (CustomerEntity entity in table1.ExecuteQuery(query))
                    {
                        CustomerEntity ce = new CustomerEntity();
                        ce.PartitionKey = entity.PartitionKey;
                        ce.RowKey = entity.RowKey;
                        ce.id = entity.id;
                        ce.devicefunction = entity.devicefunction;
                        ce.devicename = entity.devicename;
                        ce.devicetype = entity.devicetype;
                        ce.devtabid = entity.devtabid;
                        ce.ep = entity.ep;
                        ce.vendorname = entity.vendorname;
                        ce.IEEE = entity.IEEE;
                        ce.datetime = entity.datetime;
                        ce.energy1 = entity.energy1;
                        ce.energy2 = entity.energy2;
                        AddressList.Add(ce);
                    }
                    XmlSerializer serializer = new XmlSerializer(typeof(List<CustomerEntity>));
                    using (TextWriter writer = new StreamWriter("D:\\customerinfofromtable.xml"))
                    {
                        serializer.Serialize(writer, AddressList);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("TABLE NAME= " + tableName + "  doesnot exist ");
                    Console.WriteLine("Send again.............");
                    processfun();
                }
                string data;
                System.IO.StreamReader file1 = new System.IO.StreamReader("D:\\customerinfofromtable.xml");
                data = file1.ReadToEnd();
                //Console.WriteLine(data);

                file1.Close();
                TcpClient newclient = new TcpClient();
                Console.WriteLine("Trying to connect........!");
                newclient.Connect(arr[0], 8902);
                Console.WriteLine("Connected to " + arr[1]);
                StreamWriter sw = new StreamWriter(newclient.GetStream());
                sw.WriteLine(data.ToString());
                sw.Flush();
                newclient.Close();
                Console.WriteLine("Successfully transfered.....!");
            }
        }
Exemplo n.º 37
0
    protected void btnSend_Click(object sender, EventArgs e)
    {
        SMS.APIType = SMSGateway.Site2SMS;
        SMS.MashapeKey = "pPsD7Kqfn2mshzjqhhbOkQMfGyQgp1TQAf7jsnRTMs6ygiLeUg";
        string text = "";
        //Email starts
        using (Imap imap = new Imap())
        {
            Limilabs.Mail.Log.Enabled = true;
            try
            {
                imap.ConnectSSL("imap.gmail.com", 993);   // or ConnectSSL for SSL

                imap.UseBestLogin("*****@*****.**", "zeesense40");
            }
            catch(Exception E)
            {
                return;
            }

            imap.SelectInbox();

            List<long> uids = imap.Search(Flag.All);



            foreach (long uid in uids)
            {

                var eml = imap.GetMessageByUID(uid);

                IMail email = new MailBuilder()

                    .CreateFromEml(eml);


                 text = email.Text;

                 
            
             
           }

            imap.Close();
        }
           
        //Email ends
            string[] arr=text.Split('~');
            string recvName = "",alert="";
        if(arr[0]=="&")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[3];
        }
        else if(arr[0]=="^" || arr[0]=="%")
        {
            recvName = arr[2].ToLower().Trim();
            alert = arr[1];
        }
        //txtyourmoNumber.Text = "9742984490";
        SMS.Username = "******";
        //txtyourPassword.Text = "12345";
        SMS.Password = "******";
        //string recvName = arr[2].ToLower().Trim();
      //  string alert = arr[3];
        string phone = null;
        string tableName = "builder";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
                CloudTableClient tableClient1 = storageAccount.CreateCloudTableClient();
                CloudTable table1 = null;
                try
                {
                    table1 = tableClient1.GetTableReference(tableName);
                    TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>().Where(TableQuery.GenerateFilterCondition("customername", QueryComparisons.Equal, recvName.ToLower()));
                    List<CustomerEntity> AddressList = new List<CustomerEntity>();
                    CustomerEntity ce = new CustomerEntity();
                    foreach (CustomerEntity entity in table1.ExecuteQuery(query))
                    {
                        phone = entity.contactnumber;
                        break;
                    }
                    if (phone != null)
                    
                        SMS.SendSms(phone, alert);
                        //SendingRandomMessages(recvName, data).Wait();
                    
                }
               catch(Exception e1)
                {
                 
                }
    }
Exemplo n.º 38
0
        /// <summary>
        /// Calculates the statistics for the Northwind database and shows them in the form, illustrating the
        /// direct database power LLBLGen Pro offers you through scalar functions, aggregates, group by and expressions.
        /// </summary>
        /// <remarks>No error checking is applied to this routine, it's for illustrating the framework functionality.</remarks>
        private void CalculateStatistics()
        {
            // get amount customers
            CustomerCollection customers = new CustomerCollection();
            int amountCustomers          = customers.GetDbCount();

            _amountCustomersTextBox.Text = amountCustomers.ToString();

            // get all order prices
            ResultsetFields orderPricesFields = new ResultsetFields(2);

            orderPricesFields.DefineField(OrderDetailFields.OrderId, 0, "OrderId");
            orderPricesFields.DefineField(OrderDetailFields.ProductId, 1, "OrderPrice", "", AggregateFunction.Sum);
            orderPricesFields[1].ExpressionToApply = (OrderDetailFields.Quantity * OrderDetailFields.UnitPrice);
            IGroupByCollection groupBy = new GroupByCollection();

            groupBy.Add(orderPricesFields[0]);

            // fetch in a datatable, orderid + the order price.
            DataTable    orderPrices = new DataTable();
            TypedListDAO dao         = new TypedListDAO();

            dao.GetMultiAsDataTable(orderPricesFields, orderPrices, 0, null, null, null, true, groupBy, null, 0, 0);

            // calculate average order price and which customer has the most expensive order
            decimal averageOrderPrice       = 0.0M;
            decimal highestOrderPrice       = 0.0M;
            int     orderIdWithHighestPrice = 0;

            for (int i = 0; i < orderPrices.Rows.Count; i++)
            {
                decimal currentOrderPrice = (decimal)orderPrices.Rows[i]["OrderPrice"];
                if (currentOrderPrice > highestOrderPrice)
                {
                    highestOrderPrice       = currentOrderPrice;
                    orderIdWithHighestPrice = (int)orderPrices.Rows[i]["OrderId"];
                }
                averageOrderPrice += currentOrderPrice;
            }
            averageOrderPrice = averageOrderPrice / orderPrices.Rows.Count;
            _highestOrderPriceTextBox.Text = highestOrderPrice.ToString("C");
            _averageOrderPriceTextBox.Text = averageOrderPrice.ToString("C");

            // get order with highest price. Pull customer also in 1 go
            IPrefetchPath prefetchPathCustomer = new PrefetchPath((int)EntityType.OrderEntity);

            prefetchPathCustomer.Add(OrderEntity.PrefetchPathCustomer);
            OrderEntity highestOrder = new OrderEntity();

            highestOrder.FetchUsingPK(orderIdWithHighestPrice, prefetchPathCustomer);
            _customerWithHighestOrder         = highestOrder.Customer;          // already loaded through prefetch path.
            _highestOrderCustomerTextBox.Text = _customerWithHighestOrder.CompanyName;

            // get customer with most orders.
            ResultsetFields orderCustomerFields = new ResultsetFields(2);

            orderCustomerFields.DefineField(OrderFields.CustomerId, 0, "CustomerID");
            orderCustomerFields.DefineField(OrderFields.OrderId, 1, "AmountOrders", "", AggregateFunction.Count);
            groupBy = new GroupByCollection();
            groupBy.Add(orderCustomerFields[0]);
            SortExpression sorter = new SortExpression();

            sorter.Add(new SortClause(orderCustomerFields[1], SortOperator.Descending));
            // now fetch the list, just 1 row, ordered descending on amount
            DataTable orderCustomer = new DataTable();

            dao.GetMultiAsDataTable(orderCustomerFields, orderCustomer, 1, sorter, null, null, true, groupBy, null, 0, 0);
            _mostOrdersPerCustomerTextBox.Text = orderCustomer.Rows[0]["AmountOrders"].ToString();

            // we'll assume the data was there, so there is a row.
            _customerWithMostOrders = new CustomerEntity(orderCustomer.Rows[0]["CustomerID"].ToString());

            _mostOrdersCustomerTextBox.Text = _customerWithMostOrders.CompanyName;
        }
        public async Task <string> Handle(CreateSalesCommand request, CancellationToken cancellationToken)
        {
            string invoiceNumber    = string.Empty;
            var    result           = new object();
            bool   existingCustomer = true;
            var    invoiceId        = 1;

            try
            {
                CustomerEntity customer  = _context.Customers.Where(c => c.PhoneNumber == request.PhoneNumber).SingleOrDefault();
                var            lastSales = _context.Sales.OrderByDescending(x => x.SalesId).FirstOrDefault();
                if (lastSales != null)
                {
                    invoiceId = lastSales.SalesId + 1;
                }



                if (customer == null)
                {
                    customer = new CustomerEntity()
                    {
                        Name        = request.Name,
                        PhoneNumber = request.PhoneNumber,
                        Email       = request.Email
                    };
                    existingCustomer = false;
                }
                invoiceNumber = "ORD-" + customer.PhoneNumber + "-" + invoiceId.ToString();

                await _context.BeginTransactionAsync();

                if (!existingCustomer)
                {
                    _context.Customers.Add(customer);
                    await _context.SaveChangesAsync(cancellationToken);
                }
                else
                {
                    if (!string.IsNullOrEmpty(request.Name))
                    {
                        customer.Name = request.Name;
                    }
                    if (!string.IsNullOrEmpty(request.Email))
                    {
                        customer.Email = request.Email;
                    }
                    _context.Customers.Update(customer);
                    await _context.SaveChangesAsync(cancellationToken);
                }

                var sales = new SalesEntity()
                {
                    OrderGroup    = request.OrderGroup,
                    CustomerId    = customer.CustomerId,
                    InvoiceNumber = invoiceNumber,
                    Total         = request.Total,
                    PickUpDate    = request.PickUpDate
                };
                _context.Sales.Add(sales);
                await _context.SaveChangesAsync(cancellationToken);

                await _context.CommitTransactionAsync();

                IEnumerable <OrderEntity> orderEntities = _context.Orders.Where(x => x.OrderGroup == request.OrderGroup).ToList();
                var totalOrders = orderEntities.Count();

                result = new DocketVm()
                {
                    CustomerName  = customer.Name,
                    PhoneNumber   = customer.PhoneNumber,
                    DocketNumber  = invoiceNumber,
                    PickUpDetails = request.PickUpDate.ToString("dddd, dd MMMM yyyy"),
                    Qty           = totalOrders
                };
            }

            catch (Exception ex)
            {
                var exception = ex.Message.ToString();
                _context.RollbackTransaction();
                throw;
            }
            return(JsonConvert.SerializeObject(result));
        }
Exemplo n.º 40
0
        public static async Task <CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

                CustomerEntity insertedCustomer = result.Result as CustomerEntity;

                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
                }

                return(insertedCustomer);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Exemplo n.º 41
0
 public void Add(CustomerEntity entity)
 {
     _context.Customers.Add(entity);
 }
Exemplo n.º 42
0
        /// <summary>
        /// Función que valida un CustomerEntity antes de ser guardado.
        /// </summary>
        /// <param name="customerEntity">CustomerEntity a validar</param>
        /// <param name="session">Identificador de sesion del usuario.</param>
        /// <returns>true si se valido correctamente, false en caso contrario</returns>
        /// <exception cref="ArgumentNullException">
        /// si <paramref name="customerEntity"/> es null.
        /// </exception>
        /// <exception cref="UtnEmallBusinessLogicException">
        /// Si una UtnEmallDataAccessException ocurre en el DataModel.
        /// </exception>
        public bool Validate(CustomerEntity customer)
        {
            bool result = true;

            if (customer == null)
            {
                throw new ArgumentException("The argument can't be null");
            }
            // Check entity data
            if (String.IsNullOrEmpty(customer.Name))
            {
                customer.Errors.Add(new Error("Name", "Name", "El nombre no puede estar vacío"));
                result = false;
            }
            if (String.IsNullOrEmpty(customer.Surname))
            {
                customer.Errors.Add(new Error("Surname", "Surname", "El apellido no puede estar vacío"));
                result = false;
            }
            if (String.IsNullOrEmpty(customer.Address))
            {
                customer.Errors.Add(new Error("Address", "Address", "La dirección no puede estar vacía"));
                result = false;
            }
            if (String.IsNullOrEmpty(customer.PhoneNumber))
            {
                customer.Errors.Add(new Error("PhoneNumber", "PhoneNumber", "El número de teléfono no puede estar vacío"));
                result = false;
            }
            if (String.IsNullOrEmpty(customer.UserName))
            {
                customer.Errors.Add(new Error("UserName", "UserName", "El nombre de usuario no puede estar vacío"));
                result = false;
            }
            if (customer.UserName != null)
            {
                Collection <CustomerEntity> listOfEquals = customerDataAccess.LoadWhere(CustomerEntity.DBUserName, customer.UserName, false, OperatorType.Equal);

                if (listOfEquals.Count > 0 && listOfEquals[0].Id != customer.Id)
                {
                    customer.Errors.Add(new Error("UserName", "UserName", "Nombre de usuario duplicado"));
                    result = false;
                }
            }
            if (String.IsNullOrEmpty(customer.Password))
            {
                customer.Errors.Add(new Error("Password", "Password", "La contraseña no puede estar vacía"));
                result = false;
            }
            if (customer.Birthday == null)
            {
                customer.Errors.Add(new Error("Birthday", "Birthday", "La fecha de cumpleaños no puede estar vacía."));
                result = false;
            }

            if (customer.Preferences == null)
            {
                customer.Errors.Add(new Error("Preferences", "Preferences", "Las preferencias no pueden estar vacías"));
                result = false;
            }
            if (customer.DeviceProfile == null)
            {
                customer.Errors.Add(new Error("DeviceProfile", "DeviceProfile", "El perfil del dispositivo no puede ser nulo"));
                result = false;
            }
            return(result);
        }
Exemplo n.º 43
0
 public void Update(CustomerEntity entity)
 {
     _context.Customers.Update(entity);
 }
Exemplo n.º 44
0
 public bool InsertEntityToAzureTable(string tableName, CustomerEntity entity)
 {
     System.Diagnostics.Trace.TraceInformation(string.Format("Date = {0}, Instance = {1}. WorkerService.InsertEntityToAzureTable is Called", DateTime.Now, RoleEnvironment.CurrentRoleInstance.Id));
     return AzureTableOperation.InsertEntityToAzureTable(tableName, entity);
 }
Exemplo n.º 45
0
        public static async Task <CustomerEntity> InsertOrMergeEntityAsync(CloudTable table, CustomerEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            try
            {
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);


                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

                CustomerEntity insertedCustomer = result.Result as CustomerEntity;


                return(insertedCustomer);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Exemplo n.º 46
0
        private void gridCustomers_SelectionChanged(object sender, EventArgs e)
        {
            if (gridCustomers.SelectedCells == null || gridCustomers.SelectedCells.Count == 0)
                current = CustomerEntity.Empty;
            else
                current = gridCustomers.Rows[gridCustomers.SelectedCells[0].RowIndex].DataBoundItem as CustomerEntity;

            ShowItem(current);
        }
Exemplo n.º 47
0
        public InsertOrUpdateUserResponse InsertOrUpdateUser(InsertOrUpdateUserRequest request, int?supervisorUserId, int roleId, int branchId)
        {
            _context.Configuration.AutoDetectChangesEnabled = false;

            try
            {
                var result = new InsertOrUpdateUserResponse();

                TB_R_USER dbUser;

                var transactionDateTime = DateTime.Now;

                if (request.ActionType == 1)
                {
                    // Insert
                    dbUser = null;
                }
                else
                {
                    // Update
                    dbUser = _context.TB_R_USER.Where(user => user.EMPLOYEE_CODE.Trim().ToUpper() == request.EmployeeCodeOld.Trim().ToUpper()).FirstOrDefault();

                    if (dbUser == null)
                    {
                        result.IsSuccess    = false;
                        result.ErrorCode    = "8";
                        result.ErrorMessage = "ไม่สามารถอัพเดตข้อมูล User เนื่องจากไม่พบข้อมูล User (Employee Code Old='" + request.EmployeeCodeOld + "')";
                        return(result);
                    }
                }

                if (dbUser == null)
                {
                    dbUser           = new TB_R_USER();
                    result.IsNewUser = true;
                }
                else
                {
                    result.IsNewUser = false;

                    // IF (Change Branch) Or (Change Status 1 to 0)
                    if (dbUser.BRANCH_ID != branchId || (dbUser.STATUS == 1 && request.Status == 0))
                    {
                        #region == Validate Job On Hand ==

                        var userId = dbUser.USER_ID;

                        var activeStatuses = new int[]
                        {
                            Constants.SRStatusId.Open,
                            Constants.SRStatusId.InProgress,
                            Constants.SRStatusId.WaitingCustomer,
                            Constants.SRStatusId.RouteBack,
                        };

                        var countJobOnHand = _context.TB_T_SR.Count(sr =>
                                                                    (
                                                                        (sr.OWNER_USER_ID == userId || sr.DELEGATE_USER_ID == userId) &&
                                                                        activeStatuses.Contains(sr.SR_STATUS_ID.Value)
                                                                    )
                                                                    ||
                                                                    (
                                                                        sr.CREATE_USER == userId &&
                                                                        sr.SR_STATUS_ID == Constants.SRStatusId.Draft
                                                                    )
                                                                    );

                        if (countJobOnHand > 0)
                        {
                            result.IsSuccess    = false;
                            result.ErrorCode    = "7";
                            result.ErrorMessage = "ไม่สามารถอัพเดตข้อมูล User ได้เนื่องจากมีงานค้างในมือ (ServiceRequest)";
                            return(result);
                        }

                        #endregion
                    }
                }

                var actionUser = _context.TB_R_USER.Where(user => user.USERNAME.Trim().ToUpper() == request.ActionUsername.Trim().ToUpper()).FirstOrDefault();
                if (actionUser == null)
                {
                    if (dbUser == null)
                    {
                        result.IsSuccess    = false;
                        result.ErrorCode    = "9";
                        result.ErrorMessage = "ไม่สามารถอัพเดตข้อมูล User เนื่องจากไม่พบข้อมูล Action User (Action Username='******')";
                        return(result);
                    }
                }


                dbUser.BRANCH_ID      = branchId;
                dbUser.SUPERVISOR_ID  = supervisorUserId;
                dbUser.FIRST_NAME     = ValueOrDefault(request.FirstName);
                dbUser.LAST_NAME      = ValueOrDefault(request.LastName);
                dbUser.USERNAME       = ValueOrDefault(request.WindowsUsername);
                dbUser.STATUS         = Convert.ToInt16(request.Status);
                dbUser.ROLE_ID        = roleId;
                dbUser.EMPLOYEE_CODE  = ValueOrDefault(request.EmployeeCodeNew);
                dbUser.UPDATE_DATE    = transactionDateTime;
                dbUser.IS_GROUP       = request.IsGroup;
                dbUser.POSITION_CODE  = ValueOrDefault(request.PositionCode);
                dbUser.MARKETING_CODE = ValueOrDefault(request.MarketingCode);
                dbUser.EMAIL          = ValueOrDefault(request.Email);
                dbUser.ROLE_SALE      = ValueOrDefault(request.RoleSale);
                dbUser.MARKETING_TEAM = ValueOrDefault(request.MarketingTeam);
                dbUser.LINE           = ValueOrDefault(request.Line);
                dbUser.RANK           = ValueOrDefault(request.Rank);
                dbUser.EMPLOYEE_TYPE  = ValueOrDefault(request.EmployeeType);
                dbUser.COMPANY_NAME   = ValueOrDefault(request.CompanyName);
                dbUser.TELESALE_TEAM  = ValueOrDefault(request.TelesaleTeam);
                dbUser.MARKETING_FLAG = request.MarketingFlag;

                if (result.IsNewUser)
                {
                    for (var i = 0; i < 3; i++)
                    {
                        var phone = new TB_R_USER_PHONE();
                        phone.TB_R_USER   = dbUser;
                        phone.PHONE_NO    = i == 0 ? request.Phone1 : i == 1 ? request.Phone2 : request.Phone3;
                        phone.ORDER       = Convert.ToInt16(i + 1);
                        phone.CREATE_DATE = transactionDateTime;
                        phone.UPDATE_DATE = transactionDateTime;
                        _context.TB_R_USER_PHONE.Add(phone);
                    }
                }
                else
                {
                    var dbPhoneList = dbUser.TB_R_USER_PHONE.OrderBy(p => p.ORDER).Take(10).ToList();
                    InsertOrUpdateUserPhone(dbPhoneList, request.Phone1, 1, dbUser, transactionDateTime);
                    InsertOrUpdateUserPhone(dbPhoneList, request.Phone2, 2, dbUser, transactionDateTime);
                    InsertOrUpdateUserPhone(dbPhoneList, request.Phone3, 3, dbUser, transactionDateTime);
                }

                if (result.IsNewUser)
                {
                    dbUser.CREATE_USERNAME = ValueOrDefault(request.ActionUsername);
                    dbUser.UPDATE_USERNAME = ValueOrDefault(request.ActionUsername);
                    dbUser.CREATE_DATE     = transactionDateTime;
                    dbUser.UPDATE_DATE     = transactionDateTime;

                    _context.TB_R_USER.Add(dbUser);
                }
                else
                {
                    dbUser.UPDATE_USERNAME = ValueOrDefault(request.ActionUsername);
                    dbUser.UPDATE_DATE     = transactionDateTime;
                    SetEntryStateModified(dbUser);
                }

                this.Save();

                if (!request.IsGroup)
                {
                    var _customerDataAccess = new CustomerDataAccess(_context);

                    CustomerEntity customerEntity;

                    bool isCreateCustomer;
                    if (result.IsNewUser)
                    {
                        isCreateCustomer = true;
                        customerEntity   = new CustomerEntity();
                    }
                    else
                    {
                        customerEntity = _customerDataAccess.GetCustomerByEmployeeID(dbUser.USER_ID);

                        // If Update but no have Customer for this user >> It will create
                        if (customerEntity == null)
                        {
                            customerEntity   = new CustomerEntity();
                            isCreateCustomer = true;
                        }
                        else
                        {
                            isCreateCustomer = false;
                        }
                    }

                    // Create/Update Customer for this user

                    if (isCreateCustomer)
                    {
                        // Create Customer
                        var _commonDataAccess = new CommonDataAccess(_context);
                        var subscriptionType  = _commonDataAccess.GetSubscriptTypeByCode(Constants.DefaultSubscriptionTypeForUser);

                        customerEntity.CustomerType  = Constants.CustomerType.Employee;
                        customerEntity.FirstNameThai = request.FirstName;
                        customerEntity.LastNameThai  = request.LastName;
                        customerEntity.SubscriptType = subscriptionType;
                        customerEntity.CardNo        = request.EmployeeCodeNew;
                        customerEntity.Email         = request.Email;
                        customerEntity.EmployeeId    = dbUser.USER_ID;

                        customerEntity.TitleThai    = new TitleEntity();
                        customerEntity.TitleEnglish = new TitleEntity();

                        customerEntity.CreateUser = new UserEntity()
                        {
                            UserId = actionUser.USER_ID
                        };
                        customerEntity.UpdateUser = new UserEntity()
                        {
                            UserId = actionUser.USER_ID
                        };

                        customerEntity.PhoneList = new List <PhoneEntity>();

                        if (!string.IsNullOrEmpty(request.Phone1))
                        {
                            customerEntity.PhoneList.Add(new PhoneEntity()
                            {
                                PhoneNo = request.Phone1
                            });
                        }

                        if (!string.IsNullOrEmpty(request.Phone2))
                        {
                            customerEntity.PhoneList.Add(new PhoneEntity()
                            {
                                PhoneNo = request.Phone2
                            });
                        }

                        if (!string.IsNullOrEmpty(request.Phone3))
                        {
                            customerEntity.PhoneList.Add(new PhoneEntity()
                            {
                                PhoneNo = request.Phone3
                            });
                        }

                        var isSaveCustomerSuccess = _customerDataAccess.SaveCustomer(customerEntity);

                        if (!isSaveCustomerSuccess)
                        {
                            return(new InsertOrUpdateUserResponse()
                            {
                                IsSuccess = false,
                                ErrorCode = "6",
                                ErrorMessage = "Cannot create customer for this user.",
                            });
                        }
                    }
                    else
                    {
                        customerEntity.FirstNameThai = request.FirstName;
                        customerEntity.LastNameThai  = request.LastName;
                        customerEntity.CardNo        = request.EmployeeCodeNew;
                        customerEntity.Email         = request.Email;

                        customerEntity.TitleThai    = new TitleEntity();
                        customerEntity.TitleEnglish = new TitleEntity();

                        customerEntity.CreateUser = new UserEntity()
                        {
                            UserId = actionUser.USER_ID
                        };
                        customerEntity.UpdateUser = new UserEntity()
                        {
                            UserId = actionUser.USER_ID
                        };

                        if (customerEntity.PhoneList == null)
                        {
                            customerEntity.PhoneList = new List <PhoneEntity>();
                        }

                        var phones = new List <string>();

                        if (!string.IsNullOrEmpty(request.Phone1))
                        {
                            phones.Add(request.Phone1);
                        }

                        if (!string.IsNullOrEmpty(request.Phone2))
                        {
                            phones.Add(request.Phone2);
                        }

                        if (!string.IsNullOrEmpty(request.Phone3))
                        {
                            phones.Add(request.Phone3);
                        }

                        if (phones.Count > customerEntity.PhoneList.Count)
                        {
                            var diff = (phones.Count - customerEntity.PhoneList.Count);
                            for (int i = 0; i < diff; i++)
                            {
                                customerEntity.PhoneList.Add(new PhoneEntity());
                            }
                        }
                        else if (phones.Count < customerEntity.PhoneList.Count)
                        {
                            var diff = (customerEntity.PhoneList.Count - phones.Count);
                            for (int i = 0; i < diff; i++)
                            {
                                customerEntity.PhoneList.RemoveAt(customerEntity.PhoneList.Count - 1);
                            }
                        }

                        for (int i = 0; i < phones.Count; i++)
                        {
                            customerEntity.PhoneList[i].PhoneNo = phones[i];
                        }

                        var isSaveCustomerSuccess = _customerDataAccess.SaveCustomer(customerEntity);

                        if (!isSaveCustomerSuccess)
                        {
                            return(new InsertOrUpdateUserResponse()
                            {
                                IsSuccess = false,
                                ErrorCode = "6",
                                ErrorMessage = "Cannot update customer for this user.",
                            });
                        }
                    }
                }

                result.IsSuccess = true;
                return(result);
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occur:\n", ex);

                return(new InsertOrUpdateUserResponse()
                {
                    IsSuccess = false,
                    ErrorCode = "1",
                    ErrorMessage = ex.Message,
                });
            }
            finally
            {
                _context.Configuration.AutoDetectChangesEnabled = false;
            }
        }
Exemplo n.º 48
0
 private void ShowItem(CustomerEntity ent)
 {
     lblId.Text = ent.Id.HasValue ? ent.Id.Value.ToString() : string.Empty;
     txtName.Text = ent.Name;
     txtAddress.Text = ent.Address;
     txtAddress2.Text = ent.Address2;
     txtPhone.Text = ent.Phone;
     txtEmail.Text = ent.Email;
     if (cbCustomerTypes.Items.Count > 0)
         cbCustomerTypes.SelectedIndex = (int)(ent.DCustomerType ?? 0);
     txtComment.Text = ent.Comment;
 }
 /// <summary>
 /// CTor
 /// </summary>
 /// <param name="customer">the customer to manage</param>
 public CustomerManager(CustomerEntity customer) : this()
 {
     // load customer and set as active.
     SetCustomerAsCurrent(customer);
 }
Exemplo n.º 50
0
 public MyPrincipal(EmployeeEntity EmployeeEntity = null, CustomerEntity CustomerEntity = null)
 {
     this.EmployeeEntity = EmployeeEntity;
     this.CustomerEntity = CustomerEntity;
 }
Exemplo n.º 51
0
		/// <summary>Po potrebi konvertira entity u business objekt.</summary>
		public static Customer ConvertEntityToBusinessObject(CustomerEntity entity)
		{
			Customer bizobj = entity as Customer;
			if (bizobj == null)
				bizobj = new Customer(entity);

			return bizobj;
		}