public static int?ServiceWillClose(this HelperService service) { var openingHours = service.OpeningHoursForDayOfWeek(DateTime.Today.DayOfWeek); int?willClose = openingHours.WillClose(); return(willClose); }
public void Setup() { var optionsBuilder = new DbContextOptionsBuilder <PortFreightContext>() .UseInMemoryDatabase("InMemoryDb") .Options; var httpContext = new DefaultHttpContext(); tempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); var modelState = new ModelStateDictionary(); actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState); var modelMetadataProvider = new EmptyModelMetadataProvider(); viewData = new ViewDataDictionary(modelMetadataProvider, modelState); pageContext = new PageContext(actionContext) { ViewData = viewData }; actualContext = new PortFreightContext(optionsBuilder); cargoPortValidateService = new CargoPortValidateService(null, helperService); helperService = new HelperService(actualContext); }
public void Setup() { var optionsBuilder = new DbContextOptionsBuilder <PortFreightContext>() .UseInMemoryDatabase("InMemoryDb") .Options; var httpContext = new DefaultHttpContext(); tempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); var modelState = new ModelStateDictionary(); actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState); var modelMetadataProvider = new EmptyModelMetadataProvider(); viewData = new ViewDataDictionary(modelMetadataProvider, modelState); pageContext = new PageContext(actionContext) { ViewData = viewData }; actualContext = new PortFreightContext(optionsBuilder); MSD1 Msd1 = new MSD1(); tempData["MSD1Key"] = JsonConvert.SerializeObject(Msd1); CommonFunction = new HelperService(actualContext); }
private void UpdateSubmissionNumber(ITS_Submission submission) { HelperService helper = new HelperService(); string subNumber; int counter; //Reset submission number counter var TodaysSub = GetAll().Where(p => p.DateCreated.Date == DateTime.Now.Date).ToList(); if (TodaysSub != null) { counter = TodaysSub.Count(); } else { counter = 1; } try { subNumber = helper.GenerateSubmissionNumber(counter); } catch (Exception ex) { subNumber = ""; throw ex; } submission.SubmissionNumber = subNumber; Update(submission); }
public async Task <IHttpActionResult> PutHelperService(int id, [FromBody] HelperService helperService) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != helperService.HelperServiceId) { return(BadRequest()); } db.Entry(helperService).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!HelperServiceExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
// Function definition to extract list of all strains from Genotype tbl in DB public List <Geno> GetGenoList(int?strainID) { List <int> lstGenoID = new List <int>(); List <Geno> GenoList = new List <Geno>(); string lstGenoIDCsv; if (strainID == null || strainID == 0) { return(GenoList); } lstGenoID = HelperService.GetGenoID(strainID); lstGenoIDCsv = String.Join(",", lstGenoID.Select(x => x.ToString()).ToArray()); using (DataTable dt = Dal.GetDataTable($@"Select * From Genotype where ID in ({lstGenoIDCsv})")) { foreach (DataRow dr in dt.Rows) { GenoList.Add(new Geno { ID = Int32.Parse(dr["ID"].ToString()), Genotype = Convert.ToString(dr["Genotype"].ToString()), Link = Convert.ToString(dr["Link"].ToString()), Description = Convert.ToString(dr["Description"].ToString()), }); } } return(GenoList); }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { try { Mapper.Initialize(cfg => cfg.CreateMap <RegisterModel, UserDTO>() .ForMember("Role", opt => opt.MapFrom(src => "user"))); UserDTO userDto = Mapper.Map <RegisterModel, UserDTO>(model); await UserService.CreateAsync(userDto); return(RedirectToAction("Index", "Home")); } catch (ValidationException ex) { var exceptions = HelperService.ParseExceptionList(ex); foreach (var exception in exceptions) { ModelState.AddModelError(exception.Key, exception.Value); } } } return(View(model)); }
public ActionResult Search(string searchStudent, string hiddenDistrictFilterSearch, string hiddenSchoolFilterSearch, string hiddenSchoolYearFilterSearch) { try { dbTIREntities db = new dbTIREntities(); SiteUser siteUser = ((SiteUser)Session["SiteUser"]); StudentService studentService = new StudentService(siteUser, db); SchoolService schoolService = new SchoolService(siteUser, db); ModelServices modelService = new ModelServices(); ViewBag.DistrictDesc = siteUser.Districts[0].Name; int schoolYearId = modelService.GetSchoolYearId(Convert.ToInt32(hiddenSchoolYearFilterSearch)); ViewBag.SchoolId = modelService.DropDownDataSchool(hiddenSchoolFilterSearch, siteUser.EdsUserId, schoolYearId, true); ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT"); ViewBag.SchoolYearList = schoolService.DropDownDataSchoolYear(hiddenSchoolYearFilterSearch); ViewBag.SchoolYear = hiddenSchoolYearFilterSearch; return(View("Index", new SiteModels() { Students = studentService.GetViewData(hiddenSchoolYearFilterSearch, hiddenSchoolFilterSearch, searchStudent) })); } catch (Exception ex) { Logging log = new Logging(); log.LogException(ex); return(View("GeneralError")); } }
public int InsertExperiment(Experiment experiment, string userID, string Email) { var repoGuid = new Guid(); string repoString = "null"; if (Guid.TryParse(experiment.RepoGuid, out repoGuid)) { repoString = "'" + experiment.RepoGuid + "'"; } string sql = $"insert into Experiment " + $"(UserID, PUSID, ExpName, StartExpDate, EndExpDate, TaskID, SpeciesID, TaskDescription, DOI, Status, TaskBattery, MultipleSessions, RepoGuid) Values " + $"('{userID}', {experiment.PUSID}, '{HelperService.EscapeSql(experiment.ExpName.Trim())}', '{experiment.StartExpDate}', '{experiment.EndExpDate}', " + $"'{experiment.TaskID}', '{experiment.SpeciesID}', '{HelperService.EscapeSql(experiment.TaskDescription)}'," + $" '{HelperService.EscapeSql(experiment.DOI)}', {(experiment.Status ? 1 : 0)}, '{HelperService.EscapeSql(experiment.TaskBattery)}', {(experiment.MultipleSessions ? 1 : 0)}, " + $" {repoString} );" + $" SELECT @@IDENTITY AS 'Identity';"; // Calling function to send an email to Admin that new Exp with public Status has been added to MouseBytes string strBody = $@"Hi Admin: <br /><br /> User with Email address <b>{Email}</b> has just created the experiment: <b>{HelperService.EscapeSql(experiment.ExpName.Trim())}</b> with public Status! <br /><br /> Thanks <br /> MouseBytes"; HelperService.SendEmail("", "", "New Experiment with pubic status added!", strBody); return(Int32.Parse(Dal.ExecScalar(sql).ToString())); }
public IActionResult SearchProduct(string inputSearch) { ViewData["Title"] = "Search"; List <ProductViewModel> productsVMs = _productService.GetAllProducts(); if (!HelperService.AProductExists(productsVMs)) { RedirectToAction(nameof(ProductNotFound), new { message = "" }); } _logger.LogInfo("Got products that user searched for from product service."); var productsFound = HelperService.GetProductsWithTerm(inputSearch, productsVMs); if (productsFound.Count == 0) { return(RedirectToAction(nameof(ProductNotFound), new { message = inputSearch })); } else { productsVMs = productsFound; } var productsVM = new ProductsViewModel() { Products = productsVMs }; return(View(productsVM)); }
// GET: /Students/ public ActionResult Index() { try { dbTIREntities db = new dbTIREntities(); SiteUser siteUser = ((SiteUser)Session["SiteUser"]); StudentService studentService = new StudentService(siteUser, db); SchoolService schoolService = new SchoolService(siteUser, db); ModelServices modelService = new ModelServices(); string currentSchoolYear = schoolService.GetCurrentSchoolYear(); ViewBag.DistrictDesc = siteUser.Districts[0].Name; int schoolYearId = modelService.SchoolYearId(); ViewBag.SchoolId = modelService.DropDownDataSchool("", siteUser.EdsUserId, schoolYearId, true); ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT"); //ViewBag.SchoolYear = HelperService.SchoolYearDescription(db); ViewBag.SchoolYearList = schoolService.DropDownDataSchoolYear(currentSchoolYear); ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT"); ViewBag.SchoolYear = currentSchoolYear; return(View(new SiteModels() { Students = studentService.GetViewData(currentSchoolYear, "", "") })); } catch (Exception ex) { Logging log = new Logging(); log.LogException(ex); return(View("GeneralError")); } }
public static string NextOpen(this HelperService service) { var currentHour = DateTime.Now.Hour; var openingHours = service.OpeningHoursForDayOfWeek(DateTime.Today.DayOfWeek); int openingHour = openingHours.First(); int closingHour = openingHours.Last(); DateTime openTime = DateTime.Today.AddHours(openingHour); if (currentHour < openingHour) { return(string.Format("today at {0}", openTime.ToString("hh:mm tt"))); } else { DayOfWeek tomorrowDayOfWeek = DateTime.Today.DayOfWeek + 1; string reopensText = service.ReOpensText(tomorrowDayOfWeek); if (reopensText == tomorrowDayOfWeek.ToString()) { return("tomorrow"); } else { return(reopensText); } } }
public static string ExtraInfo(this HelperService service) { string info = ""; if (service.ServiceIsOpenNow()) { if (service.ServiceWillClose().HasValue) { info = string.Format("Open until {0}", service.ServiceWillClose().Value); } else { throw new Exception("An error occured when calculating when the service will close"); } } else { info = string.Format("Reopens {0}", service.NextOpen()); } return(info); }
public static bool ServiceIsOpenNow(this HelperService service) { var openingHours = service.OpeningHoursForDayOfWeek(DateTime.Today.DayOfWeek); bool isOpenNow = openingHours.IsOpenNow(); return(isOpenNow); }
public ActionResult CaricaInclusioni(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string path = Path.GetFileName(file.FileName); string ente = path.Split('_')[0].ToString(); using (HelperService _hp = new HelperService()) { string codiceEnte = _hp.channel.GetAllEnti().Where(x => x.CodiceEnte.Equals(ente)).Select(y => y.CodiceEnte).ToString(); if (!string.IsNullOrEmpty(codiceEnte)) { Helper hp = new Helper(); DataTable dt = hp.ConvertCSVtoDataTable(file); hp.InsertIntoTableAppoggio(dt, "Inclusioni"); return(RedirectToAction("InLavorazione", "GestioneAnagrafica", new { en = ente })); } else { ViewBag.Message = "Codice ente specificato nel tracciato non censito."; return(View()); } } } else { ViewBag.Message = "Il tracciato caricato è vuoto."; return(View()); } }
public void UpdateExp(Experiment experiment, string userID, string Email) { var repoGuid = new Guid(); string repoString = "null"; if (Guid.TryParse(experiment.RepoGuid, out repoGuid)) { repoString = "'" + experiment.RepoGuid + "'"; } string sql = $@"UPDATE Experiment " + $"SET PUSID = {experiment.PUSID}, ExpName = '{HelperService.EscapeSql(experiment.ExpName)}', StartExpDate = '{experiment.StartExpDate}'," + $"EndExpDate = '{experiment.EndExpDate}', SpeciesID = {experiment.SpeciesID}, TaskDescription = '{HelperService.EscapeSql(experiment.TaskDescription)}'," + $" DOI = '{HelperService.EscapeSql(experiment.DOI)}', TaskBattery = '{HelperService.EscapeSql(experiment.TaskBattery)}', Status = {(experiment.Status ? 1 : 0)}," + $" MultipleSessions = {(experiment.MultipleSessions ? 1 : 0)}, RepoGuid = {repoString}" + $" WHERE ExpID = {experiment.ExpID} AND UserID = '{userID}';"; if (experiment.Status) { string strBody = $@"Hi Admin: <br /><br /> User with Email address <b>{Email}</b> has just changed the status of the experiment: <b>{HelperService.EscapeSql(experiment.ExpName.Trim())}</b> to public! <br /><br /> Thanks <br /> MouseBytes"; HelperService.SendEmail("", "", "Status of experiment changed to public!", strBody); } Dal.ExecuteNonQuery(sql); }
public string GetTableOjects(int appDatabaseId, string tableName) { // get TableSchema TableSchema tableSchema = DataService.GetTableSchema(appDatabaseId, tableName); var jsonTableSchema = JsonConvert.SerializeObject(tableSchema, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); // set default grid and form DataService.SetDefaultGridAndForm(appDatabaseId, tableName); // get grids var sql = @"SELECT * FROM Grid WHERE AppDatabaseId = @AppDatabaseId AND TableName = @TableName"; var jsonGrids = HelperService.GetJsonData(0, sql, new[] { new SqlParameter("@AppDatabaseId", appDatabaseId), new SqlParameter("@TableName", tableName) }); // get forms sql = @"SELECT * FROM Form WHERE AppDatabaseId = @AppDatabaseId AND TableName = @TableName"; var jsonForms = HelperService.GetJsonData(0, sql, new[] { new SqlParameter("@AppDatabaseId", appDatabaseId), new SqlParameter("@TableName", tableName) }); return("{ \"TableSchema\" : " + jsonTableSchema + ", \"Grids\" : " + jsonGrids + ", \"Forms\" : " + jsonForms + " } "); }
public ActionResult Private() { ViewBag.Message = "Your Personalized Video"; var userSessionVideo = UserSessionVideoModel.Current; ViewBag.Poster = userSessionVideo.PublicPosterUrl; int replayed = 0; string personalVid = userSessionVideo.VideoWithSignedAccessSignature; ViewBag.Vid = personalVid; if (null != Request.QueryString["replay"]) { HelperService.LogAnEvent(Request.QueryString["replay"].Equals("1") ? LogEvents.Replay : LogEvents.StartVideo); replayed = Request.QueryString["replay"].Equals("1") ? 1 : 0; } else { HelperService.LogAnEvent(LogEvents.StartVideo); } ViewBag.Replayed = replayed; return(View()); }
public List <Animal> GetAnimalByExpID(int expID) { List <Animal> lstAnimal = new List <Animal>(); using (DataTable dt = Dal.GetDataTable($@"SELECT Animal.*, Strain.Strain, Genotype.Genotype From Animal left join Genotype on Genotype.ID = Animal.GID left join Strain on Strain.ID = Animal.SID WHERE ExpID = {expID}")) { foreach (DataRow dr in dt.Rows) { lstAnimal.Add(new Animal { ExpID = Int32.Parse(dr["ExpID"].ToString()), AnimalID = Int32.Parse(dr["AnimalID"].ToString()), UserAnimalID = Convert.ToString(dr["UserAnimalID"].ToString()), SID = HelperService.ConvertToNullableInt(dr["SID"].ToString()), GID = HelperService.ConvertToNullableInt(dr["GID"].ToString()), Sex = Convert.ToString(dr["Sex"].ToString()), Genotype = Convert.ToString(dr["Genotype"].ToString()), Strain = Convert.ToString(dr["Strain"].ToString()), }); } } return(lstAnimal); }
public async Task <LoginResponse> Login(LoginRequest request) { var result = await _signInManager.PasswordSignInAsync(request.Username, request.Password, request.RememberMe, true); if (result.RequiresTwoFactor) { return(LoginResponse.TwoFactorAuthenticationEnabled()); } if (result.IsLockedOut) { return(LoginResponse.LockedOut()); } if (result.Succeeded) { var user = _applicationUserManager.Users.Include(y => y.Groups).First(x => x.UserName.ToLower().Equals(request.Username)); var roles = await _applicationUserManager.GetRolesAsync(user); var groups = user.Groups.Select(x => x.Group.Name); var token = _jwtTokenService.CreateToken(HelperService.ToUser(user), roles); return(LoginResponse.Success(token, GetResponseUser(user, token))); } else { return(LoginResponse.Failure("Invalid Username or Password")); } }
public UtilityModule(DatabaseService databaseService, ResponseService responseService, HelperService helperService, InteractiveService interactiveService) { _databaseService = databaseService; _responseService = responseService; _helperService = helperService; _interactiveService = interactiveService; }
public async Task <TwoFaLoginResponse> LoginWith2Fa(TwoFaLoginRequest request) { var user = await _applicationUserManager.FindByEmailAsync(request.Username); if (user == null) { return(new TwoFaLoginResponse() { IsCodeValid = false }); } var authenticatorCode = request.Code.Replace(" ", string.Empty).Replace("-", string.Empty); var result = await _applicationUserManager.VerifyTwoFactorTokenAsync(user, new IdentityOptions().Tokens.AuthenticatorTokenProvider, authenticatorCode); if (!result) { return new TwoFaLoginResponse() { IsCodeValid = false } } ; user = _applicationUserManager.Users.Include(y => y.Groups).First(x => x.UserName.ToLower().Equals(request.Username)); var roles = await _applicationUserManager.GetRolesAsync(user); var groups = user.Groups.Select(x => x.Group.Name); var token = _jwtTokenService.CreateToken(HelperService.ToUser(user), roles); return(new TwoFaLoginResponse() { IsCodeValid = true, LoginResponse = LoginResponse.Success(token: token, GetResponseUser(user, token)) }); }
public IHttpActionResult Create(FianceProjectViewModel project) { project.OwnerId = HelperService.GetUserId(User); var id = _projectRepo.Create(project); return(Ok(id)); }
/* EOF not sure on these ties */ /* this is to let us just add or remove a file to add * an option to the styles. Goal here is that if we * have a file it'll get pulled in and put to the json * this is an extension of the "virtual" model idea */ virtual public String[] getOptions(string gType) { String filePath = HelperService.getRootPath() + "Views/admin/maps/styles/options/" + gType + "/"; String[] used = Directory.GetFiles(filePath, "*.vm").Select(fileName => Path.GetFileNameWithoutExtension(fileName)).ToArray(); return(used); }
/// <summary> /// Allows the user to begin constructing and placing an order of products from one of the locations. /// </summary> /// <param name="hs"></param> static void PlaceANewOrder(HelperService hs) { Console.WriteLine("Please wait while we get things ready..."); List <Domain.Customer> customers = hs.GetAllCustomers(); List <Domain.Location> locations = hs.GetAllLocations(); string input = ""; bool valid = false; do { Console.WriteLine("\nEnter the ID of the customer placing this order:"); Console.WriteLine("l : View list of customers"); Console.WriteLine("b : Go back a menu"); Console.WriteLine("q : Quit out of the program"); input = ""; input = Console.ReadLine(); valid = Char.IsLetter(input[0]); if (valid) { char userInput = input[0]; switch (userInput) { case 'l': Console.WriteLine("ID | First Name\tLastName"); Console.WriteLine("-------------------------"); foreach (var c in customers) { Console.WriteLine($"{c.ID} | {c.FirstName}\t{c.LastName}"); } valid = false; break; case 'b': // go up a level in the menu return; case 'q': Environment.Exit(0); break; default: break; } } else if (char.IsDigit(input[0])) { int i = input[0] - '0'; valid = customers.Any(c => c.ID == i); if (valid) { PlaceOrderChooseLocation(hs, locations, i); } else { Console.WriteLine("Invalid customer ID number. Please enter another number."); } } } while (!valid); Environment.Exit(0); }
public void DisplayAllLogsSavedSoFar() { HelperService.GetInstance().EnsureThatActionSucceed(() => { _txtService.DisplayAllSavedLogs(_fileName); }, null, "Could not get all logs saved so far"); }
public void AddNewAge(Request request) { string sql = $@"Insert into Request (Type, FullName, Email, Age) Values ('AddAge', '{HelperService.EscapeSql(request.FullName)}', '{request.Email}', '{HelperService.EscapeSql(request.Age)}'); SELECT @@IDENTITY AS 'Identity';"; Int32.Parse(Dal.ExecScalar(sql).ToString()); }
public ActionResult Modifica(SoggettiImportAppoggioDao modello) { List <SelectListItem> soggettiList = new List <SelectListItem>(); List <SelectListItem> tipoAdesioniList = new List <SelectListItem>(); List <SelectListItem> tipoLegamiList = new List <SelectListItem>(); soggettiList = Session["TipiSoggList"] as List <SelectListItem>; tipoLegamiList = Session["TipiLegamiList"] as List <SelectListItem>; tipoAdesioniList = Session["TipiAdesList"] as List <SelectListItem>; ViewBag.TipiSoggList = soggettiList; ViewBag.TipiLegamiList = tipoLegamiList; ViewBag.TipiAdesList = tipoAdesioniList; string ente = modello.Ente; long idSoggetto = modello.IdSoggetto; SoggettiImportAppoggioDao modelloValidato = new SoggettiImportAppoggioDao(); using (HelperService _hp = new HelperService()) { _hp.channel.ValidaSoggettoSingolo(modello, modello.TipoTracciato); modelloValidato = _hp.channel.SelectById(idSoggetto); } if (!modelloValidato.ErroriList.Any()) { Session["tracciato"] = modello.TipoTracciato; return(RedirectToAction("InLavorazione", "GestioneAnagrafica", new { en = ente, page = Session["page"].ToString() })); } else { return(View("EditSoggettoImportato", modelloValidato)); } }
public List <TreeChartTooltipData> getChartTooltipData() { var result = (from m in _context.Stocklevelnp join pr in _context.Products on m.product_code equals pr.product_code join w in _context.Warehouses on m.warehouse equals w.warehouse_id where m.on_hand_qty > 0 select new TreeChartTooltipData { category10_desc = string.IsNullOrEmpty(pr.category10_desc)? "Others" : pr.category10_desc, continentName = HelperService.getContinentFromCountry(w.country), value = m.on_hand_qty < 0 ? 0 : Convert.ToDecimal(m.on_hand_qty), countryName = w.country_name }).ToList(); var stocklevelbynp = (from m in result group m by new { m.category10_desc, m.continentName, m.countryName } into g select new TreeChartTooltipData { category10_desc = g.Key.category10_desc, continentName = g.Key.continentName, countryName = g.Key.countryName, value = g.Sum(sl => sl.value), }).ToList(); stocklevelbynp.RemoveAll(x => x.value == 0); stocklevelbynp = stocklevelbynp.OrderBy(x => x.category10_desc).ToList(); return(stocklevelbynp); }
public static List <int> OpeningHoursForDayOfWeek(this HelperService service, DayOfWeek dayOfWeek) { switch (dayOfWeek) { case DayOfWeek.Monday: return(service.MondayOpeningHours); case DayOfWeek.Tuesday: return(service.TuesdayOpeningHours); case DayOfWeek.Wednesday: return(service.WednesdayOpeningHours); case DayOfWeek.Thursday: return(service.ThursdayOpeningHours); case DayOfWeek.Friday: return(service.FridayOpeningHours); case DayOfWeek.Saturday: return(service.SaturdayOpeningHours); case DayOfWeek.Sunday: return(service.SundayOpeningHours); } return(null); }