예제 #1
0
        /////////////// Initialize window
        public ConsoleWindow()
        {
            InitializeComponent();
            if (!LocalUserSession.LoggedIn)
            {
                // User not logged in, display login window instead
            }
            else
            {
                // Initialize the server components
                nt = new NetworkUtility(commPort, null);
                nt.StartServer();
                nt.ClientConnect += OnClientConnectedEvent;
                //nt.Cmd.SimUpdateEvent += OnSimUpdateEvent;
                //nt.CmdAdmin.SimUpdateEvent += OnSimUpdateEvent;

                db = new SQLiteController();
                bs = db.PullBusinessSettings();
                SetTheme();

                systemClock = new Thread(() => RunClock());
                //RunLockoutTimerThread();

                consoleAreaPanel.Click += ((sender, e) => consoleAreaPanel.Focus());
                UpdateUser();

                contextMenuStrip1.Closed     += ((sender, e) => profileVisible = false);
                consoleAreaPanel.SizeChanged += InitialSimDisplayLoad;
                systemClock.Start();
            }
        }
예제 #2
0
        private void SetTheme()
        {
            bs  = db.PullBusinessSettings();
            mtc = bs.GetTheme().MainThemeColor;

            buttonTabBorderPNL.BackColor = mtc;
        }
예제 #3
0
        public static TBusiness GetBusiness <TBusiness>(string key)
            where TBusiness : class
        {
            // Initialize the provider's default value
            string keyName = key;

            // Get the repositoryMappingsConfiguration config section
            BusinessSettings settings = (BusinessSettings)ConfigurationManager.GetSection(BusinessMappingConstants.BusinessMappingsConfigurationSectionName);

            // Get the type to be created
            Type businessType = null;

            // See if a valid interfaceShortName was passed in
            if (settings.BusinessMappings.ContainsKey(keyName))
            {
                businessType = Type.GetType(settings.BusinessMappings[keyName].BusinessFullTypeName);
            }

            // Throw an exception if the right Repository
            // Mapping Element could not be found and the resulting
            // Repository Type could not be created
            if (businessType == null)
            {
                throw new ArgumentNullException("خطا در ایجاد نوع . نوع انباره ی درخواست شده در فایل تنظیمات یافت نشد" + " Requested Repository Name: " + keyName);
            }

            // Create the repository, and cast it to the interface specified

            return(Activator.CreateInstance(businessType, new object[] { }) as TBusiness);
        }
예제 #4
0
        public NewBookingWindow(Dictionary <string, Simulator> sims, DateTime dt, BookingSheetWindow bsw, Booking existing, string selSimMac, int x)
        {
            InitializeComponent();
            bs = db.PullBusinessSettings();
            SetTheme();
            this.sims = sims;
            selDay    = dt;
            this.bsw  = bsw;
            hours     = bs.GetTodaysHours(selDay);
            //this.selSim = selSim;
            this.selSimMac = selSimMac;
            if (existing != null)
            {
                existingBooking     = existing;
                editExistingBooking = true;
            }

            GenerateTimeSlots();

            PopulateSimsDropdown();
            selSimDD.SelectedIndexChanged += SelSimChanged;

            PopulateStartTime();
            timeStartDD.SelectedIndexChanged += StartTimeChanged;

            PopulateEndTime(0);
            timeEndDD.SelectedIndexChanged += EndTimeChanged;

            PopulatePricingConfigurations();

            SetXCoordTime(x);

            EditBooking();
        }
        public CategoryController(BusinessDbContext context, IOptionsSnapshot <BusinessSettings> settings)
        {
            _categoryContext = context ?? throw new ArgumentNullException(nameof(context));

            _settings = settings.Value;
            ((DbContext)context).ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }
예제 #6
0
파일: Global.asax.cs 프로젝트: Htaung/C-MVC
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     BusinessSettings.SetBusiness();
 }
예제 #7
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesERPDAL>());
     BusinessSettings.SetBussiness();
 }
예제 #8
0
 protected void Application_Start()
 {
     //Database.SetInitializer<SalesERPDAL>( null ); // Before Day 7
     BundleTable.EnableOptimizations = true;
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     BusinessSettings.SetBusiness();
 }
예제 #9
0
 public LockWindowLocal(ConsoleWindow cw)
 {
     InitializeComponent();
     this.cw = cw;
     db      = new SQLiteController();
     bs      = db.PullBusinessSettings();
     SetTheme();
     passwordTB.KeyDown += KeyDownHandler;
     usernameLBL.Text    = username.ToUpper();
 }
예제 #10
0
 private BusinessFactory()
 {
     try
     {
         _businessSettings = (BusinessSettings)ConfigurationManager.GetSection("BusinessSettings");
     }
     catch (Exception e)
     {
         throw e;
     }
 }
예제 #11
0
 public SimulatorsWindowMain(Dictionary <string, Simulator> sims, ConsoleWindow cw, int windowWidth)
 {
     InitializeComponent();
     db                 = new SQLiteController();
     bs                 = db.PullBusinessSettings();
     origin             = cw;
     simulators         = sims;
     consoleWindowWidth = windowWidth;
     CalculateMaxCount();
     GenerateSimPanels();
 }
예제 #12
0
        protected void Application_Start()
        {
            BundleTable.EnableOptimizations = true; // enable bundle
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // ef setting
            BusinessSettings.SetBusiness();
        }
예제 #13
0
 public SimulatorPanel(string simName, int index, ConsoleWindow cw, BusinessSettings bs)
 {
     InitializeComponent();
     SimPanelIndex = index;
     origin        = cw;
     this.bs       = bs;
     SetTheme();
     BorderColor = bs.GetTheme().BorderColor;
     UpdateNameLabel(simName);
     ApplyClickHandles();
     SetNextBooking(null, false);
     this.SetStyle(ControlStyles.UserPaint, true);
 }
예제 #14
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            //string name = "MyName";
            //DomainObject1 theObject = ObjectSpace.FindObject<DomainObject1>(CriteriaOperator.Parse("Name=?", name));
            //if(theObject == null) {
            //    theObject = ObjectSpace.CreateObject<DomainObject1>();
            //    theObject.Name = name;
            //}
            PermissionPolicyUser sampleUser = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "User"));

            if (sampleUser == null)
            {
                sampleUser          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                sampleUser.UserName = "******";
                sampleUser.SetPassword("");
            }
            PermissionPolicyRole defaultRole = CreateDefaultRole();

            sampleUser.Roles.Add(defaultRole);

            PermissionPolicyUser userAdmin = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Admin"));

            if (userAdmin == null)
            {
                userAdmin          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                userAdmin.UserName = "******";
                // Set a password if the standard authentication type is used
                userAdmin.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));

            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;
            userAdmin.Roles.Add(adminRole);
            ObjectSpace.CommitChanges(); //This line persists created object(s).


            CriteriaOperator bbs = new BinaryOperator("Oid", 1);
            BusinessSettings bs  = (BusinessSettings)ObjectSpace.FindObject(typeof(BusinessSettings), bbs, true);

            if (bs == null)
            {
                CreateBusinessSetting();
            }
        }
예제 #15
0
        protected void Application_Start()
        {
            //AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

            BundleTable.EnableOptimizations = true;
            AreaRegistration.RegisterAllAreas();
            BusinessSettings.SetBusiness();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            // reister custom view engine
            ViewEngines.Engines.Add(new MyCustomViewEngine());
            //ModelBinders.Binders.Add(typeof(CustomModelBinder), new CustomModelBinder()); //register custom model binder
            //ModelBinders.Binders.DefaultBinder = new DropDownDateTimeBinder(); // register overriden model binder
        }
예제 #16
0
        private void SetupWindow(int windowWidth, int windowHeight, Dictionary <string, Simulator> sims, ConsoleWindow cw, DateTime dt)
        {
            InitializeComponent();
            bs = db.PullBusinessSettings();
            SetTheme();
            origin = cw;
            dateTimePicker1.Value = dt;
            dateLabel.Text        = dateTimePicker1.Value.ToString("MMM dd, yyyy");
            this.Width            = windowWidth;
            this.Height           = windowHeight - 10;
            this.sims             = sims;

            dateTimePicker1.ValueChanged += DateTimeChanged;

            GenerateTimeSlots();
        }
예제 #17
0
        public static bool ApplyNewLicense(string license)
        {
            bool   good = false;
            string dec  = DecryptSimpleLicense(license);
            string type = dec.Substring(0, 1);

            if (types.Contains(type))
            {
                good = true;
                SQLiteController db = new SQLiteController();
                BusinessSettings bs = db.PullBusinessSettings();
                bs.LicenseType = dec;
                bs.License     = license;
                db.UpdateBusinessSettings(bs);
            }
            return(good);
        }
예제 #18
0
        public static bool Exists(string key)

        {
            // Initialize the provider's default value
            string keyName = key;

            // Get the repositoryMappingsConfiguration config section
            BusinessSettings settings = (BusinessSettings)ConfigurationManager.GetSection(BusinessMappingConstants.BusinessMappingsConfigurationSectionName);

            // See if a valid interfaceShortName was passed in
            if (settings.BusinessMappings.ContainsKey(keyName))
            {
                return(true);
            }

            return(false);
        }
예제 #19
0
        public static int CheckCurrentLicense()
        {
            SQLiteController db   = new SQLiteController();
            BusinessSettings bs   = db.PullBusinessSettings();
            string           type = bs.LicenseType;
            int output;

            if (type == "00")
            {
                output = 0;
            }
            else
            {
                string decrypt = DecryptSimpleLicense(bs.License);
                output = type == decrypt ? 2 : 1;
            }
            return(output);
        }
예제 #20
0
        public LoginWindowLocal(ConsoleWindow cw)
        {
            InitializeComponent();
            this.cw = cw;
            try
            {
                db = new SQLiteController();
                bs = db.PullBusinessSettings();
                SetTheme();
                this.ActiveControl  = usernameTB;
                usernameTB.KeyDown += KeyDownHandler;
                passwordTB.KeyDown += KeyDownHandler;

                passwordTB.GotFocus += ((sender, e) => ClearField(passwordTB));
            } catch (FileNotFoundException f)
            {
                Console.WriteLine("FNFE: " + f.Message + "; " + f.StackTrace);
            }
        }
예제 #21
0
        public bool UpdateBusinessSettings(BusinessSettings bs)
        {
            // Updates all values, including non-changing values
            string query = "UPDATE " + bizTbl + " SET " +
                           bizTblV[1] + "='" + bs.Name + "', " +
                           bizTblV[2] + "='" + bs.Address + "', " +
                           bizTblV[3] + "='" + bs.HoursString + "', " +
                           bizTblV[4] + "=" + bs.BookingSlotSize + ", " +
                           bizTblV[5] + "='" + bs.LogoFilePath + "', " +
                           bizTblV[6] + "=" + bs.Theme + ", " +
                           bizTblV[7] + "='" + bs.LicenseType + "', " +
                           bizTblV[8] + "='" + bs.License + "', " +
                           bizTblV[9] + "=" + bs.SlotLength + ", " +
                           bizTblV[10] + "=" + (bs.AutoStartFromBooking ? 1 : 0) +
                           " WHERE " + bizTblV[0] + "=" + bs.DatabaseID;

            Exe(query);
            return(true);
        }
예제 #22
0
        public SettingsWindow(ConsoleWindow cw)
        {
            InitializeComponent();
            origin = cw;

            db = new SQLiteController();
            bs = db.PullBusinessSettings();
            SetTheme();
            sims = db.AllExistingSims();
            SetSelectedTab(simSettingsTab, simSettingsTabBtn);
            selectSimDropdown.SelectedIndexChanged += SelectSimFromDropdown;
            PopulateSimDropdown();

            PopulateCurrentPriceOptions();

            EstablishBusinessSettings();
            businessSettingsTab.Click += ((sender, e) => businessSettingsTab.Focus());

            EstablishUserManagement();
        }
예제 #23
0
        ////////////  Business Configurations Table
        private void SetupSystemSettings()
        {
            // Insert default business settings configuration into the system
            int[][] hours = new int[7][];
            int[]   temp  = new int[2];
            temp[0] = 8;
            temp[1] = 22;
            for (int x = 0; x < hours.Length; x++)
            {
                hours[x] = temp;
            }
            BusinessSettings bs = new BusinessSettings();

            bs.SetHoursArray(hours);
            int autoStart = bs.AutoStartFromBooking ? 1 : 0;
            // { "id", "name", "address", "hours", "booking_size_slot", "logo_path", "theme" };
            string query = "INSERT INTO " + bizTbl + " (" + bizTblV[1] + "," + bizTblV[2] + "," + bizTblV[3] + "," + bizTblV[4] + "," + bizTblV[5] + "," + bizTblV[6] + "," + bizTblV[7] + "," + bizTblV[8] + "," + bizTblV[9] + "," + bizTblV[10] + ") " +
                           "VALUES ('" + bs.Name + "','" + bs.Address + "','" + bs.HoursString + "'," + bs.BookingSlotSize + ",'" +
                           bs.LogoFilePath + "'," + bs.Theme + ",'" + bs.LicenseType + "','" + bs.License + "'," + bs.SlotLength + "," +
                           autoStart + ")";

            Exe(query);
        }
예제 #24
0
        public BusinessSettings PullBusinessSettings()
        {
            BusinessSettings bs    = null;
            string           query = "SELECT * FROM " + bizTbl;
            SQLiteDataReader dr    = ReadExe(query);

            while (dr.Read())
            {
                bs                 = new BusinessSettings();
                bs.DatabaseID      = Convert.ToInt32((long)dr[bizTblV[0]]);
                bs.Name            = (string)dr[bizTblV[1]];
                bs.Address         = (string)dr[bizTblV[2]];
                bs.BookingSlotSize = (double)dr[bizTblV[4]];
                bs.SetHoursString((string)dr[bizTblV[3]]);
                bs.LogoFilePath         = (string)dr[bizTblV[5]];
                bs.Theme                = Convert.ToInt32((long)dr[bizTblV[6]]);
                bs.LicenseType          = (string)dr[bizTblV[7]];
                bs.License              = (string)dr[bizTblV[8]];
                bs.SlotLength           = Convert.ToInt32((long)dr[bizTblV[9]]);
                bs.AutoStartFromBooking = Convert.ToInt32((long)dr[bizTblV[10]]) == 1;
            }
            return(bs);
        }
예제 #25
0
        public virtual ActionResult AddQtyProduct(ProductDto dto)
        {
            string alertMessage = string.Empty, inventory = string.Empty;
            bool   isSuccess = true;

            var branchId  = Session[SessionVariables.UserDetails].GetBranchIdFromSession();
            var createdBy = Session[SessionVariables.UserDetails].GetUserIdFromSession();
            var dateNow   = System.DateTime.Now;

            int    PONumber = _orderService.GeneratePONumber();
            string pONumber = string.Format(Constants.POSOFormat, BusinessSettings.CreatePOSONumber(Enums.OrderTypeAbbrev.PO), PONumber == 0 ? 1 : PONumber++);

            if (!_inventoryService.AddQty(dto))
            {
                isSuccess = false;
                Danger(Messages.ErrorOccuredDuringProcessing);
            }
            else
            {
                OrderDto orderDto = new OrderDto()
                {
                    OrderId       = 0,
                    OrderNum      = pONumber,
                    OrderDetailId = 0,
                    BranchId      = branchId,
                    CreatedBy     = createdBy,
                    DateCreated   = dateNow
                };
                var identityPurchaseOrderId = _orderService.SavePurchaseOrder(orderDto);

                if (identityPurchaseOrderId <= 0)
                {
                    isSuccess = false;
                    Danger(Messages.ErrorOccuredDuringProcessing);
                }
                else
                {
                    OrderDetailDto orderDetailDto = new OrderDetailDto()
                    {
                        ProductId          = dto.ProductID,
                        PurchaseOrderId    = identityPurchaseOrderId,
                        SupplierId         = dto.SupplierID,
                        OverrideDisplay    = dto.OverrideDisplay,
                        OverrideExtDisplay = dto.OverrideExtDisplay,
                        Quantity           = dto.Quantity
                    };

                    if (!_orderService.SavePurchaseOrderDetail(orderDetailDto))
                    {
                        isSuccess = false;
                        Danger(Messages.ErrorOccuredDuringProcessing);
                    }
                    else
                    {
                        if (!_orderService.SaveReportCombination(orderDto, orderDetailDto, Enums.OrderTypeAbbrev.PO.ToString()))
                        {
                            isSuccess = false;
                            Danger(Messages.ErrorOccuredDuringProcessing);
                        }
                        else
                        {
                            isSuccess = true;
                            Success(Messages.UpdateSuccess);
                        }
                    }
                }
            }



            alertMessage = this.RenderRazorViewToString(IOBALANCEMVC.Shared.Views._Alerts, string.Empty);
            var jsonResult = new
            {
                isSuccess    = isSuccess,
                alertMessage = alertMessage,
                inventory    = inventory
            };

            return(Json(jsonResult, JsonRequestBehavior.AllowGet));
        }
예제 #26
0
        public virtual ActionResult SaveProductAndPurchaseOrder(ProductDto dto)
        {
            string inventory = string.Empty, alertMessage = string.Empty;
            bool   isSuccess = true, isPurchaseOrderNew = false;


            var createdBy  = Session[SessionVariables.UserDetails].GetUserIdFromSession();
            var branchId   = Session[SessionVariables.UserDetails].GetBranchIdFromSession();
            var userTypeId = Session[SessionVariables.UserDetails].GetUserTypeIdFromSession();


            DateTime?dateNow  = System.DateTime.Now;
            int      PONumber = _orderService.GeneratePONumber();
            string   pONumber = string.Format(Constants.POSOFormat, BusinessSettings.CreatePOSONumber(Enums.OrderTypeAbbrev.PO), PONumber == 0 ? 1 : PONumber += 1);

            //decimal oldProductQty = 0;
            long?identityProductId = 0;

            ProductDto productList = new ProductDto();

            if (userTypeId == Constants.UserTypeAdminId)
            {
                productList = GetProduct().Where(p => p.ProductCode == dto.ProductCode && p.ProductName == dto.ProductName && p.ProductExtension == dto.ProductExtension && p.BranchID == dto.BranchID && p.Size == dto.Size).FirstOrDefault();
            }
            else
            {
                productList = GetProduct().Where(p => p.ProductCode == dto.ProductCode && p.ProductName == dto.ProductName && p.ProductExtension == dto.ProductExtension && p.BranchID == branchId && p.Size == dto.Size).FirstOrDefault();
            }


            if (productList.IsNull())
            {
                dto.CreatedBy      = createdBy;
                dto.DateCreated    = dateNow;
                dto.ProductID      = 0;
                dto.IsActive       = true;
                dto.BranchID       = userTypeId == Constants.UserTypeUserId ? branchId : dto.BranchID;
                isPurchaseOrderNew = true;
                //oldProductQty = dto.Quantity;
                identityProductId = _inventoryService.SaveProduct(dto);

                if (identityProductId <= 0)
                {
                    isSuccess = false;
                    Danger(Messages.ErrorOccuredDuringProcessing);
                }
            }
            else
            {
                dto.UpdatedBy   = createdBy;
                dto.DateUpdated = dateNow;
                //oldProductQty = productList.Quantity;

                if (!_inventoryService.UpdateProductQty(productList.ProductID, dto))
                {
                    isSuccess = false;
                    Danger(Messages.ErrorOccuredDuringProcessing);
                }
                else
                {
                    identityProductId = productList.ProductID;
                }
            }

            OrderDto orderDto = new OrderDto()
            {
                OrderId       = 0,
                OrderNum      = pONumber,
                OrderDetailId = 0,
                BranchId      = userTypeId == Constants.UserTypeUserId ? branchId : dto.BranchID,
                CreatedBy     = createdBy,
                DateCreated   = dateNow
            };
            var identityPurchaseOrderId = _orderService.SavePurchaseOrder(orderDto);

            if (identityPurchaseOrderId <= 0)
            {
                isSuccess = false;
                Danger(Messages.ErrorOccuredDuringProcessing);
            }
            else
            {
                OrderDetailDto orderDetailDto = new OrderDetailDto()
                {
                    ProductId          = identityProductId,
                    PurchaseOrderId    = identityPurchaseOrderId,
                    SupplierId         = dto.SupplierID,
                    OverrideDisplay    = dto.OverrideDisplay,
                    OverrideExtDisplay = dto.OverrideExtDisplay,
                    Quantity           = dto.Quantity,
                    isNewPurchaseOrder = isPurchaseOrderNew
                };

                if (!_orderService.SavePurchaseOrderDetail(orderDetailDto))
                {
                    isSuccess = false;
                }


                if (!_orderService.SaveReportCombination(orderDto, orderDetailDto, Enums.OrderTypeAbbrev.PO.ToString()))
                {
                    isSuccess = false;
                }

                if (!isSuccess)
                {
                    Danger(Messages.ErrorOccuredDuringProcessing);
                }
                else
                {
                    isSuccess = true;
                    //var list = GetProduct();
                    //inventory = this.RenderRazorViewToString(IOBALANCEMVC.OrderManagement.PurchaseOrder.Views._ListInventory, list);
                    Success(Messages.InsertSuccess);
                }
            }



            alertMessage = this.RenderRazorViewToString(IOBALANCEMVC.Shared.Views._Alerts, string.Empty);
            var jsonResult = new
            {
                isSuccess    = isSuccess,
                alertMessage = alertMessage,
                inventory    = inventory
            };

            return(Json(jsonResult, JsonRequestBehavior.AllowGet));
        }
예제 #27
0
        private void CreateBusinessSetting()
        {
            BusinessSettings bs = ObjectSpace.CreateObject <BusinessSettings>();

            ObjectSpace.CommitChanges();
        }
 public SiteController(IHostingEnvironment env, IOptionsSnapshot <BusinessSettings> settings, BusinessService businessService)
 {
     _env             = env;
     _settings        = settings.Value;
     _businessService = businessService;
 }
        public virtual ActionResult SaveSalesOrder(List <SalesOrderDetailDto> salesOrderDetailDto, int customerId, int?branchIdAdmin)
        {
            string alertMessage = string.Empty, salesOrder = string.Empty, products = string.Empty;
            string orderNum  = string.Empty;
            bool   isSuccess = true;

            long identitySalesOrderId = 0;
            int  SONumber             = _orderService.GenerateSONumber();


            string sONumber = string.Format("{0}{1:D4}", BusinessSettings.CreatePOSONumber(Enums.OrderTypeAbbrev.SO), SONumber == 0 ? 1 : SONumber += 1);

            var      createdBy  = Session[SessionVariables.UserDetails].GetUserIdFromSession();
            DateTime?dateNow    = System.DateTime.Now;
            int?     branchId   = Session[SessionVariables.UserDetails].GetBranchIdFromSession();
            int?     userTypeId = Session[SessionVariables.UserDetails].GetUserTypeIdFromSession();

            int?discountAmount = 0;

            if (userTypeId == Constants.UserTypeAdminId)
            {
                branchId       = branchIdAdmin;
                discountAmount = GetDiscount(branchIdAdmin);
            }
            else
            {
                discountAmount = GetDiscount();
            }

            List <OrderDetailDto> orderDetailsDto = new List <OrderDetailDto>();
            List <ProductDto>     productDto      = new List <ProductDto>();

            alertMessage = isValidSalesOrder(customerId);

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(alertMessage))
                {
                    isSuccess = false;
                    Danger(alertMessage);
                }
                else
                {
                    if (salesOrderDetailDto.IsNull())
                    {
                        isSuccess = false;
                        Danger(string.Format(Messages.PleaseSelectItem, "Product"));
                    }
                    else
                    {
                        OrderDto orderDto = new OrderDto()
                        {
                            OrderNum           = sONumber,
                            CustomerId         = customerId,
                            CreatedBy          = createdBy,
                            DateCreated        = dateNow,
                            BranchId           = branchId,
                            DiscountPercentage = discountAmount
                        };
                        identitySalesOrderId = _orderService.SaveSalesOrder(orderDto);

                        if (identitySalesOrderId == 0)
                        {
                            isSuccess = false;
                            Danger(Messages.ErrorOccuredDuringProcessing);
                        }
                        else
                        {
                            var unitList = _unitService.GetAll().ToList();

                            foreach (var item in salesOrderDetailDto)
                            {
                                orderDetailsDto.Add(new OrderDetailDto()
                                {
                                    SalesOrderId = identitySalesOrderId,
                                    ProductId    = item.ProductID,
                                    Quantity     = item.Quantity,
                                    UnitId       = unitList.Where(u => u.UnitDesc == item.UnitDesc).FirstOrDefault() == null ? null : (int?)unitList.Where(u => u.UnitDesc == item.UnitDesc).FirstOrDefault().UnitID,
                                    UnitPrice    = item.UnitPrice
                                });

                                productDto.Add(new ProductDto()
                                {
                                    ProductID = item.ProductID,
                                    Quantity  = (decimal)item.Quantity
                                });
                            }
                            if (!_orderService.SaveSalesOrderDetail(orderDetailsDto))
                            {
                                isSuccess = false;
                                Danger(Messages.ErrorOccuredDuringProcessing);
                            }
                            else
                            {
                                foreach (var item in productDto)
                                {
                                    if (!_inventoryService.UpdateProductQtyOrder(item.ProductID, item, Enums.OrderTypeAbbrev.SO.ToString()))
                                    {
                                        isSuccess = false;
                                    }
                                }

                                foreach (var item in orderDetailsDto)
                                {
                                    if (!_orderService.SaveReportCombination(orderDto, item, Enums.OrderTypeAbbrev.SO.ToString()))
                                    {
                                        isSuccess = false;
                                    }
                                }



                                if (!isSuccess)
                                {
                                    Danger(Messages.ErrorOccuredDuringProcessing);
                                }
                                else
                                {
                                    Success(Messages.InsertSuccess);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                isSuccess = false;
            }



            alertMessage = this.RenderRazorViewToString(IOBALANCEMVC.Shared.Views._Alerts, string.Empty);
            var jsonResult = new
            {
                isSuccess    = isSuccess,
                alertMessage = alertMessage,
                salesOrder   = salesOrder
            };

            return(Json(jsonResult, JsonRequestBehavior.AllowGet));
        }