public Document CreateDocument(string path, HttpPostedFileBase error) { string curId = HttpContext.Current.User.Identity.GetUserId(); // получаем текущего пользователя ApplicationUser user = _db.Users.FirstOrDefault(m => m.Id == curId); DateTime current = DateTime.Now; Document doc = new Document { Size = error.ContentLength }; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); doc.Type = ext; doc.IsDeleted = false; doc.CreateDateTime = current; int userIdHach; if(user!=null) userIdHach = user.Id.GetHashCode(); else { userIdHach = DateTime.Now.GetHashCode(); } if (curId.IsEmpty()) curId = "AVATAR"; using (var transaction = _db.Database.BeginTransaction()) { try { // сохраняем файл по определенному пути на сервере string url = "user" + curId + "_" + current.ToString(userIdHach + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".").Replace(" ", "_") + ext; error.SaveAs(path + url); doc.Url = url; _db.Documents.Add(doc); _db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); throw new Exception(ex.Message); } } return doc; }
public ActionResult ChangeAvatar(HttpPostedFileBase error) { if (error != null) { var curId = this.User.Identity.GetUserId(); var user = db.Users.First(x => x.Id == curId); var newAvatar = new Document { Size = error.ContentLength }; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); newAvatar.Type = ext; // сохраняем файл по определенному пути на сервере string path = DateTime.Now.ToString(this.User.Identity.GetUserId().GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; error.SaveAs(Server.MapPath("~/Files/UserAvatarFiles/" + path)); newAvatar.Url = path; user.Avatar.Add(newAvatar); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); } return RedirectToAction("Index", "Manage"); }
public ActionResult Create([Bind(Include = "Id,Name,Comment,MathTaskId")] MathTaskSolution mathTaskSolution, HttpPostedFileBase error) { var curId = this.User.Identity.GetUserId(); if (ModelState.IsValid) { // если получен файл var current = DateTime.Now; var user = db.Users.Find(curId); if (error != null) { Document doc = new Document(); doc.Size = error.ContentLength; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); doc.Type = ext; // сохраняем файл по определенному пути на сервере string path = current.ToString(user.Id.GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; error.SaveAs(Server.MapPath("~/Files/RequestSolutionFiles/" + path)); doc.Url = path; mathTaskSolution.Document = doc; db.Documents.Add(doc); } else mathTaskSolution.Document = null; var req = db.Requests.Find(mathTaskSolution.MathTaskId); mathTaskSolution.MathTask = req; mathTaskSolution.Author = user; mathTaskSolution.AuthorId = user.Id; mathTaskSolution.IsRight = false; mathTaskSolution.Date = DateTime.Now; // Отметим, что решение относится к этой задаче req.RequestSolutions.Add(mathTaskSolution); req.Executors.Add(user); db.Entry(req).State = EntityState.Modified; db.RequestSolutions.Add(mathTaskSolution); db.SaveChanges(); return RedirectToAction("MyIndex"); } ViewBag.Requests = new SelectList(db.Requests.Where(x => x.Executors.Count(y => y.Id == curId) == 0), "Id", "Name"); return View(mathTaskSolution); }
protected void TryCreate(ApplicationUser user, MathTask mathTask, HttpPostedFileBase file) { //получаем время открытия DateTime current = DateTime.Now; Document doc = null ; ; string fileName = current.ToString(user.Id.GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".").Replace(" ", "_"); string path = Server.MapPath("~/Files/RequestFiles/" + fileName); string ext = "png"; // Если приложен код латекса - грузим его как файл(создаем и грузим) // Иначе - сохраняем как файл if ( !mathTask.LatexCode.IsNullOrWhiteSpace() ) { Bitmap bmp = MathMLFormulaControl.generateBitmapFromLatex(mathTask.LatexCode); bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png); bmp.Dispose(); doc = new Document(); doc.Size = 0; doc.Type = "png"; doc.Url = path + ".png"; } else if (file != null) { // Получаем расширение ext = file.FileName.Substring(file.FileName.LastIndexOf('.')); path = path + ext; // сохраняем файл по определенному пути на сервере file.SaveAs(path); doc = new Document(); doc.Size = file.ContentLength; doc.Type = ext; doc.Url = path; } else { mathTask.Description = DeterminantComplexity.GenerateByLevel(mathTask.MathTaskTypeId - 1, mathTask.Level, true).ToString(); } mathTask.Executors = new List<ApplicationUser>(); // Если не рассылка - добавляем всю выбранную группу if (mathTask.SelectedExecutorId != null) { var executor = this.Db.Users.First(x => x.Id == mathTask.SelectedExecutorId); mathTask.Executors.Add(executor); } else { var students = Db.Users.Where(x => x.Id == mathTask.StudentsGroupId.ToString()); foreach (var student in students) { mathTask.Executors.Add(student); } } // Иначе - добавляем указанного пользователя // указываем автора задачи mathTask.Author = user; mathTask.AuthorId = user.Id; // если сформирован файл if (doc != null) { mathTask.Document = doc; Db.Documents.Add(doc); } else mathTask.Document = null; mathTask.Status = (int)MathTaskStatus.Open; //Добавляем задачу с возможно приложенными документами Db.MathTasks.Add( mathTask ); user.MathTasks.Add( mathTask ); Db.Entry(user).State = EntityState.Modified; try { Db.SaveChanges(); } catch (Exception e) { throw new Exception(e.Message); } }
public void Create(string forAdm, HttpPostedFileBase error) { var uploadText = Request.Params["Text"]; var curId = HttpContext.User.Identity.GetUserId(); // получаем текущего пользователя ApplicationUser user = db.Users.FirstOrDefault(m => m.Id == curId); ErrorMessage erM; if (user != null) { erM= new ErrorMessage { Author = user, AuthorId = user.Id, CreateDate = DateTime.Now, ErrorStatus = 0 }; } else { erM = new ErrorMessage { CreateDate = DateTime.Now, ErrorStatus = 0 }; } // если получен файл if (error != null) { DateTime current = DateTime.Now; Document doc = new Document(); doc.Size = error.ContentLength; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); doc.Type = ext; // сохраняем файл по определенному пути на сервере string path = current.ToString(user.Id.GetHashCode()+"dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; error.SaveAs(Server.MapPath("~/Files/ErrorMessageFiles/" + path)); doc.Url = path; erM.Document = doc; db.Documents.Add(doc); } else erM.Document = null; if (uploadText == null) erM.Text = ""; else erM.Text = uploadText; if (forAdm == "1") { erM.ForAdministration = true; var email = Request.Params["email"].ToString(); erM.Email = email; } else erM.ForAdministration = false; //var cat = db.Categories.Find(request.CategoryId); //request.Category = cat; //request.Comment = ""; // Добавляем задачу с возможно приложенными документами db.ErrorMessages.Add(erM); user.ErrorMessages.Add(erM); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); Response.Redirect(Request.UrlReferrer.AbsoluteUri); }
public ActionResult Register(RegisterViewModel model, HttpPostedFileBase avatar) { if (ModelState.IsValid) { //получаем время открытия DateTime current = DateTime.Now; var newAvatar = new Document(); if (avatar!=null) { newAvatar.Size = avatar.ContentLength; // Получаем расширение string ext = avatar.FileName.Substring(avatar.FileName.LastIndexOf('.')); newAvatar.Type = ext; // сохраняем файл по определенному пути на сервере string path = current.ToString(this.User.Identity.GetUserId().GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; avatar.SaveAs(Server.MapPath("~/Files/UserAvatarFiles/" + path)); newAvatar.Url = path; db.SaveChanges(); } var user = new ApplicationUser { UserName = model.Email, Name = model.Name, Password=model.Password, Email = model.Email, RegistrationDate = DateTime.Now, UserInfo="user" }; var result = UserManager.Create(user, model.Password); if (result.Succeeded) { if(avatar!=null) { var newUser = db.Users.First(x => x.Id == user.Id); newUser.Avatar.Add(newAvatar); db.Entry(newUser).State = EntityState.Modified; db.SaveChanges(); } SignInManager.SignIn(user, isPersistent:false, rememberBrowser:false); // Дополнительные сведения о том, как включить подтверждение учетной записи и сброс пароля, см. по адресу: http://go.microsoft.com/fwlink/?LinkID=320771 // Отправка сообщения электронной почты с этой ссылкой // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Article.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Подтверждение учетной записи", "Подтвердите вашу учетную запись, щелкнув <a href=\"" + callbackUrl + "\">здесь</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // Появление этого сообщения означает наличие ошибки; повторное отображение формы return View(model); }
//[Authorize] public ActionResult Create(MathTask request, HttpPostedFileBase error) { var curId = HttpContext.User.Identity.GetUserId(); // получаем текущего пользователя ApplicationUser user = db.Users.FirstOrDefault(m => m.Id == curId); if (user == null) { return RedirectToAction("LogOff", "Account"); } if (ModelState.IsValid) { // указываем статус Открыта у задачи request.Status = (int)RequestStatus.Open; //получаем время открытия DateTime current = DateTime.Now; // указываем пользователя задачи request.Author = user; request.AuthorId = user.Id; // если получен файл if (error != null) { Document doc = new Document(); doc.Size = error.ContentLength; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); doc.Type = ext; // сохраняем файл по определенному пути на сервере string path = current.ToString(user.Id.GetHashCode()+"dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; error.SaveAs(Server.MapPath("~/Files/RequestFiles/" + path)); doc.Url = path; request.Document = doc; db.Documents.Add(doc); } else request.Document = null; request.Status = (int)RequestStatus.Open; //Добавляем задачу с возможно приложенными документами db.Requests.Add(request); user.Requests.Add(request); db.Entry(user).State = EntityState.Modified; try { db.SaveChanges(); } catch(Exception e) { return Content(e.Message); } return RedirectToAction("Index"); } return View(request); }
public ActionResult Create([Bind(Include = "Id,Name,Description,Difficulty,TypeId")] Article article, int[] ingridient, HttpPostedFileBase error) { var curId = HttpContext.User.Identity.GetUserId(); // получаем текущего пользователя ApplicationUser user = _db.Users.FirstOrDefault(m => m.Id == curId); if (user == null) { return RedirectToAction("LogOff", "Account"); } if (ModelState.IsValid) { try { if (ingridient != null) { //получаем выбранные ингридиенты foreach (var c in ingridient) { var ingr = _db.Ingridients.Find(c); // И добавляем article.Ingridients.Add(ingr); } } // если получен файл if (error != null) { DateTime current = DateTime.Now; Document doc = new Document(); doc.Size = error.ContentLength; // Получаем расширение string ext = error.FileName.Substring(error.FileName.LastIndexOf('.')); doc.Type = ext; // сохраняем файл по определенному пути на сервере string path = current.ToString(user.Id.GetHashCode() + "dd/MM/yyyy H:mm:ss").Replace(":", "_").Replace("/", ".") + ext; error.SaveAs(Server.MapPath("~/Files/ArticleFiles/" + path)); doc.Url = path; article.Document = doc; _db.Documents.Add(doc); } else article.Document = null; // указываем пользователя рецепты article.Author = user; article.AuthorId = user.Id; article.Type = _db.Types.Find(article.TypeId); var type = _db.Types.Find(article.TypeId); article.Type = type; article.TypeId = type.Id; _db.Articles.Add(article); _db.Entry(user).State = EntityState.Modified; _db.SaveChanges(); } catch (Exception e) { return Content(e.Message); } return RedirectToAction("Index"); } return View(article); }