Ejemplo n.º 1
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("MergesController_Seed", entry =>
 {
     entry.AbsoluteExpirationRelativeToNow = MemoryCacheExpirationDefault;
     return(SeedService.GetAllAsync <Merge, MergeSeedDto>(typeof(Merge).GetProperty("MergeFilterListId"),
                                                          typeof(Merge).GetProperty("UpstreamFilterListId")));
 }));
Ejemplo n.º 2
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("ForksController_Seed", entry =>
 {
     entry.SlidingExpiration = MemoryCacheSlidingExpirationDefault;
     return(SeedService.GetAllAsync <Fork, ForkSeedDto>(typeof(Fork).GetProperty("UpstreamFilterListId"),
                                                        typeof(Fork).GetProperty("ForkFilterListId")));
 }));
        public void SelectAll_Succeeds()
        {
            string dbName = "SelectAllPeople_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IDataService <Person> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            int expectedPeopleCount = 3;

            for (int i = 0; i < expectedPeopleCount; i++)
            {
                SeedService.SeedPerson(options, string.Format("Montana{0}", i), "Joe", null, null, "FB", true, false, false, "Notre Dame", "Fighting Irish");
            }

            // Run the test
            var peopleList = serviceToTest.Select();

            // Verify results match expected results
            Assert.Equal(expectedPeopleCount, peopleList.Count);
        }
        public void SelectAll_Succeeds()
        {
            string dbName = "SelectAllTeams_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IDataService <Team> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            int expectedTeamCount = 3;

            for (int i = 0; i < expectedTeamCount; i++)
            {
                SeedService.SeedTeam(options, string.Format("SanFrancisco49ers {0}", i), "San Francisco", "49ers", "NFL", i == 0);
            }

            // Run the test
            var teamList = serviceToTest.Select();

            // Verify results match expected results
            Assert.Equal(expectedTeamCount, teamList.Count);
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              UserManager <Usuario> userManager, RoleManager <TipoUsuario> roleManager, IUsuarioService usuarioService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors(x => x
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .SetIsOriginAllowed(origin => true)
                        .AllowCredentials());
            app.UseAuthentication();
            app.UseAuthorization();

            var seedService = new SeedService(userManager, roleManager, usuarioService);

            seedService.Seed().GetAwaiter().GetResult();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 6
0
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // Add-Migration Name
            // Update-Database
            app.UseExceptionHandler();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseExceptionHandler();
            app.UseCors("CorsHwol");
            app.UseAuthentication();
            //app.UseHttpsRedirection();
            app.UseMvc();
            using (IServiceScope scope = app.ApplicationServices.CreateScope())
            {
                SeedService seedService = scope.ServiceProvider.GetService <SeedService>();
                await seedService.StartSeed();
            }
        }
Ejemplo n.º 7
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using var scope = host.Services.CreateScope();

            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService <DataContext>();
                await context.Database.MigrateAsync();
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService <ILogger <Program> >();
                logger.LogError(ex, "An error occured during migration");
            }
            try
            {
                var context = services.GetRequiredService <DataContext>();
                var logger  = services.GetRequiredService <ILogger <Program> >();
                await SeedService.SeedUsersAsync(context, logger);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService <ILogger <Program> >();
                logger.LogError(ex, "An error occured during seeding");
            }


            await host.RunAsync();
        }
Ejemplo n.º 8
0
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                try
                {
                    var db = scope.ServiceProvider.GetService <AppCtx>();
                    //db.Database.EnsureDeleted();


                    if (db.Database.EnsureCreated())
                    {
                        string      filePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).ToString(), "Data\\employees.json");
                        SeedService seed     = new SeedService();
                        seed.Seed(filePath, db);
                    }
                }
                catch (Exception ex)
                {
                    var logger = scope.ServiceProvider.GetService <ILogger <Program> >();
                    logger.LogError(ex, "Error when creating db");
                }
            }

            host.Run();
        }
        public void SelectAll_Succeeds()
        {
            string dbName = "SelectAllCollectibles_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IDataService <Collectible> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            int expectedCollectibleCount = 3;

            for (int i = 0; i < expectedCollectibleCount; i++)
            {
                SeedService.SeedCard(options, "NFL", 1, "Montana", "Joe", "San Francisco", "49ers", 1981 + i, "Topps", false, i == 0, true, false, 100, 80);
            }

            // Run the test
            var collectibleList = serviceToTest.Select();

            // Verify results match expected results
            Assert.Equal(expectedCollectibleCount, collectibleList.Count);
        }
Ejemplo n.º 10
0
        public void FootballSearch_WithNoResults_Succeeds()
        {
            string dbName = "FootballSearch_WithNoResults_Succeeds";
            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve services necessary for test
            var serviceToTest = serviceProvider.GetService <ICollectibleSearchService <CardSearch, CardSearchFilterOptions> >();

            // Add Code Values for sports, leagues, collectible types, and collectible statuses
            SeedService.SeedCodeValues(options);

            // Seed a single baseball card
            SeedService.SeedCard(options, "MLB", 1, "Montana", "Joe", "San Francisco", "49ers", 1981, "Topps", false, true, true, false, 100, 80);

            // Run test to search for football cards
            var filterOptions = new CardSearchFilterOptions
            {
                SportId = SportCodeService.Football.Id
            };
            var collectibleSearch = serviceToTest.Get(filterOptions);

            // Verify that results returned zero football cards
            Assert.Equal(0, collectibleSearch.NumCards);
        }
Ejemplo n.º 11
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("SoftwareSyntaxesController_Seed", entry =>
 {
     entry.SlidingExpiration = MemoryCacheSlidingExpirationDefault;
     return(SeedService.GetAllAsync <SoftwareSyntax, SoftwareSyntaxSeedDto>(
                typeof(SoftwareSyntax).GetProperty("SyntaxId"), typeof(SoftwareSyntax).GetProperty("SoftwareId")));
 }));
Ejemplo n.º 12
0
        public static void UseMadInitialize(this IApplicationBuilder app, SeedService seeder)
        {
            app.UseResponseCompression();
            seeder.SeedUsers();
            app.UseRouting();
            app.UseImageResizer();

            app.UseCsp(opt => opt
                       .StyleSources(s => s.Self()
                                     .UnsafeInline().CustomSources("pay.madpay724.ir", "api.madpay724.ir", "fonts.googleapis.com"))
                       .ScriptSources(s => s.Self()
                                      .UnsafeInline().UnsafeEval().CustomSources("pay.madpay724.ir", "api.madpay724.ir", "apis.google.com", "connect.facebook.net"))
                       .ImageSources(s => s.Self()
                                     .CustomSources("pay.madpay724.ir", "api.madpay724.ir", "res.cloudinary.com", "cloudinary.com", "data:"))
                       .MediaSources(s => s.Self()
                                     .CustomSources("pay.madpay724.ir", "api.madpay724.ir", "res.cloudinary.com", "cloudinary.com", "data:"))
                       .FontSources(s => s.Self()
                                    .CustomSources("fonts.gstatic.com", "data:"))
                       .FrameSources(s => s.Self()
                                     .CustomSources("accounts.google.com"))
                       );


            app.UseXfo(o => o.Deny());
        }
Ejemplo n.º 13
0
        public IHttpActionResult Post()
        {
            var service = new SeedService();

            service.SeedPlants();
            return(Ok("Plants Seeded"));
        }
Ejemplo n.º 14
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SeedService seeder)
        {
            SyncfusionLicenseProvider
            .RegisterLicense(Configuration.GetSection("TokenSetting")
                             .GetSection("SyncfusionKey").Value);

            app.UseMadExceptionHandle(env);

            app.UseMadInitialize(seeder);
            app.UseMadAuth();
            app.UseMadSwagger();
            app.UseMadParbad();

            //app.UseRendertron();

            app.UseEndpoints(end =>
            {
                end.MapControllers();
                end.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=home}/{action=index}");
                end.MapFallbackToController("Index", "FallBack");
                end.MapHub <ChatHubService>(SiteV1Routes.BaseChatPanel + "/chat");
            });

            app.UseMadSpa();
        }
        public void Execute_WithSportFilter_Succeeds()
        {
            string dbName = "ExecuteTeamsQuery_WithSportFilter_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IQueryService <Team, TeamQueryFilterOptions> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            var nfl = LeagueCodeService.NFL;
            var nhl = LeagueCodeService.NHL;

            SeedService.SeedTeam(options, "SanFrancisco49ers", "San Francisco", "49ers", nfl.Identifier, true);
            SeedService.SeedTeam(options, "SanJoseSharks", "San Jose", "Sharks", nhl.Identifier, false);
            SeedService.SeedTeam(options, "LosAngelesChargers", "Los Angeles", "Chargers", nfl.Identifier, false);

            int expectedFootballTeamCount = 2;

            var teamQueryFilterOptions = new TeamQueryFilterOptions
            {
                SportId = SportCodeService.Football.Id
            };

            // Run the test
            var teamList = serviceToTest.Execute(teamQueryFilterOptions);

            // Verify results match expected results
            Assert.Equal(expectedFootballTeamCount, teamList.Count);
        }
Ejemplo n.º 16
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("ForksController_Seed", entry =>
 {
     entry.AbsoluteExpirationRelativeToNow = FourHoursFromNow;
     return(SeedService.GetAllAsync <Fork, ForkSeedDto>(typeof(Fork).GetProperty("UpstreamFilterListId"),
                                                        typeof(Fork).GetProperty("ForkFilterListId")));
 }));
Ejemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SeedService seed)
        {
            app.UsePayExceptionHandle(env);
            app.UsePayInitialize(seed);

            app.UsePayAuth();
            app.UsePaySwagger();


            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/wwwroot")
            });

            //app.UseMvc();

            //app.UseEndpoints(end =>
            //{
            //    end.MapControllers();
            //    end.MapControllerRoute(
            //         name: "default",
            //       pattern: "{controller=home}/{action=index}/{id}");
            //});

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void Execute_WithNotableFilter_Succeeds()
        {
            string dbName = "ExecuteTeamsQuery_WithNotableFilter_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IQueryService <Team, TeamQueryFilterOptions> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            SeedService.SeedTeam(options, "SanFrancisco49ers", "San Francisco", "49ers", "NFL", true);  // only one notable team
            SeedService.SeedTeam(options, "SanJoseSharks", "San Jose", "Sharks", "NHL", false);
            SeedService.SeedTeam(options, "LosAngelesChargers", "Los Angeles", "Chargers", "NFL", false);

            int expectedNotableTeamCount = 1;

            var teamQueryFilterOptions = new TeamQueryFilterOptions
            {
                NotableFlag = true
            };

            // Run the test
            var teamList = serviceToTest.Execute(teamQueryFilterOptions);

            // Verify results match expected results
            Assert.Equal(expectedNotableTeamCount, teamList.Count);
        }
        public void Select_WithInvalidId_Fails()
        {
            string dbName = "SelectPerson_WithInvalidId_Fails";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IDataService <Person> >();

            // Seed data required for the test
            SeedService.SeedCodeValues(options);

            // Run the test

            try
            {
                var person = serviceToTest.Select(0);

                Assert.Null(person);
            }
            catch (InvalidIdException invalidIdException)
            {
                Assert.NotNull(invalidIdException);
            }
            catch (Exception ex)
            {
                Assert.Null(ex);
            }
        }
Ejemplo n.º 20
0
        protected override void Seed(ApplicationContext context)
        {
            var rnd = new Random();

            var seedService = new SeedService();

            context.SaveChanges();

            var flats = new List <Flat>();

            for (int i = 0; i < 20; i++)
            {
                var flat = seedService.GetFlat();
                context.Flats.Add(flat);
            }

            var houses = new List <House>();

            for (int i = 0; i < 25; i++)
            {
                var house = seedService.GetHouse();
                context.Houses.Add(house);
            }

            var lands = new List <Land>();

            for (int i = 0; i < 10; i++)
            {
                var land = seedService.GetLand();
                context.Lands.Add(land);
            }

            context.SaveChanges();
        }
Ejemplo n.º 21
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("SoftwareSyntaxesController_Seed", entry =>
 {
     entry.AbsoluteExpirationRelativeToNow = FourHoursFromNow;
     return(SeedService.GetAllAsync <SoftwareSyntax, SoftwareSyntaxSeedDto>(
                typeof(SoftwareSyntax).GetProperty("SyntaxId"), typeof(SoftwareSyntax).GetProperty("SoftwareId")));
 }));
Ejemplo n.º 22
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SeedService seeder, IHttpContextAccessor _httpContextAccessor)
        {
            //app.UseForwardedHeaders(new ForwardedHeadersOptions
            //{
            //    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            //});

            app.UseMadExceptionHandle(env);
            app.UseMadInitialize(seeder);
            app.UseMadAuth();
            app.UseMadSwagger();
            app.UseMadParbad();


            var rewriteOptions = new RewriteOptions();

            rewriteOptions.Rules.Add(new NonWwwRewriteRule());
            //rewriteOptions.AddRedirect(@"^\s*$", "https://api.madpay724.ir/swagger", 301);

            app.UseRewriter(rewriteOptions);


            app.UseEndpoints(end =>
            {
                end.MapControllers();
            });
        }
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("DependentsController_Seed", entry =>
 {
     entry.SlidingExpiration = MemoryCacheSlidingExpirationDefault;
     return(SeedService.GetAllAsync <Dependent, DependentSeedDto>(typeof(Dependent).GetProperty("DependentFilterListId"),
                                                                  typeof(Dependent).GetProperty("DependencyFilterListId")));
 }));
Ejemplo n.º 24
0
        public void SelectAll_Succeeds()
        {
            string dbName = "SelectAllProducts_Succeeds";

            // Create dependency injection provider using method as database name
            var serviceProvider = BuildServiceProvider(dbName);
            var options         = GetContextOptions(dbName);

            // Retrieve service to be tested
            var serviceToTest = serviceProvider.GetService <IDataService <Product> >();

            // Seed data required for test
            SeedService.SeedCodeValues(options);

            int expectedProductCount = 3;

            for (int i = 0; i < expectedProductCount; i++)
            {
                SeedService.SeedProduct(options, string.Format("Product {0}", i));
            }

            // Run the test
            var productList = serviceToTest.Select();

            // Verify results match expected results
            Assert.Equal(expectedProductCount, productList.Count);
        }
Ejemplo n.º 25
0
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("ListsTagsController_Seed", entry =>
 {
     entry.AbsoluteExpirationRelativeToNow = MemoryCacheExpirationDefault;
     return(SeedService.GetAllAsync <FilterListTag, FilterListTagSeedDto>(
                typeof(FilterListTag).GetProperty("FilterListId"),
                typeof(FilterListTag).GetProperty("TagId")));
 }));
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("ListsMaintainersController_Seed", entry =>
 {
     entry.AbsoluteExpirationRelativeToNow = FourHoursFromNow;
     return(SeedService.GetAllAsync <FilterListMaintainer, FilterListMaintainerSeedDto>(
                typeof(FilterListMaintainer).GetProperty("MaintainerId"),
                typeof(FilterListMaintainer).GetProperty("FilterListId")));
 }));
Ejemplo n.º 27
0
        public IHttpActionResult Post()
        {
            SeedService seedService = new SeedService();

            seedService.SeedAdjustmentTable();
            seedService.SeedLevelTable();
            return(Ok());
        }
 public async Task <IActionResult> Seed() =>
 Json(await MemoryCache.GetOrCreate("ListsMaintainersController_Seed", entry =>
 {
     entry.SlidingExpiration = MemoryCacheSlidingExpirationDefault;
     return(SeedService.GetAllAsync <FilterListMaintainer, FilterListMaintainerSeedDto>(
                typeof(FilterListMaintainer).GetProperty("MaintainerId"),
                typeof(FilterListMaintainer).GetProperty("FilterListId")));
 }));
Ejemplo n.º 29
0
        public void SeedPerson_Succeeds()
        {
            string dbName = "SeedPerson_Succeeds";

            var options = GetContextOptions(dbName);


            // Run test
            string personLastName        = "Montana";
            string personFirstName       = "Joe";
            string personMiddleName      = null;
            string personSuffix          = null;
            string personSportIdentifier = "FB";
            bool   personHOFFlag         = true;
            bool   personHeismanFlag     = false;
            bool   personNotableFlag     = false;
            string personCollegeName     = "Notre Dame";
            string personCollegeNickname = "Fightin Irish";

            SeedService.SeedCodeValues(options);

            int personId = SeedService.SeedPerson(options, personLastName, personFirstName, personMiddleName, personSuffix, personSportIdentifier, personHOFFlag, personHeismanFlag, personNotableFlag, personCollegeName, personCollegeNickname);

            // Create a new db context to use for verification - I don't know how to get a separate instance from the DI framework...
            using (var qdbContext = GetQdbContext(dbName))
            {
                // Retrieve data directly from entity framework context
                var person = qdbContext.People
                             .Include(x => x.College)
                             .SingleOrDefault(x => x.Id == personId);

                // Verify results contain all expected relationships
                Assert.NotNull(person);
                Assert.NotNull(person.College);

                // Verify results contain values specified in service call
                Assert.Equal(person.LastName, personLastName);
                Assert.Equal(person.FirstName, personFirstName);
                Assert.Equal(person.MiddleName, personMiddleName);
                Assert.Equal(person.Suffix, personSuffix);
                Assert.Equal(person.HOFFlag, personHOFFlag);
                Assert.Equal(person.HeismanFlag, personHeismanFlag);
                Assert.Equal(person.NotableFlag, personNotableFlag);

                Assert.Equal(person.College.Name, personCollegeName);
                Assert.Equal(person.College.Nickname, personCollegeNickname);

                var personSports = qdbContext.PersonSports
                                   .Include(x => x.Sport)
                                   .Where(x => x.PersonId == personId)
                                   .ToList();

                var sport = personSports.Select(x => x.Sport).SingleOrDefault();

                Assert.NotNull(sport);
                Assert.Equal(personSportIdentifier, sport.Identifier);
            }
        }
        protected override void Seed(HardwareInventoryManager.Models.ApplicationDbContext context)
        {
            //if (System.Diagnostics.Debugger.IsAttached == false)
            //    System.Diagnostics.Debugger.Launch();

            //  This method will be called after migrating to the latest version.
            CustomApplicationDbContext customContext = new CustomApplicationDbContext();
            SeedService initialSeed = new SeedService(customContext);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (validator1.Validate() && cbxCustomer.SelectedValue != null && cbxCustomer.SelectedIndex > 0)
            {
                BillService billService = new BillService();
                if (bill == null)
                {
                    double amount = 0;
                    string amountStr = string.IsNullOrEmpty(txtAmount.WorkingText) ? txtAmount.Text : txtAmount.WorkingText;
                    double.TryParse(amountStr, out amount);
                    DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                    int userId = 0;
                    if (Global.CurrentUser != null)
                    {
                        userId = Global.CurrentUser.Id;
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    
                    SeedService ss = new SeedService();
                    bill = new Bill
                    {
                        BillCode = ss.AddSeedID(BHConstant.PREFIX_FOR_BILLING),
                        Note = txtNote.Text,
                        CreatedDate = systime,
                        Amount = amount,
                        CustId = cbxCustomer.SelectedValue != null ? (int)cbxCustomer.SelectedValue : 0,
                        UserId = userId
                    };

                    bool result = billService.AddBill(bill);
                    CustomerLogService cls = new CustomerLogService();
                    CustomerLog cl = new CustomerLog
                    {
                        CustomerId = bill.CustId,
                        RecordCode = bill.BillCode,
                        Amount = bill.Amount,
                        Direction = BHConstant.DIRECTION_IN,
                        CreatedDate = systime
                    };
                    result = cls.AddCustomerLog(cl);
                    if (result)
                    {
                        MessageBox.Show("Phiếu thanh toán đã được thêm!");
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                if (this.CallFromUserControll != null && this.CallFromUserControll is BillList)
                {
                    ((BillList)this.CallFromUserControll).loadBillList();
                }
                this.Close();
                return;
            }
            MessageBox.Show("Vui lòng kiểm tra các thông tin cần thiết!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;  
        }
        private bool saveData()
        {
            calculateTotal();
            if (validator1.Validate() && ValidateData())
            {
                if (cbxCustomer.SelectedValue == null || cbxCustomer.SelectedIndex <= 0)
                {
                    MessageBox.Show("Bạn cần có một khách hàng cho phiếu này!");
                    return false;
                }
                DialogResult dialogResult = Preview();
                if (dialogResult == DialogResult.OK)
                {
                    XKNumber = PrintPreview.XKNumber;
                    BHNumber = PrintPreview.BHNumber;
                    double discount = 0;
                    Double.TryParse(txtDiscount.WorkingText, out discount);
                    DateTime createdDate = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();

                    double vat = 0;
                    Double.TryParse(txtVAT.WorkingText, out vat);
                    int userId = 0;
                    if (Global.CurrentUser != null)
                    {
                        userId = Global.CurrentUser.Id;
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                    if (order != null)//update
                    {
                        #region Update

                        order.CustId = (int)cbxCustomer.SelectedValue;
                        order.Discount = discount;
                        order.Note = txtNote.Text;
                        order.VAT = vat;
                        order.OrderCode = txtOrderCode.Text;
                        order.Reason = txtReason.Text;
                        order.WareHouse = txtWare.Text;
                        order.Total = totalWithTax;
                        order.UpdatedDate = createdDate;

                        #region Update Order Detail

                        string msg = "";
                        int error = 0, amount_change = 0;
                        ProductLog pl, newpl;
                        OrderDetail prd;

                        // Check old data

                        OrderDetailService orderDetailService = new OrderDetailService();
                        List<OrderDetail> deleted_details = old_orderDetails.Where(x => !orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        List<OrderDetail> updated_details = old_orderDetails.Where(x => orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        List<OrderDetail> new_details = orderDetails.Where(x => !old_orderDetails.Select(y => y.ProductId.ToString() + '_' +
                            y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                            x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                        foreach (OrderDetail item in updated_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            prd = orderDetails.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                                x.UnitId == item.UnitId).FirstOrDefault();
                            amount_change = Convert.ToInt32(prd.NumberUnit - item.NumberUnit);
                            if (amount_change > 0 && pl.AfterNumber - amount_change < 0) // Tang nguyen lieu
                            {
                                if (error == 0)
                                {
                                    msg += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                            }
                        }
                        foreach (OrderDetail item in new_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            if (pl.AfterNumber - item.NumberUnit < 0)
                            {
                                if (error < 2)
                                {
                                    msg += "Những sản phẩm sau không đủ số lượng để tạo phiếu bán hàng:\n";
                                    error = 2;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                            }
                        }

                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        foreach (OrderDetail item in deleted_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            newpl = new ProductLog()
                            {
                                ProductId = item.ProductId,
                                AttributeId = item.AttributeId,
                                UnitId = item.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount = item.NumberUnit,
                                AfterNumber = pl.AfterNumber + item.NumberUnit,
                                RecordCode = order.OrderCode,
                                Status = BHConstant.ACTIVE_STATUS,
                                Direction = BHConstant.DIRECTION_IN,
                                UpdatedDate = createdDate
                            };
                            productLogService.AddProductLog(newpl);
                        }
                        foreach (OrderDetail od in orderDetails)
                        {
                            od.OrderId = order.Id;
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                totalCommission += od.Commission;
                                OrderDetail tmp_ode = old_orderDetails.Where(x => x.ProductId == od.ProductId &&
                                    x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.OrderId == order.Id).FirstOrDefault();
                                if (tmp_ode != null)
                                {
                                    double amount = tmp_ode.NumberUnit - od.NumberUnit;
                                    bool ret = orderDetailService.UpdateOrderDetail(od);
                                    //Save in Production Log
                                    if (amount != 0)
                                    {
                                        pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                        newpl = new ProductLog()
                                        {
                                            ProductId = od.ProductId,
                                            AttributeId = od.AttributeId,
                                            UnitId = od.UnitId,
                                            BeforeNumber = pl.AfterNumber,
                                            Amount = Math.Abs(amount),
                                            AfterNumber = pl.AfterNumber + amount,
                                            RecordCode = order.OrderCode,
                                            Status = BHConstant.ACTIVE_STATUS,
                                            Direction = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                            UpdatedDate = createdDate
                                        };
                                        productLogService.AddProductLog(newpl);
                                    }
                                }
                                else
                                {
                                    bool ret = (od.Id != null && od.Id > 0) ? orderDetailService.UpdateOrderDetail(od) 
                                        : orderDetailService.AddOrderDetail(od);
                                    //Save in Production Log
                                    pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = od.ProductId,
                                        AttributeId = od.AttributeId,
                                        UnitId = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = od.NumberUnit,
                                        AfterNumber = pl.AfterNumber - od.NumberUnit,
                                        RecordCode = order.OrderCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = BHConstant.DIRECTION_OUT,
                                        UpdatedDate = createdDate
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                        }

                        OrderService orderService = new OrderService();
                        bool result = orderService.UpdateOrder(order);

                        #endregion

                        #region KH & NV

                        CustomerLogService cls = new CustomerLogService();
                        CustomerLog newest = cls.GetCustomerLog(order.OrderCode);
                        if (newest != null)
                        {
                            newest.Amount = totalWithTax;
                            cls.UpdateCustomerLog(newest);
                        }

                        int salerId = (int)order.Customer.SalerId;
                        if (salerId > 0)
                        {
                            EmployeeLogService els = new EmployeeLogService();
                            EmployeeLog order_el = els.SelectEmployeeLogByWhere(x => x.RecordCode == order.OrderCode).FirstOrDefault();
                            if (order_el != null)
                            {
                                order_el.Amount = totalCommission;
                                els.UpdateEmployeeLog(order_el);
                            }
                        }

                        #endregion

                        if (result)
                        {
                            MessageBox.Show("Phiếu bán hàng đã được cập nhật thành công");
                            this.Close();
                            return true;
                        }
                        else
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        #endregion
                    }
                    else//add new
                    {
                        #region Create New

                        ProductLog pl, newpl;
                        string msg = "";
                        int error = 0;
                        foreach (OrderDetail item in orderDetails)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            if (pl.AfterNumber - item.NumberUnit < 0)
                            {
                                if (error == 0)
                                {
                                    msg += "Những sản phẩm sau không đủ số lượng để tạo phiếu bán hàng:\n";
                                    error = 1;
                                }
                                msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                            }
                        }

                        if (error > 0)
                        {
                            MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        SeedService ss = new SeedService();
                        order = new Order
                        {
                            CustId = cbxCustomer.SelectedValue != null ? (int)cbxCustomer.SelectedValue : 0,
                            Discount = discount,
                            Note = txtNote.Text,
                            VAT = vat,
                            OrderCode = ss.AddSeedID(BHConstant.PREFIX_FOR_ORDER),
                            CreatedDate = createdDate,
                            UserId = userId,
                            Reason = txtReason.Text,
                            WareHouse = txtWare.Text,
                            Total = totalWithTax
                        };
                        OrderService orderService = new OrderService();
                        bool result = orderService.AddOrder(order);
                        long newOrderId = -1;
                        try
                        {
                            newOrderId = order.Id;// BaoHienRepository.GetMaxId<Order>();
                        }
                        catch
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }

                        #region New Order Detail

                        OrderDetailService orderDetailService = new OrderDetailService();
                        foreach (OrderDetail od in orderDetails)
                        {
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                od.OrderId = (int)newOrderId;
                                bool ret = orderDetailService.AddOrderDetail(od);
                                totalCommission += od.Commission;

                                //Save in Production Log
                                pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                newpl = new ProductLog()
                                {
                                    ProductId = od.ProductId,
                                    AttributeId = od.AttributeId,
                                    UnitId = od.UnitId,
                                    BeforeNumber = pl.AfterNumber,
                                    Amount = od.NumberUnit,
                                    AfterNumber = pl.AfterNumber - od.NumberUnit,
                                    RecordCode = order.OrderCode,
                                    Status = BHConstant.ACTIVE_STATUS,
                                    Direction = BHConstant.DIRECTION_OUT,
                                    UpdatedDate = createdDate
                                };
                                productLogService.AddProductLog(newpl);
                            }
                        }

                        #endregion

                        #region KH & NV

                        CustomerLogService cls = new CustomerLogService();
                        CustomerLog cl = new CustomerLog
                        {
                            CustomerId = order.CustId,
                            RecordCode = order.OrderCode,
                            Amount = totalWithTax,
                            Direction = BHConstant.DIRECTION_OUT,
                            CreatedDate = createdDate
                        };
                        result = cls.AddCustomerLog(cl);

                        int salerId = (int)order.Customer.SalerId;
                        if (salerId > 0)
                        {
                            EmployeeLogService els = new EmployeeLogService();
                            EmployeeLog newel = new EmployeeLog
                            {
                                EmployeeId = salerId,
                                RecordCode = order.OrderCode,
                                Amount = totalCommission,
                                CreatedDate = createdDate
                            };
                            result = els.AddEmployeeLog(newel);
                        }

                        #endregion

                        if (result)
                        {
                            MessageBox.Show("Phiếu bán hàng đã được tạo thành công");
                            this.Close();
                            return true;
                        }
                        else
                        {
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return false;
                        }
                        #endregion
                    }
                }
                return false;
            }
            else
            {
                MessageBox.Show("Vui lòng kiểm tra các thông tin cần thiết!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.validator1.Validate() && ValidateData())
            {
                ProductionRequestService prs = new ProductionRequestService();
                ProductionRequestDetailService productionRequestDetailService = new ProductionRequestDetailService();
                DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                if (productionRequest != null)
                {
                    #region Fix Update
                        
                    productionRequest.UpdatedDate = systime;
                    productionRequest.Note = txtNote.Text;

                    string msg = "";
                    int error = 0, amount_change = 0;
                    ProductLog pl, newpl;
                    ProductionRequestDetail prd;

                    #region Check old data

                    // Material
                    List<ProductionRequestDetail> deleted_material_details = old_marterial_details.Where(x => !productionRequestDetailInMaterials.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    List<ProductionRequestDetail> updated_material_details = old_marterial_details.Where(x => productionRequestDetailInMaterials.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    List<ProductionRequestDetail> new_material_details = productionRequestDetailInMaterials.Where(x => !old_marterial_details.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (ProductionRequestDetail item in updated_material_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        prd = productionRequestDetailInMaterials.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                            x.UnitId == item.UnitId).FirstOrDefault();
                        amount_change = Convert.ToInt32(prd.NumberUnit - item.NumberUnit);
                        if (amount_change > 0 && pl.AfterNumber - amount_change < 0) // Tang nguyen lieu
                        {
                            if (error == 0)
                            {
                                msg += "Phần NGUYÊN LIỆU\n";
                                msg += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 1;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                        }
                    }
                    foreach (ProductionRequestDetail item in new_material_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        if (pl.AfterNumber - item.NumberUnit < 0)
                        {
                            if (error < 2)
                            {
                                msg += "Phần NGUYÊN LIỆU\n";
                                msg += "Những sản phẩm sau không đủ số lượng để tạo phiếu sản xuất:\n";
                                error = 2;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                        }
                    }

                    // Production
                    List<ProductionRequestDetail> deleted_production_details = old_production_details.Where(x => !productionRequestDetailInProductions.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    List<ProductionRequestDetail> updated_production_details = old_production_details.Where(x => productionRequestDetailInProductions.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (ProductionRequestDetail item in deleted_production_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        if (pl.AfterNumber - item.NumberUnit < 0)
                        {
                            if (error < 3)
                            {
                                msg += "Phần THÀNH PHẨM\n";
                                msg += "Những sản phẩm sau đã bị XÓA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 3;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + item.NumberUnit + "\n";
                        }
                    }
                    foreach (ProductionRequestDetail item in updated_production_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        prd = productionRequestDetailInProductions.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                            x.UnitId == item.UnitId).FirstOrDefault();
                        amount_change = Convert.ToInt32(prd.NumberUnit - item.NumberUnit);
                        if (amount_change < 0 && pl.AfterNumber + amount_change < 0) // Giam so luong thanh pham
                        {
                            if (error < 4)
                            {
                                msg += "Phần THÀNH PHẨM\n";
                                msg += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 4;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                        }
                    }

                    if (error > 0)
                    {
                        MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    #endregion

                    #region Update Marterial

                    foreach (ProductionRequestDetail item in deleted_material_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        newpl = new ProductLog()
                        {
                            ProductId = item.ProductId,
                            AttributeId = item.AttributeId,
                            UnitId = item.UnitId,
                            BeforeNumber = pl.AfterNumber,
                            Amount = item.NumberUnit,
                            AfterNumber = pl.AfterNumber + item.NumberUnit,
                            RecordCode = productionRequest.ReqCode,
                            Status = BHConstant.ACTIVE_STATUS,
                            Direction = BHConstant.DIRECTION_IN,
                            UpdatedDate = systime
                        };
                        productLogService.AddProductLog(newpl);
                    }
                    foreach (ProductionRequestDetail od in productionRequestDetailInMaterials)
                    {
                        od.ProductionRequestId = productionRequest.Id;
                        od.Direction = BHConstant.DIRECTION_OUT;
                        if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                        {
                            ProductionRequestDetail tmp_ode = old_marterial_details.Where(x => x.ProductId == od.ProductId &&
                                x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.ProductionRequestId == productionRequest.Id).FirstOrDefault();
                            if (tmp_ode != null)
                            {
                                double amount = tmp_ode.NumberUnit - od.NumberUnit;
                                productionRequestDetailService.UpdateProductionRequestDetail(od);
                                //Save in Production Log
                                if (amount != 0)
                                {
                                    pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = od.ProductId,
                                        AttributeId = od.AttributeId,
                                        UnitId = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = Math.Abs(amount),
                                        AfterNumber = pl.AfterNumber + amount,
                                        RecordCode = productionRequest.ReqCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                        UpdatedDate = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                            else
                            {
                                bool ret = (od.Id != null && od.Id > 0) ? productionRequestDetailService.UpdateProductionRequestDetail(od) 
                                    : productionRequestDetailService.AddProductionRequestDetail(od);
                                //Save in Production Log
                                pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                newpl = new ProductLog()
                                {
                                    ProductId = od.ProductId,
                                    AttributeId = od.AttributeId,
                                    UnitId = od.UnitId,
                                    BeforeNumber = pl.AfterNumber,
                                    Amount = od.NumberUnit,
                                    AfterNumber = pl.AfterNumber - od.NumberUnit,
                                    RecordCode = productionRequest.ReqCode,
                                    Status = BHConstant.ACTIVE_STATUS,
                                    Direction = BHConstant.DIRECTION_OUT,
                                    UpdatedDate = systime
                                };
                                productLogService.AddProductLog(newpl);
                            }
                        }
                    }

                    #endregion

                    #region Update Production

                    foreach (ProductionRequestDetail item in deleted_production_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        newpl = new ProductLog()
                        {
                            ProductId = item.ProductId,
                            AttributeId = item.AttributeId,
                            UnitId = item.UnitId,
                            BeforeNumber = pl.AfterNumber,
                            Amount = item.NumberUnit,
                            AfterNumber = pl.AfterNumber - item.NumberUnit,
                            RecordCode = productionRequest.ReqCode,
                            Status = BHConstant.ACTIVE_STATUS,
                            Direction = BHConstant.DIRECTION_OUT,
                            UpdatedDate = systime
                        };
                        productLogService.AddProductLog(newpl);
                    }
                    foreach (ProductionRequestDetail od in productionRequestDetailInProductions)
                    {
                        od.ProductionRequestId = productionRequest.Id;
                        od.Direction = BHConstant.DIRECTION_IN;
                        if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                        {
                            ProductionRequestDetail tmp_ode = old_production_details.Where(x => x.ProductId == od.ProductId &&
                                x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.ProductionRequestId == productionRequest.Id).FirstOrDefault();
                            if (tmp_ode != null)
                            {
                                double amount = od.NumberUnit - tmp_ode.NumberUnit;
                                productionRequestDetailService.UpdateProductionRequestDetail(od);
                                //Save in Production Log
                                if (amount != 0)
                                {
                                    pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = od.ProductId,
                                        AttributeId = od.AttributeId,
                                        UnitId = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = Math.Abs(amount),
                                        AfterNumber = pl.AfterNumber + amount,
                                        RecordCode = productionRequest.ReqCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                        UpdatedDate = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                            else
                            {
                                bool ret = (od.Id != null && od.Id > 0) ? productionRequestDetailService.UpdateProductionRequestDetail(od) 
                                    : productionRequestDetailService.AddProductionRequestDetail(od);
                                //Save in Production Log
                                pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                newpl = new ProductLog()
                                {
                                    ProductId = od.ProductId,
                                    AttributeId = od.AttributeId,
                                    UnitId = od.UnitId,
                                    BeforeNumber = pl.AfterNumber,
                                    Amount = od.NumberUnit,
                                    AfterNumber = pl.AfterNumber + od.NumberUnit,
                                    RecordCode = productionRequest.ReqCode,
                                    Status = BHConstant.ACTIVE_STATUS,
                                    Direction = BHConstant.DIRECTION_IN,
                                    UpdatedDate = systime
                                };
                                productLogService.AddProductLog(newpl);
                            }
                        }
                    }

                    #endregion

                    bool result = prs.UpdateProductionRequest(productionRequest);
                    if (result)
                        MessageBox.Show("Phiếu sản xuất đã được cập nhật thành công");
                    else
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();

                    #endregion
                }
                else
                {
                    #region New

                    int userId = 0;
                    ProductLog pl, newpl;
                    if (Global.CurrentUser != null)
                    {
                        userId = Global.CurrentUser.Id;
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    string msg = "";
                    int error = 0;
                    foreach (ProductionRequestDetail prd in productionRequestDetailInMaterials)
                    {
                        pl = productLogService.GetProductLog(prd.ProductId, prd.AttributeId, prd.UnitId);
                        if (pl.AfterNumber - prd.NumberUnit < 0)
                        {
                            if (error == 0)
                            {
                                msg += "Những sản phẩm sau bên phần nguyên liệu không đủ số lượng để tạo phiếu sản xuất:\n";
                                error = 1;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " còn : " + pl.AfterNumber + "\n";
                        }
                    }

                    if (error > 0)
                    {
                        MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    SeedService ss = new SeedService();
                    productionRequest = new ProductionRequest
                    {
                        Note = txtNote.Text,
                        ReqCode = ss.AddSeedID(BHConstant.PREFIX_FOR_PRODUCTION),
                        CreatedDate = systime,
                        UserId = userId,
                    };

                    bool result = prs.AddProductionRequest(productionRequest);
                    if (result)
                    {
                        long newProductionRequestId = BaoHienRepository.GetMaxId<ProductionRequest>();
                        try
                        {
                            foreach (ProductionRequestDetail prd in productionRequestDetailInProductions)
                            {
                                prd.Direction = BHConstant.DIRECTION_IN;
                                if (prd.ProductId > 0 && prd.AttributeId > 0 && prd.UnitId > 0)
                                {
                                    prd.ProductionRequestId = (int)newProductionRequestId;
                                    prd.Direction = BHConstant.DIRECTION_IN;
                                    productionRequestDetailService.AddProductionRequestDetail(prd);
                                    //Save in Production Log
                                    pl = productLogService.GetProductLog(prd.ProductId, prd.AttributeId, prd.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = prd.ProductId,
                                        AttributeId = prd.AttributeId,
                                        UnitId = prd.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = prd.NumberUnit,
                                        AfterNumber = pl.AfterNumber + prd.NumberUnit,
                                        RecordCode = productionRequest.ReqCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = BHConstant.DIRECTION_IN,
                                        UpdatedDate = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }

                            foreach (ProductionRequestDetail prd in productionRequestDetailInMaterials)
                            {
                                prd.Direction = BHConstant.DIRECTION_OUT;
                                if (prd.ProductId > 0 && prd.AttributeId > 0 && prd.UnitId > 0)
                                {
                                    prd.ProductionRequestId = (int)newProductionRequestId;
                                    prd.Direction = BHConstant.DIRECTION_OUT;
                                    productionRequestDetailService.AddProductionRequestDetail(prd);

                                    //Save in Product Log
                                    pl = productLogService.GetProductLog(prd.ProductId, prd.AttributeId, prd.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = prd.ProductId,
                                        AttributeId = prd.AttributeId,
                                        UnitId = prd.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = prd.NumberUnit,
                                        AfterNumber = pl.AfterNumber - prd.NumberUnit,
                                        RecordCode = productionRequest.ReqCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = BHConstant.DIRECTION_OUT,
                                        UpdatedDate = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                        }
                        catch { }
                        MessageBox.Show("Phiếu sản xuất đã được tạo thành công");
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    #endregion
                }
            } 
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.validator1.Validate() && ValidateData())
            {
                DateTime systime = BaoHienRepository.GetBaoHienDBDataContext().GetSystemDate();
                int userId = 0;
                if (Global.CurrentUser != null)
                {
                    userId = Global.CurrentUser.Id;
                }
                else
                {
                    MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (entranceStock != null && isUpdating)//update
                {
                    #region Fix Update

                    string msg = "";
                    int error = 0, amount_change = 0;
                    ProductLog pl, newpl;
                    EntranceStockDetail esd;
                    // Check update old data
                    List<EntranceStockDetail> deleted_details = old_details.Where(x => !entranceStockDetails.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (EntranceStockDetail item in deleted_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        if (pl.AfterNumber - item.NumberUnit < 0)
                        {
                            if (error == 0)
                            {
                                msg += "Những sản phẩm sau đã bị XÓA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 1;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + item.NumberUnit + "\n";
                        }
                    }

                    List<EntranceStockDetail> updated_details = old_details.Where(x => entranceStockDetails.Select(y => y.ProductId.ToString() + '_' +
                        y.AttributeId.ToString() + '_' + y.UnitId.ToString()).Contains(x.ProductId.ToString() + '_' +
                        x.AttributeId.ToString() + '_' + x.UnitId.ToString())).ToList();
                    foreach (EntranceStockDetail item in updated_details)
                    {
                        pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                        esd = entranceStockDetails.Where(x => x.ProductId == item.ProductId && x.AttributeId == item.AttributeId &&
                            x.UnitId == item.UnitId).FirstOrDefault();
                        amount_change = Convert.ToInt32(esd.NumberUnit - item.NumberUnit);
                        if (amount_change < 0 && pl.AfterNumber + amount_change < 0) // Giam so luong nhap
                        {
                            if (error < 2)
                            {
                                msg += "Những sản phẩm sau đã bị SỬA nhưng không đảm bảo dữ liệu trong kho:\n";
                                error = 2;
                            }
                            msg += "- " + productLogService.GetNameOfProductLog(pl) + " : " + amount_change.ToString() + "\n";
                        }
                    }

                    if (error > 0)
                    {
                        MessageBox.Show(msg, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        entranceStock.UserId = userId;
                        entranceStock.Note = txtNote.Text;
                        entranceStock.UpdatedDate = systime;

                        EntranceStockDetailService entranceStockDetailService = new EntranceStockDetailService();
                        foreach (EntranceStockDetail item in deleted_details)
                        {
                            pl = productLogService.GetProductLog(item.ProductId, item.AttributeId, item.UnitId);
                            newpl = new ProductLog()
                            {
                                ProductId = item.ProductId,
                                AttributeId = item.AttributeId,
                                UnitId = item.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount = item.NumberUnit,
                                AfterNumber = pl.AfterNumber - item.NumberUnit,
                                RecordCode = entranceStock.EntranceCode,
                                Status = BHConstant.ACTIVE_STATUS,
                                Direction = BHConstant.DIRECTION_OUT,
                                UpdatedDate = systime
                            };
                            productLogService.AddProductLog(newpl);
                        }
                        foreach (EntranceStockDetail od in entranceStockDetails)
                        {
                            od.EntranceStockId = entranceStock.Id;
                            if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                            {
                                EntranceStockDetail tmp_ode = old_details.Where(x => x.ProductId == od.ProductId &&
                                    x.AttributeId == od.AttributeId && x.UnitId == od.UnitId && x.EntranceStockId == entranceStock.Id).FirstOrDefault();
                                if (tmp_ode != null)
                                {
                                    double amount = od.NumberUnit - tmp_ode.NumberUnit;
                                    entranceStockDetailService.UpdateEntranceStockDetail(od);
                                    //Save in Production Log
                                    if (amount != 0)
                                    {
                                        pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                        newpl = new ProductLog()
                                        {
                                            ProductId = od.ProductId,
                                            AttributeId = od.AttributeId,
                                            UnitId = od.UnitId,
                                            BeforeNumber = pl.AfterNumber,
                                            Amount = Math.Abs(amount),
                                            AfterNumber = pl.AfterNumber + amount,
                                            RecordCode = entranceStock.EntranceCode,
                                            Status = BHConstant.ACTIVE_STATUS,
                                            Direction = amount > 0 ? BHConstant.DIRECTION_IN : BHConstant.DIRECTION_OUT,
                                            UpdatedDate = systime
                                        };
                                        productLogService.AddProductLog(newpl);
                                    }
                                }
                                else
                                {
                                    bool ret = (od.Id != null && od.Id > 0) ? entranceStockDetailService.UpdateEntranceStockDetail(od)
                                        : entranceStockDetailService.AddEntranceStockDetail(od);
                                    //Save in Production Log
                                    pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                                    newpl = new ProductLog()
                                    {
                                        ProductId = od.ProductId,
                                        AttributeId = od.AttributeId,
                                        UnitId = od.UnitId,
                                        BeforeNumber = pl.AfterNumber,
                                        Amount = od.NumberUnit,
                                        AfterNumber = pl.AfterNumber + od.NumberUnit,
                                        RecordCode = entranceStock.EntranceCode,
                                        Status = BHConstant.ACTIVE_STATUS,
                                        Direction = BHConstant.DIRECTION_IN,
                                        UpdatedDate = systime
                                    };
                                    productLogService.AddProductLog(newpl);
                                }
                            }
                        }

                        EntranceStockService entranceStockService = new EntranceStockService();
                        bool result = entranceStockService.UpdateEntranceStock(entranceStock);

                        if (result)
                            MessageBox.Show("Phiếu nhập kho đã được cập nhật thành công");
                        else
                            MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.Close();
                    }
                    catch { }
                    #endregion
                }
                else//add new
                {
                    #region New

                    SeedService ss = new SeedService();
                    entranceStock = new EntranceStock
                    {
                        EntranceCode = ss.AddSeedID(BHConstant.PREFIX_FOR_ENTRANCE),
                        UserId = userId,
                        CreatedDate = systime,
                        Note = txtNote.Text
                    };
                    EntranceStockService entranceStockService = new EntranceStockService();
                    bool result = entranceStockService.AddEntranceStock(entranceStock);
                    long newOrderId = BaoHienRepository.GetMaxId<EntranceStock>();
                    EntranceStockDetailService entranceStockDetailService = new EntranceStockDetailService();
                    foreach (EntranceStockDetail od in entranceStockDetails)
                    {
                        if (od.ProductId > 0 && od.AttributeId > 0 && od.UnitId > 0)
                        {
                            od.EntranceStockId = (int)newOrderId;
                            bool ret = entranceStockDetailService.AddEntranceStockDetail(od);
                            if (!ret)
                            {
                                MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            //Save in Product Log
                            ProductLog pl = productLogService.GetProductLog(od.ProductId, od.AttributeId, od.UnitId);
                            ProductLog newpl = new ProductLog()
                            {
                                ProductId = od.ProductId,
                                AttributeId = od.AttributeId,
                                UnitId = od.UnitId,
                                BeforeNumber = pl.AfterNumber,
                                Amount = od.NumberUnit,
                                AfterNumber = pl.AfterNumber + od.NumberUnit,
                                RecordCode = entranceStock.EntranceCode,
                                Status = BHConstant.ACTIVE_STATUS,
                                Direction = BHConstant.DIRECTION_IN,
                                UpdatedDate = systime
                            };
                            productLogService.AddProductLog(newpl);
                        }
                    }
                    if (result)
                        MessageBox.Show("Phiếu nhập kho đã được tạo thành công");
                    else
                        MessageBox.Show("Hiện tại hệ thống đang có lỗi. Vui lòng thử lại sau!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();

                    #endregion
                }
            }            
        }