public JsonResult CheckConnection(int idclass, int id1, int id2) { AjaxResponseModel option = new AjaxResponseModel(); var db = new Models.DataModels.CourseDataBaseEntities(); int isvalid = 1; foreach (var i in db.StudentConnections) { if (i.Connection.ClassificationId == idclass && ((i.Connection.ParentConceptId == id1 && i.Connection.ChildConceptId == id2) || (i.Connection.ParentConceptId == null && i.Connection.ChildConceptId == id2 && id1 == -1)) ) { if (i.Status == 0) { isvalid = 0; } } } option.Length = isvalid; JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
public JsonResult DeleteConfirmConnection(int idclass, int id1, int id2, int act) { AjaxResponseModel option = new AjaxResponseModel(); var db = new Models.DataModels.CourseDataBaseEntities(); foreach (var i in db.StudentConnections) { if (i.Connection.ClassificationId == idclass && ((i.Connection.ParentConceptId == id1 && i.Connection.ChildConceptId == id2) || (i.Connection.ParentConceptId == null && i.Connection.ChildConceptId == id2 && id1 == -1)) ) { if (act == 0) { db.Connections.Remove(i.Connection); db.StudentConnections.Remove(i); break; } i.Status = 1; i.Rating = 1; break; } } db.SaveChanges(); JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
private static AjaxResponseModel EmailSend(string message, string subject) { var resp = new AjaxResponseModel(); var mm = new MailMessage(); var smtpClient = new SmtpClient { Host = "mail.mediviron-puchongavenue.com", UseDefaultCredentials = false, Credentials = new NetworkCredential("*****@*****.**", "LuckyIron123") }; mm.From = new MailAddress("*****@*****.**"); mm.Subject = subject; mm.IsBodyHtml = true; mm.To.Add("*****@*****.**"); mm.Body = message; try { smtpClient.Send(mm); resp.IsSuccess = true; resp.Message = "Successfully Submit."; } catch (Exception) { resp.IsSuccess = false; resp.Message = "Unable to request due to technical issue. Please contact us through hotline."; } return resp; }
public AjaxResponseModel Update(ProductModel model, string userId) { var resultModel = new AjaxResponseModel(); try { var product = _context.MstProducts.Include(x => x.ProductTechniques) .FirstOrDefault(x => x.Cd == model.Cd); if (product != null) { product.ItemCategory = model.ItemCategory.Trim(); product.ItemName = model.ItemName?.Trim(); product.JappaneseName = model.JapaneseName?.Trim(); product.Code = model.Code.Trim(); product.OriginalName = model.OriginalName.Trim(); product.Name = model.Name.Trim(); product.CategoryName = model.CategoryName.Trim(); product.Price = model.Price; product.NameKana = model.NameKana.Trim(); product.ArtistCd = model.ArtistCd; product.UpdateDate = DateTime.Now; product.UpdateUserId = userId; Update(product); if (product.ProductTechniques != null) { // remove technique of product _context.ProductTechniques.RemoveRange(product.ProductTechniques); // add technique for product List <ProductTechnique> listProductTechniques = AddNewProductTechniques(model, model.Cd); _context.ProductTechniques.AddRange(listProductTechniques); } _context.SaveChanges(); resultModel.Status = true; resultModel.Message = "編集に成功しました。"; return(resultModel); } resultModel.Status = false; resultModel.Message = "作品が見つかりません。"; return(resultModel); } catch (Exception) { resultModel.Status = false; resultModel.Message = "作品編集に失敗しました。"; return(resultModel); } }
public JsonResult EmptyConcepts() { AjaxResponseModel option = new AjaxResponseModel(); var db = new Models.DataModels.CourseDataBaseEntities(); List <string> enames = new List <string>(); List <string> eid = new List <string>(); List <string> names = new List <string>(); List <string> id = new List <string>(); foreach (var i in db.Connections) { if (i.Concept != null && !names.Contains(i.Concept.Name)) { names.Add(i.Concept.Name); id.Add((i.Id).ToString()); } if (i.Concept1 != null && !names.Contains(i.Concept1.Name)) { names.Add(i.Concept1.Name); id.Add((i.Id).ToString()); } } foreach (var i in db.Concepts) { if (names.Count() == 0) { enames.Add(i.Name); eid.Add((i.Id).ToString()); } for (int j = 0; j < names.Count(); j++) { if (!names.Contains(i.Name)) { enames.Add(i.Name); eid.Add((i.Id).ToString()); } } } option.Data = enames.ToArray(); option.Length = enames.Count; option.Value = eid.ToArray(); JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
public AjaxResponseModel Update(ArtistModel model, string userId) { var resultModel = new AjaxResponseModel(); try { var artist = _context.MstArtists.Include(x => x.ArtistDepartments) .FirstOrDefault(x => x.Cd == model.Cd); if (artist != null) { artist.Code = model.Code.Trim(); artist.Name = model.Name.Trim(); artist.ItemName = model.ItemName.Trim(); artist.CategoryName = model.NameCategory.Trim(); artist.NameKana = model.NameKana.Trim(); artist.IsFavorited = model.IsFavorited; artist.UpdateDate = DateTime.Now; artist.UpdateUserId = userId; Update(artist); if (artist.ArtistDepartments != null) { // remove department of artist _context.ArtistDepartments.RemoveRange(artist.ArtistDepartments); // add department agian for artist List <ArtistDepartment> result = AddNewArtistDepartments(model, model.Cd); _context.ArtistDepartments.AddRange(result); } _context.SaveChanges(); resultModel.Status = true; resultModel.Message = "編集に成功しました。"; return(resultModel); } resultModel.Status = false; resultModel.Message = "作家が見つかりません。"; return(resultModel); } catch (Exception) { resultModel.Status = false; resultModel.Message = "作家の編集に失敗しました。"; return(resultModel); } }
public JsonResult AddConnection(int idclass, int id1, int id2) { AjaxResponseModel option = new AjaxResponseModel(); List <string> names = new List <string>(); List <string> id = new List <string>(); var db = new Models.DataModels.CourseDataBaseEntities(); Connection connection; if (id1 == -1) { connection = db.Connections.Add(new Connection() { ChildConceptId = id2, ClassificationId = idclass }); } else { connection = db.Connections.Add(new Connection() { ChildConceptId = id2, ParentConceptId = id1, ClassificationId = idclass }); } var studentId = DataManager.DefineUser(HttpContext).Id; db.StudentConnections.Add(new StudentConnection() { Status = 0, ConnectionId = connection.Id, StudentId = studentId,//DistantLearningSystem.Models.Authorization.AuthorizedObject.Id, AddedDate = DateTime.Now, Rating = 0, }); db.SaveChanges(); option.Data = names.ToArray(); option.Length = names.Count; option.Value = id.ToArray(); JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
public AjaxResponseModel Create(ProductModel model, string userId) { var resultModel = new AjaxResponseModel(); try { var entity = new MstProduct { Code = model.Code.Trim(), Name = model.Name.Trim(), NameKana = model.NameKana.Trim(), ArtistCd = model.ArtistCd, Price = model.Price, OriginalName = model.OriginalName.Trim(), JappaneseName = model.JapaneseName?.Trim(), ItemName = model.ItemName?.Trim(), CategoryName = model.CategoryName?.Trim(), ItemCategory = model.ItemCategory.Trim(), InsertDate = DateTime.Now, IsDeleted = false, InsertUserId = userId }; // add technique for product List <ProductTechnique> listProductTechniques = AddNewProductTechniques(model, 0); entity.ProductTechniques = listProductTechniques; _context.MstProducts.Add(entity); _context.SaveChanges(); resultModel.Status = true; resultModel.Message = "新規作成に成功しました。"; return(resultModel); } catch (Exception) { resultModel.Status = false; resultModel.Message = "新規作品作成に失敗しました。"; return(resultModel); } }
public JsonResult Classifications() { AjaxResponseModel option = new AjaxResponseModel(); var db = new Models.DataModels.CourseDataBaseEntities(); List <string> bases = new List <string>(); List <string> id = new List <string>(); foreach (var i in db.Classifications) { bases.Add(i.Base); id.Add((i.Id).ToString()); } option.Data = bases.ToArray(); option.Length = bases.Count; option.Value = id.ToArray(); JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
public JsonResult ImgCapture(string stl_val, int stl_img_no) { AjaxResponseModel response = new AjaxResponseModel(); response.Success = false; string saveImgFolder = "Article/article_img"; string fileImgpath = string.Format("\\\\localhost\\fileupload\\{0}\\", saveImgFolder); if (new FileHelper().FilePathCreater(fileImgpath)) { if (!string.IsNullOrEmpty(stl_val) && stl_img_no != 0) { ArticleFileT file = _articleFileDac.GetArticleFileByNo(stl_img_no); string fileNm = file.Rename + ".jpg"; using (FileStream fs = new FileStream(fileImgpath + fileNm, FileMode.Create, FileAccess.Write)) { using (BinaryWriter bw = new BinaryWriter(fs)) { byte[] data = Convert.FromBase64String(stl_val.Replace("data:image/png;base64,", "")); bw.Write(data); bw.Close(); } fs.Close(); } file.ImgName = fileNm; response.Success = _articleFileDac.UpdateArticleFile(file); response.Result = file.No.ToString(); } } response.Success = true; return(Json(response, JsonRequestBehavior.AllowGet)); }
public AjaxResponseModel Create(ArtistModel model, string userId) { var resultModel = new AjaxResponseModel(); try { var entity = new MstArtist { Code = model.Code.Trim(), Name = model.Name.Trim(), NameKana = model.NameKana.Trim(), ItemName = model.ItemName.Trim(), CategoryName = model.NameCategory.Trim(), IsFavorited = model.IsFavorited, InsertDate = DateTime.Now, IsDeleted = false, InsertUserId = userId, }; // add department for artist List <ArtistDepartment> listArtistDepartments = AddNewArtistDepartments(model, 0); entity.ArtistDepartments = listArtistDepartments; _context.MstArtists.Add(entity); _context.SaveChanges(); resultModel.Status = true; resultModel.Message = "新規作成に成功しました。"; return(resultModel); } catch (Exception) { resultModel.Status = false; resultModel.Message = "作家の新規作成に失敗しました。"; return(resultModel); } }
public JsonResult Concepts(int data) { AjaxResponseModel option = new AjaxResponseModel(); var db = new Models.DataModels.CourseDataBaseEntities(); List <string> names = new List <string>(); List <string> id = new List <string>(); foreach (var i in db.Connections) { if (i.ClassificationId == data && i.ParentConceptId == null) { names.Add(i.Concept.Name); id.Add((i.Concept.Id).ToString()); } } option.Data = names.ToArray(); option.Length = names.Count; option.Value = id.ToArray(); JsonResult res = Json(option); res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }
//public JsonResult ImgUpload(FormCollection collection) public JsonResult ImgUpload(HttpPostedFileBase file, string temp, string fileIdx) { AjaxResponseModel response = new AjaxResponseModel(); response.Success = false; string fileName = string.Empty; //HttpPostedFileBase imgupload = Request.Files["file"]; if (file != null) { if (file.ContentLength > 0) { string[] extType = { ".jpg", ".png", ".gif" }; string extension = Path.GetExtension(file.FileName).ToLower(); if (extType.Contains(extension)) { fileName = new UploadFunc().FileUpload(file, ImageSize.GetArticleResize(), "Article", null); ArticleFileT articleFileT = new ArticleFileT(); articleFileT.FileGubun = "temp"; articleFileT.FileType = "img"; //articleFileT.MemberNo = profileModel.UserNo; articleFileT.MemberNo = 1; articleFileT.Seq = 5000; articleFileT.ImgUseYn = "U"; articleFileT.Ext = extension; articleFileT.ThumbYn = "Y"; articleFileT.MimeType = file.ContentType; articleFileT.Name = file.FileName; articleFileT.Size = file.ContentLength.ToString(); articleFileT.Rename = fileName; articleFileT.Path = "/Article/article_img/"; articleFileT.Width = "630"; articleFileT.Height = "470"; articleFileT.UseYn = "Y"; articleFileT.Temp = temp; articleFileT.RegIp = IPAddressHelper.GetIP(this); articleFileT.RegId = profileModel.UserId; articleFileT.RegDt = DateTime.Now; int articleFileNo = _articleFileDac.InsertArticleFile(articleFileT); response.Success = true; response.Result = articleFileNo.ToString(); } else { response.Message = "gif, jpg, png 형식 파일만 가능합니다."; } } } if (!string.IsNullOrEmpty(fileIdx)) { string[] idxArr = fileIdx.Split(','); if (idxArr.Length > 1) { _articleFileDac.UpdateArticleFileSeq(idxArr); } } return(Json(response, JsonRequestBehavior.AllowGet)); }
public JsonResult StlUpload(HttpPostedFileBase file, string temp, string fileIdx) { AjaxResponseModel response = new AjaxResponseModel(); response.Success = false; string fileName = string.Empty; //HttpPostedFileBase stlupload = Request.Files["stlupload"]; if (file != null) { if (file.ContentLength > 0) { if (file.ContentLength < 200 * 1024 * 1024) { string[] extType = { ".stl", ".obj" }; string extension = Path.GetExtension(file.FileName).ToLower(); if (extType.Contains(extension)) { string save3DFolder = "Article/article_3d"; string saveJSFolder = "Article/article_js"; fileName = new UploadFunc().FileUpload(file, null, save3DFolder, null); string file3Dpath = string.Format("\\\\localhost\\fileupload\\{0}\\", save3DFolder); string fileJSpath = string.Format("\\\\localhost\\fileupload\\{0}\\", saveJSFolder); Object3DModel _3dModel = new Modeling3DHelper().Get3DModel(file3Dpath + fileName, extension); //ArticleFileT sizeResult = GetSizeFor3DFile(file3Dpath + fileName, extension); var jsonBuff = JsonConvert.SerializeObject(_3dModel); string jsFileNm = fileJSpath + fileName + ".json"; new FileHelper().FileWriteAllText(jsFileNm, jsonBuff); ArticleFileT articleFileT = new ArticleFileT(); articleFileT.FileGubun = "temp"; articleFileT.FileType = "stl"; //articleFileT.MemberNo = profileModel.UserNo; articleFileT.MemberNo = 1; articleFileT.Seq = 5000; articleFileT.ImgUseYn = "N"; articleFileT.Ext = extension; articleFileT.ThumbYn = "N"; articleFileT.MimeType = file.ContentType; articleFileT.Name = file.FileName; articleFileT.Size = file.ContentLength.ToString(); articleFileT.Rename = fileName; articleFileT.Path = string.Format("/{0}/", save3DFolder); articleFileT.X = 0; articleFileT.Y = 0; articleFileT.Z = 0; articleFileT.Volume = 0; articleFileT.UseYn = "Y"; articleFileT.Temp = temp; articleFileT.RegIp = IPAddressHelper.GetIP(this); articleFileT.RegId = profileModel.UserId; articleFileT.RegDt = DateTime.Now; int articleFileNo = _articleFileDac.InsertArticleFile(articleFileT); response.Success = true; response.Result = articleFileNo.ToString(); } else { response.Message = "stl, obj 형식 파일만 가능합니다."; } } else { response.Message = "최대 사이즈 200MB 파일만 가능합니다."; } } } if (!string.IsNullOrEmpty(fileIdx)) { string[] idxArr = fileIdx.Split(','); if (idxArr.Length > 1) { _articleFileDac.UpdateArticleFileSeq(idxArr); } } return(Json(response, JsonRequestBehavior.AllowGet)); }
public AjaxResponseModel ImportCSV(IFormFile file, string userId) { string[] headers = new string[] { "作家コード", "作家名", "作家名(略称)", "事業区分" }; var result = new AjaxResponseModel(false, ""); try { string fileExtension = Path.GetExtension(file.FileName); if (fileExtension.ToUpper() != ".CSV") { result.Message = "アプロードファイルはCSVのみ指定ください。"; return(result); } var artists = new List <ImportedArtistModel>(); var errorRecords = new CustomLookup(); var isBadRecord = false; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (var reader = new StreamReader(file.OpenReadStream(), Encoding.GetEncoding(932))) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <ImportedArtistModelMap>(); csv.Configuration.TrimOptions = TrimOptions.Trim | TrimOptions.InsideQuotes; csv.Configuration.BadDataFound = context => { if (context.Row > 1) { isBadRecord = true; var field = context.RawRecord.Replace("\r\n", ""); var message = string.Format("「{0}」はCSVフォーマットが正しくありません。", field.Length > 25 ? $"{field.Substring(0, 25)}..." : field); errorRecords.Add(context.Row, message); } }; csv.Read(); csv.ReadHeader(); string[] headerRow = csv.Context.HeaderRecord; if (headerRow.Length != headers.Length) { var message = $"以下の{headers.Length}列のCSVファイルを選択してください。\n"; message += string.Join("\n", headers.Select(h => $"「{h}」")); result.Message = message; return(result); } while (csv.Read()) { if (!isBadRecord) { if (csv.Context.Record.Length != headers.Length) { errorRecords.Add(csv.Context.Row, "カラム数があっていません。"); } var validationResults = new List <ValidationResult>(); var artist = csv.GetRecord <ImportedArtistModel>(); var context = new ValidationContext(artist, null, null); var isValid = Validator.TryValidateObject(artist, context, validationResults, true); if (isValid) { artists.Add(artist); } else { foreach (var valResult in validationResults) { errorRecords.Add(csv.Context.Row, valResult.ErrorMessage); } } } isBadRecord = false; } } if (errorRecords.Count > 0) { var message = "データが無効です。\n"; message += string.Join("\n", errorRecords.Select(a => $"{a.Key}行目・{a.Value}")); message += "\n再度確認してください。"; result.Message = message; return(result); } if (artists.Count > 0) { //check duplicates var duplicateDic = artists.GroupBy(a => a.Code) .Where(a => a.Count() > 1) .ToDictionary(a => a.Key, a => a.Count()); if (duplicateDic.Count > 0) { var message = "作家コードは以下の値が重複しています。\n"; message += string.Join("\n", duplicateDic.Select(a => $"「{a.Key}」({a.Value}回)")); message += "\n再度確認してください。"; result.Message = message; return(result); } var now = DateTime.Now; var newArtistList = new List <MstArtist>(); foreach (var csvArtist in artists) { var artistInDb = _context.MstArtists.Include(a => a.ArtistDepartments).FirstOrDefault(a => a.Code == csvArtist.Code); if (artistInDb != null) { artistInDb.Name = csvArtist.Name; artistInDb.ItemName = csvArtist.ItemName; artistInDb.CategoryName = csvArtist.CategoryName; artistInDb.UpdateUserId = userId; artistInDb.UpdateDate = now; if (csvArtist.DepartmentCd.HasValue) { if (!artistInDb.ArtistDepartments.Any(ad => ad.DepartmentCd == csvArtist.DepartmentCd)) { artistInDb.ArtistDepartments.Add(new ArtistDepartment { ArtistCd = artistInDb.Cd, DepartmentCd = csvArtist.DepartmentCd.Value, }); } } } else { var newArtist = new MstArtist { Code = csvArtist.Code, Name = csvArtist.Name, ItemName = csvArtist.ItemName, CategoryName = csvArtist.CategoryName, InsertUserId = userId, InsertDate = now, UpdateUserId = userId, UpdateDate = now, }; if (csvArtist.DepartmentCd.HasValue) { newArtist.ArtistDepartments = new List <ArtistDepartment> { new ArtistDepartment { DepartmentCd = csvArtist.DepartmentCd.Value, } }; } newArtistList.Add(newArtist); } } if (newArtistList.Count > 0) { _context.MstArtists.AddRange(newArtistList); } _context.SaveChanges(); result.Status = true; return(result); } else { result.Message = "CSVファイルにデータがありません。再度確認してください。"; return(result); } } catch { result.Status = false; result.Message = "エラーが発生しました。もう一度お試しください。"; return(result); } }
public AjaxResponseModel ImportCSV(IFormFile file, string userId) { string[] headers = new string[] { "作家コード", "作品コード", "アイテムド", "作品名", "作品名(略称)", "カナ名称", "事業分類" }; var result = new AjaxResponseModel(false, ""); try { string fileExtension = Path.GetExtension(file.FileName); if (fileExtension.ToUpper() != ".CSV") { result.Message = "アプロードファイルはCSVのみ指定ください。"; return(result); } var products = new List <ImportedProductModel>(); var errorRecords = new CustomLookup(); var isBadRecord = false; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (var reader = new StreamReader(file.OpenReadStream(), Encoding.GetEncoding(932))) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <ImportedProductModelMap>(); csv.Configuration.TrimOptions = TrimOptions.Trim | TrimOptions.InsideQuotes; csv.Configuration.BadDataFound = context => { if (context.Row > 1) { isBadRecord = true; var field = context.RawRecord.Replace("\r\n", ""); var message = string.Format("「{0}」はCSVフォーマットが正しくありません。", field.Length > 25 ? $"{field.Substring(0, 25)}..." : field); errorRecords.Add(context.Row, message); } }; csv.Read(); csv.ReadHeader(); string[] headerRow = csv.Context.HeaderRecord; if (headerRow.Length != headers.Length) { var message = $"以下の{headers.Length}列のCSVファイルを選択してください。\n"; message += string.Join("\n", headers.Select(h => $"「{h}」")); result.Message = message; return(result); } while (csv.Read()) { if (!isBadRecord) { if (csv.Context.Record.Length != headers.Length) { errorRecords.Add(csv.Context.Row, "カラム数があっていません。"); } var validationResults = new List <ValidationResult>(); var product = csv.GetRecord <ImportedProductModel>(); var context = new ValidationContext(product, null, null); var isValid = Validator.TryValidateObject(product, context, validationResults, true); if (isValid) { products.Add(product); } else { foreach (var valResult in validationResults) { errorRecords.Add(csv.Context.Row, valResult.ErrorMessage); } } } isBadRecord = false; } } if (errorRecords.Count > 0) { var message = "データが無効です。\n"; message += string.Join("\n", errorRecords.Select(a => $"{a.Key}行目・{a.Value}")); message += "\n再度確認してください。"; result.Message = message; return(result); } if (products.Count > 0) { //check duplicates var duplicateDic = products.GroupBy(p => new { p.ArtistCode, p.Code, p.ItemCategory }) .Where(p => p.Count() > 1) .ToDictionary(p => $"{p.Key.ArtistCode}・{p.Key.Code}・{p.Key.ItemCategory}", p => p.Count()); if (duplicateDic.Count > 0) { var message = "作家コード・作品コード・アイテムドは以下の値が重複しています。\n"; message += string.Join("\n", duplicateDic.Select(p => $"「{p.Key}」({p.Value}回)")); message += "\n再度確認してください。"; result.Message = message; return(result); } var artistCodeCdDic = new Dictionary <string, int>(); var artistCodeList = products.Select(p => p.ArtistCode).Distinct().ToList(); foreach (var artistCode in artistCodeList) { var artistCd = _context.MstArtists.Where(a => a.Code == artistCode).Select(a => a.Cd).FirstOrDefault(); artistCodeCdDic.Add(artistCode, artistCd); } if (artistCodeCdDic.Any(cc => cc.Value == 0)) { var message = "以下の作家コードが存在していません。\n"; message += string.Join("\n", artistCodeCdDic.Where(cc => cc.Value == 0).Select(cc => $"「{cc.Key}」")); message += "\n再度確認してください。"; result.Message = message; return(result); } var now = DateTime.Now; var newProductList = new List <MstProduct>(); foreach (var csvProduct in products) { var productInDb = _context.MstProducts.FirstOrDefault(p => p.ArtistCd == artistCodeCdDic[csvProduct.ArtistCode] && p.Code == csvProduct.Code && p.ItemCategory == csvProduct.ItemCategory); if (productInDb != null) { productInDb.Name = csvProduct.Name; productInDb.OriginalName = csvProduct.OriginalName; productInDb.NameKana = csvProduct.NameKana; productInDb.CategoryName = csvProduct.CategoryName; productInDb.UpdateUserId = userId; productInDb.UpdateDate = now; } else { var newProduct = new MstProduct { ArtistCd = artistCodeCdDic[csvProduct.ArtistCode], Code = csvProduct.Code, ItemCategory = csvProduct.ItemCategory, Name = csvProduct.Name, OriginalName = csvProduct.OriginalName, NameKana = csvProduct.NameKana, CategoryName = csvProduct.CategoryName, InsertUserId = userId, InsertDate = now, UpdateUserId = userId, UpdateDate = now, }; newProductList.Add(newProduct); } } if (newProductList.Count > 0) { _context.MstProducts.AddRange(newProductList); } _context.SaveChanges(); result.Status = true; return(result); } else { result.Message = "CSVファイルにデータがありません。再度確認してください。"; return(result); } } catch { result.Status = false; result.Message = "エラーが発生しました。もう一度お試しください。"; return(result); } }
public JsonResult Upload(FormCollection collection) { AjaxResponseModel response = new AjaxResponseModel(); response.Success = false; int articleNo = 0; string paramNo = collection["No"]; string temp = collection["temp"]; string mode = collection["mode"]; int mainImg = Convert.ToInt32(collection["main_img"]); string articleTitle = collection["article_title"]; string articleContents = collection["article_contents"]; int codeNo = Convert.ToInt32(collection["lv1"]); int copyright = Convert.ToInt32(collection["copyright"]); string delNo = collection["del_no"]; string VideoSource = collection["insertVideoSource"]; string tags = collection["article_tags"]; var mulltiSeq = collection["multi[]"]; string[] seqArray = mulltiSeq.Split(','); if (tags.Length > 1000) { response.Message = "태그는 1000자 이하로 가능합니다."; return(Json(response, JsonRequestBehavior.AllowGet)); } ArticleT articleT = null; if (!Int32.TryParse(paramNo, out articleNo)) { response.Success = false; response.Message = "pk error"; } if (articleNo > 0) { //update articleT = _articleDac.GetArticleByNo(articleNo); if (articleT != null) { if (articleT.MemberNo == profileModel.UserNo && articleT.Temp == temp) { articleT.UpdDt = DateTime.Now; articleT.UpdId = profileModel.UserId; articleT.RegIp = IPAddressHelper.GetIP(this); } } } else { //save articleT = new ArticleT(); articleT.MemberNo = profileModel.UserNo; //태그 #** articleT.Tag = tags; articleT.Temp = temp; articleT.ViewCnt = 0; articleT.RegDt = DateTime.Now; articleT.RegId = profileModel.UserId; articleT.RegIp = IPAddressHelper.GetIP(this); articleT.RecommendYn = "N"; articleT.RecommendDt = null; } if (articleT != null) { articleT.Title = articleTitle; articleT.Contents = articleContents; articleT.Visibility = mode == "upload" ? "Y" : "N"; articleT.Copyright = copyright; articleT.CodeNo = codeNo; articleT.MainImage = mainImg; articleT.VideoUrl = VideoSource; articleT.Tag = tags; //articleNo = _articleDac.SaveOrUpdate(articleT, delNo); response.Success = true; response.Result = articleNo.ToString();; } //_articleFileDac.UpdateArticleFileSeq(seqArray); return(Json(response, JsonRequestBehavior.AllowGet)); }
public AjaxResponseModel ImportCSV(IFormFile file, string userId) { string[] headers = new string[] { "媒体コード", "媒体名" }; var result = new AjaxResponseModel(false, ""); try { string fileExtension = Path.GetExtension(file.FileName); if (fileExtension.ToUpper() != ".CSV") { result.Message = "アプロードファイルはCSVのみ指定ください。"; return(result); } var medias = new List <ImportedMediaModel>(); var errorRecords = new CustomLookup(); var isBadRecord = false; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (var reader = new StreamReader(file.OpenReadStream(), Encoding.GetEncoding(932))) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <ImportedMediaModelMap>(); csv.Configuration.TrimOptions = TrimOptions.Trim | TrimOptions.InsideQuotes; csv.Configuration.BadDataFound = context => { if (context.Row > 1) { isBadRecord = true; var field = context.RawRecord.Replace("\r\n", ""); var message = string.Format("「{0}」はCSVフォーマットが正しくありません。", field.Length > 25 ? $"{field.Substring(0, 25)}..." : field); errorRecords.Add(context.Row, message); } }; csv.Read(); csv.ReadHeader(); string[] headerRow = csv.Context.HeaderRecord; if (headerRow.Length != headers.Length) { var message = $"以下の{headers.Length}列のCSVファイルを選択してください。\n"; message += string.Join("、", headers.Select(h => $"「{h}」")); result.Message = message; return(result); } while (csv.Read()) { if (!isBadRecord) { if (csv.Context.Record.Length != headers.Length) { errorRecords.Add(csv.Context.Row, "カラム数があっていません。"); } var validationResults = new List <ValidationResult>(); var media = csv.GetRecord <ImportedMediaModel>(); var context = new ValidationContext(media, null, null); var isValid = Validator.TryValidateObject(media, context, validationResults, true); if (isValid) { medias.Add(media); } else { foreach (var valResult in validationResults) { errorRecords.Add(csv.Context.Row, valResult.ErrorMessage); } } } isBadRecord = false; } } if (errorRecords.Count > 0) { var message = "データが無効です。\n"; message += string.Join("\n", errorRecords.Select(r => $"{r.Key}行目・{r.Value}")); message += "\n再度確認してください。"; result.Message = message; return(result); } if (medias.Count > 0) { //check duplicates var duplicateDic = medias.GroupBy(m => new { m.Code, m.BranchCode }) .Where(m => m.Count() > 1) .ToDictionary(m => $"{m.Key.Code}{m.Key.BranchCode}", m => m.Count()); if (duplicateDic.Count > 0) { var message = "媒体コード・枝番は以下の値が重複しています。\n"; message += string.Join("\n", duplicateDic.Select(m => $"「{m.Key}」({m.Value}回)")); message += "\n再度確認してください。"; result.Message = message; return(result); } var now = DateTime.Now; var newMediaList = new List <MstMedia>(); foreach (var csvMedia in medias) { var mediaInDb = _context.MstMedias.FirstOrDefault(m => m.Code == csvMedia.Code && m.BranchCode == csvMedia.BranchCode); if (mediaInDb != null) { mediaInDb.Name = csvMedia.Name; mediaInDb.Flag = csvMedia.Flag; mediaInDb.UpdateUserId = userId; mediaInDb.UpdateDate = now; } else { var newMedia = new MstMedia { Code = csvMedia.Code, BranchCode = csvMedia.BranchCode, Name = csvMedia.Name, Flag = csvMedia.Flag, InsertUserId = userId, InsertDate = now, UpdateUserId = userId, UpdateDate = now, }; newMediaList.Add(newMedia); } } if (newMediaList.Count > 0) { _context.MstMedias.AddRange(newMediaList); } _context.SaveChanges(); result.Status = true; return(result); } else { result.Message = "CSVファイルにデータがありません。再度確認してください。"; return(result); } } catch { result.Status = false; result.Message = "エラーが発生しました。もう一度お試しください。"; return(result); } }
public async Task <AjaxResponseModel> ImportCSVAsync(IFormFile file, string userId) { var strategy = _context.Database.CreateExecutionStrategy(); var result = await strategy.ExecuteAsync(async() => { using (var dbTran = _context.Database.BeginTransaction()) { string[] headers = new string[] { "催事コード", "催事名称", "催事略称" }; var opResult = new AjaxResponseModel(false, ""); try { string fileExtension = Path.GetExtension(file.FileName); if (fileExtension.ToUpper() != ".CSV") { opResult.Message = "アプロードファイルはCSVのみ指定ください。"; return(opResult); } var events = new List <ImportedEventModel>(); var errorRecords = new CustomLookup(); var isBadRecord = false; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); using (var reader = new StreamReader(file.OpenReadStream(), Encoding.GetEncoding(932))) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.RegisterClassMap <ImportedEventModelMap>(); csv.Configuration.TrimOptions = TrimOptions.Trim | TrimOptions.InsideQuotes; csv.Configuration.BadDataFound = context => { if (context.Row > 1) { isBadRecord = true; var field = context.RawRecord.Replace("\r\n", ""); var message = string.Format("「{0}」はCSVフォーマットが正しくありません。", field.Length > 25 ? $"{field.Substring(0, 25)}..." : field); errorRecords.Add(context.Row, message); } }; csv.Read(); csv.ReadHeader(); string[] headerRow = csv.Context.HeaderRecord; if (headerRow.Length != headers.Length) { var message = $"以下の{headers.Length}列のCSVファイルを選択してください。\n"; message += string.Join("、", headers.Select(h => $"「{h}」")); opResult.Message = message; return(opResult); } while (csv.Read()) { if (!isBadRecord) { if (csv.Context.Record.Length != headers.Length) { errorRecords.Add(csv.Context.Row, "カラム数があっていません。"); } var validationResults = new List <ValidationResult>(); var importedEvent = csv.GetRecord <ImportedEventModel>(); var context = new ValidationContext(importedEvent, null, null); var isValid = Validator.TryValidateObject(importedEvent, context, validationResults, true); if (isValid) { events.Add(importedEvent); } else { foreach (var valResult in validationResults) { errorRecords.Add(csv.Context.Row, valResult.ErrorMessage); } } } isBadRecord = false; } } if (errorRecords.Count > 0) { var message = "データが無効です。\n"; message += string.Join("\n", errorRecords.Select(a => $"{a.Key}行目・{a.Value}")); message += "\n再度確認してください。"; opResult.Message = message; return(opResult); } if (events.Count > 0) { //check duplicates var duplicateDic = events.GroupBy(e => e.Code) .Where(e => e.Count() > 1) .ToDictionary(e => e.Key, e => e.Count()); if (duplicateDic.Count > 0) { var message = "催事コードは以下の値が重複しています。\n"; message += string.Join("\n", duplicateDic.Select(e => $"「{e.Key}」({e.Value}回)")); message += "\n再度確認してください。"; opResult.Message = message; return(opResult); } var now = DateTime.Now; var newEventList = new List <MstEvent>(); foreach (var csvEvent in events) { var eventInDb = _context.MstEvents.FirstOrDefault(e => e.Code == csvEvent.Code); if (eventInDb != null) { eventInDb.Name = csvEvent.Name; eventInDb.NameAbbr = csvEvent.NameAbbr; eventInDb.UpdateUserId = userId; eventInDb.UpdateDate = now; } else { var eventAccount = new ApplicationUser { UserName = csvEvent.Code, FirstName = "催事", LastName = csvEvent.Name, EmailConfirmed = false, PhoneNumberConfirmed = false, TwoFactorEnabled = false }; var createEventAccResult = await _userManager.CreateAsync(eventAccount, Constants.ImportedEventPwd); var surveyAccount = new ApplicationUser { UserName = $"{csvEvent.Code}{Constants.SurveyUserName}", FirstName = "アンケート", LastName = csvEvent.Name, EmailConfirmed = false, PhoneNumberConfirmed = false, TwoFactorEnabled = false }; var createSurveyAccResult = await _userManager.CreateAsync(surveyAccount, Constants.ImportedEventPwd); if (createEventAccResult.Succeeded && createSurveyAccResult.Succeeded) { var addToRoleEventResult = await _userManager.AddToRoleAsync(eventAccount, Role.User.ToString()); var addToRoleSurveyResult = await _userManager.AddToRoleAsync(surveyAccount, Role.Survey.ToString()); if (addToRoleEventResult.Succeeded && addToRoleSurveyResult.Succeeded) { var newEvent = new MstEvent { Code = csvEvent.Code, ApplicationUserId = eventAccount.Id, Name = csvEvent.Name, NameAbbr = csvEvent.NameAbbr, InsertUserId = userId, InsertDate = now, UpdateUserId = userId, UpdateDate = now, }; newEventList.Add(newEvent); } else { throw new Exception(); } } else { throw new Exception(); } } } if (newEventList.Count > 0) { _context.MstEvents.AddRange(newEventList); } _context.SaveChanges(); dbTran.Commit(); opResult.Status = true; return(opResult); } else { opResult.Message = "CSVファイルにデータがありません。再度確認してください。"; return(opResult); } } catch { dbTran.Rollback(); opResult.Status = false; opResult.Message = "エラーが発生しました。もう一度お試しください。"; return(opResult); } } }); return(result); }