private Image ProcessUploadedImage(HttpPostedFileBase file) { var WorkingImageExtension = Path.GetExtension(file.FileName).ToLower(); string[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" }; // Make sure it is an image that can be processed if (allowedExtensions.Contains(WorkingImageExtension)) { Image workingImage = new Bitmap(file.InputStream); workingImage = ResizeImage(workingImage); return workingImage; } else { throw new Exception("Cannot process files of this type."); } }
// helper that returns the original file if there was content uploaded, null if empty internal static HttpPostedFileBase ChooseFileOrNull(HttpPostedFileBase rawFile) { // case 1: there was no <input type="file" ... /> element in the post if (rawFile == null) { return null; } // case 2: there was an <input type="file" ... /> element in the post, but it was left blank if (rawFile.ContentLength == 0 && String.IsNullOrEmpty(rawFile.FileName)) { return null; } // case 3: the file was posted return rawFile; }
public async Task<bool> Upload(HttpPostedFileBase file, string fileName) { try { CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileName); await blockBlob.UploadFromStreamAsync(file.InputStream); blockBlob.Properties.ContentType = file.ContentType; await blockBlob.SetPropertiesAsync(); return true; } catch { return false; } }
public void SubirArchivoAsync(MyModel model, HttpPostedFileBase inputFileId) { AsyncManager.OutstandingOperations.Increment(); AsyncManager.Sync(() => { try { if (ModelState.IsValid) { // ¡¡¡ Código para procesar archivo !!! AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = true, Message = "mensaje ok" } }; } else { AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = false, Message = this.GetHtmlModelStateErrors() } }; } } catch (Exception exception) { AsyncManager.Parameters["WrappedJsonResult"] = new WrappedJsonResult { Data = new UploadFileResult { Success = false, Message = (exception is PortalLoadFileFailedException) ? exception.Message : "otro mensaje", CodeError = codError } }; } finally { AsyncManager.OutstandingOperations.Decrement(); } }); }
public string Upload(HttpPostedFileBase file) { // Verify that the user selected a file if (file != null && file.ContentLength > 0) { // extract only the fielname var fileName = Path.GetFileName(file.FileName); // store the file inside ~/App_Data/uploads folder var path = Path.Combine(Server.MapPath("~/Uploads/Temp"), fileName); var WorkingImageId = Guid.NewGuid(); Image image = ProcessUploadedImage(file); var WorkingImageExtension = Path.GetExtension(file.FileName).ToLower(); var imagePath = Server.MapPath("/Uploads/Temp") + @"\" + WorkingImageId + WorkingImageExtension; image.Save(imagePath); return WorkingImageId + WorkingImageExtension; } // redirect back to the index action to show the form once again return ""; }
/// <summary> /// The save. /// </summary> /// <param name="img"> /// The img. /// </param> /// <returns> /// The <see cref="ActionResult"/>. /// </returns> public ContentResult SavePicture(HttpPostedFileBase img) { try { if (img != null) { var fileName = Path.GetFileName(img.FileName); if (fileName != null) { var physicalPath = Path.Combine(this.Server.MapPath("~/Images/pro"), fileName); img.SaveAs(physicalPath); } } return Content(string.Empty); } catch (Exception exception) { throw new Exception(exception.Message, exception); } }
public ActionResult Upload(HttpPostedFileBase file) { if (file == null || file.ContentLength <= 0) return RedirectToAction("Index"); try { using (StreamReader st = new StreamReader(file.InputStream)) { var newBooks = _bookReaderFactory.GetReader(Path.GetExtension(file.FileName)); _bookRepository.Merge(newBooks.GetBooks(st)); } return RedirectToAction("Index"); } catch { return RedirectToAction("Error"); } }
public ActionResult UploadScanfiles(string str, string FileTypeName, StudyMaterial model) { string userID = User.Identity.Name; var userid = (from a in dbcontext.CommitteeMembers_Profile where a.EmailID == userID select a.CmtID).FirstOrDefault(); string msg = ""; int Status = 0; string fileName = ""; string filesnames = ""; var Stringimages = new List<string>(); string savedFileName = ""; DateTime d1 = DateTime.Now; var storedData = dbcontext.StudyMaterials.Where(up => up.CmtID == userid).ToList(); if (storedData.Count > 0) { if (!System.IO.Directory.Exists(Server.MapPath("\\Content\\Doc\\" + userid))) { System.IO.Directory.CreateDirectory(Server.MapPath("\\Content\\Doc\\" + userid)); for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } else { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } //data opration perperom here int len = storedData.Count; var smdat = dbcontext.StudyMaterials.FirstOrDefault(s => s.CmtID == userid); { smdat.CourseID = model.CourseID; smdat.SemID = model.SemID; smdat.SM_Description = model.SM_Description; smdat.SM_Name = model.SM_Name; smdat.Attachments = savedFileName; smdat.ModifiedDate = DateTime.Now; } var In = dbcontext.SaveChanges(); ; if (In > 0) { msg = "file uploaded Successfully"; } else { msg = "Error Occured"; } } else { if (!System.IO.Directory.Exists(Server.MapPath("\\Content\\Doc\\" + userid))) { System.IO.Directory.CreateDirectory(Server.MapPath("\\Content\\Doc\\" + userid)); for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } else { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } int len = storedData.Count; StudyMaterial studyupload = new StudyMaterial(); { studyupload.CmtID = userid; studyupload.CourseID = model.CourseID; studyupload.SemID = model.SemID; studyupload.SM_Description = model.SM_Description; studyupload.SM_Name = model.SM_Name; studyupload.Attachments = savedFileName; studyupload.CreatedDate = DateTime.Now; } dbcontext.StudyMaterials.Add(studyupload); Status = dbcontext.SaveChanges(); if (Status > 0) { msg = "file uploaded Successfully"; } else { msg = "Erro Occuerred"; } } return Json(new { responstext = msg }, JsonRequestBehavior.AllowGet); }
public async Task <ActionResult> Edit([Bind(Include = "id,UserID,NomeExibicao,FotoPerfil")] PerfilViewModel perfil, HttpPostedFileBase imgPerfil) { if (ModelState.IsValid) { if (imgPerfil != null) { try { // Envia a foto para o blob var imgUri = await servicoBlob.UploadFileAsync(imgPerfil, "fotoperfil"); perfil.FotoPerfil = imgUri.ToString(); } catch (Exception) { //Se houver excessão, atribui a foto que foi guardada na sessão perfil.FotoPerfil = Session["FotoPerfil"].ToString(); } } else { // Se for nula, atribui a foto que foi guardada na sessão perfil.FotoPerfil = Session["FotoPerfil"].ToString(); } var perfilModel = PerfilViewModel.ConvertToModel(perfil); if (Session["UserId"] == null) { Session["UserId"] = User.Identity.GetUserId(); } perfilModel.UserID = Session["UserId"].ToString(); servico.EditaPerfil(perfilModel); return(RedirectToAction("Index", "Gerenciador")); } return(View(perfil)); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { // Check model state if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // Make sure product name is unique using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Declare product id int id; // Init and save productDTO using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Calorie = model.Calorie; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); // Get the id id = product.Id; } // Set TempData message TempData["SM"] = "You have added a product!"; #region Upload Image // Create necessary directories var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } // Check if a file was uploaded if (file != null && file.ContentLength > 0) { // Get file extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Init image name string imageName = file.FileName; // Save image name to DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Set original and thumb image paths var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); // Save original file.SaveAs(path); // Create and save thumb WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion // Redirect return(RedirectToAction("AddProduct")); }
public JsonResult ExportAdd(EditViewModel model) { CustomJsonResult r = new CustomJsonResult(); r.ContentType = "text/html"; try { HttpPostedFileBase file_upload = Request.Files[0]; if (file_upload == null) { return(Json("text/html", ResultType.Failure, "找不到上传的对象")); } if (file_upload.ContentLength == 0) { return(Json("text/html", ResultType.Failure, "文件内容为空,请重新选择")); } System.IO.FileInfo file = new System.IO.FileInfo(file_upload.FileName); string ext = file.Extension.ToLower(); if (ext != ".xls") { return(Json("text/html", ResultType.Failure, "上传的文件不是excel格式(xls)")); } HSSFWorkbook workbook = new HSSFWorkbook(file_upload.InputStream); ISheet sheet = workbook.GetSheetAt(0); ExportCheckErrorPoint exportCheckErrorPoint = new ExportCheckErrorPoint(); IRow rowTitle = sheet.GetRow(0); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(0), "设备ID"); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(1), "机身号"); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(2), "终端号"); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(3), "版本号"); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(4), "押金"); exportCheckErrorPoint.CheckCellTitle(rowTitle.GetCell(5), "租金"); if (exportCheckErrorPoint.TitleHasError) { return(Json("text/html", ResultType.Failure, "上传的文件模板错误,请点击下载的文件模板")); } int rowCount = sheet.LastRowNum + 1; if (rowCount == 1) { return(Json("text/html", ResultType.Failure, "上传的文件数据为空,请检查后再次上传")); } List <PosMachine> posMachines = new List <PosMachine>(); for (int i = 1; i < rowCount; i++) { IRow row = sheet.GetRow(i); string deviceId = row.GetCell(0).ToString(); string fuselageNumber = row.GetCell(1) == null ? "" : row.GetCell(1).ToString(); string terminalNumber = row.GetCell(2) == null ? "" : row.GetCell(2).ToString(); string version = row.GetCell(3) == null ? "" : row.GetCell(3).ToString(); string deposit = row.GetCell(4) == null ? "" : row.GetCell(4).ToString(); string rent = row.GetCell(5) == null ? "" : row.GetCell(5).ToString(); if (string.IsNullOrEmpty(deviceId)) { return(Json("text/html", ResultType.Failure, "检查到有为空的设备ID,请完善后再次上传")); } if (string.IsNullOrEmpty(deviceId) || deviceId.Length > 100) { exportCheckErrorPoint.AddPoint(deviceId, "设备ID不能为空,且不能超过100个字符"); } if (string.IsNullOrEmpty(fuselageNumber) || fuselageNumber.Length > 100) { exportCheckErrorPoint.AddPoint(deviceId, "机身号不能为空,且不能超过100个字符"); } if (string.IsNullOrEmpty(terminalNumber) || terminalNumber.Length > 100) { exportCheckErrorPoint.AddPoint(deviceId, "终端号不能为空,且不能超过100个字符"); } if (string.IsNullOrEmpty(version) || version.Length > 100) { exportCheckErrorPoint.AddPoint(deviceId, "版本号不能为空,且不能超过100个字符"); } if (CommonUtils.IsDecimal(deposit)) { exportCheckErrorPoint.AddPoint(deviceId, "押金必须数字格式,且整数位最多16位,小数位最多2位"); } if (CommonUtils.IsDecimal(rent)) { exportCheckErrorPoint.AddPoint(deviceId, "租金必须数字格式,且整数位最多16位,小数位最多2位"); } PosMachine posMachine = new PosMachine(); posMachine.DeviceId = deviceId; posMachine.FuselageNumber = fuselageNumber; posMachine.TerminalNumber = terminalNumber; posMachine.Version = version; posMachines.Add(posMachine); } if (exportCheckErrorPoint.ErrorPoint.Count > 0) { return(Json("text/html", ResultType.Failure, exportCheckErrorPoint.ErrorPoint, "更新数据失败,检查到无效的数据")); } using (TransactionScope ts = new TransactionScope()) { foreach (var posMachine in posMachines) { var old = CurrentDb.PosMachine.Where(m => m.DeviceId == posMachine.DeviceId).FirstOrDefault(); if (old != null) { exportCheckErrorPoint.AddPoint(old.DeviceId, "设备ID号:" + posMachine.DeviceId + ",已经存在"); } } if (exportCheckErrorPoint.ErrorPoint.Count > 0) { return(Json("text/html", ResultType.Failure, exportCheckErrorPoint.ErrorPoint, "更新数据失败,检查到无效的数据")); } DateTime dateNow = DateTime.Now; foreach (var posMachine in posMachines) { posMachine.CreateTime = dateNow; posMachine.Creator = this.CurrentUserId; CurrentDb.PosMachine.Add(posMachine); } CurrentDb.SaveChanges(); ts.Complete(); } return(Json("text/html", ResultType.Success, "上传成功")); } catch (Exception ex) { Log.Error("导入POS机信息", ex); return(Json("text/html", ResultType.Exception, "上传失败,系统出现异常")); } }
public ActionResult DiemDanhHocSinh(int HocSinh, DateTime thoigian, string nguoiduadon, string trangthai, HttpPostedFileBase file) { List <DiemDanhHocSinh> d = db.DiemDanhHocSinhs.Where(x => x.Id_HocSinh == HocSinh && EntityFunctions.TruncateTime(x.ThoiGian) == EntityFunctions.TruncateTime(thoigian)).ToList(); if (d.Count() > 0) { foreach (var item in d) { if (item.DenVe == trangthai) { return(View()); } } } DiemDanhHocSinh diemdanh = new DiemDanhHocSinh(); diemdanh.Id_HocSinh = HocSinh; diemdanh.ThoiGian = thoigian; diemdanh.NguoiDuaDon = nguoiduadon; diemdanh.DenVe = trangthai; diemdanh.Id_NguoiDiemDanh = User.Identity.GetUserId(); db.DiemDanhHocSinhs.Add(diemdanh); db.SaveChanges(); string subPath = "~/Content/UserUpload/img/DiemDanhHocSinh/"; bool exists = System.IO.Directory.Exists(Server.MapPath(subPath)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(subPath)); } try { if (file.ContentLength > 0) { var path = Path.Combine(Server.MapPath(subPath), diemdanh.Id.ToString() + ".png"); file.SaveAs(path); } } catch (Exception ex) { return(RedirectToAction("DiemDanhHocSinh")); } return(View()); }
public ActionResult Create([Bind(Include = "PRO_N_CODIGO,PRO_N_REFERENCIA,PRO_C_NOME,PRO_C_DESCRICAO,PRO_C_MARCA,PRO_C_COR,PRO_C_VALOR,PRO_C_VALOR_VENDA,PRO_C_PORCENTAGEM,PRO_D_DATA_CADASTRO,PRO_D_DATA_VENDA,PRO_C_TAMANHO,PRO_N_SITUACAO,PRO_C_IMAGEM,PRO_B_ATIVO")] PRO_PRO_PRODUTO pRO_PRO_PRODUTO, HttpPostedFileBase image) { if(ModelState.IsValid) { db.PRO_PRO_PRODUTO.Add(pRO_PRO_PRODUTO); db.SaveChanges(); if(image != null) UploadFiles(image, pRO_PRO_PRODUTO.PRO_N_CODIGO); return RedirectToAction("Index"); } return View(pRO_PRO_PRODUTO); }
public ActionResult Create([Bind(Include = "Id,Title,Abstract,Slug,Body,MediaUrl,Published,Created,Updated")] BlogPost blogPost, HttpPostedFileBase image) { if (ModelState.IsValid) { var Slug = StringUtilities.URLFriendly(blogPost.Title); if (String.IsNullOrWhiteSpace(Slug)) { ModelState.AddModelError("Title", "Invalid title"); return(View(blogPost)); } if (db.BlogPosts.Any(p => p.Slug == Slug)) { ModelState.AddModelError("Title", "The title must be unique"); return(View(blogPost)); } if (ImageUploadValidator.IsWebFriendlyImage(image)) { var fileName = Path.GetFileName(image.FileName); image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), fileName)); blogPost.MediaURL = "/Uploads/" + fileName; } blogPost.Slug = Slug; blogPost.Created = DateTimeOffset.Now; db.BlogPosts.Add(blogPost); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(blogPost)); }
public ActionResult Edit([Bind(Include = "Id,Title,Abstract,Slug,Body,MediaUrl,Published,Created,Updated")] BlogPost blogPost, HttpPostedFileBase image) { if (ModelState.IsValid) { if (ImageUploadValidator.IsWebFriendlyImage(image)) { var fileName = Path.GetFileName(image.FileName); image.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), fileName)); blogPost.MediaURL = "/Uploads/" + fileName; } db.Entry(blogPost).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(blogPost)); }
public ActionResult AddVehicle_post(Online_Logistics_Registration.Models.VehicleModel vehicle, HttpPostedFileBase fileBase) { ViewBag.Vehicle = new SelectList(vehiclePath.GetVehicle(), "VehicleTypeID", "VehicleTypes"); if (fileBase != null && fileBase.ContentLength > 0) { var fileName = Path.GetFileName(fileBase.FileName); var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName); fileBase.SaveAs(path); } if (ModelState.IsValid) { ///VehicleModel vehicleModel = new VehicleModel(); vehicle.Image = new byte[fileBase.ContentLength]; fileBase.InputStream.Read(vehicle.Image, 0, fileBase.ContentLength); Vehicle vehicleObject = AutoMapper.Mapper.Map <Models.VehicleModel, Online_Logistics_Registration_Entity.Vehicle>(vehicle); ////vehicleEntity.VehicleID = vehicle.VehicleID; //vehicleEntity.VehicleNumber = vehicle.VehicleNumber; //vehicleEntity.VehicleTypeID = vehicle.VehicleTypeID; //vehicleEntity.StartLocation = vehicle.StartLocation; //vehicleEntity.DestinationLocation = vehicle.DestinationLocation; //vehicleEntity.VehicleLoadWeight = vehicle.VehicleLoadWeight; int result = vehiclePath.Add(vehicleObject); if (result == 1) { return(RedirectToAction("ViewVehicle")); } } return(View()); }
public ActionResult Create([Bind(Include = "Id,ProjeAdi,ProjeDili,ProjelerSol,ProjelerSag,Detay,Url,Resim")] Projeler projeler, HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var extension = Path.GetExtension(file.FileName); if (extension == ".jpg" || extension == ".png") { var filename = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/upload"), filename); projeler.Resim = filename; file.SaveAs(path); } else { ViewData["Uyarı"] = "Dosya türünüz .jpg ve .png olmalıdır."; } } else { ViewData["Uyarı"] = "Dosya Seçmediniz"; } if (ModelState.IsValid) { projeler.EklemeTarih = DateTime.Now; db.Projeler.Add(projeler); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(projeler)); }
public ActionResult EditDiemDanhHocSinh(int id, DateTime thoigian, string nguoiduadon, string trangthai, HttpPostedFileBase file) { DiemDanhHocSinh diemdanh = db.DiemDanhHocSinhs.Where(x => x.Id == id).FirstOrDefault(); diemdanh.ThoiGian = thoigian; diemdanh.NguoiDuaDon = nguoiduadon; diemdanh.DenVe = trangthai; db.SaveChanges(); string subPath = "~/Content/UserUpload/img/DiemDanhHocSinh/"; bool exists = System.IO.Directory.Exists(Server.MapPath(subPath)); if (!exists) { System.IO.Directory.CreateDirectory(Server.MapPath(subPath)); } try { if (file.ContentLength > 0) { var path = Path.Combine(Server.MapPath(subPath), diemdanh.Id.ToString() + ".png"); file.SaveAs(path); } } catch (Exception ex) { return(RedirectToAction("DiemDanhHocSinh")); } return(RedirectToAction("DiemDanhHocSinh")); }
public ActionResult Create([Bind(Include = "ArticleId,Headline,ArticleContent,IframeLink,Reads,CreateDate,ArticlePhoto,LanguageId")] Article article, HttpPostedFileBase Photo) { if (ModelState.IsValid) { if (Photo != null) { WebImage img = new WebImage(Photo.InputStream); FileInfo photoInfo = new FileInfo(Photo.FileName); string newPhoto = Guid.NewGuid().ToString() + photoInfo.Extension; img.Save("~/Uploads/BlogImage/" + newPhoto); article.ArticlePhoto = "/Uploads/BlogImage/" + newPhoto; } db.Articles.Add(article); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.LanguageId = new SelectList(db.LanguageTBs, "LanguageId", "CultureName", article.LanguageId); return(View(article)); }
public ActionResult Edit([Bind(Include = "PRO_N_CODIGO,PRO_N_REFERENCIA,PRO_C_NOME,PRO_C_DESCRICAO,PRO_C_MARCA,PRO_C_COR,PRO_C_VALOR,PRO_C_VALOR_VENDA,PRO_C_PORCENTAGEM,PRO_D_DATA_CADASTRO,PRO_D_DATA_VENDA,PRO_C_TAMANHO,PRO_N_SITUACAO,PRO_C_IMAGEM,PRO_B_ATIVO")] PRO_PRO_PRODUTO pRO_PRO_PRODUTO, HttpPostedFileBase image) { if (ModelState.IsValid) { db.Entry(pRO_PRO_PRODUTO).State = EntityState.Modified; db.Entry(pRO_PRO_PRODUTO).Property(x => x.PRO_C_IMAGEM).IsModified = false; db.SaveChanges(); if (image != null) { UploadFiles(image, pRO_PRO_PRODUTO.PRO_N_CODIGO); } return RedirectToAction("Index"); } return View(pRO_PRO_PRODUTO); }
public ActionResult ReportIssue([Bind(Include = "Name,Email,Subject,Message")] IssueReport issueMessage, HttpPostedFileBase upload) { return(View(issueMessage)); }
public JsonResult CargarCSV(HttpPostedFileBase archivoCSV, int lineaNegocio) { List <string> listaErrores = new List <string>(); var hoy = DateTime.Now; IEnumerable <string> lineas = null; object respuesta = null; int totalProcesados = 0; int lineaActual = 1; bool status = false; string exception = "Error, se presento un error inesperado."; try { List <string> csvData = new List <string>(); using (System.IO.StreamReader reader = new System.IO.StreamReader(archivoCSV.InputStream)) { while (!reader.EndOfStream) { csvData.Add(reader.ReadLine()); } } lineas = csvData.Skip(1); var datos = (from periodos in db.cargaDocumentoRoaming where periodos.idDocumento == "TAPIN" & periodos.ordenCarga == "A" & periodos.estatusCarga == "PC" group periodos by periodos.periodoCarga into g orderby g.Key ascending select new { Id = g.Key, Periodo = g.Key }).FirstOrDefault(); String Valor = ""; using (TransactionScope scope = new TransactionScope()) { foreach (string ln in lineas) { string linea = ln.Replace('%', ' '); //var lineaSplit = separarLineas(linea); //var lineaSplit = linea.Split(';'); var lineaSplit = linea.Split('|'); ++lineaActual; if (lineaSplit.Count() == 26) { RoamingDocumentoCosto entidad = new RoamingDocumentoCosto(); try { entidad.Anio = lineaSplit[0]; entidad.FechaContable = datos.Periodo.ToString(); //lineaSplit[1]; entidad.FechaConsumo = lineaSplit[2]; entidad.Compania = lineaSplit[3]; entidad.Servicio = lineaSplit[4]; entidad.Grupo = lineaSplit[5]; entidad.IdOperador = lineaSplit[6]; entidad.NombreOperador = lineaSplit[7]; entidad.Acreedor = lineaSplit[8]; entidad.Material = lineaSplit[9]; entidad.Trafico = lineaSplit[10]; entidad.Iva = lineaSplit[11]; entidad.PorcentajeIva = lineaSplit[12]; entidad.Moneda = lineaSplit[13]; entidad.Minutos = lineaSplit[14]; entidad.Tarifa = lineaSplit[15]; entidad.Monto = lineaSplit[16]; entidad.MontoFacturado = lineaSplit[17]; entidad.FechaFactura = lineaSplit[18]; entidad.FolioDocumento = lineaSplit[19]; entidad.TipoCambio = lineaSplit[20]; entidad.MontoMxn = lineaSplit[21]; entidad.CuentaContable = lineaSplit[22]; entidad.ClaseDocumento = lineaSplit[23]; entidad.ClaseDocumentoSap = lineaSplit[24]; Valor = lineaSplit[25]; entidad.NumeroDocumentoSap = Valor.Replace(",", ""); entidad.Activo = "1"; entidad.LineaNegocio = "1"; entidad.FechaCarga = DateTime.Now; totalProcesados++; db.RoamingDocumentoCosto.Add(entidad); } catch (FormatException e) { if (e.Message == "String was not recognized as a valid DateTime.") { listaErrores.Add("Línea " + lineaActual + ": Campo de Fecha con formato erróneo."); } else { listaErrores.Add("Línea " + lineaActual + ": Campo con formato erróneo."); } } catch (Exception) { listaErrores.Add("Línea " + lineaActual + ": Error desconocido. "); } } else { listaErrores.Add("Línea " + lineaActual + ": Número de campos insuficiente."); } } db.SaveChanges(); scope.Complete(); exception = "Datos cargados con éxito"; status = true; } } catch (FileNotFoundException) { exception = "El archivo Selecionado aún no existe en el Repositorio."; status = false; } catch (UnauthorizedAccessException) { exception = "No tiene permiso para acceder al archivo actual."; status = false; } catch (IOException e) when((e.HResult & 0x0000FFFF) == 32) { exception = "Falta el nombre del archivo, o el archivo o directorio está en uso."; status = false; } catch (TransactionAbortedException) { exception = "Transacción abortada. Se presentó un error."; status = false; } catch (Exception err) { exception = "Error desconocido. " + err.InnerException.ToString(); status = false; } finally { respuesta = new { success = true, results = listaErrores, mensaje = exception, totalProcesados = totalProcesados, status = status }; } return(Json(respuesta, JsonRequestBehavior.AllowGet)); }
public ActionResult _Files3(Files3 s, HttpPostedFileBase ImagePhoto, HttpPostedFileBase ImageAadhar, HttpPostedFileBase ImageHSC, HttpPostedFileBase ImageSSC, HttpPostedFileBase ImageDegree, HttpPostedFileBase ImageNativity, HttpPostedFileBase ImageIncome, HttpPostedFileBase ImageCommunity) { s.Applicant_Id = Convert.ToInt32(Session["Applicant Id"]); try{ string myfilename1 = Path.GetFileNameWithoutExtension(ImagePhoto.FileName); string extension1 = Path.GetExtension(ImagePhoto.FileName); myfilename1 = myfilename1 + extension1; s.Photo = "~/Images/Photo/" + myfilename1; myfilename1 = Path.Combine(Server.MapPath("~/Images/Photo/"), myfilename1); ImagePhoto.SaveAs(myfilename1); db.Files3.Add(s); string myfilename2 = Path.GetFileNameWithoutExtension(ImageAadhar.FileName); string extension2 = Path.GetExtension(ImageAadhar.FileName); myfilename2 = myfilename2 + extension2; s.Aadhar_Card = "~/Images/Aadhar/" + myfilename2; myfilename2 = Path.Combine(Server.MapPath("~/Images/Aadhar/"), myfilename2); ImageAadhar.SaveAs(myfilename2); db.Files3.Add(s); string myfilename3 = Path.GetFileNameWithoutExtension(ImageHSC.FileName); string extension3 = Path.GetExtension(ImageHSC.FileName); myfilename3 = myfilename3 + extension3; s.HSC_Marksheet = "~/Images/HSC/" + myfilename3; myfilename3 = Path.Combine(Server.MapPath("~/Images/HSC/"), myfilename3); ImageHSC.SaveAs(myfilename3); db.Files3.Add(s); string myfilename4 = Path.GetFileNameWithoutExtension(ImageSSC.FileName); string extension4 = Path.GetExtension(ImageSSC.FileName); myfilename4 = myfilename4 + extension4; s.SSC_MarkSheet = "~/Images/SSC/" + myfilename4; myfilename4 = Path.Combine(Server.MapPath("~/Images/SSC/"), myfilename4); ImageSSC.SaveAs(myfilename4); db.Files3.Add(s); string myfilename5 = Path.GetFileNameWithoutExtension(ImageDegree.FileName); string extension5 = Path.GetExtension(ImageDegree.FileName); myfilename5 = myfilename5 + extension5; s.Degree_Marksheet = "~/Images/Degree/" + myfilename5; myfilename5 = Path.Combine(Server.MapPath("~/Images/Degree/"), myfilename5); ImageDegree.SaveAs(myfilename5); db.Files3.Add(s); string myfilename6 = Path.GetFileNameWithoutExtension(ImageNativity.FileName); string extension6 = Path.GetExtension(ImageNativity.FileName); myfilename6 = myfilename6 + extension6; s.Nativity_Certificate = "~/Images/Nativity/" + myfilename6; myfilename6 = Path.Combine(Server.MapPath("~/Images/Nativity/"), myfilename6); ImageNativity.SaveAs(myfilename6); db.Files3.Add(s); string myfilename7 = Path.GetFileNameWithoutExtension(ImageIncome.FileName); string extension7 = Path.GetExtension(ImageIncome.FileName); myfilename7 = myfilename7 + extension7; s.Income_Certificate = "~/Images/Income/" + myfilename7; myfilename7 = Path.Combine(Server.MapPath("~/Images/Income/"), myfilename7); ImageIncome.SaveAs(myfilename7); db.Files3.Add(s); string myfilename8 = Path.GetFileNameWithoutExtension(ImageCommunity.FileName); string extension8 = Path.GetExtension(ImageCommunity.FileName); myfilename8 = myfilename8 + extension8; s.Community_Certificate = "~/Images/Community/" + myfilename8; myfilename8 = Path.Combine(Server.MapPath("~/Images/Community/"), myfilename8); ImageCommunity.SaveAs(myfilename8); db.Files3.Add(s); db.SaveChanges(); int AppId = Convert.ToInt32(Session["Applicant Id"]); var obj = (from n in db.RegScheme_details where n.Applicant_ID == AppId select n).SingleOrDefault(); obj.App_status = "Application Received"; obj.Payment_Status = "Pending"; obj.Funded_amt = 0; db.Regschstud(s.Applicant_Id, obj.App_status, obj.Payment_Status, obj.Funded_amt); db.SaveChanges(); } catch (Exception e) { ModelState.AddModelError("", "Something went wrong Check the credentials you entered or try again later......"); return(PartialView()); } return(RedirectToAction("_Files3d")); }
public ActionResult AddDataset(HttpPostedFileBase file, string DatasetName, string DatasetColumnsInfo, int DatasetHzFrequency) { if (ModelState.IsValid) //Model-binding validation - odwołuje się do adnotacji w Modelach { { //poprawność DatasetColumnsInfo string[] lines = DatasetColumnsInfo.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); DatasetColumnsInfo = ""; foreach (string line in lines) { string[] name_numbers = line.Split(new char[] { ':' }); if (name_numbers.Length != 2 || name_numbers[0].Length == 0) { ViewBag.dataseterror = "Przykładowa prawidłowa postać: ECG:1,2,3 EMG:4,5 AAA:6"; return(View()); } string[] potentialdigits = name_numbers[1].Split(new char[] { ',' }); foreach (var potentialdigit in potentialdigits) { if (potentialdigit.Length == 0) { ViewBag.dataseterror = "Przykładowa prawidłowa postać: ECG:1,2,3 EMG:4,5 AAA:6"; return(View()); } int number; bool success = Int32.TryParse(potentialdigit, out number); if (!success) { ViewBag.dataseterror = "Przykładowa prawidłowa postać: ECG:1,2,3 EMG:4,5 AAA:6"; return(View()); } } DatasetColumnsInfo += line + " "; } DatasetColumnsInfo = DatasetColumnsInfo.Substring(0, DatasetColumnsInfo.Length - 1); } if (file != null && file.ContentLength > 0) { string extension = Path.GetExtension(file.FileName); if (extension == ".csv") { ViewBag.Message = "Wybrano odpowiedni plik"; //string path = Path.Combine(Server.MapPath("~"), Path.GetFileName(file.FileName)); string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path.GetDirectoryName (AppDomain.CurrentDomain.BaseDirectory)), @"Dane\\" + DatasetName + Session["Nickname"].ToString() + ".csv"); file.SaveAs(path); Dataset NewDataSet = new Dataset(); NewDataSet.DatasetName = DatasetName; NewDataSet.DatasetColumnsInfo = DatasetColumnsInfo; NewDataSet.DatasetHzFrequency = DatasetHzFrequency; NewDataSet.ConcreteUser = db.Users.Find(Convert.ToInt32(Session["UserId"])); NewDataSet.Reference = path.ToString(); NewDataSet.DateAdded = DateTime.Now; db.Datasets.Add(NewDataSet); db.SaveChanges(); return(RedirectToAction("Index", "User")); } else { ViewBag.Message = "Należy wybrać plik '.csv'"; } } else { ViewBag.Message = "Nie wybrano konkretnego pliku."; } return(View()); } return(View()); }
public ActionResult UploadPalette(int?palettenId) { try { if (ModelState.IsValid) { int userId = ((CustomPrincipal)(User)).UserId; if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { HttpPostedFileBase file = Request.Files[0]; string fileName = file.FileName; if (fileName.EndsWith(".csv")) { // gibt es den Lieferanten überhaupt? string lieferantenNummer = fileName.Remove(fileName.Length - 4); Lieferant lieferant = null; using (ApplicationDbContext context = new ApplicationDbContext()) { lieferant = context.GetLieferantByLieferantennummer(int.Parse(lieferantenNummer)); if (lieferant == null) { return(new HttpNotFoundResult("Lieferant mit Nummer " + lieferantenNummer + " nicht gefunden. Hochladen der Artikeldatei nicht möglich.")); } } Stream stream = file.InputStream; using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(1252))) { int lineCount = 0; string line = string.Empty; while ((line = reader.ReadLine()) != null) { //trenne bei ; wenn nicht innerhalb von Hochkommata string pattern = ";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"; string[] lineArr = Regex.Split(line, pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); // Spaltenanzahl zu gering if (lineArr.Length < 2) { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Die Datei muss mindestens 2 Spalten enthalten. Dies ist" + "nicht der Fall für Zeile " + lineCount + ".")); } // Header verarbeiten if (lineCount == 0) { ArtikelFile artikelFile = new ArtikelFile() { ArtikelFileName = file.FileName, ArtikelnummerColumnNameFromCSVImport = lineArr[0], ArtikelnameColumnNameFromCSVImport = lineArr[1], PaletteUpdatedAt = DateTime.Now }; using (ApplicationDbContext context = new ApplicationDbContext()) { palettenId = context.UpdatePalette(lieferant.LieferantId, palettenId.HasValue ? palettenId.Value : -1, artikelFile); if (palettenId < 0) { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError, "Fehler beim Schreiben in die DB. Bitte prüfen Sie die Log-Datei")); } } } // Artikel verarbeiten else { Artikel artikel = new Artikel() { //TODO remove leading and trailing "" PaletteId = palettenId.Value, Artikelnummer = lineArr[0], Artikelname = lineArr[1] }; using (ApplicationDbContext context = new ApplicationDbContext()) { context.UpdateArtikel(artikel); } } lineCount++; } } } else { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Das Dateiformat wird nicht unterstützt.")); } } else { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Bitte wählen Sie eine Datei aus.")); } } } catch (Exception e) { Log.Error(e.Message); return(new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError, "Bei der Verarbeitung der Import-Datei ist ein Fehler aufgetreten.")); } return(new HttpStatusCodeResult(System.Net.HttpStatusCode.OK)); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // Get product id int id = model.Id; // Populate categories select list and gallery images using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name is unique using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Update product using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Calorie = model.Calorie; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } // Set TempData message TempData["SM"] = "You have edited the product!"; #region Image Upload // Check for file upload if (file != null && file.ContentLength > 0) { // Get extension string ext = file.ContentType.ToLower(); // Verify extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Set uplpad directory paths var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Delete files from directories DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (FileInfo file2 in di1.GetFiles()) { file2.Delete(); } foreach (FileInfo file3 in di2.GetFiles()) { file3.Delete(); } // Save image name string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Save original and thumb images var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion // Redirect return(RedirectToAction("EditProduct")); }
public ActionResult UploadLieferantenFile() { try { if (ModelState.IsValid) { int userId = ((CustomPrincipal)(User)).UserId; if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { HttpPostedFileBase file = Request.Files[0]; if (file.FileName.EndsWith(".csv")) { Stream stream = file.InputStream; bool success = false; using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding(1252))) { int lineCount = 0; string line = string.Empty; while ((line = reader.ReadLine()) != null) { //trenne bei ; wenn nicht innerhalb von Hochkommata string pattern = ";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"; string[] lineArr = Regex.Split(line, pattern, RegexOptions.None, TimeSpan.FromSeconds(1)); // Spaltenanzahl zu gering if (lineArr.Length < 5) { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Die Datei muss mindestens 5 Spalten enthalten. Dies ist" + "nicht der Fall für Zeile " + lineCount + ".")); } // Header verarbeiten if (lineCount == 0) { LieferantenFile lieferantenFile = new LieferantenFile() { LieferantenFileName = file.FileName, LieferantenNummerColumnNameFromCSVImport = lineArr[0], LieferantenNameColumnNameFromCSVImport = lineArr[1], LieferantenStraßeColumnNameFromCSVImport = lineArr[2], LieferantenPLZColumnNameFromCSVImport = lineArr[3], LieferantenOrtColumnNameFromCSVImport = lineArr[4], LieferantenUpdatedAt = DateTime.Now }; using (ApplicationDbContext context = new ApplicationDbContext()) { success = context.UpdateLieferantenDateiForUser(userId, lieferantenFile); if (!success) { Log.Error("UpdateLieferantenDateiForUser nicht erfolgreich für Nutzer " + userId); return(new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError, "Fehler beim Schreiben in die DB. Bitte prüfen Sie die Log-Datei")); } } } // Lieferanten verarbeiten else { Lieferant lieferant = new Lieferant() { //TODO remove leading and trailing "" UserId = userId, Lieferantennummer = int.Parse(lineArr[0]), Lieferantenname = lineArr[1], Straße = lineArr[2], PLZ = int.Parse(lineArr[3]), Ort = lineArr[4], }; using (ApplicationDbContext context = new ApplicationDbContext()) { context.UpdateLieferant(lieferant); } } lineCount++; } } } else { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Das Dateiformat wird nicht unterstützt.")); } } else { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Bitte wählen Sie eine Datei aus.")); } } } catch (Exception e) { Log.Error(e.Message); return(new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError, "Bei der Verarbeitung der Import-Datei ist ein Fehler aufgetreten.")); } return(new HttpStatusCodeResult(System.Net.HttpStatusCode.OK)); }
public async Task <ActionResult> Create([Bind(Include = "LearnerID,UserID,Names,Email,Province,City,Surbub,Street,ZipCode,Phone,IDNum,Location,BookingDate,Photo,Picture,Code")] Licence licence, HttpPostedFileBase upload) { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { string _FileName = Path.GetFileName(upload.FileName); string _path = Path.Combine(Server.MapPath("~/Images"), _FileName); upload.SaveAs(_path); licence.Picture = _FileName; //SmtpClient client = new SmtpClient("smtp.gmail.com"); ////If you need to authenticate //client.Credentials = new NetworkCredential("*****@*****.**", "@Dut123456"); //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; //MailMessage mm = new MailMessage("*****@*****.**", licence.Email); //mm.Subject = "Hello Welcome to Lindani Driving School, Your Driving licences was booked successfully"; //mm.Body = "Please save this email safe"; //mm.IsBodyHtml = false; //mailMessage.From = new MailAddress("*****@*****.**", "It's Me"); ////mailMessage.To.Add("*****@*****.**"); ////mailMessage.Subject = "Hello Welcome to Lindani Driving School, Your Driving licences was booked successfully"; ////mailMessage.Body = "Please save this email safe"; /// //SmtpClient smtp = new SmtpClient(); //smtp.Host = "smtp.gmail.com"; //smtp.Port = 587; //smtp.EnableSsl = true; //NetworkCredential nc = new NetworkCredential("*****@*****.**", "@Dut123456"); //smtp.UseDefaultCredentials = false; //smtp.Credentials = nc; // smtp.Send(mm); db.Licences.Add(licence); await db.SaveChangesAsync(); return(RedirectToAction("Index")); } /// licence.LearnerID = Session[""] return(View(licence)); } // ViewBag.PackageID = new SelectList(db.BookingPackages, "PackageID", "Name", licence.PackageID); // ViewBag.UserID = new SelectList(db.Users, "UserID", "FirstName", licence.UserID); return(View(licence)); }
public ActionResult CreateAttachment( [Bind(Include = "Id,Description,TicketId")] TicketAttachment ticketattachment, HttpPostedFileBase attachFile) //Bind Attribute tells it to add these properties when it sends to view { var user = db.Users.Find(User.Identity.GetUserId()); if (attachFile != null) { var ext = Path.GetExtension(attachFile.FileName).ToLower(); if (ext != ".png" && ext != ".jpg" && ext != ".jpeg" && ext != ".gif" && ext != ".bmp" && ext != ".pdf") { ModelState.AddModelError("attachFile", "Invalid Format."); } } if (ModelState.IsValid) //makes sure all the properties are bound { if (attachFile != null) { ticketattachment.Created = DateTimeOffset.Now; ticketattachment.AuthorId = user.Id; var filePath = "/Assets/UserUploads/"; var absPath = Server.MapPath("~" + filePath); ticketattachment.FileUrl = filePath + attachFile.FileName; attachFile.SaveAs(Path.Combine(absPath, attachFile.FileName)); db.TicketAttachments.Add(ticketattachment); } db.SaveChanges(); } var ticket = db.Tickets.Find(ticketattachment.TicketId); if (ticket.AssignToUserId != null) { return(RedirectToAction("AttachNotify", "Tickets", new { id = ticketattachment.Id })); } else { return(RedirectToAction("Details", "Tickets", new { id = ticketattachment.TicketId })); } }
public ActionResult FileUpload(StudyMaterial model) { string msg = ""; int Status = 0; string fileName = ""; string filesnames = ""; var Stringimages = new List<string>(); string savedFileName = ""; DateTime d1 = DateTime.Now; string userID = User.Identity.Name; var userid = (from a in dbcontext.CommitteeMembers_Profile where a.EmailID == userID select a.CmtID).FirstOrDefault(); if (model.SemID != 0 && model.CourseID != 0) { var sdmin = dbcontext.StudyMaterials.Where(s => s.SemID == model.SemID && s.CourseID == model.CourseID && s.CmtID == userid && s.CmtID == userid).FirstOrDefault(); if (sdmin == null) { //Insert New Files in table if (!System.IO.Directory.Exists(Server.MapPath("\\Content\\Doc\\" + userid))) { System.IO.Directory.CreateDirectory(Server.MapPath("\\Content\\Doc\\" + userid)); for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.Date.ToString("dd/MM/yyyy") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } else { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.Date.ToString("dd/MM/yyyy") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } //int len = storedData.Count; StudyMaterial studyupload = new StudyMaterial(); { studyupload.CmtID = userid; studyupload.CourseID = model.CourseID; studyupload.SemID = model.SemID; studyupload.SM_Description = model.SM_Description; studyupload.SM_Name = model.SM_Name; studyupload.Attachments = savedFileName; studyupload.UploadBy = userID; studyupload.CreatedDate = DateTime.Now; } dbcontext.StudyMaterials.Add(studyupload); Status = dbcontext.SaveChanges(); if (Status > 0) { msg = "1"; } else { msg = "0"; } } else { //Update Exisitng tabale data if (!System.IO.Directory.Exists(Server.MapPath("\\Content\\Doc\\" + userid))) { System.IO.Directory.CreateDirectory(Server.MapPath("\\Content\\Doc\\" + userid)); for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.Date.ToString("dd/MM/yyyy") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } else { // sdmin for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; //Uploaded file //Use the following properties to get file's name, size and MIMEType int fileSize = file.ContentLength; fileName = file.FileName; string mimeType = file.ContentType; System.IO.Stream fileContent = file.InputStream; savedFileName = DateTime.Now.Date.ToString("dd/MM/yyyy") + Path.GetFileName(fileName); file.SaveAs(Path.Combine(Server.MapPath("~/Content/Doc/" + userid), savedFileName)); // Save the file // errormsg.Text += String.Format("{0}<br />", file); Stringimages.Add(savedFileName); } filesnames = string.Join("|||", Stringimages.ToArray()); } //data opration perperom here //int len = storedData.Count; var smdat = dbcontext.StudyMaterials.FirstOrDefault(s => s.CmtID == userid && s.SemID == model.SemID && s.CourseID == model.CourseID && s.CmtID == userid); { smdat.CourseID = model.CourseID; smdat.SemID = model.SemID; smdat.SM_Description = model.SM_Description; smdat.SM_Name = model.SM_Name; smdat.Attachments = savedFileName; smdat.UploadBy = userID; smdat.ModifiedDate = DateTime.Now; } var In = dbcontext.SaveChanges(); ; if (In > 0) { msg = "1"; } else { msg = "0"; } // msg = "1"; } } else { msg = "0"; } Bindcourse(); BindSemester(); ViewBag.uploadedfilesdisplay = (from a in dbcontext.StudyMaterials.Where(x => x.SMID != 0) select a).ToList(); return RedirectToAction("FileUpload", "CommitteMember", new { msg }); }
public ActionResult Create([Bind(Include = "Id,Tittle,Slogan,More_url,More_text")] Slider slider, HttpPostedFileBase Slogan) { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Slogan.FileName; string path = Path.Combine(Server.MapPath("~/Upload"), filename); Slogan.SaveAs(path); slider.Slogan = filename; if (ModelState.IsValid) { db.Sliders.Add(slider); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(slider)); }
/// <summary> /// 上传图片 /// </summary> /// <returns></returns> public ActionResult UploadImage(HttpPostedFileBase upload, string typeName, string CKEditorFuncNum, string CKEditor, string langCode) { string result = ""; var file = upload; if (file != null && file.ContentLength > 0) { string fileNameEx = Path.GetExtension(file.FileName); if (string.IsNullOrEmpty(fileNameEx)) { return Content(@"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"\", \"获取图片扩展名失败!\");</script></body></html>"); } typeName = string.IsNullOrEmpty(typeName) ? "images" : typeName; string fileName = Guid.NewGuid().ToString(); string rootPath = this.Server.MapPath("~/Upload_V5/" + typeName + "/"); string savePath = string.Empty; string path = Utils.CreateDirectory(rootPath, out savePath); savePath += fileName + Path.GetExtension(file.FileName); savePath = "/Upload_V5/" + typeName + "/" + savePath; //保存图片 file.SaveAs(path + fileName + fileNameEx); result = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + savePath + "\", \"上传成功!\");</script></body></html>"; } return Content(result); }
public ActionResult SaveModelData(tblCommissioning model, HttpPostedFileBase fileUnit, string create = null) { if (!ModelState.IsValid) { return(View("Create", model)); } string message = string.Empty; try { if (fileUnit != null) { string fileExtension = Path.GetExtension(fileUnit.FileName); string FileName = Guid.NewGuid().ToString() + fileExtension; string physicalPath = Path.Combine(Server.MapPath("~/Uploads"), FileName); fileUnit.SaveAs(physicalPath); model.CommissioningFileName = FileName; } if (model.CommissioningId > 0) { model.ModifiedBy = SessionHelper.UserId; model.ModifiedDate = DateTime.Now; message = _dbRepository.Update(model); if (model.IsWarrantyPeriodChange) { tblWarrantyexpires warrantyObj = _dbRepositoryWarranty.GetEntities().Where(m => m.CommissioningId == model.CommissioningId).FirstOrDefault(); if (warrantyObj != null) { warrantyObj.WarrantyExpireDate = model.WarrantyExpireDate; _dbRepositoryWarranty.Update(warrantyObj); } } } else { model.CreatedBy = SessionHelper.UserId; model.CreatedDate = DateTime.Now; message = _dbRepository.Insert(model); } } catch (Exception ex) { message = CommonHelper.GetErrorMessage(ex); } if (model.CommissioningId > 0) { if (create == "Save & Continue") { return(RedirectToAction("Edit", new { id = model.CommissioningId })); } else if (create == "Save & New") { return(RedirectToAction("Create")); } } return(RedirectToAction("Index")); }
public ActionResult Upload(HttpPostedFileBase file) { // check if a file uploads if( file != null && file.ContentLength > 0) { // generate a new file id string n = Guid.NewGuid().ToString("D"); //generate filepath var filePath = Server.MapPath("~/App_Data/uploads/" + n); //here all image file extensions are stored with ',' seperator in app-key-value web.config file //ConfigManager.Image class extracts value from web.config file and stores in an array var imageFormats = ConfigManager.Image.CompressImageFormats; //check for image types if (imageFormats.Contains(Path.GetExtension(file.FileName))) { //convert HttpPostedFileBase file to image var image = Image.FromStream(file.InputStream, true, true); //resize image var bitmap = ResizeImage(image); //optional step - save all images as jpg for uniformity ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders() .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First(); //set the quality of output image here range [0..100] var quality = 10; using (EncoderParameters encParams = new EncoderParameters(1)) { encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality); //save bitmap bitmap.Save(filePath, jpgInfo, encParams); // return the details of the file return Json(new { id = n, name = file.FileName.Split('.').FirstOrDefault()+"."+"jpg", type = "jpg" }); } } //if here input file is not image // save the file file.SaveAs(filePath); // return the details of the file return Json(new { id = n, name = file.FileName, type = file.FileName.Split('.').Reverse().FirstOrDefault() }); } // if here, return nothing return Json(new { name = "", id = "", type = "" }); }
public ActionResult uploadFile(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { var _contenido = new byte[file.ContentLength]; file.InputStream.Read(_contenido, 0, file.ContentLength); int indiceDelUltimoPunto = file.FileName.LastIndexOf('.'); string _nombre = file.FileName.Substring(0, indiceDelUltimoPunto); string _extension = file.FileName.Substring(indiceDelUltimoPunto + 1, file.FileName.Length - indiceDelUltimoPunto - 1); ArchivoDto _ArchivoDto = new ArchivoDto() { Nombre = _nombre, Extension = _extension, Descargas = 0, DenunciaId = (int)Session["DenunciaActual"] }; var carpetaActual = (string)Session["CarpetaActual"]; _ArchivoDto.PathRelativo(carpetaActual); _ArchivoDto.SubirArchivo(_contenido); using (_dbContext = new NuevoDbContext()) { try { var usuario = System.Web.HttpContext.Current.User.Identity.Name; _ArchivoDto.usuarioCreador = usuario; var archivoNuevo = _ArchivoDto; _dbContext.Archivos.Add(_ArchivoDto); _dbContext.SaveChanges(); var logger = new CommonChangeLoggerDto(DateTime.Now, "DENUNCIA", "Archivo Creado", archivoNuevo.Nombre + '.' + archivoNuevo.Extension, archivoNuevo.path, usuario, (int)Session["DenunciaActual"]); _dbContext.Add(logger); _dbContext.SaveChanges(); } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); var fullErrorMessage = string.Join("; ", errorMessages); var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); } } } var id = (int)Session["DenunciaActual"]; using (_dbContext = new NuevoDbContext()) { var Archivos = _dbContext.Archivos.Where(x => x.DenunciaId == id).OrderByDescending(x => x.fechaCreacion).ToList(); return(PartialView("FileList", Archivos)); } // Redirigimos a la Acción 'Index' para mostrar // Los Archivos subidos al Servidor. }
public ActionResult Edit(Producto reg, HttpPostedFileBase f) { if (f == null) { ViewBag.mensaje = "Selecciona Foto"; return(View(reg)); } if (Path.GetExtension(f.FileName) != ".jpg") { ViewBag.mensaje = "debe ser extension jpg"; return(View(reg)); } List <SqlParameter> lista = new List <SqlParameter>() { //variables del procedimiento almacenado new SqlParameter() { ParameterName = "@id", SqlDbType = SqlDbType.Int, Value = reg.codigo, }, new SqlParameter() { ParameterName = "@nom", SqlDbType = SqlDbType.VarChar, Value = reg.nombre, }, new SqlParameter() { ParameterName = "@pre", SqlDbType = SqlDbType.Decimal, Value = reg.precio, }, new SqlParameter() { ParameterName = "@des", SqlDbType = SqlDbType.VarChar, Value = reg.descripcion, }, new SqlParameter() { ParameterName = "@fot", SqlDbType = SqlDbType.VarChar, Value = "~/imagenes/" + Path.GetFileName(f.FileName), }, new SqlParameter() { ParameterName = "@cat", SqlDbType = SqlDbType.VarChar, Value = reg.idcategoria } }; f.SaveAs(Path.Combine(Server.MapPath("~/imagenes/"), Path.GetFileName(f.FileName))); //ejecutar ViewBag.mensaje = CRUD("sp_actualizar_producto", lista); ViewBag.categoria = new SelectList(ListadoCategorias(), "codigo", "nombre", reg.idcategoria); return(View(reg)); }
//public ActionResult Upload(HttpPostedFileBase uploadFile) //{ // var strValidations = new StringBuilder(string.Empty); // try // { // if (uploadFile.ContentLength > 0) // { // string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), // Path.GetFileName(uploadFile.FileName)); // uploadFile.SaveAs(filePath); // var ds = new DataSet(); // //A 32-bit provider which enables the use of // string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + // ";Extended Properties=Excel 12.0;"; // var maNhaThuoc = this.GetNhaThuoc().MaNhaThuoc; // using (var conn = new OleDbConnection(connectionString)) // { // conn.Open(); // using (var dtExcelSchema = conn.GetSchema("Tables")) // { // string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString(); // string query = "SELECT * FROM [" + sheetName + "]"; // var adapter = new OleDbDataAdapter(query, conn); // //DataSet ds = new DataSet(); // adapter.Fill(ds, "Items"); // if (ds.Tables.Count > 0) // { // if (ds.Tables[0].Rows.Count > 0) // { // for (int i = 0; i < ds.Tables[0].Rows.Count; i++) // { // var row = ds.Tables[0].Rows[i]; // var tenbacsy = row[0].ToString().Trim(); // var sodienthoai = row[2].ToString().Trim(); // if (!String.IsNullOrWhiteSpace(tenbacsy)) // { // var bacsy = new BacSy(); // if (!String.IsNullOrWhiteSpace(sodienthoai)) // { // bacsy = unitOfWork.BacSyRespository.GetMany(x => x.NhaThuoc.MaNhaThuoc == maNhaThuoc && x.TenBacSy == tenbacsy && x.DienThoai == sodienthoai).FirstOrDefault(); // } // else // { // bacsy =unitOfWork.BacSyRespository.GetMany(x => x.NhaThuoc.MaNhaThuoc == maNhaThuoc && x.TenBacSy == tenbacsy).FirstOrDefault(); // } // //Check if thuoc already exist // if (bacsy != null) // { // Bindbacsy(ref bacsy, row); // } // else // { // bacsy = new BacSy() // { // MaBacSy = 0, // NhaThuoc = unitOfWork.NhaThuocRepository.GetById(maNhaThuoc), // Created = DateTime.Now, // CreatedBy = unitOfWork.UserProfileRepository.GetById(WebSecurity.GetCurrentUserId) // }; // unitOfWork.BacSyRespository.Insert(Bindbacsy(ref bacsy, row)) ; // } // } // } // unitOfWork.Save(); // } // } // } // } // } // } // catch (Exception ex) // { // ViewBag.Message = ex.Message; // return View("Error"); // } // return RedirectToAction("Index"); //} // [Audit] public ActionResult Upload(HttpPostedFileBase uploadFile) { var strValidations = new StringBuilder(string.Empty); try { if (uploadFile.ContentLength > 0) { string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(uploadFile.FileName)); uploadFile.SaveAs(filePath); int totalupdated = 0; int totaladded = 0; int totalError = 0; string message = "<b>Thông tin bác sỹ ở dòng số {0} bị lỗi:</b><br/> {1}"; UploadObjectInfo info = new UploadObjectInfo(); var maNhaThuoc = this.GetNhaThuoc().MaNhaThuoc; foreach (var worksheet in Workbook.Worksheets(filePath)) { for (int i = 1; i < worksheet.Rows.Count(); i++) { var row = worksheet.Rows[i]; var msg = ValidateDataImport(row); if (!string.IsNullOrEmpty(msg)) { if (msg == Constants.Params.msgOk) { var tenbacsy = row.Cells[0].Text.Trim(); var sodienthoai = row.Cells[2] != null ? row.Cells[2].Text.Trim() : string.Empty; if (!String.IsNullOrWhiteSpace(tenbacsy)) { var bacsy = new BacSy(); if (!String.IsNullOrWhiteSpace(sodienthoai)) { bacsy = unitOfWork.BacSyRespository.GetMany(x => x.NhaThuoc.MaNhaThuoc == maNhaThuoc && x.TenBacSy == tenbacsy && x.DienThoai == sodienthoai).FirstOrDefault(); } else { bacsy = unitOfWork.BacSyRespository.GetMany(x => x.NhaThuoc.MaNhaThuoc == maNhaThuoc && x.TenBacSy == tenbacsy).FirstOrDefault(); } //Check if thuoc already exist if (bacsy != null) { Bindbacsy(ref bacsy, row); totalupdated++; } else { bacsy = new BacSy() { MaBacSy = 0, NhaThuoc = unitOfWork.NhaThuocRepository.GetById(maNhaThuoc), Created = DateTime.Now, CreatedBy = unitOfWork.UserProfileRepository.GetById(WebSecurity.GetCurrentUserId) }; unitOfWork.BacSyRespository.Insert(Bindbacsy(ref bacsy, row)); totaladded++; } } } else { info.ErrorMsg.Add(string.Format(message, i, msg)); totalError++; } } } unitOfWork.Save(); info.Title = "Thông tin upload bác sỹ"; info.TotalUpdated = totalupdated; info.TotalAdded = totaladded; info.TotalError = totalError; Session["UploadMessage"] = info; return(RedirectToAction("index", "Upload")); } } } catch (Exception ex) { ViewBag.Message = ""; ViewBag.FullMessage = ex.Message; return(View("Error")); } return(RedirectToAction("Index")); }
public ActionResult Edit(/*[Bind(Include = "Id,Tittle,Slogan,More_url,More_text")]*/ Slider slider, HttpPostedFileBase Slogan) { db.Entry(slider).State = System.Data.Entity.EntityState.Modified; //db.Abouts.Attach(about); //db.Entry(about).Property(m => m.Photo).IsModified = true; if (Slogan == null) { db.Entry(slider).Property(m => m.Slogan).IsModified = false; } else { string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Slogan.FileName; string path = Path.Combine(Server.MapPath("~/Upload"), filename); Slogan.SaveAs(path); slider.Slogan = filename; } if (ModelState.IsValid) { db.Entry(slider).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(slider)); }
public ActionResult Edit([Bind(Include = "ArticleId,Headline,ArticleContent,IframeLink,Reads,CreateDate,ArticlePhoto,LanguageId")] Article article, int id, HttpPostedFileBase Photo) { if (ModelState.IsValid) { var articleContents = db.Articles.SingleOrDefault(m => m.ArticleId == id); if (Photo != null) { if (System.IO.File.Exists(Server.MapPath(articleContents.ArticlePhoto))) { System.IO.File.Delete(Server.MapPath(articleContents.ArticlePhoto)); } WebImage img = new WebImage(Photo.InputStream); FileInfo photoInfo = new FileInfo(Photo.FileName); string newPhoto = Guid.NewGuid().ToString() + photoInfo.Extension; img.Save("~/Uploads/BlogImage/" + newPhoto); articleContents.ArticlePhoto = "/Uploads/BlogImage/" + newPhoto; } articleContents.Headline = article.Headline; articleContents.ArticleContent = article.ArticleContent; articleContents.IframeLink = article.IframeLink; articleContents.LanguageId = article.LanguageId; articleContents.CreateDate = article.CreateDate; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.LanguageId = new SelectList(db.LanguageTBs, "LanguageId", "CultureName", article.LanguageId); return(View(article)); }