public IActionResult BrowserClose() { Config config = ConfigJSON.Read(); config.LoggedInUsers.Remove(User.Identity.Name); ConfigJSON.Write(config); return(Ok()); }
public IActionResult SchedulerSetup([FromBody] SchedulerDuration data) { Config config = ConfigJSON.Read(); config.SchedulerDuration = data; ConfigJSON.Write(config); return(Ok()); }
public IActionResult APISetup([FromBody] Config data) { Config config = ConfigJSON.Read(); data.SchedulerDuration = config.SchedulerDuration; data.ClientPort = config.ClientPort; data.Environment = config.Environment; ConfigJSON.Write(data); return(Ok()); }
public IActionResult Index([FromBody] Setting setting) { if (ModelState.IsValid) { Config config = ConfigJSON.Read(); config.Environment = setting.Environment; config.NavCompanyId = setting.CompanyId; ConfigJSON.Write(config); } return(RedirectToAction("Index")); }
public async Task <IActionResult> LogOff() { Config config = ConfigJSON.Read(); config.LoggedInUsers.Remove(User.Identity.Name); ConfigJSON.Write(config); await _signInManager.SignOutAsync(); // _logger.LogInformation(4, "User logged out."); Response.Cookies.Append(User.Identity.Name, "", new CookieOptions() { Expires = DateTime.Now.AddDays(-1) }); return(RedirectToAction("Login", "Account")); }
public IActionResult UpdateIntegrationSetup() { try { integrationsetup_Filter[] filter = new integrationsetup_Filter[0]; integrationsetup result = Integrationsetup_PortClientService() .ReadMultipleAsync(filter, "", 0) .GetAwaiter() .GetResult() .ReadMultiple_Result1 .FirstOrDefault(); Config config = ConfigJSON.Read(); config.Integration_Setup = new Integration_Setup { Base_URL = result.Base_URL.Remove(result.Base_URL.Length - 1) + ':' + result.Port, Service_Instance = result.Service_Instance, Domain = result.Domain.Remove(result.Domain.Length - 1), Integration_Name = "WS" }; config.URL = config.Integration_Setup.Base_URL + '/' + config.Integration_Setup.Service_Instance + '/' + config.Integration_Setup.Integration_Name + '/' + config.Default_Config.Company_Name + '/' + config.Default_Config.Type + '/'; ConfigJSON.Write(config); return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), result)); } catch (Exception ex) { return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message)); } }
public IActionResult UpdateIntegrationServices() { try { integrationservice_Filter[] filter = new integrationservice_Filter[0]; var oldResult = Integrationservice_PortClientService() .ReadMultipleAsync(filter, "", 0) .GetAwaiter() .GetResult(); var newResult = oldResult.ReadMultiple_Result1; var result = newResult.ToList(); Config config = ConfigJSON.Read(); List <Integration_Service> integration_Services = new List <Integration_Service>(); foreach (var item in result) { integration_Services.Add( new Integration_Service { Integration_Type = item.Integration_Type.ToString(), Service_Name = item.Service_Name, Type = item.Type.ToString(), Company_Name = item.Company_Name }); } config.Integration_Services = integration_Services.ToArray(); ConfigJSON.Write(config); return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), result)); } catch (Exception ex) { return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message)); } }
public IActionResult UpdateDefaultSetup(ConfigSetup obj) { try { if (ModelState.IsValid) { Config config = ConfigJSON.Read(); config.Default_Config.Username = obj.Username; config.Default_Config.Password = obj.Password; config.Default_Config.Company_Name = obj.CompanyName; config.Default_Config.Type = obj.Type; config.Integration_Setup.Base_URL = obj.BaseURL; config.Integration_Setup.Service_Instance = obj.ServiceInstance; config.Integration_Setup.Domain = obj.Domain; config.URL = obj.BaseURL + '/' + obj.ServiceInstance + '/' + config.Integration_Setup.Integration_Name + '/' + obj.CompanyName + '/' + obj.Type + '/'; ConfigJSON.Write(config); return(StatusCode(Convert.ToInt32(HttpStatusCode.OK), config)); } return(StatusCode(Convert.ToInt32(HttpStatusCode.BadRequest), ModelState)); } catch (Exception ex) { return(StatusCode(Convert.ToInt32(HttpStatusCode.InternalServerError), ex.Message)); } }
public void UpdateCacheItemViewModel() { _cache.Set("IsItemCacheInProcess", true); //update cache Config config = ConfigJSON.Read(); //split data to 1lakh and save to cache int count = 100000, skip = 0, errorCount = 0; DateTime startDate = DateTime.Now; //_context.ChangeTracker.AutoDetectChangesEnabled = false; for (; ;) { try { IList <ItemViewModel> itemsTotal = new List <ItemViewModel>(); _context.Database.SetCommandTimeout(TimeSpan.FromHours(1)); //IList<ItemViewModel> itemsTemp = _context.ItemViewModel.FromSql("SPItemViewModel @p0, @p1", count, skip).ToList(); IList <ItemViewModel> itemsTemp = _context.ItemViewModel.Skip(skip).Take(count).ToList(); if (itemsTemp.Count() > 0) { _cache.TryGetValue("ItemViewModel", out itemsTotal); if (itemsTotal == null) { itemsTotal = new List <ItemViewModel>(); } itemsTotal = itemsTotal.Concat(itemsTemp).DistinctBy(x => new { x.Bar_Code, x.Code, x.Discount, x.DiscountEndDate, x.DiscountEndTime, x.DiscountItemType, x.DiscountLocation, x.DiscountMinimumQuantity, x.DiscountSalesGroupCode, x.DiscountStartDate, x.DiscountStartTime, x.DiscountType, x.Name, x.Rate, x.RateEndDate, x.RateMinimumQuantity, x.RateStartDate, x.SalesCode, x.SalesType }).ToList(); _cache.Set("ItemViewModel", itemsTotal); } else { double totalTimeTake = (DateTime.Now - startDate).TotalMinutes; config.Environment = "Total Time take " + totalTimeTake + " Mins"; ConfigJSON.Write(config); _cache.Set("IsItemCacheInProcess", false); break; } config.Environment = itemsTotal.Count() + " item cached"; // itemsTotal = itemsTotal.Concat(itemsTemp).ToList(); skip = skip + count; // config.Environment = itemsTotal.Count() + " item cached"; ConfigJSON.Write(config); } catch (Exception ex) { if (ex.Message == "Invalid object name 'ItemViewModel'.") { _cache.Set("IsItemCacheInProcess", true); break; } if (errorCount > 5) { break; } errorCount += 1; } } }
public void UpdateCacheItemViewModel() { bool IsItemCacheInProcess = false; _cache.TryGetValue("IsItemCacheInProcess", out IsItemCacheInProcess); if (!IsItemCacheInProcess) { _cache.Set("IsItemCacheInProcess", true); //update cache Config config = ConfigJSON.Read(); //split data to 1lakh and save to cache int count = 1000, skip = 0, errorCount = 0; DateTime startDate = DateTime.Now; //_context.ChangeTracker.AutoDetectChangesEnabled = false; for (; ;) { try { IList <ItemViewModel> itemsTotal = new List <ItemViewModel>(); _cache.TryGetValue("ItemViewModel", out itemsTotal); if (itemsTotal == null) { _cache.Set("IsItemCacheInProcess", false); break; } _context.Database.SetCommandTimeout(TimeSpan.FromHours(1)); var listOfItemsChanged = _context.ItemUpdateTrigger.Skip(skip).Take(count).ToList(); var listOfItemsCodeToLoad = listOfItemsChanged.Where(x => x.ACTIONS != "Delete") .Select(x => x.ITEMCODE).Distinct().ToList(); var listOfItemsChangedCode = listOfItemsChanged.Select(x => x.ITEMCODE).Distinct().ToList(); foreach (var i in listOfItemsChangedCode) { var listOfItemsToDelete = itemsTotal.Where(x => x.Code == i).ToList(); foreach (var j in listOfItemsToDelete) { itemsTotal.Remove(j); } } string listOfItemsCodeString = string.Join(",", listOfItemsCodeToLoad); IList <ItemViewModel> itemsTemp = _context.ItemViewModel.FromSql("SPItemViewModel {0}", listOfItemsCodeString).ToList(); if (itemsTemp.Count() > 0) { itemsTotal = itemsTotal.Concat(itemsTemp).ToList(); _cache.Set("ItemViewModel", itemsTotal); //now remove trigger from database _context.RemoveRange(listOfItemsChanged); _context.SaveChanges(); double totalTimeTake = (DateTime.Now - startDate).TotalMinutes; config.Environment = "Total Time take " + totalTimeTake + " Mins"; ConfigJSON.Write(config); _cache.Set("IsItemCacheInProcess", false); break; } else { _cache.Set("IsItemCacheInProcess", false); break; } } catch (Exception ex) { if (errorCount > 5) { _cache.Set("IsItemCacheInProcess", false); break; } errorCount += 1; } } } }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = null; //_logger.LogInformation("access login page"); if (ModelState.IsValid) { if (model.ClientDate.ToShortDateString() != DateTime.Now.ToShortDateString()) { ModelState.AddModelError(string.Empty, "Date Not Up-to-Date !!"); return(View(model)); } //first try to login with username IdentityUser user = await _userManager.FindByNameAsync(model.Email); var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false); if (!result.Succeeded && !result.RequiresTwoFactor && !result.IsLockedOut) { //now try to login with email user = await _userManager.FindByEmailAsync(model.Email); if (user != null) { result = await _signInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure : false); } } if (result.Succeeded) { // HttpContext.User = await _signInManager.CreateUserPrincipalAsync(user); //first check username already loggedin Config config = ConfigJSON.Read(); Store store = _context.Store.FirstOrDefault(); if (!User.Identity.IsAuthenticated && config.LoggedInUsers.Contains(user.UserName)) { //ModelState.AddModelError(string.Empty, "You're currently logged in to another system !!"); //await _signInManager.SignOutAsync(); //return View(model); } else { config.LoggedInUsers.Remove(user.UserName); config.LoggedInUsers.Add(user.UserName); ConfigJSON.Write(config); } //get user role var role = _context.UserViewModel.FirstOrDefault(x => x.UserName == user.UserName); var rolePermission = _context.RoleWisePermission.FirstOrDefault(x => x.RoleId == role.RoleId || x.RoleId == role.Role); //save to session HttpContext.Session.SetString("Role", JsonConvert.SerializeObject(role)); HttpContext.Session.SetString("TotalMenu", JsonConvert.SerializeObject(_context.Menu)); HttpContext.Session.SetString("Menus", JsonConvert.SerializeObject(_context.RoleWiseMenuPermission.Where(x => x.RoleId == role.Role).Include(x => x.Menu))); HttpContext.Session.SetString("Store", JsonConvert.SerializeObject(store)); HttpContext.Session.SetString("RolePermission", JsonConvert.SerializeObject(rolePermission)); if (model.TerminalId != 0) { HttpContext.Session.SetString("TerminalId", model.TerminalId.ToString()); HttpContext.Session.SetString("Terminal", model.TerminalName); //await _userManager.AddClaimAsync(user, new Claim("Terminal", model.TerminalId.ToString())); //await _userManager.AddClaimAsync(user, new Claim("TerminalName", model.TerminalName.ToString())); } else { //check if user required terminal //var roleName = User.FindFirstValue(ClaimTypes.Role); //var role = _roleManager.FindByNameAsync(roleName); bool requireTerminalToLogin = rolePermission == null ? false : rolePermission.Require_Terminal_To_Login; if (requireTerminalToLogin) { ModelState.AddModelError(string.Empty, "You can only login from Terminals"); await _signInManager.SignOutAsync(); return(View(model)); } else { //select default terminal var terminal = _context.Terminal.FirstOrDefault(); if (terminal != null) { HttpContext.Session.SetString("TerminalId", terminal.Id.ToString()); HttpContext.Session.SetString("Terminal", terminal.Name.ToString()); //await _userManager.AddClaimAsync(user, new Claim("Terminal", terminal.Id.ToString())); //await _userManager.AddClaimAsync(user, new Claim("TerminalName", terminal.Name.ToString())); } } } config.Environment = "successfully login"; ConfigJSON.Write(config); if (!string.IsNullOrEmpty(returnUrl) && returnUrl != "/") { return(RedirectToLocal(returnUrl)); } else { if (store.INITIAL == "WHS") { return(RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" })); } else { return(RedirectToAction("Landing", "SalesInvoice")); } //return RedirectToAction("CrLanding", "SalesInvoice", new { Mode = "tax" }); } } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return(View("Lockout")); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return(View(model)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public bool PostSalesInvoice(Store store) { Config config = ConfigJSON.Read(); var currentTime = DateTime.Now.TimeOfDay; if (config.StopInvoicePosting) { return(true); } if ((config.OfficeHourStart != null && currentTime.CompareTo(Convert.ToDateTime(config.OfficeHourStart).TimeOfDay) == 1) && (config.OfficeHourEnd != null && currentTime.CompareTo(Convert.ToDateTime(config.OfficeHourEnd).TimeOfDay) == -1)) { return(true); } var unSyncInvoice = _context.SalesInvoice.Where(x => x.IsNavSync == false).OrderBy(x => x.Trans_Date_Ad); NavIntegrationService services = _context.NavIntegrationService.FirstOrDefault(x => x.IntegrationType == "SalesInvoicePost"); int errorCount = 0, successCount = 0; foreach (var salesInvoice in unSyncInvoice) { var crNumber = ""; var bill = _context.SalesInvoiceBill.FirstOrDefault(x => x.Invoice_Number == salesInvoice.Invoice_Number && x.Trans_Mode == "CreditNote"); if (bill != null) { crNumber = bill.Account; } else { crNumber = salesInvoice.Invoice_Number; } string url = config.NavApiBaseUrl + "/" + config.NavPath + $"/companies({config.NavCompanyId})/{services.ServiceName}"; var client = NAV.NAVClient(url, config); var request = new RestRequest(Method.POST); //DeleteSalesOrder(); //delete first if already exist string urlDelete = url + "(" + salesInvoice.Id + ")"; var clientDelete = NAV.NAVClient(urlDelete, config); var requestDelete = new RestRequest(Method.DELETE); requestDelete.AddHeader("Content-Type", "application/json"); IRestResponse responseDelete = clientDelete.Execute(requestDelete); request.AddHeader("Content-Type", "application/json"); NavSalesInvoice invoice = new NavSalesInvoice() { id = salesInvoice.Id.ToString(), number = salesInvoice.Invoice_Number, externalDocumentNumber = crNumber, postingno = salesInvoice.Invoice_Number, shippingno = salesInvoice.Invoice_Number, orderDate = salesInvoice.Trans_Date_Ad.Value.ToString("yyyy-MM-dd"), customerNumber = salesInvoice.MemberId, customerName = salesInvoice.Customer_Name, vatregistrationnumber = salesInvoice.Customer_Vat, locationcode = store.INITIAL, accountabilitycenter = store.INITIAL, assigneduserid = salesInvoice.Created_By, amountrounded = salesInvoice.Total_Net_Amount != salesInvoice.Total_Payable_Amount }; request.RequestFormat = DataFormat.Json; var temp = JsonConvert.SerializeObject(invoice); request.AddJsonBody(temp); IRestResponse <SyncModel <NavSalesInvoice> > response = client.Execute <SyncModel <NavSalesInvoice> >(request); if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK) { var data = JsonConvert.DeserializeObject <NavSalesInvoice>(response.Content); //update sync status SalesInvoice sInvoice = _context.SalesInvoice.FirstOrDefault(x => x.Invoice_Number == invoice.number); sInvoice.IsNavSync = true; sInvoice.NavSyncDate = DateTime.Now; _context.Entry(sInvoice).State = Microsoft.EntityFrameworkCore.EntityState.Modified; _context.SaveChanges(); PostSalesInvoicePaymentMode(invoice.number, data.id); PostSalesInvoiceItem(invoice.number, data.id, sInvoice.Trans_Type); successCount += 1; config.Environment = "Success " + successCount + " - Error " + errorCount; //_logger.LogInformation("Post Invoice " + invoice.number + " to NAV Successfully " + DateTime.Now.ToString()); ConfigJSON.Write(config); // return true; } else { string errorMessage = "Error Invoice:: Invoice Number= " + invoice.number + " Message= " + response.Content + " " + DateTime.Now.ToString() + Environment.NewLine; WriteToFile(Path.GetFullPath("logs/"), "NAVSyncLog.log", errorMessage); // _logger.LogError("Error Invoice:: Invoice Number= " + invoice.number + " Message= " + response.Content +" " + DateTime.Now.ToString()); ////update values //SalesInvoice sInvoice = _context.SalesInvoice.FirstOrDefault(x => x.Invoice_Number == invoice.number); //if (sInvoice.SyncErrorCount < 3) //{ // sInvoice.SyncErrorCount = sInvoice.SyncErrorCount + 1; // _context.Entry(sInvoice).State = Microsoft.EntityFrameworkCore.EntityState.Modified; // _context.SaveChanges(); // //run scheduler after 1 minute // BackgroundJob.Schedule(() => PostSalesInvoice(invoice), TimeSpan.FromMinutes(sInvoice.SyncErrorCount * 5)); //} errorCount += 1; config.Environment = "Success " + successCount + " - Error " + errorCount; ConfigJSON.Write(config); // return false; } } config.Environment += " Finished"; ConfigJSON.Write(config); return(true); }