Beispiel #1
0
        public IActionResult EditTourDay(int id, IFormFile dayPicture, EditTourDayViewModel model)
        {
            byte[] pic = null;
            if (dayPicture != null)
            {
                using (var stream = new MemoryStream())
                {
                    dayPicture?.CopyTo(stream);
                    pic = stream.ToArray();
                }
            }

            var success = tours.EditТourDay(id, model.DayId, pic, model.DayTitle, model.DayDescription);

            if (success)
            {
                TempData.AddSuccessMessage($"TourDay {model.DayId} of Tour {id} was edited successfully!");
            }
            else
            {
                TempData.AddErrorMessage($"TourDay {model.DayId} of Tour {id} was not changed");
            }

            return(base.RedirectToAction(
                       nameof(Web.Controllers.ToursController.Details), "Tours", new { area = string.Empty, id = id }));
        }
Beispiel #2
0
 public async Task<string> UpdateLogoAsync(int? clubId, IFormFile file)
 {
     string path = string.Empty;
     if (clubId.HasValue)
     {
         path = await _clubService.GetNameAsync(clubId.Value);
     }
     var relativePath = path;
     if (string.IsNullOrEmpty(path) || !path.Contains(LogoPath))
     {
         var newName = (string.IsNullOrWhiteSpace(path) ? GenerateNewName() : path) + "." + file.FileName.Split('.').Last();
         var newPath = GenerateNewPath(LogoPath);
         relativePath = Path.Combine(newPath, newName);
         path = GetFullPath(relativePath);
     }
     else
     {
         path = GetFullPath(path);
     }
     
     file.CopyTo(new FileStream(path, FileMode.Create));
     relativePath = Regex.Replace(relativePath, "\\\\", "/");
     if (clubId.HasValue)
     {
         await _clubService.UpdateLogoAsync(clubId.Value, relativePath);
     }
     return relativePath;
 }
Beispiel #3
0
        public IActionResult EditHeader(int id, IFormFile headerImage, EditTourHeaderViewModel model)
        {
            byte[] pic = null;
            if (headerImage != null)
            {
                using (var stream = new MemoryStream())
                {
                    headerImage?.CopyTo(stream);
                    pic = stream.ToArray();
                }
            }

            var success = tours.EditHeader(id, pic, model.Title);

            if (success)
            {
                TempData.AddSuccessMessage($"Tour {id} header edited successfully!");
            }
            else
            {
                TempData.AddErrorMessage($"Header of tour {id} was not changed");
            }

            return(base.RedirectToAction(
                       nameof(Web.Controllers.ToursController.Details), "Tours", new { area = string.Empty, id = id }));
        }
        public IActionResult Create(AddToursFormViewModel model,
                                    IFormFile headerImage,
                                    List <IFormFile> tourDayPictures)
        {
            using (var stream = new MemoryStream())
            {
                headerImage?.CopyTo(stream);
                model.HeaderImage = stream.ToArray();
            }

            foreach (var pic in tourDayPictures)
            {
                if (pic.Length > 0)
                {
                    using (var stream = new MemoryStream())
                    {
                        pic.CopyTo(stream);
                        model.TourDayPictures.Add(stream.ToArray());
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            this.tours.Create(
                model.Title,
                model.HeaderImage,
                model.TourDayPictures,
                model.TourDayTitles,
                model.TourDayDescriptions,
                model.StartDate,
                model.EndDate,
                model.Price,
                model.BusSeats,
                model.Nights,
                model.StartingPoint,
                model.Destination,
                model.DestinationType.ToString(),
                this.html.Sanitize(model.Description),
                model.UsefulInformation,
                model.PriceIncludes,
                model.PriceDoesNotIncludes,
                model.AdditionalServicesContents,
                model.AdditionalSerivicesPrices);

            TempData.AddSuccessMessage($"Tour {model.Title} created successfully!");

            return(base.RedirectToAction(
                       nameof(Web.Controllers.ToursController.All), "Tours", new { area = string.Empty }));
        }
Beispiel #5
0
        // ensure that the file is an image
        private bool CheckIfImageFile(IFormFile file)
        {
            byte[] fileBytes;
            using (var ms = new MemoryStream())
            {
                file?.CopyTo(ms);
                fileBytes = ms.ToArray();
            }
            // Convert byte[] to Base64 String
            //string base64String = Convert.ToBase64String(fileBytes);

            return(WriteHelper.GetImageFormat(fileBytes) != WriteHelper.ImageFormat.unknown);
        }
Beispiel #6
0
        public async Task<string> UpdateAvatarAsync(int userId, IFormFile file)
        {
            var path = await _userService.GetPhotoPathAsync(userId);
            var relativePath = path;
            if (string.IsNullOrEmpty(path))
            {
                var newName = GenerateNewName() + "." + file.FileName.Split('.').Last();
                var newPath = GenerateNewPath(AvatarPath);
                relativePath = Path.Combine(newPath, newName);
                path = GetFullPath(relativePath);
            }
            else
            {
                path = GetFullPath(path);
            }

            file.CopyTo(new FileStream(path, FileMode.Create));
            relativePath = Regex.Replace(relativePath, "\\\\", "/");
            await _userService.UpdatePhotoPathAsync(userId, relativePath);
            return relativePath;
        }
Beispiel #7
0
        public async Task <ActionResult> ImportAsync()
        {
            IFormFile file = Request.Form.Files[0];

            string folderName = "UploadExcel";

            string webRootPath = hostEnvironment.WebRootPath;

            string newPath = Path.Combine(webRootPath, folderName);

            var errorDictionary = new Dictionary <int, string>();

            if (!Directory.Exists(newPath))

            {
                Directory.CreateDirectory(newPath);
            }

            if (file.Length > 0)

            {
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();

                ISheet sheet;

                string fullPath = Path.Combine(newPath, file.FileName);

                using (var stream = new FileStream(fullPath, FileMode.Create))

                {
                    file.CopyTo(stream);

                    stream.Position = 0;

                    if (sFileExtension == ".xls")

                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    else

                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format

                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    IRow headerRow = sheet.GetRow(0); //Get Header Row

                    int cellCount = headerRow.LastCellNum;

                    for (int j = 0; j < cellCount; j++)
                    {
                        ICell cell = headerRow.GetCell(j);

                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                        {
                            continue;
                        }
                    }

                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File

                    {
                        IRow row = sheet.GetRow(i);

                        if (row == null)
                        {
                            continue;
                        }

                        if (row.Cells.All(d => d.CellType == CellType.Blank))
                        {
                            continue;
                        }

                        var newProduct = new ProductInputModel();

                        for (int j = row.FirstCellNum; j < cellCount; j++)

                        {
                            string currentRow = string.Empty;

                            if (row.GetCell(j) != null)
                            {
                                currentRow = row.GetCell(j).ToString().TrimEnd();
                            }

                            switch (j)
                            {
                            case 0:
                                if (currentRow != "")
                                {
                                    newProduct.Name = currentRow;
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }

                                break;

                            case 1:
                                if (currentRow != "")
                                {
                                    newProduct.ShortName = currentRow;
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 2:
                                if (this.numbersChecker.WholeNumberCheck(currentRow))
                                {
                                    newProduct.BrandexId = int.Parse(currentRow);
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;

                            case 3:
                                if (currentRow != "")
                                {
                                    newProduct.PhoenixId = int.Parse(currentRow);
                                }
                                break;

                            case 4:
                                if (currentRow != "")
                                {
                                    newProduct.PharmnetId = int.Parse(currentRow);
                                }
                                break;

                            case 5:
                                if (currentRow != "")
                                {
                                    newProduct.StingId = int.Parse(currentRow);
                                }
                                break;

                            case 6:
                                if (currentRow != "")
                                {
                                    newProduct.SopharmaId = currentRow;
                                }
                                break;

                            case 7:
                                if (numbersChecker.NegativeNumberIncludedCheck(currentRow))
                                {
                                    newProduct.Price = double.Parse(currentRow);
                                }
                                else
                                {
                                    errorDictionary[i] = currentRow;
                                }
                                break;
                            }
                        }

                        await this.productsService.CreateProduct(newProduct);
                    }
                }
            }

            var productsErrorModel = new CustomErrorDictionaryOutputModel
            {
                Errors = errorDictionary
            };

            return(this.View(productsErrorModel));
        }
Beispiel #8
0
        public static async Task <string> ProcessFormFile(IFormFile formFile,
                                                          ModelStateDictionary modelState)
        {
            var fieldDisplayName = string.Empty;

            // Use reflection to obtain the display name for the model
            // property associated with this IFormFile. If a display
            // name isn't found, error messages simply won't show
            // a display name.
            MemberInfo property =
                typeof(FileUpload).GetProperty(
                    formFile.Name.Substring(formFile.Name.IndexOf(".") + 1));

            if (property != null)
            {
                var displayAttribute =
                    property.GetCustomAttribute(typeof(DisplayAttribute))
                    as DisplayAttribute;

                if (displayAttribute != null)
                {
                    fieldDisplayName = $"{displayAttribute.Name} ";
                }
            }

            // Use Path.GetFileName to obtain the file name, which will
            // strip any path information passed as part of the
            // FileName property. HtmlEncode the result in case it must
            // be returned in an error message.
            var fileName = WebUtility.HtmlEncode(
                Path.GetFileName(formFile.FileName));

            // Check the file length and don't bother attempting to
            // read it if the file contains no content. This check
            // doesn't catch files that only have a BOM as their
            // content, so a content length check is made later after
            // reading the file's content to catch a file that only
            // contains a BOM.
            if (formFile.Length == 0)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) is empty.");
            }
            else if (formFile.Length > 1048576)
            {
                modelState.AddModelError(formFile.Name,
                                         $"The {fieldDisplayName}file ({fileName}) exceeds 1 MB.");
            }
            else
            {
                try
                {
                    string fileContents;

                    // The StreamReader is created to read files that are UTF-8 encoded.
                    // If uploads require some other encoding, provide the encoding in the
                    // using statement. To change to 32-bit encoding, change
                    // new UTF8Encoding(...) to new UTF32Encoding().
                    using (var ms = new MemoryStream())
                    {
                        formFile.CopyTo(ms);
                        ImageToArray img = new ImageToArray();
                        await img.request_AIAsync(ms);
                    }
                }
                catch (Exception ex)
                {
                    modelState.AddModelError(formFile.Name,
                                             $"The {fieldDisplayName}file ({fileName}) upload failed. " +
                                             $"Please contact the Help Desk for support. Error: {ex.Message}");
                    // Log the exception
                }
            }

            return(fileName);
        }
Beispiel #9
0
        public IActionResult UploadQuote(QuoteModel model)
        {
            GetProjectType();

            if (string.IsNullOrEmpty(model.Company))
            {
                ModelState.AddModelError("", "Company can not be empty.");
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                ModelState.AddModelError("", "Name can not be empty.");
            }

            if (string.IsNullOrEmpty(model.Email))
            {
                ModelState.AddModelError("", "Email can not be empty.");
            }

            if (string.IsNullOrEmpty(model.Phone))
            {
                ModelState.AddModelError("", "Phone can not be empty.");
            }

            if (Request.Form.Files == null || Request.Form.Files.Count == 0)
            {
                ModelState.AddModelError("", "Please upload file.");
            }

            var code = TempData["code"].ToString();

            if (string.IsNullOrEmpty(model.Code) || model.Code.ToLower() != code.ToLower())
            {
                ModelState.AddModelError("", "Captcha error.");
            }

            IFormFile file = null;
            string    ext  = string.Empty;

            if (Request.Form.Files.Count > 0)
            {
                file = Request.Form.Files[0];
                if (file.Length > 1024 * 1024 * 10)
                {
                    ModelState.AddModelError("", "Upload file is too large.");
                }
                ext = Path.GetExtension(file.FileName);

                if (string.IsNullOrEmpty(ext))
                {
                    ModelState.AddModelError("", "Upload file must be zip ,pdf, rar ,arj .");
                }

                ext = ext.ToLower();
                //zip, tgz, rar, arj, pdf
                string[] extarray = new string[] { ".zip", ".pdf", ".rar", ".arj" };
                if (!extarray.ToList().Contains(ext))
                {
                    ModelState.AddModelError("", "Upload file must be zip ,pdf, rar ,arj.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Please upload file");
            }

            if (!ModelState.IsValid)
            {
                return(View());
            }


            string fileid   = Guid.NewGuid().ToString();
            var    filepath = Directory.GetCurrentDirectory() + "\\upload\\" + fileid + ext;

            if (file.Length > 0)
            {
                using (var inputStream = new FileStream(filepath, FileMode.Create))
                {
                    // read file to stream
                    file.CopyTo(inputStream);
                }
            }

            Quote domainmodel = new Quote
            {
                Commnet    = model.Commnet,
                Company    = model.Company,
                Deleted    = false,
                Email      = model.Email,
                Leadtime   = model.Leadtime,
                Name       = model.Name,
                PartNo     = model.PartNo,
                Phone      = model.Phone,
                Quantity   = model.Quantity,
                Type       = model.Type == "0" ? string.Empty : model.Type,
                Uploadfile = fileid + ext
            };

            _quoteService.AddQuote(domainmodel);
            SendMail(domainmodel, filepath);

            return(RedirectToAction("Success"));
        }
Beispiel #10
0
        public IActionResult shopInfoImport(IFormFile excelfile)
        {
            var response = ResponseModelFactory.CreateInstance;

            using (_dbContext)
            {
                DateTime beginTime = DateTime.Now;

                string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportUserInfoExcel";


                //var schoolinfo = _dbContext.SchoolInforManagement.AsQueryable();
                string   uploadtitle = "箱房监控信息导入" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string   sFileName   = $"{uploadtitle}.xlsx";
                FileInfo file        = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                //string conStr = ConnectionStrings.DefaultConnection;
                string responsemsgsuccess = "";
                string responsemsgrepeat  = "";
                string responsemsgdefault = "";
                int    successcount       = 0;
                int    repeatcount        = 0;
                int    defaultcount       = 0;
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                try
                {
                    //把excelfile中的数据复制到file中
                    using (FileStream fs = new FileStream(file.ToString(), FileMode.Create)) //初始化一个指定路径和创建模式的FileStream
                    {
                        excelfile.CopyTo(fs);
                        fs.Flush();  //清空stream的缓存,并且把缓存中的数据输出到file
                    }
                    System.Data.DataTable dt = Haikan3.Utils.ExcelTools.ExcelToDataTable(file.ToString(), "Sheet1", true);

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        response.SetFailed("表格无数据");
                        return(Ok(response));
                    }
                    else
                    {
                        if (!dt.Columns.Contains("region_id"))
                        {
                            response.SetFailed("无‘region_id’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("index_code"))
                        {
                            response.SetFailed("无‘index_code’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("name"))
                        {
                            response.SetFailed("无‘name’列");
                            return(Ok(response));
                        }
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var entity = new GrabageMonitoring();
                            entity.GrabageMonitoringUuid = Guid.NewGuid();
                            if (!string.IsNullOrEmpty(dt.Rows[i]["region_id"].ToString()))
                            {
                                string cc = "";
                                cc = dt.Rows[i]["region_id"].ToString();
                                entity.RegionId = Convert.ToInt32(cc);
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["index_code"].ToString()))
                            {
                                var a    = dt.Rows[i]["index_code"].ToString();
                                var user = _dbContext.GrabageMonitoring.FirstOrDefault(x => x.MonitoringNum == dt.Rows[i]["index_code"].ToString());

                                if (user == null)
                                {
                                    entity.MonitoringNum = dt.Rows[i]["index_code"].ToString();
                                }
                                else
                                {
                                    responsemsgrepeat += "<p style='color:orange'>" + "第" + (i + 2) + "行index_code已存在" + "</p></br>";
                                    repeatcount++;
                                    continue;
                                }
                            }
                            else
                            {
                                responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行index_code为空" + "</p></br>";
                                defaultcount++;
                                continue;
                            }

                            if (!string.IsNullOrEmpty(dt.Rows[i]["name"].ToString()))
                            {
                                entity.JiankongName = dt.Rows[i]["name"].ToString();
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["longitude"].ToString()))
                            {
                                entity.Longitude = dt.Rows[i]["longitude"].ToString();
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["latitude"].ToString()))
                            {
                                entity.Latitude = dt.Rows[i]["latitude"].ToString();
                            }

                            entity.AddTime = DateTime.Now.ToString("yyyy-MM-dd");
                            _dbContext.GrabageMonitoring.Add(entity);
                            _dbContext.SaveChanges();
                            successcount++;
                        }
                    }
                    responsemsgsuccess = "<p style='color:green'>导入成功:" + successcount + "条</p></br>" + responsemsgsuccess;
                    responsemsgrepeat  = "<p style='color:orange'>重复需手动修改数据:" + repeatcount + "条</p></br>" + responsemsgrepeat;
                    responsemsgdefault = "<p style='color:red'>导入失败:" + defaultcount + "条</p></br>" + responsemsgdefault;


                    DateTime endTime  = DateTime.Now;
                    TimeSpan useTime  = endTime - beginTime;
                    string   taketime = "导入时间" + useTime.TotalSeconds.ToString() + "秒  ";
                    response.SetData(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new
                    {
                        time       = taketime,
                        successmsg = responsemsgsuccess
                        ,
                        repeatmsg  = responsemsgrepeat,
                        defaultmsg = responsemsgdefault
                    })));
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    response.SetFailed(ex.Message);
                    return(Ok(response));
                }
            }
        }
Beispiel #11
0
        public List <T> Import <T>(IFormFile formFile, bool hasTitle = false) where T : class, new()
        {
            var result = new List <T>();

            using var ms = new MemoryStream();
            formFile.CopyTo(ms);
            ms.Seek(0, SeekOrigin.Begin);

            var workbook = new XSSFWorkbook(ms);
            var sheet    = workbook.GetSheetAt(0);

            var cellNum       = sheet.GetRow(0);
            var cols          = cellNum.LastCellNum; //列数
            var rowStartIndex = hasTitle ? 2 : 1;    //数据起始行
            var headIndex     = hasTitle ? 1 : 0;    //列名行下标

            var pros = typeof(T).GetProperties();

            for (int i = rowStartIndex; i <= sheet.LastRowNum; i++)
            {
                var row  = sheet.GetRow(i);
                var item = new T();
                for (int j = 0; j <= cols; j++)
                {
                    var dataVal = sheet.GetRow(i).GetCell(j)?.ToString();
                    var headCol = sheet.GetRow(headIndex).GetCell(j)?.ToString();
                    foreach (var pro in pros)
                    {
                        var descAtr = (DescriptionAttribute[])pro.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (descAtr.Length <= 0)
                        {
                            continue;
                        }

                        if (descAtr[0].Description != headCol)
                        {
                            continue;
                        }

                        var dataType = pro.PropertyType.FullName;
                        switch (dataType)
                        {
                        case "System.String":
                            pro.SetValue(item, dataVal);
                            break;

                        case "System.DateTime":
                            pro.SetValue(item, Convert.ToDateTime(dataVal));
                            break;

                        case "System.Boolean":
                            pro.SetValue(item, Convert.ToBoolean(dataVal));
                            break;

                        case "System.Int16":
                            pro.SetValue(item, Convert.ToInt16(dataVal));
                            break;

                        case "System.Int32":
                            pro.SetValue(item, Convert.ToInt32(dataVal));
                            break;

                        case "System.Int64":
                            pro.SetValue(item, Convert.ToInt64(dataVal));
                            break;

                        case "System.Byte":
                            pro.SetValue(item, Convert.ToByte(dataVal));
                            break;
                        }
                        break;
                    }
                }

                result.Add(item);
            }

            return(result);
        }
Beispiel #12
0
        public IActionResult Upload(IFormFile image, string path)
        {
            IFormFile file       = image;
            string    PathUpload = _environment.WebRootPath + "/../../../images/" + path + "/";
            dynamic   response   = new ExpandoObject();

            if (file != null && file.Length != 0)
            {
                if (Path.GetExtension(file.FileName) == "php")
                {
                    response.status             = 0;
                    response.extra              = new ExpandoObject();
                    response.extra.errorMessage = "Upload image not a shell php";
                    return(BadRequest(response));
                }

                Random rnd = new Random();
                using (Stream stream = file.OpenReadStream())
                {
                    using (var binaryReader = new BinaryReader(stream))
                    {
                        byte[] fileContent = binaryReader.ReadBytes((int)file.Length);
                        var    alea        = rnd.Next(10, int.MaxValue);

                        var filename = alea + "_" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + Path.GetExtension(file.FileName);
                        if (!Directory.Exists(PathUpload))
                        {
                            Directory.CreateDirectory(PathUpload);
                        }
                        string FullFileName = PathUpload + filename;
                        Console.WriteLine("FullFileName" + FullFileName);

                        using (FileStream fs = System.IO.File.Create(FullFileName))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }

                        response.status             = 1;
                        response.extra              = new ExpandoObject();
                        response.extra.filename     = filename;
                        response.extra.FullFileName = FullFileName;
                        return(Ok(response));
                    }
                }
            }
            else
            {
                response.status             = 0;
                response.extra              = new ExpandoObject();
                response.extra.path         = file;
                response.extra.errorMessage = _modelS.GetErrorMessage(ModelState);
                if (file == null)
                {
                    response.extra.errorMessage += " , File is null";
                }
                else if (file.Length == 0)
                {
                    response.extra.errorMessage += " , File is empty";
                }
                return(BadRequest(response));
            }
        }
Beispiel #13
0
        public IActionResult uploadyoutube(string channelid, string title, string descrip, string category, string status, IFormFile files)
        {
            IFormFile updatevideo = files;
            string    postmessage = "";
            string    titlemsg    = "";

            string[] updatedmessgae = Regex.Split(descrip, "<br>");
            string[] updatedTitle   = Regex.Split(title, "<br>");

            foreach (var item in updatedmessgae)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    if (item.Contains("hhh") || item.Contains("nnn") || item.Contains("ppp") || item.Contains("jjj"))
                    {
                        if (item.Contains("hhh"))
                        {
                            postmessage = postmessage + item.Replace("hhh", "#");
                        }
                        if (item.Contains("nnn"))
                        {
                            postmessage = postmessage.Replace("nnn", "&");
                        }
                        if (item.Contains("ppp"))
                        {
                            postmessage = postmessage.Replace("ppp", "+");
                        }
                        if (item.Contains("jjj"))
                        {
                            postmessage = postmessage.Replace("jjj", "-+");
                        }
                    }
                    else
                    {
                        postmessage = postmessage + "\n\r" + item;
                    }
                }
            }
            descrip = postmessage;


            foreach (var itemTitle in updatedTitle)
            {
                if (!string.IsNullOrEmpty(itemTitle))
                {
                    if (itemTitle.Contains("hhh") || itemTitle.Contains("nnn") || itemTitle.Contains("ppp") || itemTitle.Contains("jjj"))
                    {
                        if (itemTitle.Contains("hhh"))
                        {
                            titlemsg = titlemsg + itemTitle.Replace("hhh", "#");
                        }
                        if (itemTitle.Contains("nnn"))
                        {
                            titlemsg = titlemsg.Replace("nnn", "&");
                        }
                        if (itemTitle.Contains("ppp"))
                        {
                            titlemsg = titlemsg.Replace("ppp", "+");
                        }
                        if (itemTitle.Contains("jjj"))
                        {
                            titlemsg = titlemsg.Replace("jjj", "-+");
                        }
                    }
                    else
                    {
                        titlemsg = titlemsg + "\n\r" + itemTitle;
                    }
                }
            }

            title = titlemsg;


            string[] arrdata = new string[4];
            arrdata[0] = title;
            arrdata[1] = descrip;
            arrdata[2] = category;
            arrdata[3] = status;

            string filename = "";
            var    fileName = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue.Parse(files.ContentDisposition).FileName.Trim('"');

            filename = Microsoft.Net.Http.Headers.ContentDispositionHeaderValue
                       .Parse(files.ContentDisposition)
                       .FileName
                       .Trim('"');
            var tempName = Domain.Socioboard.Helpers.SBHelper.RandomString(10) + '.' + fileName.Split('.')[1];

            filename = _appEnv.WebRootPath + "\\upload" + $@"\{tempName}";
            DatabaseRepository dbr = new Model.DatabaseRepository(_logger, _appEnv);

            try
            {
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    files.CopyTo(fs);
                    fs.Flush();
                }
            }
            catch (Exception ex)
            {
            }
            List <Domain.Socioboard.Models.YoutubeChannel> lstchannels = dbr.Find <Domain.Socioboard.Models.YoutubeChannel>(t => t.YtubeChannelId == channelid).ToList();
            int _resp = Repositories.UploadVideo.videosss(channelid, lstchannels.First().RefreshToken, files, filename, lstchannels.First().Channel_EmailId, arrdata, _appSettings);

            if (_resp == 0)
            {
                return(Ok("Posted"));
            }
            else
            {
                return(Ok("error"));
            }
        }
        public IActionResult CreateAccount(string DisplayName,
                                           string UserName,
                                           string PhoneNumber,
                                           string Email,
                                           string Password,
                                           IFormFile profileImage)
        {
            if (string.IsNullOrWhiteSpace(UserName) || Regex.Match(UserName, @"\s").Success)
            {
                ModelState.AddModelError("UserName", "UserName is Invalid. Username cannot be empty or have spaces within it");
                return(Redirect("LogInSignUp"));
            }
            else if (string.IsNullOrWhiteSpace(Email))
            {
                ModelState.AddModelError("Email", "Email is Required");
                return(Redirect("LogInSignUp"));
            }
            else if (string.IsNullOrWhiteSpace(Password))
            {
                ModelState.AddModelError("Password", "Password is Invaild");
                return(Redirect("LogInSignUp"));
            }
            else
            {
                bool userIsTaken = DatabaseConnection.GetAccount(UserName) != null;

                if (userIsTaken)
                {
                    ModelState.AddModelError("UserName", "UserName is taken");
                    return(Redirect("LogInSignUp"));
                }
                else if (Regex.Match(UserName, @"\s").Success)
                {
                    ModelState.AddModelError("UserName", "UserName may not contain spaces because it ruins file structure");
                    return(Redirect("LogInSignUp"));
                }
                else
                {
                    DisplayName = string.IsNullOrWhiteSpace(DisplayName) ? UserName : DisplayName;
                    if (ModelState.IsValid)
                    {
                        if (profileImage == null)
                        {
                            string  pathForImage = "~/Images/Users/Default/defaultprofile.png";
                            Account account      = new Account()
                            {
                                DisplayName = DisplayName,
                                UserName    = UserName,
                                PhoneNumber = PhoneNumber,
                                Password    = Password,
                                Email       = Email,
                                ProfPicPath = pathForImage
                            };
                            DatabaseConnection.InsertAccount(account);
                            return(Redirect("/"));
                        }
                        else if (profileImage.ContentType.ToString() != "image/png" && profileImage.ContentType.ToString() != "image/jpeg" && profileImage.ContentType.ToString() != "image/jpg")
                        {
                            string  pathForImage = "~/Images/Users/Default/defaultprofile.png";
                            Account account      = new Account()
                            {
                                DisplayName = DisplayName,
                                UserName    = UserName,
                                PhoneNumber = PhoneNumber,
                                Password    = Password,
                                Email       = Email,
                                ProfPicPath = pathForImage
                            };
                            DatabaseConnection.InsertAccount(account);
                            return(Redirect("/"));
                        }
                        else
                        {
                            //Grabs extension from image
                            var    match          = Regex.Match(profileImage.FileName, @"^.+(?<extension>\.[A-Za-z]+)$");
                            string ImageExtension = match.Groups["extension"].Value;
                            //constructs path for account image
                            string pathForImage = $"~/Images/Users/{UserName}/Profile/ProfilePicture" + ImageExtension;
                            //for local copy of image
                            string pathForCopy = $"wwwroot/Images/Users/{UserName}/Profile/ProfilePicture" + ImageExtension;

                            Directory.CreateDirectory($"wwwroot/Images/Users/{UserName}/Profile/");

                            //saves Image
                            using (FileStream stream = System.IO.File.OpenWrite(pathForCopy))
                            {
                                profileImage.CopyTo(stream);
                            }

                            Account account = new Account()
                            {
                                DisplayName      = DisplayName,
                                UserName         = UserName,
                                PhoneNumber      = PhoneNumber,
                                Password         = Password,
                                Email            = Email,
                                AllowCommissions = "No",
                                ProfPicPath      = pathForImage
                            };
                            DatabaseConnection.InsertAccount(account);
                            return(Redirect("/"));
                        }
                    }
                    return(Redirect("LogInSignUp"));
                }
            }
        }
        public IActionResult EditAccount(long userID,
                                         string DisplayName,
                                         string Biography,
                                         string PhoneNumber,
                                         string Email,
                                         string Password,
                                         string PayPal,
                                         string AllowCommissions,
                                         byte UserCommLimit,
                                         IFormFile CommissionPricesImage,
                                         IFormFile profileImage)
        {
            Account user = Account.GetAccount(userID);

            var filter = Builders <Account> .Filter.Eq("Id", user._id);

            if (UserCommLimit != 0)
            {
                user.CommissionLimit = UserCommLimit;
            }

            if (string.IsNullOrWhiteSpace(DisplayName) != true)
            {
                user.DisplayName = DisplayName;
                //var updateDef = Builders<Account>.Update.Set("DisplayName", user.DisplayName);
                //DatabaseConnection.UpdateAccount(filter, updateDef);
            }
            if (string.IsNullOrWhiteSpace(Biography) != true)
            {
                user.Biography = Biography;
                //var updateDef = Builders<Account>.Update.Set("Biography", user.Biography);
                //DatabaseConnection.UpdateAccount(filter, updateDef);
            }
            if (string.IsNullOrWhiteSpace(PhoneNumber) != true)
            {
                user.PhoneNumber = PhoneNumber;
            }
            if (string.IsNullOrWhiteSpace(Email) != true)
            {
                user.Email = Email;
            }
            if (string.IsNullOrWhiteSpace(Password) != true)
            {
                user.Password = Password;
            }
            if (string.IsNullOrWhiteSpace(PayPal) != true)
            {
                user.PayPal = PayPal;
            }
            if (string.IsNullOrWhiteSpace(AllowCommissions) != true)
            {
                user.AllowCommissions = AllowCommissions;
            }
            if (CommissionPricesImage != null)
            {
                var    match          = Regex.Match(CommissionPricesImage.FileName, @"^.+(?<extension>\.[A-Za-z]+)$");
                string ImageExtension = match.Groups["extension"].Value;
                string pathForImage   = $"~/Images/Users/{user.UserName}/Profile/CommissionPicture" + ImageExtension;
                string pathForCopy    = $"wwwroot/Images/Users/{user.UserName}/Profile/CommissionPicture" + ImageExtension;
                using (FileStream stream = System.IO.File.OpenWrite(pathForCopy))
                {
                    CommissionPricesImage.CopyTo(stream);
                }
                user.CommissionPricesImage = pathForImage;
            }
            if (profileImage != null)
            {
                var    match          = Regex.Match(profileImage.FileName, @"^.+(?<extension>\.[A-Za-z]+)$");
                string ImageExtension = match.Groups["extension"].Value;
                string pathForImage   = $"~/Images/Users/{user.UserName}/Profile/ProfilePicture" + ImageExtension;
                string pathForCopy    = $"wwwroot/Images/Users/{user.UserName}/Profile/ProfilePicture" + ImageExtension;
                using (FileStream stream = System.IO.File.OpenWrite(pathForCopy))
                {
                    profileImage.CopyTo(stream);
                }
                user.ProfPicPath = pathForImage;
            }
            DatabaseConnection.UpdateAccount(user);
            return(RedirectToAction("ShowAccount", "User"));
        }
        public IActionResult Import(IFormFile excelfile)
        {
            var response = ResponseModelFactory.CreateInstance;

            using (_dbContext)
            {
                DateTime beginTime = DateTime.Now;

                string sWebRootFolder = _hostingEnvironment.WebRootPath + "\\UploadFiles\\ImportBuidingExcel";


                //var schoolinfo = _dbContext.SchoolInforManagement.AsQueryable();
                string   uploadtitle = "孤寡老人信息导入" + DateTime.Now.ToString("yyyyMMddHHmmss");
                string   sFileName   = $"{uploadtitle}.xlsx";
                FileInfo file        = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                //string conStr = ConnectionStrings.DefaultConnection;
                string responsemsgsuccess = "";
                string responsemsgrepeat  = "";
                string responsemsgdefault = "";
                int    successcount       = 0;
                int    repeatcount        = 0;
                int    defaultcount       = 0;
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                var    query = _dbContext.Organization.FirstOrDefault(x => x.OrganizationName == "妇联");
                try
                {
                    //把excelfile中的数据复制到file中
                    using (FileStream fs = new FileStream(file.ToString(), FileMode.Create)) //初始化一个指定路径和创建模式的FileStream
                    {
                        excelfile.CopyTo(fs);
                        fs.Flush();  //清空stream的缓存,并且把缓存中的数据输出到file
                    }
                    DataTable dt = Haikan3.Utils.ExcelTools.ExcelToDataTable(file.ToString(), "Sheet1", true);

                    if (dt == null || dt.Rows.Count == 0)
                    {
                        response.SetFailed("表格无数据");
                        return(Ok(response));
                    }
                    else
                    {
                        if (!dt.Columns.Contains("姓名"))
                        {
                            response.SetFailed("无‘姓名’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("性别"))
                        {
                            response.SetFailed("无‘性别’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("出生日期"))
                        {
                            response.SetFailed("无‘出生日期’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("监护人"))
                        {
                            response.SetFailed("无‘监护人’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("监护人联系方式"))
                        {
                            response.SetFailed("无‘监护人联系方式’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("家庭地址"))
                        {
                            response.SetFailed("无‘家庭地址’列");
                            return(Ok(response));
                        }
                        if (!dt.Columns.Contains("具体情况"))
                        {
                            response.SetFailed("无‘具体情况’列");
                            return(Ok(response));
                        }
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            var entity = new HaikanSmartTownCockpit.Api.Entities.OrganPeoInfo();
                            entity.OrganPeoInfoUuid = Guid.NewGuid();
                            if (!string.IsNullOrEmpty(dt.Rows[i]["姓名"].ToString()))
                            {
                                Regex reg = new Regex("^([\\u4e00-\\u9fa5]){2,7}$");
                                if (reg.IsMatch(dt.Rows[i]["姓名"].ToString()))
                                {
                                    entity.OrganName = dt.Rows[i]["姓名"].ToString();
                                }
                                else
                                {
                                    responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行姓名格式不正确" + "</p></br>";
                                    defaultcount++;
                                    continue;
                                }
                            }
                            else
                            {
                                responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行姓名为空" + "</p></br>";
                                defaultcount++;
                                continue;
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["性别"].ToString()))
                            {
                                if (dt.Rows[i]["性别"].ToString() != "男" && dt.Rows[i]["性别"].ToString() != "女")
                                {
                                    responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行性别不正确" + "</p></br>";
                                    defaultcount++;
                                    continue;
                                }
                                else
                                {
                                    entity.Sex = dt.Rows[i]["性别"].ToString();
                                }
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["出生日期"].ToString()))
                            {
                                Regex reg = new Regex("^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
                                if (reg.IsMatch(dt.Rows[i]["出生日期"].ToString()))
                                {
                                    entity.Birth = dt.Rows[i]["出生日期"].ToString();
                                }
                                else
                                {
                                    responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行出生日期不正确" + "</p></br>";
                                    defaultcount++;
                                    continue;
                                }
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["监护人"].ToString()))
                            {
                                Regex reg = new Regex("^([\\u4e00-\\u9fa5]){2,7}$");
                                if (reg.IsMatch(dt.Rows[i]["监护人"].ToString()))
                                {
                                    entity.ZjWork = dt.Rows[i]["监护人"].ToString();
                                }
                                else
                                {
                                    responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行监护人格式不正确" + "</p></br>";
                                    defaultcount++;
                                    continue;
                                }
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["监护人联系方式"].ToString()))
                            {
                                Regex reg = new Regex("^[1][3,4,5,7,8][0-9]{9}$");
                                if (reg.IsMatch(dt.Rows[i]["监护人联系方式"].ToString()))
                                {
                                    entity.Duty = dt.Rows[i]["监护人联系方式"].ToString();
                                }
                                else
                                {
                                    responsemsgdefault += "<p style='color:red'>" + "第" + (i + 2) + "行监护人联系方式格式不正确" + "</p></br>";
                                    defaultcount++;
                                    continue;
                                }
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["家庭地址"].ToString()))
                            {
                                entity.HouseAddress = dt.Rows[i]["家庭地址"].ToString();
                            }
                            if (!string.IsNullOrEmpty(dt.Rows[i]["具体情况"].ToString()))
                            {
                                entity.Specific = dt.Rows[i]["具体情况"].ToString();
                            }
                            entity.OrganizationUuid = query.OrganizationUuid;
                            entity.ManType          = "孤寡老人";
                            entity.AddTime          = DateTime.Now.ToString("yyyy-MM-dd");
                            entity.AddPeople        = AuthContextService.CurrentUser.DisplayName;
                            entity.IsDeleted        = 0;
                            _dbContext.OrganPeoInfo.Add(entity);
                            _dbContext.SaveChanges();
                            successcount++;
                        }
                    }
                    responsemsgsuccess = "<p style='color:green'>导入成功:" + successcount + "条</p></br>" + responsemsgsuccess;
                    responsemsgrepeat  = "<p style='color:orange'>重复需手动修改数据:" + repeatcount + "条</p></br>" + responsemsgrepeat;
                    responsemsgdefault = "<p style='color:red'>导入失败:" + defaultcount + "条</p></br>" + responsemsgdefault;


                    DateTime endTime  = DateTime.Now;
                    TimeSpan useTime  = endTime - beginTime;
                    string   taketime = "导入时间" + useTime.TotalSeconds.ToString() + "秒  ";
                    response.SetData(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new
                    {
                        time       = taketime,
                        successmsg = responsemsgsuccess
                        ,
                        repeatmsg  = responsemsgrepeat,
                        defaultmsg = responsemsgdefault
                    })));
                    return(Ok(response));
                }
                catch (Exception ex)
                {
                    response.SetFailed(ex.Message);
                    return(Ok(response));
                }
            }
        }
Beispiel #17
0
        public ReturnObject ImportAsset()
        {
            ReturnObject obj = new ReturnObject();

            obj.status = -1;
            obj.value  = 0;
            ViewImportData entity    = new ViewImportData();
            IFormFile      formFiles = Request.Form.Files.First();

            entity.FileImport = formFiles;
            listWarning       = new List <string>();
            listError         = new List <string>();
            if (entity.FileImport != null)
            {
                IFormFile file = entity.FileImport;
                if (file.Length > 0)
                {
                    entity.fileName = file.FileName;
                    string sFileExtension = Path.GetExtension(file.FileName).ToLower();
                    ISheet sheet;
                    using (var stream = new FileStream(file.FileName, FileMode.Create))
                    {
                        int countUpdate = 0;
                        int countInsert = 0;
                        int countError  = 0;
                        file.CopyTo(stream);
                        stream.Position = 0;
                        XSSFWorkbook hssfwb      = new XSSFWorkbook(stream);
                        XSSFWorkbook hssfwbCheck = hssfwb;
                        if (hssfwb.NumberOfSheets > 0)
                        {
                            sheet = hssfwb.GetSheetAt(0);
                            var header = sheet.GetRow(5);
                            dict.Clear();
                            if (header != null)
                            {
                                Dictionary <string, int> dictHeaders = new Dictionary <string, int>();
                                var lstLines = new List <string>();
                                for (int j = 0; j < header.Cells.Count; j++)
                                {
                                    string key = header.Cells[j].StringCellValue.Trim().ToUpper();
                                    if (dictMap.ContainsKey(key))
                                    {
                                        dict.Add(dictMap[key], j);
                                    }
                                }
                            }
                            //Lấy dữ liệu từ dòng thứ 1
                            for (int rowIndex = 6; rowIndex < sheet.PhysicalNumberOfRows; rowIndex++)
                            {
                                // Lấy row hiện tại
                                var nowRow = sheet.GetRow(rowIndex);
                                if (nowRow.GetCell(1) != null && (nowRow.GetCell(1).CellType.ToString() != "Blank"))
                                {
                                    countInsert++;
                                    //Kiểm tra lỗi
                                    KiemTraLoi(ref nowRow);
                                    countError = listError.Count;
                                    //Nếu không có lỗi mới thực hiện tiếp
                                    if (countError <= 0)
                                    {
                                        var   now   = DateTime.Now.ToString("dd-MMM-yyyy");
                                        Asset asset = new Asset();
                                        asset.AssetCode   = GetString(nowRow, "AssetCode").TrimEnd();
                                        asset.AssetName   = GetString(nowRow, "AssetName").TrimEnd();
                                        asset.Description = GetString(nowRow, "Description").TrimEnd();
                                        asset.Unit        = GetString(nowRow, "Unit").TrimEnd();
                                        asset.Price       = GetInt(nowRow, "Price");
                                        asset.Quantity    = GetInt(nowRow, "Quantity");
                                        asset.LocationID  = GetString(nowRow, "LocationID").TrimEnd();
                                        asset.CategoryID  = GetString(nowRow, "CategoryID").TrimEnd();

                                        entity.lsAsset.Add(asset);
                                    }
                                }
                                else
                                {
                                    listError.Add("File không có dữ liệu hoặc dữ liệu không đúng định dạng");
                                    break;
                                }
                            }
                            if (listError.Count == 0)
                            {
                                DaoAsset daoAsset = new DaoAsset(tWG_ACHECKContext);
                                int      count    = daoAsset.ImportData(entity.lsAsset);
                                if (count > 0)
                                {
                                    obj.value  = count;
                                    obj.status = 1;
                                }
                            }
                        }
                        System.IO.File.Delete(stream.Name);
                        entity.countError  = countError;
                        entity.countUpdate = countUpdate;
                        entity.countInsert = countInsert;
                        entity.listError   = listError;
                        entity.listWarning = listWarning;
                        obj.message        = JsonConvert.SerializeObject(listError).ToString();
                    }
                }
            }
            return(obj);
        }
Beispiel #18
0

        
Beispiel #20
0
        public IActionResult Index(Setting setting, IFormFile logoUpload)
        {
            if (ModelState.IsValid)
            {
                Setting s;
                if (context.Settings.Any())
                {
                    s                        = context.Settings.FirstOrDefault();
                    s.WelcomeText            = setting.WelcomeText;
                    s.MembershipAgreement    = setting.MembershipAgreement;
                    s.ResumeDownloadSecurity = setting.ResumeDownloadSecurity;
                    s.LastResumeCreateDate   = setting.LastResumeCreateDate;
                    s.FooterText             = setting.FooterText;
                    s.CustomHtml             = setting.CustomHtml;
                    s.UpdateDate             = DateTime.Now;
                    s.Logo                   = setting.Logo;
                    s.Title                  = setting.Title;
                    s.SeoTitle               = setting.SeoTitle;
                    s.SeoDescription         = setting.SeoDescription;
                    s.SeoKeywords            = setting.SeoKeywords;
                    s.Address                = setting.Address;
                    s.Phone                  = setting.Phone;
                    s.Fax                    = setting.Fax;
                    s.Mail                   = setting.Mail;
                    s.Facebook               = setting.Facebook;
                    s.Twitter                = setting.Twitter;
                    s.LinkedIn               = setting.LinkedIn;
                    s.About                  = setting.About;
                    s.PrivacyPolicy          = setting.PrivacyPolicy;
                    s.TermsOfUse             = setting.TermsOfUse;

                    // file upload iþlemi yapýlýr

                    if (logoUpload != null && logoUpload.Length > 0)
                    {
                        var filePath = new Random().Next(9999).ToString() + logoUpload.FileName;
                        using (var stream = new FileStream(env.WebRootPath + "\\uploads\\" + filePath, FileMode.Create))
                        {
                            logoUpload.CopyTo(stream);
                        }
                        s.Logo = filePath;
                    }
                    context.SaveChanges();
                }
                else
                {
                    // file upload iþlemi yapýlýr
                    if (logoUpload != null && logoUpload.Length > 0)
                    {
                        var filePath = new Random().Next(9999).ToString() + logoUpload.FileName;
                        using (var stream = new FileStream(env.WebRootPath + "\\uploads\\" + filePath, FileMode.Create))
                        {
                            logoUpload.CopyTo(stream);
                        }
                        setting.Logo = filePath;
                    }
                    context.Settings.Add(setting);
                    context.SaveChanges();
                    ViewBag.Message = "Ayarlar baþarýyla kaydedildi.";
                }
            }
            return(View(setting));
        }
Beispiel #21
0
        public ActionResult OnPostImport()
        {
            IFormFile     file        = Request.Form.Files[0];
            string        folderName  = "Upload";
            string        webRootPath = _hostingEnvironment.WebRootPath;
            string        newPath     = Path.Combine(webRootPath, folderName);
            StringBuilder sb          = new StringBuilder();

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file.Length > 0)
            {
                string sFileExtension = Path.GetExtension(file.FileName).ToLower();
                ISheet sheet;
                string fullPath = Path.Combine(newPath, file.FileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file.CopyTo(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }

                    IRow headerRow = sheet.GetRow(0); //Get Header Row
                    int  cellCount = headerRow.LastCellNum;
                    sb.Append("<table class='table'><tr>");
                    for (int j = 0; j < cellCount; j++)
                    {
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                        {
                            continue;
                        }
                        sb.Append("<th>" + cell.ToString() + "</th>");
                    }
                    sb.Append("</tr>");
                    sb.AppendLine("<tr>");
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }
                        if (row.Cells.All(d => d.CellType == CellType.Blank))
                        {
                            continue;
                        }
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            if (row.GetCell(j) != null)
                            {
                                sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
                            }
                        }
                        sb.AppendLine("</tr>");
                    }
                    sb.Append("</table>");
                }
            }
            return(this.Content(sb.ToString()));
        }
        // This function should be implemented as an async function while user get notification (signalR logic)
        // when everything is done and video can be played
        public Video UploadFile(IFormFile file)
        {
            try
            {
                string fileName                 = file.FileName.Replace(" ", "");
                string videosFolder             = Path.Combine(Directory.GetCurrentDirectory(), videoFolderName);
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);

                // Create video folder
                string videoFolderPath = Path.Combine(videosFolder, fileNameWithoutExtension);
                int    ind             = 0;
                while (Directory.Exists(videoFolderPath))
                {
                    ind++;
                    videoFolderPath = videoFolderPath + "_" + ind;
                }

                Directory.CreateDirectory(videoFolderPath);
                string originalFilePath = Path.Combine(videoFolderPath, fileName);

                using (FileStream stream = new FileStream(originalFilePath, FileMode.Create))
                {
                    // Save file in videos folder
                    file.CopyTo(stream);
                }

                // Create video metadate to store in DB
                Video video = new Video()
                {
                    Name            = fileName,
                    VideoFolderPath = videoFolderPath,
                    Created         = DateTime.Now
                };


                // Create thumbnails
                HandleThumbnails(originalFilePath, video);

                // Convert to HD:
                string hdFilePath = ScaleVideo(originalFilePath, hdResolution);
                if (!string.IsNullOrEmpty(hdFilePath))
                {
                    video.HdFilePath = hdFilePath;
                }

                //Create hls files
                string hlsFilePath = CreateHlsFiles(originalFilePath);
                if (!string.IsNullOrEmpty(hlsFilePath))
                {
                    video.HlsFilePath = hlsFilePath;
                }

                video.Id = dal.Insert(video);
                return(video);
            }
            catch (Exception ex)
            {
                //TODO: log error
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        public async Task SlotImport(string line, IFormFile file)
        {
            try
            {
                List <string> noPns = new List <string>();

                var filename = ContentDispositionHeaderValue
                               .Parse(file.ContentDisposition)
                               .FileName
                               .Trim('"');

                filename = _hostingEnv.WebRootPath + $@"\{ filename }";

                System.IO.File.Delete(filename);
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                var lines = System.IO.File.ReadLines(filename).ToArray();

                string   machine = null, product = null, table = null, machineType = null, version = null, slotName = null;
                SideType boardSide = SideType.T;
                SideType side      = SideType.L;

                List <Slot> listSlot = new List <Slot>();

                if (lines[0].TrimStart().StartsWith("Machine"))  // NXT 料站表
                {
                    machineType = "NXT";
                    foreach (var l in lines)
                    {
                        var strs = l.Split("\t", StringSplitOptions.RemoveEmptyEntries);
                        if (strs.Length == 2 && strs[0] == "Machine") // 获取机器名
                        {
                            machine = strs[1];
                        }
                        if (strs.Length == 2 && strs[0].StartsWith("Recipe")) // 获取机种
                        {
                            var ps = strs[1].Split("_", StringSplitOptions.RemoveEmptyEntries);
                            product = ps[0].Substring(0, ps[0].Length - 1);

                            if (ps[0].Substring(ps[0].Length - 1) == "S")
                            {
                                boardSide = SideType.B;
                            }
                            else
                            {
                                boardSide = SideType.T;
                            }
                        }
                        if (strs.Length == 2 && strs[0] == "Revision") // 获取版本
                        {
                            version = strs[1];
                        }



                        if (strs.Length == 7 && strs[0].Contains("- "))
                        {
                            var partNoId = strs[1].Trim();

                            if (partNoId != null && _repositoryMPN.FirstOrDefault(partNoId) != null)
                            {
                                if (int.Parse(strs[5]) == 0)
                                {
                                    continue;
                                }
                                table = strs[0].Trim().Split(" ", StringSplitOptions.RemoveEmptyEntries)[0].Replace("-", "");

                                var slot = _repositorySlot.FirstOrDefault(s => s.BoardSide == boardSide && s.Machine == machine && s.ProductId == product && s.LineId == line && s.Table == table && s.PartNoId == partNoId && s.SlotName == strs[0]);
                                if (slot == null)
                                {
                                    listSlot.Add(new Slot()
                                    {
                                        BoardSide   = boardSide,
                                        Feeder      = strs[4],
                                        IsActive    = true,
                                        LineId      = line,
                                        Machine     = machine,
                                        PartNoId    = partNoId,
                                        Version     = version,
                                        Table       = table,
                                        SlotName    = strs[0],
                                        Side        = SideType.L,
                                        Qty         = int.Parse(strs[5]),
                                        ProductId   = product,
                                        MachineType = machineType,
                                        Location    = string.Join(",", strs[6].Trim().Replace("\"", "").Replace("-", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                                                  .Select(s => s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
                                                                          s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[1] :
                                                                          s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[0]).Distinct().OrderBy(s => s)),
                                        LineSide = SideType.L,
                                    });
                                }
                                else
                                {
                                    slot.BoardSide   = boardSide;
                                    slot.Feeder      = strs[4];
                                    slot.IsActive    = true;
                                    slot.LineId      = line;
                                    slot.Machine     = machine;
                                    slot.PartNoId    = partNoId;
                                    slot.Version     = version;
                                    slot.Table       = table;
                                    slot.SlotName    = strs[0];
                                    slot.Side        = SideType.L;
                                    slot.Qty         = int.Parse(strs[5]);
                                    slot.ProductId   = product;
                                    slot.MachineType = machineType;
                                    slot.Location    = string.Join(",", strs[6].Trim().Replace("\"", "").Replace("-", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                                                   .Select(s => s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
                                                                           s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[1] :
                                                                           s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[0]).OrderBy(s => s));
                                    slot.LineSide = SideType.L;
                                    listSlot.Add(slot);
                                }
                            }
                        }

                        if (strs.Length == 6 && strs[0].Contains("- "))
                        {
                            var partNoId = strs[1].Trim();

                            if (int.Parse(strs[4]) == 0)
                            {
                                continue;
                            }

                            if (partNoId != null && _repositoryMPN.FirstOrDefault(partNoId) != null)
                            {
                                table = strs[0].Split(" ", StringSplitOptions.RemoveEmptyEntries)[0].Replace("-", "");

                                var slot = _repositorySlot.FirstOrDefault(s => s.BoardSide == boardSide && s.Machine == machine && s.ProductId == product && s.LineId == line && s.Table == table && s.PartNoId == partNoId && s.SlotName == strs[0]);
                                if (slot == null)
                                {
                                    listSlot.Add(new Slot()
                                    {
                                        BoardSide   = boardSide,
                                        IsActive    = true,
                                        LineId      = line,
                                        Machine     = machine,
                                        PartNoId    = partNoId,
                                        Version     = version,
                                        Table       = table,
                                        SlotName    = strs[0],
                                        Side        = SideType.L,
                                        Qty         = int.Parse(strs[4]),
                                        ProductId   = product,
                                        MachineType = machineType,
                                        Location    = string.Join(",", strs[5].Trim().Replace("\"", "").Replace("-", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                                                  .Select(s => s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
                                                                          s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[1] :
                                                                          s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[0]).OrderBy(s => s)),
                                        LineSide = SideType.L,
                                    });
                                }
                                else
                                {
                                    slot.BoardSide   = boardSide;
                                    slot.IsActive    = true;
                                    slot.LineId      = line;
                                    slot.Machine     = machine;
                                    slot.PartNoId    = partNoId;
                                    slot.Version     = version;
                                    slot.Table       = table;
                                    slot.SlotName    = strs[0];
                                    slot.Side        = SideType.L;
                                    slot.Qty         = int.Parse(strs[4]);
                                    slot.ProductId   = product;
                                    slot.MachineType = machineType;
                                    slot.Location    = string.Join(",", strs[5].Trim().Replace("\"", "").Replace("-", "").Split(' ', StringSplitOptions.RemoveEmptyEntries)
                                                                   .Select(s => s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
                                                                           s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[1] :
                                                                           s.Trim().Split(':', StringSplitOptions.RemoveEmptyEntries)[0]).OrderBy(s => s));
                                    slot.LineSide = SideType.L;
                                    listSlot.Add(slot);
                                }
                            }
                        }
                    }
                }

                if (lines[0].TrimStart().Contains("Lot"))  // CM 料站表
                {
                    machineType = "CM";
                    DataTable dataTable = _fileHelperService.OpenCSV(filename);

                    foreach (DataRow item in dataTable.Rows)
                    {
                        if (item[0].ToString().Contains("Lot")) //
                        {
                            var strs = item[0].ToString().Split(":");

                            var ps = strs[1].Split(new char[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries);
                            product = ps[0].Substring(0, ps[0].Length - 1).Trim();
                            version = ps[1].Trim();
                            if (ps[0].Substring(ps[0].Length - 1).Trim() == "S")
                            {
                                boardSide = SideType.B;
                            }
                            else
                            {
                                boardSide = SideType.T;
                            }
                        }

                        if (item[0].ToString().Contains("MC") && !item[0].ToString().Contains("File"))
                        {
                            machine = item[0].ToString().Split(":", StringSplitOptions.RemoveEmptyEntries)[1];
                        }
                        var partNoId = item[2].ToString().Trim();
                        // 查询料号是否维护
                        if (partNoId != null && _repositoryMPN.FirstOrDefault(partNoId) != null)
                        {
                            if (int.Parse(item[7].ToString().Trim()) == 0)
                            {
                                continue;
                            }

                            // 变更站位
                            if (item[1].ToString().Trim().Length > 0)
                            {
                                slotName = item[1].ToString().Trim();
                            }

                            table = item[0].ToString().Trim();
                            if (item[4].ToString().Trim() == "R")
                            {
                                side = SideType.R;
                            }
                            else
                            {
                                side = SideType.L;
                            }

                            var slot = _repositorySlot.FirstOrDefault(s => s.BoardSide == boardSide && s.Machine == machine && s.ProductId == product && s.LineId == line && s.Table == table && s.PartNoId == partNoId && s.SlotName == slotName && s.Side == side);
                            if (slot == null)
                            {
                                listSlot.Add(new Slot()
                                {
                                    BoardSide   = boardSide,
                                    Feeder      = item[5].ToString().Trim(),
                                    IsActive    = true,
                                    LineId      = line,
                                    Machine     = machine,
                                    PartNoId    = partNoId,
                                    Version     = version,
                                    Table       = table,
                                    SlotName    = slotName,
                                    Side        = side,
                                    Qty         = int.Parse(item[7].ToString().Trim()),
                                    ProductId   = product,
                                    MachineType = machineType,
                                    Location    = string.Join(",", item[8].ToString().Trim().Replace("\"", "").Replace("-", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).OrderBy(s => s)),
                                    LineSide    = SideType.L,
                                });
                            }
                            else
                            {
                                slot.BoardSide   = boardSide;
                                slot.Feeder      = item[5].ToString().Trim();
                                slot.IsActive    = true;
                                slot.LineId      = line;
                                slot.Machine     = machine;
                                slot.PartNoId    = partNoId;
                                slot.Version     = version;
                                slot.Table       = table;
                                slot.SlotName    = slotName;
                                slot.Side        = side;
                                slot.Qty         = int.Parse(item[7].ToString().Trim());
                                slot.ProductId   = product;
                                slot.MachineType = machineType;
                                slot.Location    = string.Join(",", item[8].ToString().Trim().Replace("\"", "").Replace("-", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).OrderBy(s => s));
                                slot.LineSide    = SideType.L;
                                listSlot.Add(slot);
                            }
                        }
                    }
                }

                if (lines[0].TrimStart().StartsWith("Recipe"))  // NPM 料站表
                {
                    machineType = "NPM";
                    DataTable dataTable = _fileHelperService.OpenCSV(filename);
                    foreach (DataRow item in dataTable.Rows)
                    {
                        if (item[0].ToString().Contains("Recipe")) //
                        {
                            var strs = item[0].ToString().Split(":");

                            var ps = strs[1].Split("_", StringSplitOptions.RemoveEmptyEntries);
                            product = ps[0].Substring(0, ps[0].Length - 1).Trim();
                            version = ps[1].Trim();
                            if (ps[0].Substring(ps[0].Length - 1).Trim() == "S")
                            {
                                boardSide = SideType.B;
                            }
                            else
                            {
                                boardSide = SideType.T;
                            }
                        }

                        var partNoId = item[5].ToString().Trim();
                        // 查询料号是否维护
                        if (partNoId != null && _repositoryMPN.FirstOrDefault(partNoId) != null)
                        {
                            if (int.Parse(item[7].ToString().Trim()) == 0)
                            {
                                continue;
                            }

                            // 变更站位
                            if (item[3].ToString().Trim().Length > 0)
                            {
                                slotName = item[3].ToString().Trim();
                            }

                            table = item[2].ToString().Trim();
                            if (item[4].ToString().Trim() == "R")
                            {
                                side = SideType.R;
                            }
                            else
                            {
                                side = SideType.L;
                            }

                            machine = item[1].ToString().Trim();

                            var slot = _repositorySlot.FirstOrDefault(s => s.BoardSide == boardSide && s.Machine == machine && s.ProductId == product && s.LineId == line && s.Table == table && s.PartNoId == partNoId && s.SlotName == slotName && s.Side == side);
                            if (slot == null)
                            {
                                listSlot.Add(new Slot()
                                {
                                    BoardSide   = boardSide,
                                    Feeder      = item[6].ToString().Trim(),
                                    IsActive    = true,
                                    LineId      = line,
                                    Machine     = machine,
                                    PartNoId    = partNoId,
                                    Version     = version,
                                    Table       = table,
                                    SlotName    = slotName,
                                    Side        = side,
                                    Qty         = int.Parse(item[7].ToString().Trim()),
                                    ProductId   = product,
                                    MachineType = machineType,
                                    Location    = string.Join(",", item[8].ToString().Trim().Replace("\"", "").Replace("-", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).OrderBy(s => s)),
                                    LineSide    = SideType.L,
                                });
                            }
                            else
                            {
                                slot.BoardSide   = boardSide;
                                slot.Feeder      = item[6].ToString().Trim();
                                slot.IsActive    = true;
                                slot.LineId      = line;
                                slot.Machine     = machine;
                                slot.PartNoId    = partNoId;
                                slot.Version     = version;
                                slot.Table       = table;
                                slot.SlotName    = slotName;
                                slot.Side        = side;
                                slot.Qty         = int.Parse(item[7].ToString().Trim());
                                slot.ProductId   = product;
                                slot.MachineType = machineType;
                                slot.Location    = string.Join(",", item[8].ToString().Trim().Replace("\"", "").Replace("-", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).OrderBy(s => s));
                                slot.LineSide    = SideType.L;
                                listSlot.Add(slot);
                            }
                        }
                        else
                        {
                            if (item[5].ToString().Trim().Length > 0)
                            {
                                noPns.Add(item[5].ToString().Trim());
                            }
                        }
                    }
                }
                int slotIndex = 1;
                foreach (var item in listSlot)
                {
                    item.Index = slotIndex;
                    slotIndex++;
                    await _repositorySlot.InsertOrUpdateAsync(item);
                }
                CurrentUnitOfWork.SaveChanges();

                // 将不在本次料表中的站位更新为无效
                // 查询该机种该线别该版本
                var NoActives = _repositorySlot.GetAll().Where(r => r.BoardSide == listSlot.FirstOrDefault().BoardSide&& r.ProductId == listSlot.FirstOrDefault().ProductId&& r.LineId == listSlot.FirstOrDefault().LineId&& !listSlot.Select(s => s.Id).Contains(r.Id)).ToArray();

                foreach (var item in NoActives)
                {
                    item.IsActive = false;
                    await _repositorySlot.UpdateAsync(item);
                }
                System.IO.File.Delete(filename);
            }
            catch (Exception ex)
            {
                throw new LYException(ex.Message);
            }
        }
        public string PostFile(int id, FileType fileType)
        {
            string message = "OK";

            if (!Request.Form.Files.Any())
            {
                return("Failure");
            }

            string subFolder = "";

            try
            {
                if (fileType == FileType.Trailer)
                {
                    subFolder = "Trailers";
                }
                else if (fileType == FileType.Poster)
                {
                    subFolder = "Posters";
                }
                else if (fileType == FileType.Still)
                {
                    subFolder = "Stills";
                }
                else if (fileType == FileType.Director)
                {
                    subFolder = "Directors";
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            string myFileName = "";
            string folder     = AppDomain.CurrentDomain.BaseDirectory + "wwwroot\\" + subFolder + "\\";

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            try
            {
                IFormFile myFile = Request.Form.Files.First();

                //myFileName = myFile.Name.Replace(" ", "");
                myFileName = Guid.NewGuid().ToString() + Path.GetExtension(myFile.Name);

                FileStream stream = new FileStream(folder + myFileName, FileMode.Create);

                myFile.CopyTo(stream);

                stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            Film        film    = null;
            FilmDetails details = null;

            try
            {
                film    = db.Films.Find(id);
                details = db.FilmDetails.Include(fd => fd.Film).Include(fd => fd.StillUrls).Where(fd => fd.FilmID == id).FirstOrDefault();

                if (details == null)
                {
                    details = new FilmDetails()
                    {
                        FilmID    = id,
                        Film      = film,
                        StillUrls = new List <StillUrl>()
                    };

                    db.FilmDetails.Add(details);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            try
            {
                if (fileType == FileType.Trailer)
                {
                    details.TrailerUrl = "/" + subFolder + "/" + myFileName;
                }
                else if (fileType == FileType.Poster)
                {
                    details.PosterUrl = "/" + subFolder + "/" + myFileName;
                }
                else if (fileType == FileType.Still)
                {
                    details.StillUrls.Add(new StillUrl()
                    {
                        Url = "/" + subFolder + "/" + myFileName
                    });
                }
                else if (fileType == FileType.Director)
                {
                    details.DirectorPicUrl = "/" + subFolder + "/" + myFileName;
                }

                message = "OK" + myFileName;

                db.SaveChanges();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            return(message);
        }
        public IActionResult Upload(IFormFile file, string Delimeter, string Location, string Name)
        {
            if (file == null || Delimeter == null || Location == null || Name == null)
            {
                return(View());
            }
            else
            {
                this._verifyUploadFolderExistence();
            }
            Console.WriteLine("Načtení controlleru a souboru: " + file.FileName);
            Uploader uploader = new Uploader();

            if (Delimeter == "tabulator")
            {
                Delimeter = "\t";
            }
            uploader.Delimeter = Delimeter;
            if (file != null)
            {
                if (Path.GetExtension(file.FileName) != ".csv")
                {
                    uploader.SetIncorrectExtensionMessage(Path.GetExtension(file.FileName));
                    return(View(uploader));
                }
                //Generate file name
                string FileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                Console.WriteLine("Vygenerováno jméno souboru");

                //Generate url to save
                string SavePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", FileName);
                uploader.FilePath = SavePath;
                Console.WriteLine("Příprava na přesun");

                try{
                    using (var stream = new FileStream(SavePath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                }


                Console.WriteLine("Přesun kompletní");

                //Check status of upload
                bool result = uploader.CheckFileExistence(FileName);
                Console.WriteLine("Stav uploadu zkontrolován: " + result);
                List <string> delimeter = new List <string>();
                if (Delimeter == "auto")
                {
                    delimeter.Add(";");
                    delimeter.Add(",");
                    delimeter.Add("\t");
                }
                else
                {
                    if (Delimeter == "tabulator")
                    {
                        Delimeter = "\t";
                    }
                    else
                    {
                        delimeter.Add(Delimeter);
                    }
                }

                if (result)
                {
                    int  iteration           = 0;
                    bool importDoneCorrectly = false;
                    while (importDoneCorrectly == false)
                    {
                        if (this._processCSV(FileName, Name, Location, delimeter[iteration]) == true)
                        {
                            importDoneCorrectly = true;
                        }
                        else
                        {
                            iteration++;
                        }

                        if (iteration == delimeter.Count())
                        {
                            break;
                        }
                        Console.WriteLine(importDoneCorrectly);
                    }
                    if (importDoneCorrectly == false)
                    {
                        LogMessage lm = new LogMessage("Zpracování CSV", "500", "Nebylo možné přečíst CSV soubor. Zkustě jiný oddělovač", "Error");
                        new Alerter(lm, HttpContext);
                    }
                    else
                    {
                        LogMessage lm = new LogMessage("Zpracování CSV", "200", "CSV bylo zpracováno a nahráno", "OK");
                        new Alerter(lm, HttpContext);
                    }
                    //Odstraň CSV soubor
                    uploader.Delete();
                    if (importDoneCorrectly == true)
                    {
                        return(RedirectToAction("Imports", "User"));
                    }
                    else
                    {
                        uploader.AlertStatus = "bg-danger";
                        uploader.Status      = "Došlo k chybě při zpracování souboru";
                        return(View(uploader));
                    }
                }
                else
                {
                    //Odstraň CSV soubor
                    uploader.Delete();

                    return(View(uploader));
                }
            }
            return(View(uploader));
        }
Beispiel #26
0
        public async Task <IActionResult> Edit(long Id, [Bind("Id,Name,Price,ExpireDate,CategoryId,CategoryList,CategoryName,IsActive,Orders,Image,ImagePath")] ProductVM Product, IFormFile Image)
        {
            if (Id != Product.Id)
            {
                return(NotFound());
            }

            if (Image != null)
            {
                using (var ms = new MemoryStream())
                {
                    Image.CopyTo(ms);
                    //if(Image.Length<2048)
                    //{
                    Product.Image = ms.ToArray();
                    //}
                    var files = HttpContext.Request.Form.Files;
                    foreach (var image in files)
                    {
                        if (image != null && image.Length > 0)
                        {
                            var file = Image;
                            // var root = _appEnvironment.WebRootPath;
                            var root    = "wwwroot\\";
                            var uploads = "uploads\\img";
                            if (file.Length > 0)
                            {
                                // you can change the Guid.NewGuid().ToString().Replace("-", "")
                                // to Guid.NewGuid().ToString("N") it will produce the same result
                                var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);

                                using (var fileStream = new FileStream(Path.Combine(root, uploads, fileName), FileMode.Create))
                                {
                                    await file.CopyToAsync(fileStream);

                                    // This will produce uploads\img\fileName.ext
                                    Product.ImagePath = Path.Combine(uploads, fileName);
                                }
                            }
                        }
                    }

                    // ImageConverter converter = new ImageConverter();
                    // model.Image = (byte[])converter.ConvertTo(Image, typeof(byte[]));
                }
            }
            else
            {
                Product.Image     = Product.Image;
                Product.ImagePath = Product.ImagePath;
            }
            if (ModelState.IsValid)
            {
                var aProduct = _mapper.Map <Product>(Product);
                aProduct.Image     = Product.Image;
                aProduct.ImagePath = Product.ImagePath;

                bool isUpdated = _productManager.Update(aProduct);
                if (isUpdated)
                {
                    var Products = _productManager.GetAll();
                    ViewBag.SuccessMessage = "Updated Successfully!";
                    //VwBg();
                    return(View("Index", Products));
                }
                //}
            }
            else
            {
                ViewBag.ErrorMessage = "Update Failed!";
            }
            Product.ProductList = _productManager.GetAll().ToList();
            //VwBg();
            return(View(Product));
        }
Beispiel #27
0
        public async Task <IActionResult> Create([FromForm] Tutorial tutorial)
        {
            if (ModelState.IsValid)
            {
                IFormFile file      = Request.Form.Files["UploadedFile"];
                var       name      = Request.Form["UploadedFileName"];
                var       parentid  = Request.Form["UploadedFileParentID"];
                var       path      = Request.Form["UploadedFilePath"];
                var       projectid = Request.Form["UploadedProjectID"];
                var       taskid    = Request.Form["UploadedTaskID"];
                if (file != null)
                {
                    if (!Directory.Exists(_environment.WebRootPath + "\\video\\"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "\\video\\");
                    }
                    using FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\video\\" + file.FileName);
                    file.CopyTo(fileStream);
                    fileStream.Flush();

                    var item = new Tutorial
                    {
                        Level    = 1,
                        Name     = name.ToSafetyString(),
                        ParentID = parentid.ToInt(),
                        URL      = $"{Request.Scheme}://{Request.Host.Value}/video/{file.FileName}",
                        Path     = path.ToSafetyString()
                    };
                    if (projectid.ToInt() > 0)
                    {
                        item.ProjectID = projectid.ToInt();
                    }
                    if (taskid.ToInt() > 0)
                    {
                        item.TaskID = taskid.ToInt();
                    }
                    await _tutorialService.Create(item);
                }
                else
                {
                    var item = tutorial;
                    item.Level = 1;
                    item.Name  = name.ToSafetyString();
                    item.Path  = path.ToSafetyString();
                    if (projectid.ToInt() > 0)
                    {
                        item.ProjectID = projectid.ToInt();
                    }

                    item.ParentID = parentid.ToInt();
                    if (taskid.ToInt() > 0)
                    {
                        item.TaskID = taskid.ToInt();
                    }
                    await _tutorialService.Create(item);
                }
                return(Ok(tutorial));
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors);
            }
            return(Ok(tutorial));
        }
        public IActionResult ImportExport(IFormFile files)
        {
            ArrayList outArr      = new ArrayList();
            ArrayList stockSymbol = new ArrayList();

            IFormFile file = Request.Form.Files[0];

            if (file != null)
            {
                string        folderName  = "Upload";
                string        webRootPath = _hostingEnvironment.WebRootPath;
                string        newPath     = Path.Combine(webRootPath, folderName);
                StringBuilder sb          = new StringBuilder();
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (file.Length > 0)
                {
                    string sFileExtension = Path.GetExtension(file.FileName).ToLower();
                    ISheet sheet;
                    string fullPath = Path.Combine(newPath, file.FileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                        stream.Position = 0;
                        if (sFileExtension == ".xls")
                        {
                            HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                            sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                        }
                        else
                        {
                            XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                            sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                        }

                        IRow headerRow = sheet.GetRow(0); //Get Header Row
                        int  cellCount = headerRow.LastCellNum;
                        sb.Append("<table class='table table-hover'><tr>");
                        for (int j = 0; j < cellCount; j++)
                        {
                            NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                            if (cell == null || string.IsNullOrWhiteSpace(cell.ToString()))
                            {
                                continue;
                            }
                            outArr.Add(cell.ToString());                    // Add to the array
                            sb.Append("<th>" + cell.ToString() + "</th>");
                        }
                        sb.Append("</tr>");
                        sb.AppendLine("<tr>");
                        for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null)
                            {
                                continue;
                            }
                            if (row.Cells.All(d => d.CellType == CellType.Blank))
                            {
                                continue;
                            }
                            for (int j = row.FirstCellNum; j < cellCount; j++)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    outArr.Add(row.GetCell(j).ToString());
                                    sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");

                                    //Check if it's a unique stock Symbol (if so add to stockSymbol arrayList)
                                    if (j == 1 && !stockSymbol.Contains(row.GetCell(j).ToString()))
                                    {
                                        stockSymbol.Add(row.GetCell(j).ToString());
                                    }
                                }
                            }
                            sb.AppendLine("</tr>");
                        }
                        sb.Append("</table>");
                        stream.Close();             // Close the reading stream
                    }
                }
                Debug.WriteLine(outArr.ToArray());
                DataSaveWrite.WriteDataToFile(outArr, "stockInfo");     // Write it to a file
                DataSaveWrite.WriteDataToFile(stockSymbol, "stockList");
                return(this.Content(sb.ToString()));
            }

            return(new EmptyResult());
        }
        public async Task <IActionResult> Edit(int TfcId, String TfcType, String Name, String Details,
                                               String Company, String Location, IFormFile fil)
        {
            var tfc = _context.Tfc.FromSqlRaw("SELECT * FROM [dbo].[Tfc] WHERE TfcId = " + TfcId).ToList().First();

            if (fil != null)
            {
                string folderName  = "Tfcs";
                string webRootPath = _hostingEnvironment.WebRootPath;
                string newPath     = Path.Combine(webRootPath, folderName);

                if (!Directory.Exists(newPath))// Create New Directory if not exist as per the path
                {
                    Directory.CreateDirectory(newPath);
                }

                var fiName = Guid.NewGuid().ToString() + Path.GetExtension(fil.FileName);
                using (var fileStream = new FileStream(Path.Combine(newPath, fiName), FileMode.Create))
                {
                    fil.CopyTo(fileStream);
                }
                // Get uploaded file path with root
                string   fileName = @"wwwroot/Tfcs/" + fiName;
                FileInfo file     = new FileInfo(fileName);

                if (tfc.TfcFile != null)
                {
                    // Delete existing photo paths of the user from Directory
                    System.IO.DirectoryInfo di = new DirectoryInfo(newPath);
                    foreach (FileInfo filesDelete in di.GetFiles())
                    {
                        var name      = filesDelete.FullName;
                        var split     = name.Split("\\");
                        var finalPath = "wwwroot/Tfcs/" + split[split.Length - 1];

                        if (finalPath.Equals(tfc.TfcFile))
                        {
                            filesDelete.Delete();
                        }
                    }// End Deleting files from directories
                }

                tfc.TfcFile = file.ToString();
            }
            try
            {
                tfc.TfcType  = TfcType;
                tfc.Name     = Name;
                tfc.Details  = Details;
                tfc.Company  = Company;
                tfc.Location = Location;
                _context.SaveChanges();
                Alert("Tfc Editado!", "O " + TfcType + " selecionado foi editado com sucesso!", NotificationType.success);
            }
            catch
            {
                Alert("Ocorreu um erro!", "Não foi possivel alterar o " + TfcType + " selecionado!", NotificationType.error);
            }

            return(RedirectToAction("Index"));
        }
Beispiel #30
0
        public IActionResult EditProfiles(ProfileEdit pf, IFormFile picture)
        {
            var context = new masdatabaseContext();

            if (HttpContext.Session.GetInt32("Oid") == null)
            {
                return(RedirectToAction("Login", "User"));
            }
            else
            {
                SqlConnection sqlcon = new SqlConnection("Data Source=(LocalDb)\\MSSQLLocalDb;Initial Catalog=MasSql;Integrated Security=True");
                if (picture != null)
                {
                    var fileName = "";
                    var uploads  = Path.Combine(he.WebRootPath, "uploads\\img_profile");
                    fileName = Guid.NewGuid().ToString().Substring(0, 10) + Path.GetExtension(picture.FileName);
                    picture.CopyTo(new FileStream(Path.Combine(uploads, fileName), FileMode.Create));

                    if (pf.Picture != null)
                    {
                        var editOwner = context.Owner.First(a => a.Oid == HttpContext.Session.GetInt32("Oid"));
                        editOwner.Name    = pf.Name;
                        editOwner.Surname = pf.Surname;
                        editOwner.Tel     = pf.Tel;
                        context.SaveChanges();
                        sqlcon.Open();
                        string     query1  = "UPDATE owner SET Name='" + pf.Name + "',Surname='" + pf.Surname + "',Tel='" + pf.Tel + "' WHERE Oid = " + HttpContext.Session.GetInt32("Oid") + " ";
                        SqlCommand sqlcom1 = new SqlCommand(query1);
                        sqlcom1.Connection = sqlcon;
                        SqlDataReader sqlReader1 = sqlcom1.ExecuteReader();
                        sqlcon.Close();
                        TempData["EditSuccessful"] = "<script>swal({type: 'success', title: 'แก้ไขข้อมูลสำเร็จ', showConfirmButton: false,  timer: 1500,backdrop: 'rgba(0,0, 26,0.8)' })</script>";
                        HttpContext.Session.SetString("Name", pf.Name);
                        HttpContext.Session.SetString("Surname", pf.Surname);
                        HttpContext.Session.SetString("Tel", pf.Tel);
                        return(RedirectToAction("ManageDorm", "Manage"));
                    }
                    else
                    {
                        var editOwner = context.Owner.First(a => a.Oid == HttpContext.Session.GetInt32("Oid"));
                        editOwner.Name    = pf.Name;
                        editOwner.Surname = pf.Surname;
                        editOwner.Tel     = pf.Tel;
                        editOwner.Picture = fileName;
                        context.SaveChanges();
                        sqlcon.Open();
                        string     query1  = "UPDATE owner SET Name='" + pf.Name + "',Surname='" + pf.Surname + "',Tel='" + pf.Tel + "',Picture='" + fileName + "' WHERE Oid = " + HttpContext.Session.GetInt32("Oid") + " ";
                        SqlCommand sqlcom1 = new SqlCommand(query1);
                        sqlcom1.Connection = sqlcon;
                        SqlDataReader sqlReader1 = sqlcom1.ExecuteReader();
                        sqlcon.Close();
                        TempData["EditSuccessful"] = "<script>swal({type: 'success', title: 'แก้ไขข้อมูลสำเร็จ', showConfirmButton: false,  timer: 1500,backdrop: 'rgba(0,0, 26,0.8)' })</script>";
                        HttpContext.Session.SetString("Name", pf.Name);
                        HttpContext.Session.SetString("Surname", pf.Surname);
                        HttpContext.Session.SetString("Tel", pf.Tel);
                        HttpContext.Session.SetString("Picture", fileName);
                        return(RedirectToAction("ManageDorm", "Manage"));
                    }
                }
                else
                {
                    if (pf.Picture != null)
                    {
                        var editOwner = context.Owner.First(a => a.Oid == HttpContext.Session.GetInt32("Oid"));
                        editOwner.Name    = pf.Name;
                        editOwner.Surname = pf.Surname;
                        editOwner.Tel     = pf.Tel;
                        context.SaveChanges();
                        sqlcon.Open();
                        string     query1  = "UPDATE owner SET Name='" + pf.Name + "',Surname='" + pf.Surname + "',Tel='" + pf.Tel + "' WHERE Oid = " + HttpContext.Session.GetInt32("Oid") + " ";
                        SqlCommand sqlcom1 = new SqlCommand(query1);
                        sqlcom1.Connection = sqlcon;
                        SqlDataReader sqlReader1 = sqlcom1.ExecuteReader();
                        sqlcon.Close();
                        TempData["EditSuccessful"] = "<script>swal({type: 'success', title: 'แก้ไขข้อมูลสำเร็จ', showConfirmButton: false,  timer: 1500,backdrop: 'rgba(0,0, 26,0.8)' })</script>";
                        HttpContext.Session.SetString("Name", pf.Name);
                        HttpContext.Session.SetString("Surname", pf.Surname);
                        HttpContext.Session.SetString("Tel", pf.Tel);
                        return(RedirectToAction("ManageDorm", "Manage"));
                    }
                    else
                    {
                        var editOwner = context.Owner.First(a => a.Oid == HttpContext.Session.GetInt32("Oid"));
                        editOwner.Name    = pf.Name;
                        editOwner.Surname = pf.Surname;
                        editOwner.Tel     = pf.Tel;
                        context.SaveChanges();
                        sqlcon.Open();
                        string     query1  = "UPDATE owner SET Name='" + pf.Name + "',Surname='" + pf.Surname + "',Tel='" + pf.Tel + "' WHERE Oid = " + HttpContext.Session.GetInt32("Oid") + " ";
                        SqlCommand sqlcom1 = new SqlCommand(query1);
                        sqlcom1.Connection = sqlcon;
                        SqlDataReader sqlReader1 = sqlcom1.ExecuteReader();
                        sqlcon.Close();
                        TempData["EditSuccessful"] = "<script>swal({type: 'success', title: 'แก้ไขข้อมูลสำเร็จ', showConfirmButton: false,  timer: 1500,backdrop: 'rgba(0,0, 26,0.8)' })</script>";
                        HttpContext.Session.SetString("Name", pf.Name);
                        HttpContext.Session.SetString("Surname", pf.Surname);
                        HttpContext.Session.SetString("Tel", pf.Tel);
                        return(RedirectToAction("ManageDorm", "Manage"));
                    }
                }
            }
        }
        public IActionResult ImportUpload(IFormFile reportfile)
        {
            string folderName  = "UploadTFC";
            string webRootPath = _hostingEnvironment.WebRootPath;
            string newPath     = Path.Combine(webRootPath, folderName);

            // Delete Files from Directory
            System.IO.DirectoryInfo di = new DirectoryInfo(newPath);
            foreach (FileInfo filesDelete in di.GetFiles())
            {
                filesDelete.Delete();
            }// End Deleting files form directories

            if (!Directory.Exists(newPath))// Crate New Directory if not exist as per the path
            {
                Directory.CreateDirectory(newPath);
            }
            var fiName = Guid.NewGuid().ToString() + Path.GetExtension(reportfile.FileName);

            using (var fileStream = new FileStream(Path.Combine(newPath, fiName), FileMode.Create))
            {
                reportfile.CopyTo(fileStream);
            }
            // Get uploaded file path with root
            string   rootFolder = _hostingEnvironment.WebRootPath;
            string   fileName   = @"UploadTFC/" + fiName;
            FileInfo file       = new FileInfo(Path.Combine(rootFolder, fileName));

            using (ExcelPackage package = new ExcelPackage(file))
            {
                ExcelWorksheet workSheet  = package.Workbook.Worksheets[0];
                int            totalRows  = workSheet.Dimension.Rows;
                List <Tfc>     reportList = new List <Tfc>();
                for (int i = 2; i <= totalRows + 1; i++)
                {
                    try
                    {
                        string TfcType  = workSheet?.Cells[i, 1]?.Value?.ToString();
                        string Name     = workSheet?.Cells[i, 2]?.Value?.ToString();
                        string Details  = workSheet?.Cells[i, 3]?.Value?.ToString();
                        string Company  = workSheet?.Cells[i, 4]?.Value?.ToString();
                        string Location = workSheet?.Cells[i, 5]?.Value?.ToString();
                        string TfcFile  = workSheet?.Cells[i, 6]?.Value?.ToString();
                        if (TfcType != null)
                        {
                            reportList.Add(new Tfc
                            {
                                TfcType  = TfcType,
                                Name     = Name,
                                Details  = Details,
                                Company  = Company,
                                Location = Location,
                                TfcFile  = TfcFile,
                            });
                        }
                    }
                    catch (Exception Ex)
                    {
                        return(RedirectToAction("Index", "Tfcs"));
                    }
                }
                using (_context)
                {
                    _context.Tfc.AddRange(reportList);
                    _context.SaveChanges();
                    return(RedirectToAction("Index", "Tfcs"));
                }
            }
        }
Beispiel #32
0
        public async Task <IActionResult> Create(AnnoncerObjectViewModel objetVM, IFormFile pic, IList <IFormFile> attachments)
        {
            if (ModelState.IsValid)
            {
                //validation supplémentaire
                if (objetVM.CategorieID == 1000)
                {
                    List <Categorie> CategoryList = new List <Categorie>();

                    CategoryList = (from categorie in _context.Categories select categorie).ToList();
                    CategoryList.Insert(0, new Categorie {
                        CategorieId = 1000, Nom = "Select"
                    });
                    ViewBag.CategoryList = CategoryList;

                    ViewData["CategorieID"] = new SelectList(_context.Categories, "Nom", "Nom");

                    ModelState.AddModelError("", "Select Category");
                    return(View(objetVM));
                } //fin validation sup

                Objet objet = Mapper.Map <AnnoncerObjectViewModel, Objet>(objetVM);

                // Affectation des autres propriétés requise... (Vendeur, Miseur, DateInscription, imageUrl, ConfigurationAdmin, Categorie, List d'enchere et Liste de fichiers)
                var userManager = _serviceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                var userName    = await userManager.FindByNameAsync(User.Identity.Name);

                objet.Vendeur         = (Vendeur)userName;
                objet.DateInscription = DateTime.Now;


                if (pic != null)
                {
                    var file     = Path.GetFileName(pic.FileName);
                    var fileName = System.IO.Path.Combine(he.WebRootPath, "Uploads") + $@"\{file}";
                    pic.CopyTo(new FileStream(fileName, FileMode.Create));
                    objet.imageUrl = "Uploads/" + file;
                }

                //carles
                foreach (IFormFile item in attachments)
                {
                    if (item != null)
                    {
                        var attachmentfile     = Path.GetFileName(item.FileName);
                        var attachmentFileName = System.IO.Path.Combine(he.WebRootPath, "Attachments") + $@"\{attachmentfile}";
                        item.CopyTo(new FileStream(attachmentFileName, FileMode.Create));
                        objet.Fichiers = new List <Fichier>();
                        objet.Fichiers.Add(new Fichier()
                        {
                            NomOriginal = attachmentfile, NomLocale = attachmentFileName, verseLe = DateTime.Now
                        });
                    }
                }

                objet.Categorie          = _context.Categories.FirstOrDefault(p => p.CategorieId == objetVM.CategorieID);
                objet.ConfigurationAdmin = _context.ConfigurationAdmins.Last();
                objet.Encheres           = new List <Enchere>();
                // objet.Fichiers = new List<Fichier>();

                //Affectation d'une 1e mise.. (Par défaut celui qui crée un objet place une première mise sur son objet, comme ça il est facturé si jamais personne mise et il "remporte" son objet)
                Miseur miseur = (Miseur)userName;
                objet.Encheres.Add(new Enchere()
                {
                    Objet = objet, Niveau = objet.PrixDepart, MiseMax = objet.PrixDepart, Miseur = miseur
                });
                // Fin affection 1e mise


                // Fin affectation des autres propriétés requises

                //Ajout à la BD de l'Objet à vendre ainsi qu'une première mise par défaut
                _context.Add(objet);
                await _context.SaveChangesAsync();

                //Fin ajout BD

                //Ajout Arash pour mettre objet en status Vendu apres certain temp !!!!!!!!!!!!!! ces ligne du code doit être exactement ici !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                BackgroundJob.Schedule(() => ChangeStatus(objet.ObjetID), objet.DateLimite);


                TempData["message"] = $"Objet '{objet.Nom}' has been created for bidding starting now and ending at '{objet.DateLimite}'.";
                return(RedirectToAction(nameof(Index)));
            }

            foreach (var modelState in ViewData.ModelState.Values)
            {
                foreach (var error in modelState.Errors)
                {
                }
            }

            return(View(objetVM));
        }