private void ChangeUserAuthor_Load(object sender, EventArgs e) { if (user.programs == null) { var tmp = new UserProgram(user); user.programs = tmp.programs; } checkedListBox1.Items.Clear(); var tmpp = new UserProgram(new User { userClass = User.UserClass.Admin }); foreach (var p in tmpp.programs) { checkedListBox1.Items.Add(UserProgram.DisplayProgram(p)); } foreach (var p in user.programs) { checkedListBox1.SetItemChecked(p, true); } if (user.name.Equals("Admin")) { checkedListBox1.Enabled = false; prompt.Show(); } else { prompt.Hide(); } }
public static void SCPFileSender(UserProgram userProgram) { try { //choofdlog.Multiselect = true using (SshClient client = new SshClient("127.0.0.1", 10022, "lvuser", "")) { client.Connect(); client.RunCommand("rm FRCUserProgram FRCUserProgram.jar"); // Delete existing files so the frc program chooser knows which to run client.Disconnect(); } using (ScpClient client = new ScpClient("127.0.0.1", 10022, "lvuser", "")) { client.Connect(); using (Stream localFile = File.OpenRead(userProgram.fullFileName)) { client.Upload(localFile, @"/home/lvuser/" + userProgram.targetFileName); } client.Disconnect(); } } catch (Exception) {} }
public override int Eval(Stack stack) { int narg = GetNarg(stack); var local = Session.Proc.Store.Clone(); var code = GetList(stack); var ups = new Stack(); int ret = UserProgram.process_block(code, ups, local, false); Session.Proc.Store.Update(local); if (ret != Processor.ERROR && ups.Count > 0) { var y = ups.Pop(); stack.Push(y); } else { throw new SymbolicException("Error processing block."); } return(0); }
public override int Eval(Stack stack) { int narg = GetNarg(stack); var local = pc.env.copy(); var code = GetList(stack); var ups = new Stack(); int ret = UserProgram.process_block(code, ups, local, false); pc.env.update(local); if (ret != Processor.ERROR && ups.Count > 0) { var y = ups.Pop(); stack.Push(y); } else { throw new JasymcaException("Error processing block."); } return(0); }
/// <summary> /// /// </summary> /// <param name="userID"></param> /// <param name="date"></param> /// <returns> /// 0: el cliente va en el mismo dia que el servidor /// entero positivo >0 : el cliente va mas adelante que el servidor /// -1: el cliente ya supero la fecha de finalizacion del programa /// </returns> /// <remarks> /// </remarks> public int CheckUserProgramDay(int userID, DateTime date) { int retVal = 0; //obtener lafecha de inicio del programa UserProgram userProgram = this.SelectCurrentUserProgram(userID); //de acuerdo a la fehca del cliente, calcular en que dia va el usuario int userCurrentDay = (date.Date - userProgram.StartDate.Date).Days + 1; //checar si han pasado mas dias de los dias que tiene el programa if (userCurrentDay > userProgram.Duration) { retVal = -1; } //si el dia del programa no es igual al dia del usuario //actualizar el programa con el dia en el que va el usuario else if (userCurrentDay > userProgram.CurrentDay) { using (var context = new WorkoutEntities()) { int?rowcount = context.spUserProgramUpdateCurrentDay(userID, userProgram.ProgramID, userCurrentDay).SingleOrDefault(); } retVal = userCurrentDay; } return(retVal); }
static void Main(string[] args) { var userRepository = new UserRepository(); var program = new UserProgram(userRepository); program.CreateUser("001", "ymiyamoto"); }
public void PopulateHighCharts() { UserProgram greProgram = new UserProgram() { ID = "1", Name = "GRE", Score = 23 }; greProgram.userSubPrograms.Add(new UserProgram() { ID = "11", Name = "GRE1", Score = 25 }); greProgram.userSubPrograms.Add(new UserProgram() { ID = "12", Name = "GRE2", Score = 25 }); greProgram.userSubPrograms.Add(new UserProgram() { ID = "13", Name = "GRE3", Score = 25 }); UserPrograms.Add(greProgram); UserProgram gmatProgram = new UserProgram() { ID = "2", Name = "GMAT", Score = 27 }; gmatProgram.userSubPrograms.Add(new UserProgram() { ID = "21", Name = "GMAT1", Score = 25 }); gmatProgram.userSubPrograms.Add(new UserProgram() { ID = "22", Name = "GMAT2", Score = 25 }); gmatProgram.userSubPrograms.Add(new UserProgram() { ID = "23", Name = "GMAT3", Score = 25 }); UserPrograms.Add(gmatProgram); UserProgram kbrProgram = new UserProgram() { ID = "3", Name = "KBR", Score = 45 }; kbrProgram.userSubPrograms.Add(new UserProgram() { ID = "31", Name = "KBR1", Score = 25 }); kbrProgram.userSubPrograms.Add(new UserProgram() { ID = "32", Name = "KBR2", Score = 25 }); kbrProgram.userSubPrograms.Add(new UserProgram() { ID = "33", Name = "KBR3", Score = 25 }); UserPrograms.Add(kbrProgram); UserProgram MCADProgram = new UserProgram() { ID = "3", Name = "MCAD", Score = 5 }; MCADProgram.userSubPrograms.Add(new UserProgram() { ID = "31", Name = "KBR1", Score = 25 }); MCADProgram.userSubPrograms.Add(new UserProgram() { ID = "32", Name = "KBR2", Score = 25 }); MCADProgram.userSubPrograms.Add(new UserProgram() { ID = "33", Name = "KBR3", Score = 25 }); UserPrograms.Add(MCADProgram); }
private void ensure_Click(object sender, EventArgs e) { User admin = new User(); admin.name = username.Text; admin.pass = password.Text; admin.userClass = (User.UserClass)userClassComboBox.SelectedIndex; var tmp = new UserProgram(admin); if (username.Text.Equals("Admin")) { prompt.Show(); } else { if (InitData.users == null) { InitData.users = new List <User>(); } if (InitData.users.Any(u => u.name == admin.name)) { dialog.MessageBox.Show(GlobalData.GlobalLanguage.user_exist); } else if (szwlForm.mainForm.dm.insertUser(admin)) { InitData.users = szwlForm.mainForm.dm.selectUser(); dialog.MessageBox.Show(GlobalData.GlobalLanguage.add_success); this.DialogResult = DialogResult.OK; this.Close(); } } }
public static async Task <IActionResult> CreateUserProgramListing( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "progress/program/listing")] HttpRequest req, [CosmosDB( databaseName: "UserProgress", collectionName: "UserPrograms", ConnectionStringSetting = "AzureWebJobsStorage")] IAsyncCollector <UserProgram> userProgramOut, ILogger log) { log.LogInformation("Create a new user program"); // Read the request body string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var input = JsonConvert.DeserializeObject <UserProgramCreateModel>(requestBody); var userprogram = new UserProgram() { Username = input.Username, Programs = input.Programs, Status = input.Status }; try { await userProgramOut.AddAsync(userprogram); } catch (Exception e) { return(new BadRequestResult()); } return(new OkObjectResult(userprogram)); }
public List <UserProgram> GetUserProgramList(int userId) { List <UserProgram> lstUserProg = null; UserProgram userProg; try { SQLiteParam param = new SQLiteParam(1) { CommandText = StoreProcedure.Instance.GetScript("GetUserProgramList") }; param.ParamInt32(0, "@USER_ID", userId); SQLiteReader.Instance.SLReader = GlobalSqliteDB.Instance.DataAc.ExecuteDataReader(param); if (SQLiteReader.Instance.HasRows) { lstUserProg = new List <UserProgram>(); while (SQLiteReader.Instance.SLReader.Read()) { userProg = new UserProgram(); userProg.USER_PROG_ID = SQLiteReader.Instance.GetInteger("USER_PROG_ID"); userProg.PG_ICON = SQLiteReader.Instance.GetString("PG_ICON"); userProg.PROG_TYPE_NAME = SQLiteReader.Instance.GetString("PROG_TYPE_NAME"); userProg.ICON = SQLiteReader.Instance.GetString("ICON"); userProg.PROG_ID = SQLiteReader.Instance.GetInteger("PROG_ID"); userProg.PROG_NAME = SQLiteReader.Instance.GetString("PROG_NAME"); userProg.IS_ACCESS = SQLiteReader.Instance.GetString("IS_ACCESS").ToUpper().Equals("Y"); userProg.IS_INSERT = SQLiteReader.Instance.GetString("IS_INSERT").ToUpper().Equals("Y"); userProg.IS_UPDATE = SQLiteReader.Instance.GetString("IS_UPDATE").ToUpper().Equals("Y"); userProg.IS_DELETE = SQLiteReader.Instance.GetString("IS_DELETE").ToUpper().Equals("Y"); userProg.IS_PRINT = SQLiteReader.Instance.GetString("IS_PRINT").ToUpper().Equals("Y"); userProg.CUSTOM1 = SQLiteReader.Instance.GetString("CUSTOM1"); userProg.IS_CUSTOM1 = SQLiteReader.Instance.GetString("IS_CUSTOM1").ToUpper().Equals("Y"); userProg.CUSTOM2 = SQLiteReader.Instance.GetString("CUSTOM2"); userProg.IS_CUSTOM2 = SQLiteReader.Instance.GetString("IS_CUSTOM2").ToUpper().Equals("Y"); userProg.CUSTOM3 = SQLiteReader.Instance.GetString("CUSTOM3"); userProg.IS_CUSTOM3 = SQLiteReader.Instance.GetString("IS_CUSTOM3").ToUpper().Equals("Y"); userProg.USER_ID = SQLiteReader.Instance.GetString("USER_ID"); userProg.FLAG = SQLiteReader.Instance.GetInteger("FLAG"); lstUserProg.Add(userProg); } } //Always call Close when done reading. SQLiteReader.Instance.Close(); } catch (Exception ex) { lstUserProg = null; } return(lstUserProg); //return UtilityBLL.ListToDataTable(lstUserProg, "M_USER_PROGRAM"); }
public ActionResult DeleteConfirmed(int id) { UserProgram userProgram = db.UserPrograms.Find(id); db.UserPrograms.Remove(userProgram); db.SaveChanges(); return(RedirectToAction("Index")); }
//public async Task<int> SaveImageAsync(ImageObject image) //{ // await _context.Images.AddAsync(image); // await _context.SaveChangesAsync(); // return image.Id; //} //public async Task<ImageObject> GetImageAsync(int id) //{ // return await _context.Images.FirstOrDefaultAsync(i => i.Id.Equals(id)); //} //public async Task<List<ImageObject>> GetImagesAsync(int ownerId, string relationType) //{ // if (ownerId == 0 || string.IsNullOrEmpty(relationType)) // { // return null; // } // return await _context.Images.Where(i => i.OwnerId.Equals(ownerId) && i.RelationType.Equals(relationType)).ToListAsync(); //} public async Task <int> AddClientProgramAsync(UserProgram userProgram) { await _context.UsersPrograms.AddAsync(userProgram); await _context.SaveChangesAsync(); return(userProgram.Id); }
public ActionResult Edit([Bind(Include = "Id,ProgramId,UserId,ScheduleTime,Duration,Description,CreationTime,UpdateTime")] UserProgram userProgram) { if (ModelState.IsValid) { db.Entry(userProgram).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(userProgram)); }
public ActionResult Create(UserProgram userProgram) { if (ModelState.IsValid) { db.UserPrograms.Add(userProgram); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(userProgram)); }
public async Task UpdateFromFileAsync(Stream fileStream, bool onlyActual) { var fileParser = new ExcelFileParser(); var parsedPrograms = fileParser.ParsePrograms(fileStream); parsedPrograms = NormalizePrograms(parsedPrograms, onlyActual); foreach (var nProg in parsedPrograms) { var program = (await Database.Programs.GetAsync(nProg.Name)) ?? new Program { Name = nProg.Name }; var user = await Database.Users.GetAsync(nProg.UserId); if (user != null) { var activeProgram = await Database.UserPrograms.GetActiveAsync(nProg.UserId); //TODO Заменить на Find в случае чего if (activeProgram != null) { if (activeProgram.StartedAt >= nProg.StartedAt) { continue; } activeProgram.FinishedAt = DateTime.Now; Database.UserPrograms.Update(activeProgram); } } else { user = new User { Id = nProg.UserId }; Database.Users.Create(user); } var newUserProgram = new UserProgram { UserId = user.Id, Foolowing = nProg.IsFollowed, Program = program, StartedAt = nProg.StartedAt }; Database.UserPrograms.Create(newUserProgram); await Database.SaveAsync(); } }
public UserProgram GetCurrentUserProgram(int userID) { UserProgram program = repository.SelectCurrentUserProgram(userID); if (program == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)); } return(program); }
// GET: UserPrograms/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } UserProgram userProgram = db.UserPrograms.Find(id); if (userProgram == null) { return(HttpNotFound()); } return(View(userProgram)); }
//设置COM信息 public static void Init() { com = Common.GetComInfo(); callbtnsetting = GetCallBtnSetting(); orderby = GetOrederBy(); timecolor = GetTimeColor(); TimeOut = 5; UnFinish = 20; users = szwlForm.mainForm.dm.selectUser(); employees = szwlForm.mainForm.dm.selectEmployee(); employeeRFID = szwlForm.mainForm.dm.selectEmployeeRFID(); list_zone = szwlForm.mainForm.dm.selectZone(); list_caller = szwlForm.mainForm.dm.selectCaller(); program = new UserProgram(LogOnForm.currentUser); }
//设置COM信息 public static void Clear() { com = null; callbtnsetting = null; orderby = null; timecolor = null; TimeOut = 5; UnFinish = 20; users = null; employees = null; employeeRFID = null; list_zone = null; list_caller = null; program = null; LogOnForm.currentUser = null; }
public override int Eval(Stack st) { int narg = GetNarg(st); var code_in = GetList(st); var fname = GetSymbol(st).Substring(1); int nvar = GetNarg(st); var vars = new SimpleVariable[nvar]; for (int i = 0; i < nvar; i++) { vars[i] = new SimpleVariable(GetSymbol(st)); } Lambda func = null; var env = new Environment(); var ups = new Stack(); object y = null; if (nvar == 1) { int res = UserProgram.process_block(code_in, ups, env, false); if (res != Processor.ERROR) { y = ups.Pop(); } } if (y is Algebraic) { func = new UserFunction(fname, vars, ( Algebraic )y, null, null); } else { func = new UserProgram(fname, vars, code_in, null, env, ups); } pc.env.putValue(fname, func); st.Push(fname); return(0); }
public async Task UpdateClientProgramAsync(UserProgram userProgram) { var entity = await _context.UsersPrograms.FirstOrDefaultAsync(p => p.Id.Equals(userProgram.Id)); if (entity == null) { return; } entity.UserId = userProgram.UserId; entity.ProgramId = userProgram.ProgramId; entity.StartedOn = userProgram.StartedOn; entity.FinishedOn = userProgram.FinishedOn; entity.Notes = userProgram.Notes; entity.ModifiedOn = DateTime.Now; await _context.SaveChangesAsync(); }
public override int lambda(Stack st) { int narg = getNarg(st); Environment local = pc.env.copy(); List code = getList(st); Stack ups = new Stack(); int ret = UserProgram.process_block(code, ups, local, false); pc.env.update(local); if (ret != Processor.ERROR && ups.Count > 0) { object y = ups.Pop(); st.Push(y); } else { throw new JasymcaException("Error processing block."); } return(0); }
public async void LoadCode() { string[] selectedFiles = SFB.StandaloneFileBrowser.OpenFilePanel("Robot Code Executable", "C:\\", "", false); if (selectedFiles.Length != 1) { AnalyticsManager.GlobalInstance.LogEventAsync(AnalyticsLedger.EventCatagory.EmulationTab, AnalyticsLedger.EventAction.CodeType, "No Code", AnalyticsLedger.getMilliseconds().ToString()); } else { UserProgram userProgram = new UserProgram(selectedFiles[0]); if (userProgram.ProgramType == UserProgram.Type.INVALID) { UserMessageManager.Dispatch("Invalid user program type", EmulationWarnings.WARNING_DURATION); } else if (userProgram.Size > EmulatorManager.MAX_FILE_SIZE) { UserMessageManager.Dispatch(Math.Round((double)userProgram.Size / (1024 * 1024), 2) + " MB user program is too large (capacity is " + Math.Round((double)EmulatorManager.MAX_FILE_SIZE / (1024 * 1024), 2) + " MB)", EmulationWarnings.WARNING_DURATION); } else { if (userProgram.Size > EmulatorManager.WARNING_FILE_SIZE) { UserMessageManager.Dispatch("Uploading large, " + Math.Round((double)userProgram.Size / (1024 * 1024), 2) + " MB user program. Upload may take a while.", EmulationWarnings.WARNING_DURATION); } PlayerPrefs.SetString("UserProgramType", userProgram.ProgramType.ToString()); AnalyticsManager.GlobalInstance.LogEventAsync(AnalyticsLedger.EventCatagory.EmulationTab, AnalyticsLedger.EventAction.CodeType, userProgram.ProgramType.ToString(), AnalyticsLedger.getMilliseconds().ToString()); loadingPanel.SetActive(true); uploadSuccess = await EmulatorManager.SCPFileSender(userProgram); uploadFinished = true; } } }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Please enter a file path"); return; } UserProgram userProgram = new UserProgram(); UserProgram.Result sourceResult = userProgram.SetSource(args[0]); Console.WriteLine(sourceResult.Message); if (sourceResult.Status == UserProgram.Result.StatusType.Failed) { return; } UserProgram.Result compilationResult = userProgram.Compile(); Console.WriteLine(compilationResult.Message); if (compilationResult.Status == UserProgram.Result.StatusType.Failed) { return; } UserProgram.Result programResult = userProgram.Execute(args.Length < 2 ? "" : args[1]); Console.WriteLine(programResult.Message); if (programResult.Status == UserProgram.Result.StatusType.Failed) { return; } string expectedOutput = args.Length < 3 ? "Hello World!" : args[2]; UserProgram.Result outputResult = userProgram.Evaluate(expectedOutput); Console.WriteLine(outputResult.Message); }
public async Task <int> AddUserProgramAsync(UserProgram userProgram) { int userProgramId; if (await _context.FindAsync <User>(userProgram.UserId) == null) { throw new Exception("User not found"); } if (await _context.Programs.FindAsync(userProgram.ProgramId) == null) { throw new Exception("Program not found"); } var userProgramEntity = await _context.UsersPrograms.FirstOrDefaultAsync( p => p.UserId == userProgram.UserId && p.ProgramId == userProgram.ProgramId && p.IsActive == true); if (userProgramEntity == null) { await _context.UsersPrograms.AddAsync(userProgram); userProgramId = userProgram.Id; } else { userProgramEntity.IsActive = userProgram.IsActive; userProgramEntity.StartedOn = userProgram.StartedOn; userProgramEntity.FinishedOn = userProgram.FinishedOn; userProgramEntity.Notes = userProgram.Notes; userProgramId = userProgramEntity.Id; } await _context.SaveChangesAsync(); return(userProgramId); }
public UserProgram SelectCurrentUserProgram(int userID) { UserProgram userProgram = null; using (var context = new WorkoutEntities()) { spSelectCurrentUserProgram_Result userProgramEF = context.spSelectCurrentUserProgram(userID).FirstOrDefault(); if (userProgramEF != null) { userProgram = new UserProgram(); userProgram.ProgramID = userProgramEF.ProgramID; userProgram.Name = userProgramEF.Name; userProgram.Description = userProgramEF.Description; userProgram.LongDescription = userProgramEF.LongDescription; userProgram.ProgramStatusID = userProgramEF.ProgramStatusID; userProgram.ProgramStatusName = userProgramEF.ProgramStatusName; userProgram.GoalID = userProgramEF.GoalID; userProgram.GoalName = userProgramEF.GoalName; userProgram.Raiting = userProgramEF.Raiting.HasValue ? userProgramEF.Raiting.Value : 0; userProgram.ImageFile = userProgramEF.ImageFile; userProgram.IsCompleted = userProgramEF.IsCompleted; userProgram.StartDate = userProgramEF.StartDate.HasValue ? userProgramEF.StartDate.Value : DateTime.MinValue; userProgram.EndDate = userProgramEF.EndDate.HasValue ? userProgramEF.EndDate.Value : DateTime.MinValue; userProgram.OnProgress = userProgramEF.OnProgress.HasValue ? userProgramEF.OnProgress.Value : false; userProgram.CreatedDate = userProgramEF.CreatedDate; userProgram.Duration = userProgramEF.Duration.HasValue ? userProgramEF.Duration.Value : 0; userProgram.UnitOfMeasureID = userProgramEF.UnitOfMeasureID.HasValue ? userProgramEF.UnitOfMeasureID.Value : 0; userProgram.UnitOfMeasureCode = userProgramEF.UnitOfMeasureCode; userProgram.UnitOfMeasureDescription = userProgramEF.UnitOfMeasureDescription; userProgram.CurrentDay = userProgramEF.CurrentDay.HasValue ? userProgramEF.CurrentDay.Value : 0; userProgram.BMIStart = userProgramEF.BMIStart.HasValue ? userProgramEF.BMIStart.Value:0; } } return(userProgram); }
public void Update(UserProgram item) { throw new NotImplementedException(); }
public void Create(UserProgram item) { _db.UserPrograms.Add(item); }
public async Task <IActionResult> Result(int id, string filePath) { Problem problem = await dbContext.Problems.Include(m => m.Tests).FirstOrDefaultAsync(p => p.ProblemID == id); if (problem == null) { return(RedirectToAction(nameof(List))); } if (!System.IO.File.Exists(filePath)) { return(RedirectToAction(nameof(Solve), new { id })); } string parentFolderPath = Directory.GetParent(filePath).FullName; ResultViewModel viewModel = new ResultViewModel() { ProblemID = problem.ProblemID, Name = problem.Name, ShowFailedTestCases = problem.ShowFailedTestCases }; UserProgram userProgram = new UserProgram(); var result = userProgram.SetSource(filePath); viewModel.CompilationResult = result; if (result.Status == UserProgram.Result.StatusType.Failed) { Directory.Delete(parentFolderPath, true); return(View(viewModel)); } result = userProgram.Compile(); viewModel.CompilationResult = result; if (result.Status == UserProgram.Result.StatusType.Failed) { Directory.Delete(parentFolderPath, true); viewModel.CompilationResult = result; return(View(viewModel)); } int passed = 0; foreach (Test t in problem.Tests) { result = userProgram.Execute(t.GivenInput); ResultViewModel.TestResult testResult = new ResultViewModel.TestResult() { Test = t, ExecutionResult = result }; if (result.Status == UserProgram.Result.StatusType.Successful) { // Format expected output lines string[] expectedOutputLines = t.ExpectedOutput.Split('\n'); for (int i = 0; i < expectedOutputLines.Length; i++) { expectedOutputLines[i] = expectedOutputLines[i].Trim('\u202c').Trim(); } result = userProgram.EvaluateAndGetResultIfFailed(expectedOutputLines); if (result.Status == UserProgram.Result.StatusType.Successful) { passed++; } testResult.EvaluationResult = result; viewModel.TestResults.Add(testResult); } else { viewModel.TestResults.Add(testResult); } } viewModel.PassedTests = passed; try { Directory.Delete(parentFolderPath, true); } catch (UnauthorizedAccessException) // Sometimes the process isn't killed fast enough { Thread.Sleep(100); Directory.Delete(parentFolderPath, true); } ApplicationUser partialUser = await userManager.GetUserAsync(User); ApplicationUser currentUser = await userManager.Users .Include(u => u.ProblemResults) .ThenInclude(r => r.FirstResult) .Include(u => u.ProblemResults) .ThenInclude(r => r.BestResult) .FirstOrDefaultAsync(u => u == partialUser); if (currentUser != null) { bool hasProblem = currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID); bool gotPerfectPercentage = false; if (hasProblem) { ProblemResult problemResult = currentUser.ProblemResults.Where(r => r.ProblemID == problem.ProblemID).First(); int bestPercentage = problemResult.BestResult.PercentageResult; gotPerfectPercentage = bestPercentage < 100; } bool isAdmin = await userManager.IsInRoleAsync(currentUser, "Admin"); // A unique user solved the problem and is not an Admin if (passed == problem.Tests.Count && (!hasProblem || (hasProblem && gotPerfectPercentage)) && !isAdmin) { problem.TimesSolved++; if (await TryUpdateModelAsync(problem)) { try { await dbContext.SaveChangesAsync(); } catch (DbUpdateException) { return(View(viewModel)); } } } ProgramResult programResult = viewModel.GetProgramResult(); if (currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID)) { // Tried to solve the problem again ProblemResult problemResult = currentUser.ProblemResults.First(r => r.ProblemID == problem.ProblemID); if (programResult.PercentageResult > problemResult.BestResult.PercentageResult) { if (problemResult.BestResult != problemResult.FirstResult) { dbContext.Remove(problemResult.BestResult); } problemResult.BestResult = programResult; } } else { // Solved this problem for the first time ProblemResult problemResult = new ProblemResult() { ProblemID = problem.ProblemID, FirstResult = programResult, BestResult = programResult }; currentUser.ProblemResults.Add(problemResult); } await userManager.UpdateAsync(currentUser); } return(View(viewModel)); }
public static async Task <IActionResult> InitializeUserProgram( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "progress/program")] HttpRequest req, [CosmosDB( databaseName: "UserProgress", collectionName: "UserPrograms", ConnectionStringSetting = "AzureWebJobsStorage")] DocumentClient userProgsCient, [CosmosDB( databaseName: "UserProgress", collectionName: "UserProgramDetails", ConnectionStringSetting = "AzureWebJobsStorage")] IAsyncCollector <UserProgramDetail> userProgDetsOut, ILogger log) { List <Document> output = new List <Document>(); log.LogInformation("Initializa a new user program"); // Get the program details string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var inputProgDetails = JsonConvert.DeserializeObject <UserProgramDetailCreateModel>(requestBody); // Get the active program for this user Uri collectionUri = UriFactory.CreateDocumentCollectionUri("UserProgress", "UserPrograms"); IDocumentQuery <UserProgram> query = userProgsCient.CreateDocumentQuery <UserProgram>(collectionUri) .Where(p => p.Username.Equals(inputProgDetails.Username)) .Where(p => p.Status.Equals("active")) .AsDocumentQuery(); try { while (query.HasMoreResults) { foreach (Document doc in await query.ExecuteNextAsync()) { UserProgram userProgram = (dynamic)doc; // If the program has already been started let the caller know and don't continue foreach (var program in userProgram.Programs) { if (program.Id == inputProgDetails.ProgId) { return(new ConflictObjectResult("Program already started")); } } // If the program hasn't started then you're here, update the active program list userProgram.Programs.Add(new Program() { Id = inputProgDetails.ProgId, Name = inputProgDetails.ProgName }); output.Add(await userProgsCient.ReplaceDocumentAsync(doc.SelfLink, userProgram)); // Map the create model to the database required model var progDetail = new UserProgramDetail() { Username = inputProgDetails.Username, ProgId = inputProgDetails.ProgId, ProgName = inputProgDetails.ProgName, TotalDays = inputProgDetails.TotalDays, Exersices = inputProgDetails.Exersices }; // Create the framework in the program details container await userProgDetsOut.AddAsync(progDetail); } } } catch (Exception e) { return(new BadRequestResult()); } return(new OkObjectResult(output)); }
public async Task RegisterAccountAsync(RegisterViewModel model) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); //create user profile AspNetUser netUser = db.AspNetUsers.Where(tuser => tuser.Id.Equals(user.Id)).FirstOrDefault(); netUser.PeriodID = WebSettings.CurrentPeriod().PeriodID; netUser.ValidationPeriod = db.ValidationPeriods.Where(e => e.PeriodID == netUser.PeriodID).FirstOrDefault(); StudentProfile studentProfile = db.StudentProfiles.Where(e => e.Email.Equals(model.Email)).FirstOrDefault(); //Assign Profile UserProfile userProfile = new UserProfile(); userProfile.AspNetUser = netUser; userProfile.StudentProfile = studentProfile; userProfile.ProfileID = studentProfile.ProfileID; userProfile.UserID = netUser.Id; db.UserProfiles.Add(userProfile); // Assign user role AspNetRole role = db.AspNetRoles.Where(trole => trole.Name.Equals("Student")).FirstOrDefault(); AspNetUserRole userRole = new AspNetUserRole { AspNetRole = role, AspNetUser = netUser, RoleId = role.Id, UserId = user.Id }; db.AspNetUserRoles.Add(userRole); // add user program int programID = db.Programs.Where(e => e.ProgramName.Equals(studentProfile.Program)).FirstOrDefault().ProgramID; int year = studentProfile.Year; Program program = db.Programs.Where(tPrg => tPrg.ProgramID.Equals(programID)).FirstOrDefault(); UserProgram userProgram = new UserProgram() { AspNetUser = netUser, ProgramID = programID, Program = program, UserID = user.Id, Year = year }; db.UserPrograms.Add(userProgram); if (!result.Succeeded) { AddErrors(result); } db.SaveChanges(); // Send Verification link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); }