コード例 #1
0
        public ActionResult Upload(FormCollection form)
        {
            if (Request.Files.Count == 0)
            {
      //Request.Files.Count 文件数为0上传不成功
      return View(); 
     }

            var file = Request.Files[0];
            if (file.ContentLength == 0)
            {
                //文件大小大(以字节为单位)为0时,做一些操作
                return View();
     }
     else
    {
      //文件大小不为0
      HttpPostedFileBase fileData = Request.Files[0];
      //保存成自己的文件全路径,newfile就是你上传后保存的文件,
      //服务器上的UpLoadFile文件夹必须有读写权限      
     // file.SaveAs(Server.MapPath(@"Upload"));
      UploadHelper helper = new UploadHelper("Http://192.168.0.24/File/File/Upload");
                  string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
                    byte[] buffer = new byte[fileData.InputStream.Length + 1]; // 上传文件字节数组大小
                    fileData.InputStream.Read(buffer, 0, buffer.Length);  // 把上传文件的大小放入 buffer里
                  var re=  helper.Post("apptest", "", fileName, buffer);
                  return Content(re.FileId);
    }
     
     
      
            
            return View();

        }
コード例 #2
0
ファイル: HomeController.cs プロジェクト: POORM80/ExcelImport
        public ActionResult Index(HttpPostedFileBase file)
        {
            try
            {
                if (file != null)
                {
                    string extension = Path.GetExtension(file.FileName);
                    if (extension.Equals(".xlsx"))
                    {
                        DateTime dt = DateTime.Now;
                        string filePath = "TransactionData";
                        string format = dt.ToString();
                        format = format.Replace('/', '_');
                        format = format.Replace(':', '_');
                        format = format.Replace(' ', '_');
                        filePath += "_" + format + ".xlsx";
                        string finalFilePath = Server.MapPath("~/Uploads/" + filePath);
                        file.SaveAs(finalFilePath);

                        UploadHelper objHelper = new UploadHelper(repository);
                        IList<Transaction> lstData = new List<Transaction>();
                        DataSet dsTransactions = objHelper.ReadExcelFile(finalFilePath);
                        DataView dvTransactions = dsTransactions.Tables[0].DefaultView;
                        if (dvTransactions.ToTable().Rows.Count > 0)
                        {
                            dvTransactions.RowFilter = "Error = ''";

                            foreach (DataRow dr in dvTransactions.ToTable().Rows)
                            {
                                lstData.Add(new Transaction { Account = Convert.ToString(dr[Constants.Account]), Description = Convert.ToString(dr[Constants.Description]), CurrencyCode = Convert.ToString(dr[Constants.Currency]), Amount = Convert.ToDecimal(dr[Constants.Amount]) });
                            }

                            repository.SaveTransaction(lstData);
                            ViewBag.UploadMsg = dvTransactions.ToTable().Rows.Count + " row(s) have been saved successfully.";
                        }
                        else
                        {
                            ViewBag.UploadMsg = "No valid data to be uploaded.";
                        }

                        return View("Index", dsTransactions);
                    }
                    else
                    {
                        ViewBag.Error = "Invalid File Format " + extension + " Valid File Format allowed is .xlsx";
                        return View("Index");
                    }
                }
                else
                {
                    ViewBag.Error = "Please select an excel file to upload";
                    return View("Index");
                }
            }
            catch(Exception ex)
            {
                ViewBag.Error = "Error occurred while processing your request";
                return View("Index");
            }
        }
コード例 #3
0
 public PixelPushingMode(BrowserLinkConnection connection)
 {
     ExtensionByConnection[connection] = this;
     _uploadHelper = new UploadHelper();
     _connection = connection;
     Settings.BrowserLinkOptions.SettingsUpdated += (sender, args) => _ignoreList = null;
 }
コード例 #4
0
 public UnusedCssExtension(BrowserLinkConnection connection)
 {
     ExtensionByConnection[connection] = this;
     _uploadHelper = new UploadHelper();
     _connection = connection;
     UnusedCssOptions.SettingsUpdated += InstallIgnorePatterns;
 }
コード例 #5
0
        public void FileUp(FormCollection form)
        {
            HttpContextBase context = this.HttpContext;
            context.Response.ContentType = "text/plain";

            //上传配置
            String pathbase = Url.Content("~/Uploads/Files/");                                      //保存路径
            string[] filetype = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv" };    //文件允许格式
            int size = 100;   //文件大小限制,单位MB,同时在web.config里配置环境默认为100MB

            //上传文件
            Hashtable info = new Hashtable();
            UploadHelper up = new UploadHelper();
            info = up.upFile(context, pathbase, filetype, size); //获取上传状态

            context.Response.Write("{'state':'" + info["state"] + "','url':'" + info["url"] + "','fileType':'" + info["currentType"] + "','original':'" + info["originalName"] + "'}"); //向浏览器返回数据json数据
        }
コード例 #6
0
        private ActionResult PrepareFileResult(IReport report, string ext, bool download,
            byte[] renderedBytes, ReportRegistry.Report reportInfo)
        {
            string fileDownloadName;
            var customFileName = report as ICustomFileName;
            if (customFileName != null)
                fileDownloadName = customFileName.GetFileName();
            else
                fileDownloadName = (reportInfo.Title ?? reportInfo.Key) + "_" +
                    DateTime.Now.ToString("yyyyMMdd_HHss");

            fileDownloadName += "." + ext;

            if (download)
            {
                return new FileContentResult(renderedBytes, "application/octet-stream")
                {
                    FileDownloadName = fileDownloadName
                };
            }

            Response.Headers["Content-Disposition"] = "inline;filename=" + System.Net.WebUtility.UrlEncode(fileDownloadName);
            return File(renderedBytes, UploadHelper.GetMimeType(fileDownloadName));
        }
コード例 #7
0
        public async Task <IActionResult> Create([Bind("ProductImageID,Name,IsMainImage,ImageUrl,ProductID")] ProductImage productImage)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                foreach (var image in files)
                {
                    if (image != null && image.Length > 0)
                    {
                        var file = image;
                        if (file.Length > 0)
                        {
                            try
                            {
                                UploadHelper helper = new UploadHelper(_environment);
                                var          names  = await helper.FileUploadAsync(file, "images/store", true);

                                productImage.ImageUrl = names.Filename;
                                productImage.Name     = names.Name;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                    }
                }

                _context.Add(productImage);
                await _context.SaveChangesAsync();

                return(Redirect("/Admin/Products/Details?id=" + productImage.ProductID));
            }
            ViewData["ProductID"] = new SelectList(_context.Products, "ProductID", "ProductID", productImage.ProductID);
            return(View(productImage));
        }
コード例 #8
0
ファイル: UploadController.cs プロジェクト: ncelsRS/ncelsRepo
        public ActionResult Remove(string[] fileNames, string documentId)
        {
            // The parameter of the Remove action must be called "fileNames"

            if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    var fileName = Path.GetFileName(fullName);
                    UploadHelper.DeleteFile(documentId, fileName);
                    //var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                    //// bbnrrf TODO: Verify user permissions

                    //if (System.IO.File.Exists(physicalPath)) {
                    //	// The files are not actually removed in this demo
                    //	// System.IO.File.Delete(physicalPath);
                    //}
                }
            }

            // Return an empty string to signify success
            return(Content(""));
        }
コード例 #9
0
        public ActionResult ICO(int type)
        {
            ResultInfo ri = new ResultInfo();

            HttpPostedFileBase upfile = Request.Files["file"];

            if (upfile == null)
            {
                ri.Msg = "请选择要上传的文件";
            }
            else
            {
                string fullPath = string.Empty;
                switch (type)
                {
                case 1: fullPath = "/favicon.ico"; break;

                case 2: fullPath = "/Content/U/Site/levelname.png"; break;

                case 3: fullPath = "/Content/U/Site/onlylevelname.png"; break;

                case 4: fullPath = "/Content/U/Site/master.png"; break;
                }
                int maxlength = Convert.ToInt32(ConfigHelper.AppSettings("UploadFileMax"));//最大上传大小/M
                if (upfile.ContentLength > maxlength * 1024 * 1024)
                {
                    ri.Msg = "上传文件最大只能是{0}M".FormatWith(maxlength);
                }
                else
                {
                    upfile.SaveAs(UploadHelper.GetMapPath(fullPath));
                    ri.Ok = true;
                }
            }
            return(Result(ri));
        }
コード例 #10
0
        public ActionResult Create([Bind(Include = "TicketId")] TicketAttachment ticketAttachment, string attachmentTitle, string attachmentDescription, HttpPostedFileBase attachment)
        {
            if (ModelState.IsValid)
            {
                ticketAttachment.Title       = attachmentTitle;
                ticketAttachment.Description = attachmentDescription;
                ticketAttachment.Created     = DateTime.Now;
                ticketAttachment.UserId      = User.Identity.GetUserId();

                if (UploadHelper.IsValidAttachment(attachment))
                {
                    var fileName = Path.GetFileName(attachment.FileName);
                    attachment.SaveAs(Path.Combine(Server.MapPath("~/Uploads/"), fileName));
                    ticketAttachment.AttachmentUrl = "/Uploads/" + fileName;
                }

                db.TicketAttachments.Add(ticketAttachment);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.TicketId = new SelectList(db.Tickets, "Id", "OwnerUserId", ticketAttachment.TicketId);
            return(View(ticketAttachment));
        }
コード例 #11
0
        private static async void OnMyTimedEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                Console.WriteLine("On timer event");
                DateTime nowDateTime = DateTime.Now.ToLocalTime();
                // Check that we are well connected
                if (Client != null && Client.IsConnected && UserId != 0)
                {
                    if (ChannelId != null && ChannelId.Count > 0)
                    {
                        TLAbsDialogs = await Client.GetUserDialogsAsync();

                        foreach (TLAbsMessage tLAbsMessage in ((TLDialogs)TLAbsDialogs).Messages.Where(x => x is TLMessage message && TimeUnixTOWindows(message.Date, true) >= nowDateTime.AddMilliseconds(-(TimerIntervalInMs - 1))))
                        {
                            ((TLMessage)tLAbsMessage).Message = CalculOffset(((TLMessage)tLAbsMessage).Message);
                            if (((TLMessage)tLAbsMessage).ToId is TLPeerUser tLPeerUser)
                            {
                                // Personal Chat Do Not Forward!
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel0 && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                int crtChannelId = channel0.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("ReplyChannelId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                    await ReplyMessage((TLMessage)tLAbsMessage);
                                }
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChat chat && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                Console.WriteLine("ReplyChatId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                await ReplyMessage((TLMessage)tLAbsMessage);
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel && ((TLMessage)tLAbsMessage).ReplyToMsgId == null)
                            {
                                int crtChannelId = channel.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("New Message Channel " + ChannelId[crtChannelId][0] + " \n" + ((TLMessage)tLAbsMessage).Message);
                                    if (ChannelId.ContainsKey(crtChannelId))
                                    {
                                        if (((TLMessage)tLAbsMessage).Message != "")
                                        {
                                            if (((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("tp") || ((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("sl"))
                                            {
                                                TLChannelMessages historyFromSourceCanal = (TLChannelMessages)await Client.GetHistoryAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = channel.ChannelId, AccessHash = (long)ChannelId[channel.ChannelId][1]
                                                });

                                                List <TLAbsMessage> tLMessageList        = historyFromSourceCanal.Messages.ToList().Where(x => x is TLMessage tL).ToList();
                                                List <TLMessage>    orderedtLMessageList = tLMessageList.Cast <TLMessage>().OrderByDescending(x => x.Id).ToList();
                                                string newMessage = CalculOffset(orderedtLMessageList[1].Message + "\n" + ((TLMessage)tLAbsMessage).Message);
                                                if (orderedtLMessageList[1].Message.ToLower().Contains("sell") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("vente") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("buy") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("achat") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                            }
                                            else
                                            {
                                                await Client.SendMessageAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, ((TLMessage)tLAbsMessage).Message);
                                            }
                                        }
                                        else if (((TLMessage)tLAbsMessage).Media != null)
                                        {
                                            if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaPhoto")
                                            {
                                                TLMessageMediaPhoto    tLMessageMediaPhoto    = (TLMessageMediaPhoto)((TLMessage)tLAbsMessage).Media;
                                                TLPhoto                tLPhoto                = (TLPhoto)tLMessageMediaPhoto.Photo;
                                                TLPhotoSize            tLPhotoSize            = tLPhoto.Sizes.ToList().OfType <TLPhotoSize>().Last();
                                                TLFileLocation         tLFileLocation         = (TLFileLocation)tLPhotoSize.Location;
                                                TLAbsInputFileLocation tLAbsInputFileLocation = new TLInputFileLocation()
                                                {
                                                    LocalId  = tLFileLocation.LocalId,
                                                    Secret   = tLFileLocation.Secret,
                                                    VolumeId = tLFileLocation.VolumeId
                                                };
                                                TLInputFileLocation TLInputFileLocation = tLAbsInputFileLocation as TLInputFileLocation;
                                                TLFile buffer = await Client.GetFile(TLInputFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, "", new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedPhoto(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaPhoto.Caption);
                                            }
                                            else if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaDocument")
                                            {
                                                TLMessageMediaDocument            tLMessageMediaDocument      = (TLMessageMediaDocument)((TLMessage)tLAbsMessage).Media;
                                                TLDocument                        tLDocument                  = (TLDocument)tLMessageMediaDocument.Document;
                                                TLVector <TLAbsDocumentAttribute> tLAbsDocumentAttributes     = tLDocument.Attributes;
                                                TLInputDocumentFileLocation       tLInputDocumentFileLocation = new TLInputDocumentFileLocation()
                                                {
                                                    AccessHash = tLDocument.AccessHash,
                                                    Id         = tLDocument.Id,
                                                    Version    = tLDocument.Version,
                                                };
                                                TLFile buffer = await Client.GetFile(tLInputDocumentFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, ((TLDocumentAttributeFilename)tLAbsDocumentAttributes[0]).FileName, new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedDocument(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaDocument.Caption, tLDocument.MimeType, tLAbsDocumentAttributes);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
コード例 #12
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var rowF = RowsRow.Fields;

            var proj = ProjectorsRow.Fields;
            var phas = PhasesRow.Fields;
            var clie = ClientsRow.Fields;
            var part = PartsRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 2; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var rowReaded = uow.Connection.TryFirst <RowsRow>(q => q
                                                                      .Select(rowF.RowId)
                                                                      .Where(
                                                                          rowF.ClientName == Convert.ToString(worksheet.Cells[row, 2].Value ?? "") &&
                                                                          rowF.ClassifierNumber == Convert.ToInt16(worksheet.Cells[row, 3].Value ?? 0) &&
                                                                          rowF.Number == Convert.ToInt16(worksheet.Cells[row, 4].Value ?? 0)));

                    if (rowReaded == null)
                    {
                        rowReaded = new RowsRow {
                        }
                    }
                    ;
                    else
                    {
                        // avoid assignment errors
                        rowReaded.TrackWithChecks = false;
                    }

                    var projectorName = Convert.ToString(worksheet.Cells[row, 7].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(projectorName))
                    {
                        var project = uow.Connection.TryFirst <ProjectorsRow>(q => q
                                                                              .Select(proj.ProjectorId)
                                                                              .Where(proj.Name == projectorName));

                        if (project == null)
                        {
                            project = new ProjectorsRow
                            {
                                Name = projectorName
                            };
                            var phaseId = Convert.ToInt32(uow.Connection.InsertAndGetID(project));
                            rowReaded.ProjectorId = phaseId;
                        }
                        else
                        {
                            rowReaded.ProjectorId = project.ProjectorId.Value;
                        }
                    }
                    else
                    {
                        response.ErrorList.Add("Error On Row " + row + ", Projector Name can't be empty");
                        continue;
                    }

                    var phaseName = Convert.ToString(worksheet.Cells[row, 10].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(phaseName))
                    {
                        var phase = uow.Connection.TryFirst <PhasesRow>(q => q
                                                                        .Select(phas.PhaseId)
                                                                        .Where(phas.Name == phaseName));

                        if (phase == null)
                        {
                            phase = new PhasesRow
                            {
                                Name = phaseName
                            };
                            var phaseId = Convert.ToInt32(uow.Connection.InsertAndGetID(phase));
                            rowReaded.PhaseId = phaseId;
                        }
                        else
                        {
                            rowReaded.PhaseId = phase.PhaseId.Value;
                        }
                    }
                    else
                    {
                        response.ErrorList.Add("Error On Row " + row + ", Phase Name can't be empty");
                        continue;
                    }


                    var clientName = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(clientName))
                    {
                        var client = uow.Connection.TryFirst <ClientsRow>(q => q
                                                                          .Select(clie.ClientsId)
                                                                          .Where(clie.Name == clientName));

                        if (client == null)
                        {
                            client = new ClientsRow
                            {
                                Name = clientName
                            };
                            var clientId = Convert.ToInt32(uow.Connection.InsertAndGetID(client));
                            rowReaded.ClientId = clientId;
                        }
                        else
                        {
                            rowReaded.ClientId = client.ClientsId.Value;
                        }
                    }
                    else
                    {
                        response.ErrorList.Add("Error On Row " + row + ", Client Name can't be empty");
                        continue;
                    }


                    var partName = Convert.ToString(worksheet.Cells[row, 9].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(partName))
                    {
                        var parts = uow.Connection.TryFirst <PartsRow>(q => q
                                                                       .Select(part.PartId)
                                                                       .Where(part.Name == partName));

                        if (parts == null)
                        {
                            parts = new PartsRow()
                            {
                                Name = partName
                            };
                            var partId = Convert.ToInt32(uow.Connection.InsertAndGetID(parts));
                            rowReaded.PartId = partId;
                        }
                        else
                        {
                            rowReaded.PartId = parts.PartId.Value;
                        }
                    }
                    else
                    {
                        response.ErrorList.Add("Error On Row " + row + ", Part Name can't be empty");
                        continue;
                    }



                    rowReaded.ClassifierNumber = Convert.ToInt16(worksheet.Cells[row, 3].Value ?? 0);
                    rowReaded.Number           = Convert.ToInt16(worksheet.Cells[row, 4].Value ?? 0);
                    rowReaded.Object           = Convert.ToString(worksheet.Cells[row, 5].Value ?? "");
                    rowReaded.SubObject        = Convert.ToString(worksheet.Cells[row, 6].Value ?? "");
                    rowReaded.Date             = DateTime.Parse(worksheet.Cells[row, 8].Value.ToString(), System.Globalization.CultureInfo.CreateSpecificCulture("bg-BG"));
                    rowReaded.FoldersCount     = Convert.ToString(worksheet.Cells[row, 11].Value ?? "");

                    if (rowReaded.RowId == null)
                    {
                        new MyRepository().Create(uow, new SaveRequest <MyRow>
                        {
                            Entity = rowReaded
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new MyRepository().Update(uow, new SaveRequest <MyRow>
                        {
                            Entity   = rowReaded,
                            EntityId = rowReaded.RowId.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }

            return(response);
        }
コード例 #13
0
        public ActionResult UploadImage()
        {
            string filePath = "/Upload/ProductPhoto/Original/" + RequestHelper.DateNow.ToString("yyyyMM") + "/";

            if (FileHelper.SafeFullDirectoryName(filePath))
            {
                try
                {
                    //上传文件
                    UploadHelper upload = new UploadHelper();
                    upload.Path           = "/Upload/ProductPhoto/Original/" + RequestHelper.DateNow.ToString("yyyyMM") + "/";
                    upload.FileType       = ShopConfig.ReadConfigInfo().UploadFile;
                    upload.FileNameType   = FileNameType.Guid;
                    upload.MaxWidth       = ShopConfig.ReadConfigInfo().AllImageWidth;  //整站图片压缩开启后的压缩宽度
                    upload.AllImageIsNail = ShopConfig.ReadConfigInfo().AllImageIsNail; //整站图片压缩开关
                    int needNail = RequestHelper.GetQueryString <int>("NeedNail");
                    if (needNail <= 0)
                    {
                        upload.AllImageIsNail = 0;                                       //如果页面传值不压缩图片,以页面传值为准;
                    }
                    int curMaxWidth = RequestHelper.GetQueryString <int>("CurMaxWidth"); //页面传值最大宽度
                    if (curMaxWidth > 0)
                    {
                        upload.AllImageIsNail = 1;
                        upload.MaxWidth       = curMaxWidth;//如果有页面传值设置图片最大宽度,以页面传值为准
                    }
                    FileInfo file      = null;
                    int      waterType = ShopConfig.ReadConfigInfo().WaterType;

                    //前台上传图片不打水印直接保存
                    file = upload.SaveAs();

                    //生成处理
                    string originalFile = upload.Path + file.Name;
                    string otherFile    = string.Empty;
                    string makeFile     = string.Empty;

                    Dictionary <int, int> dic = new Dictionary <int, int>();

                    if (!dic.ContainsKey(75))
                    {
                        dic.Add(75, 75);                      //后台商品图集默认使用尺寸(如果不存在则手动添加)
                    }
                    foreach (KeyValuePair <int, int> de in dic)
                    {
                        makeFile   = originalFile.Replace("Original", de.Key + "-" + de.Value);
                        otherFile += makeFile + "|";
                        ImageHelper.MakeThumbnailImage(ServerHelper.MapPath(originalFile), ServerHelper.MapPath(makeFile), Convert.ToInt32(de.Key), Convert.ToInt32(de.Value), ThumbnailType.AllFix);
                    }
                    otherFile = otherFile.Substring(0, otherFile.Length - 1);
                    int proStyle = RequestHelper.GetForm <int>("proStyle");
                    if (proStyle < 0)
                    {
                        proStyle = 0;
                    }

                    int pcid = RequestHelper.GetForm <int>("pcid");
                    ProductPhotoInfo productPhoto = new ProductPhotoInfo();
                    productPhoto.ProductId = pcid;
                    productPhoto.ImageUrl  = originalFile;
                    productPhoto.ProStyle  = proStyle;
                    productPhoto.OrderId   = 0;

                    ProductPhotoBLL.Add(productPhoto);
                    return(Content("ok|" + originalFile.Replace("Original", "75-75")));
                }
                catch (Exception ex)
                {
                    return(Content(ex.Message));
                }
            }
            else
            {
                return(Content(ShopLanguage.ReadLanguage("ErrorPathName")));
            }
        }
コード例 #14
0
        public async Task <IActionResult> EMailSend([Bind("OrderID, Email, Subject, Message, Attachments")] OrderEmailViewModel orderEmail)
        {
            if (ModelState.IsValid)
            {
                OrderViewModel vm   = null;
                BankAcccount   bank = null;

                if (orderEmail.OrderID == null)
                {
                    return(NotFound());
                }
                else
                {
                    vm = await GetOrderViewModel(orderEmail.OrderID);

                    bank = await _context.BankAcccounts.FirstOrDefaultAsync();

                    string bill = $"<h2>Hallo Frau/Herr {vm.CutomerLastName},</h2>" +
                                  $"<p>noch einmal vielen Dank für Ihren Einkauf.</p>" +
                                  $"<p>Bitte überweisen Sie den Gesamtbetrag von <b>{Math.Round(vm.Total, 2)} &euro;</b> innerhalb von 7 Tagen unter Angabe der Rechungsnummer:<br/>" +
                                  $"<b>{orderEmail.Message}</b><br />" +
                                  $"auf das folgende Konto:</p>" +
                                  $"<br />" +
                                  $"<p>Kontoinhaber:<b> {bank.AccountOwner}</b><br />" +
                                  $"IBAN: <b>{bank.Iban}</b><br />" +
                                  $"SWIFT-BIC: <b>{bank.SwiftBic}</b><br />" +
                                  $"Bank: <b>{bank.Institute}</b></p><br />";
                    bill += $"<hr /><h3>Rechungsdetails</h3>" +
                            $"<p>Ihre Bestellung vom {vm.OrderDate.ToShortDateString()}</p>";
                    if (!string.IsNullOrWhiteSpace(vm.FreeText))
                    {
                        bill += $"<p>Ihre Angaben zur Bestellung: <b>{vm.FreeText}</b></p>";
                    }
                    bill += $"<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" height=\"15%\" width=\"75%\"><tr><th>Position</th><th>Artikel-Nr.</th><th>Artikelname</th><th>Menge</th><th>Betrag</th></tr>";
                    foreach (var item in vm.OderLines)
                    {
                        bill += $"<tr><td align=\"center\">{item.Position}</td>" +
                                $"<td align=\"center\">{item.ProductNumber}</td>" +
                                $"<td align=\"center\">{item.ProductName}</td>" +
                                $"<td align=\"center\">{Math.Round(item.OrderQuantity, 2)} {item.OrderUnit}</td>" +
                                $"<td align=\"center\">{Math.Round(item.OrderLineTotal,2)} &euro;</td></tr>";
                    }
                    bill += $"</table><br />" +
                            $"<table cellpadding=\"0\" cellspacing=\"1\" height=\"5%\" width=\"85%\">" +
                            $"<tr>" +
                            $"<td align=\"right\" colspan=\"4\">Versand, {vm.ShippingPriceName}:</td>" +
                            $"<td>{Math.Round(vm.ShippingPriceAtOrder,2)} &euro;</td></tr>" +
                            $"<tr>" +
                            $"<td align=\"right\" colspan=\"4\">Gesamtbetrag:</td><td>{Math.Round(vm.Total,2)} &euro;</td></tr>" +
                            $"</table>" +
                            $"<br />" +
                            $"<p>Die Lieferfrist beginnt mit der Zahlungsanweisung.</p>" +
                            $"<br />" +
                            $"<p>Viele Gr&uuml;&szlig;e,</p><p>Petra Buron</p><br />";
                    var attachments = new List <string>();
                    var files       = HttpContext.Request.Form.Files;
                    if (files != null && files.Count > 0)
                    {
                        //var file = files.First();
                        var helper = new UploadHelper(_environment);
                        var todel  = new List <string>();


                        foreach (var file in files)
                        {
                            var fnames = await helper.FileUploadAsync(file, "files", false);

                            todel.Add(fnames.Filename);
                            attachments.Add(fnames.Filename);
                        }

                        foreach (string file in todel)
                        {
                            helper.DeleteFile("files", file);
                        }
                    }

                    var agb = await _context.ShopFiles.SingleAsync(s => s.ShopFileType == Enums.ShopFileTypeEnum.AGB);

                    var wiederruf = await _context.ShopFiles.SingleAsync(s => s.ShopFileType == Enums.ShopFileTypeEnum.WRB);

                    var datenschutz = await _context.ShopFiles.SingleAsync(s => s.ShopFileType == Enums.ShopFileTypeEnum.DSK);

                    attachments.Add(agb.Filename);
                    attachments.Add(wiederruf.Filename);
                    attachments.Add(datenschutz.Filename);

                    await _emailSender.SendEmailWithAttachmentsAsync(orderEmail.Email, orderEmail.Subject, bill, attachments);

                    return(RedirectToAction(nameof(Index)));
                }
            }
            return(View(orderEmail));
        }
コード例 #15
0
        private void DeleteOldFile(FilesToDelete filesToDelete, string oldFilename)
        {
            if (!oldFilename.IsEmptyOrNull())
            {
                var actualOldFile = (attr.SubFolder.IsEmptyOrNull() ? "" : (attr.SubFolder + "/")) + oldFilename;
                filesToDelete.RegisterOldFile(actualOldFile);

                if (attr.CopyToHistory)
                {
                    var    oldFilePath = UploadHelper.ToPath(actualOldFile);
                    string date        = DateTime.UtcNow.ToString("yyyyMM", Invariants.DateTimeFormat);
                    string historyFile = "history/" + date + "/" + Path.GetFileName(oldFilePath);
                    if (File.Exists(UploadHelper.DbFilePath(oldFilePath)))
                    {
                        UploadHelper.CopyFileAndRelated(UploadHelper.DbFilePath(oldFilePath), UploadHelper.DbFilePath(historyFile), overwrite: true);
                    }
                }
            }
        }
コード例 #16
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "Filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var c = CategoryRow.Fields;
            var t = CategoryTypeRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 2; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var categoryName = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    if (categoryName.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var category = uow.Connection.TryFirst <CategoryRow>(q => q
                                                                         .Select(c.CategoryID)
                                                                         .Where(c.CategoryName == categoryName));

                    if (category == null)
                    {
                        category = new CategoryRow
                        {
                            CategoryName = categoryName
                        }
                    }
                    ;
                    else
                    {
                        category.TrackWithChecks = false;
                    }

                    #region Type

                    var typeName = Convert.ToString(worksheet.Cells[row, 1].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(typeName))
                    {
                        var type = uow.Connection.TryFirst <CategoryTypeRow>(q => q
                                                                             .Select(t.CategoryTypeID)
                                                                             .Where(t.CategoryType == typeName));

                        if (type == null)
                        {
                            response.ErrorList.Add("Error On Row" + row + ": Category with name '" +
                                                   typeName + "' is not found!");
                            continue;
                        }

                        category.CategoryTypeID = Convert.ToInt16(type.CategoryTypeID.Value);
                    }
                    else
                    {
                        category.CategoryTypeID = null;
                    }

                    #endregion Type

                    category.CategoryCode = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    category.Description  = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");

                    if (category.CategoryID == null)
                    {
                        new CategoryRepository().Create(uow, new SaveWithLocalizationRequest <MyRow>
                        {
                            Entity = category
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new CategoryRepository().Update(uow, new SaveWithLocalizationRequest <MyRow>
                        {
                            Entity   = category,
                            EntityId = category.CategoryID.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }

            return(response);
        }
コード例 #17
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var p = ProductRow.Fields;
            var s = SupplierRow.Fields;
            var c = CategoryRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 2; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var productName = Convert.ToString(worksheet.Cells[row, 1].Value ?? "");
                    if (productName.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var product = uow.Connection.TryFirst <ProductRow>(q => q
                                                                       .Select(p.ProductID)
                                                                       .Where(p.ProductName == productName));

                    if (product == null)
                    {
                        product = new ProductRow
                        {
                            ProductName = productName
                        }
                    }
                    ;
                    else
                    {
                        // avoid assignment errors
                        product.TrackWithChecks = false;
                    }

                    var supplierName = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(supplierName))
                    {
                        var supplier = uow.Connection.TryFirst <SupplierRow>(q => q
                                                                             .Select(s.SupplierID)
                                                                             .Where(s.CompanyName == supplierName));

                        if (supplier == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Supplier with name '" +
                                                   supplierName + "' is not found!");
                            continue;
                        }

                        product.SupplierID = supplier.SupplierID.Value;
                    }
                    else
                    {
                        product.SupplierID = null;
                    }

                    var categoryName = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(categoryName))
                    {
                        var category = uow.Connection.TryFirst <CategoryRow>(q => q
                                                                             .Select(c.CategoryID)
                                                                             .Where(c.CategoryName == categoryName));

                        if (category == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Category with name '" +
                                                   categoryName + "' is not found!");
                            continue;
                        }

                        product.CategoryID = category.CategoryID.Value;
                    }
                    else
                    {
                        product.CategoryID = null;
                    }

                    product.QuantityPerUnit = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    product.UnitPrice       = Convert.ToDecimal(worksheet.Cells[row, 5].Value ?? 0);
                    product.UnitsInStock    = Convert.ToInt16(worksheet.Cells[row, 6].Value ?? 0);
                    product.UnitsOnOrder    = Convert.ToInt16(worksheet.Cells[row, 7].Value ?? 0);
                    product.ReorderLevel    = Convert.ToInt16(worksheet.Cells[row, 8].Value ?? 0);

                    if (product.ProductID == null)
                    {
                        new ProductRepository().Create(uow, new SaveRequest <MyRow>
                        {
                            Entity = product
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new ProductRepository().Update(uow, new SaveRequest <MyRow>
                        {
                            Entity   = product,
                            EntityId = product.ProductID.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }

            return(response);
        }
コード例 #18
0
        public void addItems(UploadItemVO obj)
        {
            uploadDetail.uploading_FileCountLabel.Text = "正在上传" + uploadHelper.voList.Count + "个文档";
            Panel gb1 = new Panel();

            gb1.Width  = 260;
            gb1.Height = 40;
            gb1.Left   = 38;
            PictureBox filePic = new PictureBox();

            //filePic.Image = Image.FromFile(@"../../Resources/images/word.png");
            //filePic.Image = global::GovDocSearch.Properties.Resources.word_24;
            filePic.Image  = UploadHelper.getImage(obj.fileExtension);
            filePic.Width  = 40;
            filePic.Height = 40;
            Label fileName = new Label();

            fileName.Text  = obj.fileName;
            fileName.Width = 200;
            fileName.Left  = 50;
            Label fileSize = new Label();

            fileSize.Font = new Font("微软雅黑", 9, fileName.Font.Style);
            fileSize.Text = Helper.ByteConvertGBMBKB(obj.fileSize);
            fileSize.Top  = 25;
            fileSize.Left = 51;
            gb1.Controls.Add(filePic);
            gb1.Controls.Add(fileName);
            gb1.Controls.Add(fileSize);
            Controls.Add(gb1);


            //Controls.Add(timeLabel);

            ProgressBar pbar = new ProgressBar();

            pbar.Top = 6;
            //pbar.BackColor = Color.Gray;
            pbar.ForeColor = Color.Blue;
            pbar.Width     = 150;
            pbar.Left      = 300;
            pbar.Maximum   = comps.vo.maximum;
            pbar.Minimum   = comps.vo.minimum;
            Controls.Add(pbar);

            Label labelProgressBar = new Label();

            labelProgressBar.Top   = 6;
            labelProgressBar.Width = 65;
            //labelProgressBar.BackColor = Color.Transparent;
            labelProgressBar.ForeColor = Color.Red;
            labelProgressBar.Left      = 470;
            //labelProgressBar.Visible = false;
            //labelProgressBar.Text = comps.vo.minimum.ToString() + "%";
            Controls.Add(labelProgressBar);

            Label fileStatus    = new Label();
            Label fileStatusTip = new Label();

            //fileStatus.Font = new Font("微软雅黑",9);
            fileStatus.Text       = "上传中";
            fileStatus.Width      = 150;
            fileStatus.Top        = 6;
            fileStatus.Left       = 547;
            fileStatusTip.Font    = new Font("微软雅黑", 9);
            fileStatusTip.Visible = false;
            fileStatusTip.Text    = "";
            fileStatusTip.Width   = 170;
            fileStatusTip.Top     = 20;
            fileStatusTip.Left    = 542;
            Controls.Add(fileStatus);
            Controls.Add(fileStatusTip);
            FlowLayoutPanel gb2 = new FlowLayoutPanel();

            //TableLayoutPanel gb2 = new TableLayoutPanel();
            //gb2.ColumnCount = 3;
            //gb2.RowCount = 1;
            gb2.Top   = 5;
            gb2.Left  = 715;
            gb2.Width = 60;
            //gb2.Width = 72;
            //gb2.Height = 24;
            //foreach (ColumnStyle cs in gb2.ColumnStyles)
            //{
            //    cs.Width = 24;
            //}
            PictureBox start = new PictureBox();

            start.Width  = 18;
            start.Height = 18;
            //start.Image = Image.FromFile(@"../../Resources/images/start.png");
            start.Image       = global::GovDocSearch.Properties.Resources.start;
            start.Cursor      = Cursors.Hand;
            start.MouseClick += OnStartMouseClick;
            start.Visible     = false;
            ToolTip startTip = new ToolTip();

            startTip.SetToolTip(start, "开始上传");
            PictureBox pause = new PictureBox();

            pause.Width  = 18;
            pause.Height = 18;
            //pause.Image = Image.FromFile(@"../../Resources/images/pause.png");
            pause.Image  = global::GovDocSearch.Properties.Resources.pause;
            pause.Cursor = Cursors.Hand;
            ToolTip pauseTip = new ToolTip();

            pauseTip.SetToolTip(pause, "暂停上传");
            pause.MouseClick += OnPauseMouseClick;
            PictureBox del = new PictureBox();

            del.Width  = 18;
            del.Height = 18;
            //del.Image = Image.FromFile(@"../../Resources/images/del.png");
            del.Image  = global::GovDocSearch.Properties.Resources.del;
            del.Cursor = Cursors.Hand;
            ToolTip delTip = new ToolTip();

            delTip.SetToolTip(del, "删除");
            del.MouseClick += OnDelMouseClick;
            gb2.Controls.Add(start);
            gb2.Controls.Add(pause);
            gb2.Controls.Add(del);
            //gb2.Controls.Add(start, 0, 0);
            //gb2.Controls.Add(pause, 1, 0);
            //gb2.Controls.Add(del, 2, 0);
            Controls.Add(gb2);

            comps.progressBar      = pbar;
            comps.fileStatus       = fileStatus;
            comps.fileStatusTip    = fileStatusTip;
            comps.btnPanel         = gb2;
            comps.start            = start;
            comps.pause            = pause;
            comps.del              = del; //
            comps.labelProgressBar = labelProgressBar;
        }
コード例 #19
0
        private WfContent SaveAttachment(string parentPath, Attachment attachment, bool overwrite)
        {
            var parent = Node.LoadNode(parentPath);

            if (parent == null)
            {
                throw new ApplicationException("Cannot create content because parent does not exist. Path: " + parentPath);
            }

            var fileAttachment = attachment as FileAttachment;
            var name           = fileAttachment.Name;

            // check existing file
            var node = Node.LoadNode(RepositoryPath.Combine(parentPath, name));

            var  contentTypeName = UploadHelper.GetContentType(name, parentPath) ?? "File";
            File file;

            if (node == null)
            {
                // file does not exist, create new one
                file = CreateAttachment.CreateFileContent(contentTypeName, parent, name);
                if (file == null)
                {
                    return(null);
                }
            }
            else
            {
                // file exists
                if (overwrite)
                {
                    // overwrite it, so we open it
                    file = node as File;

                    // node exists and it is not a file -> delete it and create a new one
                    if (file == null)
                    {
                        node.ForceDelete();
                        file = CreateAttachment.CreateFileContent(contentTypeName, parent, name);
                        if (file == null)
                        {
                            return(null);
                        }
                    }

                    file.Name = name;
                }
                else
                {
                    // do not overwrite it
                    file = CreateAttachment.CreateFileContent(contentTypeName, parent, name);
                    if (file == null)
                    {
                        return(null);
                    }

                    file.AllowIncrementalNaming = true;
                }
            }

            file.DisableObserver(typeof(WorkflowNotificationObserver));

            try
            {
                // also saves the content
                ExchangeHelper.SetAttachment(file, fileAttachment);
            }
            catch (Exception e)
            {
                Logger.WriteException(e);
            }
            return(new WfContent(file));
        }
コード例 #20
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var m   = MobileTeamRow.Fields;
            var d   = DistrictRow.Fields;
            var r   = RoundRow.Fields;
            var usr = Administration.Entities.UserRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 3; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var roundName1   = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    var provName     = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    var districtName = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    if (districtName.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var mobileteam = uow.Connection.TryFirst <MobileTeamRow>(q => q
                                                                             .Select(m.MobileTeamId)
                                                                             .Where(m.DistrictDcode == districtName & m.RoundName == roundName1 & m.Province == provName));

                    if (mobileteam == null)
                    {
                        mobileteam = new MobileTeamRow
                        {
                            Province      = provName,
                            DistrictDcode = districtName,
                            RoundName     = roundName1
                        }
                    }
                    ;
                    else
                    {
                        // avoid assignment errors
                        mobileteam.TrackWithChecks = false;
                    }

                    var dName = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(dName))
                    {
                        var district = uow.Connection.TryFirst <DistrictRow>(q => q
                                                                             .Select(d.DistrictId)
                                                                             .Where(d.Dcode == dName & d.Pname == provName));

                        if (district == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": District with name '" +
                                                   districtName + "' is not found!");
                            continue;
                        }

                        mobileteam.DistrictId = district.DistrictId.Value;
                    }
                    else
                    {
                        mobileteam.DistrictId = null;
                    }

                    var roundName = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(roundName))
                    {
                        var round = uow.Connection.TryFirst <RoundRow>(q => q
                                                                       .Select(r.RoundId)
                                                                       .Where(r.RoundName == roundName));

                        if (round == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Round with name '" +
                                                   roundName + "' is not found!");
                            continue;
                        }

                        mobileteam.RoundId = round.RoundId.Value;
                    }
                    else
                    {
                        mobileteam.RoundId = null;
                    }

                    mobileteam.Nomads           = Convert.ToInt16(worksheet.Cells[row, 5].Value ?? 0);
                    mobileteam.Gypsis           = Convert.ToInt16(worksheet.Cells[row, 6].Value ?? 0);
                    mobileteam.BlueMosque       = Convert.ToInt16(worksheet.Cells[row, 7].Value ?? 0);
                    mobileteam.IDPs             = Convert.ToInt16(worksheet.Cells[row, 8].Value ?? 0);
                    mobileteam.Returnees        = Convert.ToInt16(worksheet.Cells[row, 9].Value ?? 0);
                    mobileteam.Kindergarden     = Convert.ToInt16(worksheet.Cells[row, 10].Value ?? 0);
                    mobileteam.Madrasa          = Convert.ToInt16(worksheet.Cells[row, 11].Value ?? 0);
                    mobileteam.EPICenters       = Convert.ToInt16(worksheet.Cells[row, 12].Value ?? 0);
                    mobileteam.BusStation       = Convert.ToInt16(worksheet.Cells[row, 13].Value ?? 0);
                    mobileteam.Prison           = Convert.ToInt16(worksheet.Cells[row, 14].Value ?? 0);
                    mobileteam.MobileTeams      = Convert.ToInt16(worksheet.Cells[row, 15].Value ?? 0);
                    mobileteam.CheckPost        = Convert.ToInt16(worksheet.Cells[row, 16].Value ?? 0);
                    mobileteam.PrivateClinics   = Convert.ToInt16(worksheet.Cells[row, 17].Value ?? 0);
                    mobileteam.Daramsal         = Convert.ToInt16(worksheet.Cells[row, 18].Value ?? 0);
                    mobileteam.HotelGuestHouses = Convert.ToInt16(worksheet.Cells[row, 19].Value ?? 0);
                    mobileteam.Crosborder       = Convert.ToInt16(worksheet.Cells[row, 20].Value ?? 0);
                    mobileteam.School           = Convert.ToInt16(worksheet.Cells[row, 21].Value ?? 0);
                    mobileteam.Others           = Convert.ToInt16(worksheet.Cells[row, 22].Value ?? 0);

                    var user = User.Identity.Name;
                    if (!string.IsNullOrWhiteSpace(user))
                    {
                        var Users = uow.Connection.TryFirst <Administration.Entities.UserRow>(q => q
                                                                                              .Select(usr.TenantId)
                                                                                              .Where(usr.Username == user));

                        if (Users == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": TenantID with name '" +
                                                   Users + "' is not found!");
                            continue;
                        }

                        mobileteam.TenantId = Users.TenantId.Value;
                    }
                    else
                    {
                        mobileteam.TenantId = null;
                    }

                    if (mobileteam.MobileTeamId == null)
                    {
                        new MobileTeamRepository().Create(uow, new SaveRequest <MyRow>
                        {
                            Entity = mobileteam
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new MobileTeamRepository().Update(uow, new SaveRequest <MyRow>
                        {
                            Entity   = mobileteam,
                            EntityId = mobileteam.MobileTeamId.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }


            return(response);
        }
コード例 #21
0
        public bool HandleUploadedFile(int BookingId, ENums.UploadXMLType uploadXMLType, ArrayList RecordList)
        {
            UploadHelper uploadHelper = new UploadHelper();

            return(uploadHelper.HandleUploadedFile(BookingId, uploadXMLType, RecordList));
        }
コード例 #22
0
 public PixelPushingMode(BrowserLinkConnection connection)
 {
     ExtensionByConnection[connection] = this;
     _uploadHelper = new UploadHelper();
     _connection = connection;
 }
コード例 #23
0
        /// <summary>
        /// 涂鸦上传
        /// </summary>
        public void ScrawlImgUp()
        {
            HttpContextBase context = this.HttpContext;
            context.Response.ContentType = "text/html";
            string action = context.Request["action"];

            if (action == "tmpImg")
            {
                //上传配置
                string pathbase = Url.Content("~/Uploads/Temps/");                                                          //保存路径
                int size = 2;                     //文件大小限制,单位mb                                                                                   //文件大小限制,单位KB
                string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };                    //文件允许格式

                //上传图片
                Hashtable info = new Hashtable();
                UploadHelper up = new UploadHelper();
                info = up.upFile(context, pathbase, filetype, size); //获取上传状态

                context.Response.Write("<script>parent.ue_callback('" + info["url"] + "','" + info["state"] + "')</script>");//回调函数
            }
            else
            {
                string pathbase = Url.Content("~/Uploads/Images/");                                         //保存路径
                string tmpPath = Url.Content("~/Uploads/Temps/");                  //临时图片目录

                //上传图片
                Hashtable info = new Hashtable();
                UploadHelper up = new UploadHelper();
                info = up.upScrawl(context, pathbase, tmpPath, context.Request["content"]); //获取上传状态

                //向浏览器返回json数据
                context.Response.Write("{'url':'" + info["url"] + "',state:'" + info["state"] + "'}");
            }
        }
コード例 #24
0
        /// <summary>
        /// 图片上传
        /// </summary> 
        public void ImageUp(FormCollection form)
        {
            HttpContextBase context = this.HttpContext;
            context.Response.ContentType = "text/plain";

            //上传配置
            String pathbase = Url.Content("~/Uploads/Images/");                                      //保存路径
            string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; ;    //文件允许格式
            int size = 20;   //文件大小限制,单位MB,同时在web.config里配置环境默认为20MB

            //上传图片
            Hashtable info = new Hashtable();
            UploadHelper up = new UploadHelper();
            info = up.upFile(context, pathbase, filetype, size);                   //获取上传状态

            string title = up.getOtherInfo(context, "pictitle");                   //获取图片描述
            string oriName = up.getOtherInfo(context, "fileName");                //获取原始文件名

            context.Response.Write("{'url':'" + info["url"] + "','title':'" + title + "','original':'" + oriName + "','state':'" + info["state"] + "'}");  //向浏览器返回数据json数据
        }
コード例 #25
0
 public HomeController(ServiceAWSDynamoDb service, ServiceAWSS3 serviceS3, UploadHelper helper)
 {
     this.serviceDynamo = service;
     this.ServiceS3     = serviceS3;
     this.uploadhelper  = helper;
 }
コード例 #26
0
ファイル: ContentInfo.cs プロジェクト: kimduquan/DMIS
        public ContentInfo(string path, Node parent, TransformerContext xsltOptions)
        {
            try
            {
                _metaDataPath = path;
                _attachments  = new List <string>();

                string directoryName = Path.GetDirectoryName(path);
                _name = Path.GetFileName(path);
                string extension = Path.GetExtension(_name);
                if (extension.ToLower() == ".content")
                {
                    var fileInfo = new FileInfo(path);
                    FileIsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                    _xmlDoc = new XmlDocument();
                    _xmlDoc.Load(path);

                    // start of xml transformation
                    if (xsltOptions != null && xsltOptions.IsValid)
                    {
                        using (MemoryStream output = new MemoryStream())
                        {
                            using (var writer = XmlWriter.Create(output, xsltOptions.XsltOutputSettings))
                            {
                                xsltOptions.XsltTransformer.Transform(_xmlDoc, xsltOptions.XsltArgList, writer);
                                output.Position = 0;
                                _xmlDoc.Load(output);
                            }
                        }
                    }
                    // end of xml transformation

                    XmlNode nameNode = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentName");
                    _name = nameNode == null?Path.GetFileNameWithoutExtension(_name) : nameNode.InnerText;

                    var deleteAttr = _xmlDoc.DocumentElement.Attributes["delete"];
                    if (deleteAttr != null && deleteAttr.Value == "true")
                    {
                        this.Delete = true;
                    }
                    else
                    {
                        this.Delete = false;

                        _contentTypeName = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentType").InnerText;

                        ClearPermissions    = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Clear") != null;
                        HasBreakPermissions = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Break") != null;
                        HasPermissions      = _xmlDoc.SelectNodes("/ContentMetaData/Permissions/Identity").Count > 0;
                        HasAspect           = _xmlDoc.SelectNodes("ContentMetaData/Fields/Aspects").Count > 0;

                        // /ContentMetaData/Properties/*/@attachment
                        foreach (XmlAttribute attachmentAttr in _xmlDoc.SelectNodes("/ContentMetaData/Fields/*/@attachment"))
                        {
                            string attachment = attachmentAttr.Value;
                            _attachments.Add(attachment);
                            bool isFolder = Directory.Exists(Path.Combine(directoryName, attachment));
                            if (isFolder)
                            {
                                if (_isFolder)
                                {
                                    throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                                }
                                _isFolder       = true;
                                _childrenFolder = Path.Combine(directoryName, attachment);
                            }
                        }
                        //-- default attachment
                        var defaultAttachmentPath = Path.Combine(directoryName, _name);
                        if (!_attachments.Contains(_name))
                        {
                            string[] paths;
                            if (Directory.Exists(defaultAttachmentPath))
                            {
                                paths = new string[] { defaultAttachmentPath }
                            }
                            ;
                            else
                            {
                                paths = new string[0];
                            }

                            //string[] paths = Directory.GetDirectories(directoryName, _name);
                            if (paths.Length == 1)
                            {
                                if (_isFolder)
                                {
                                    throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                                }
                                _isFolder       = true;
                                _childrenFolder = defaultAttachmentPath;
                                _attachments.Add(_name);
                            }
                            else
                            {
                                if (System.IO.File.Exists(defaultAttachmentPath))
                                {
                                    _attachments.Add(_name);
                                }
                            }
                        }
                    } //if (deleteAttr != null && deleteAttr.Value == "true")
                }
                else
                {
                    _isFolder = Directory.Exists(path);
                    if (_isFolder)
                    {
                        var dirInfo = new DirectoryInfo(path);
                        FileIsHidden = (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                        ContentTypeIsInferredFolder = true;

                        _contentTypeName = GetParentAllowedContentTypeName(path, parent, "Folder");
                        _childrenFolder  = path;

                        // start of xml transformation - for possible contentname conversion
                        if (xsltOptions != null && xsltOptions.IsValid)
                        {
                            using (MemoryStream output = new MemoryStream())
                            {
                                using (var writer = XmlWriter.Create(output, xsltOptions.XsltOutputSettings))
                                {
                                    var processXml = new XmlDocument();
                                    processXml.LoadXml(String.Format("<ContentMetaData><ContentName>{0}</ContentName></ContentMetaData>", _name));

                                    xsltOptions.XsltTransformer.Transform(processXml, xsltOptions.XsltArgList, writer);
                                    output.Position = 0;
                                    processXml.Load(output);

                                    XmlNode nameNode = processXml.SelectSingleNode("/ContentMetaData/ContentName");
                                    _name = nameNode == null?Path.GetFileNameWithoutExtension(_name) : nameNode.InnerText;
                                }
                            }
                        }
                        // end of xml transformation
                    }
                    else
                    {
                        var fileInfo = new FileInfo(path);
                        FileIsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
                        ContentTypeIsInferredFile = true;

                        _xmlDoc          = new XmlDocument();
                        _contentTypeName = UploadHelper.GetContentType(path, parent.Path) ?? GetParentAllowedContentTypeName(path, parent, "File");

                        // modified for possible contentname conversion
                        var contentMetaData = String.Concat("<ContentMetaData><ContentType>{0}</ContentType><ContentName>{1}</ContentName><Fields><Binary attachment='", _name.Replace("'", "&apos;"), "' /></Fields></ContentMetaData>");
                        _xmlDoc.LoadXml(String.Format(contentMetaData, _contentTypeName, _name));

                        // start of xml transformation - for possible contentname conversion
                        if (xsltOptions != null && xsltOptions.IsValid)
                        {
                            using (MemoryStream output = new MemoryStream())
                            {
                                using (var writer = XmlWriter.Create(output, xsltOptions.XsltOutputSettings))
                                {
                                    xsltOptions.XsltTransformer.Transform(_xmlDoc, xsltOptions.XsltArgList, writer);
                                    output.Position = 0;
                                    _xmlDoc.Load(output);

                                    XmlNode nameNode = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentName");
                                    _name = nameNode == null?Path.GetFileNameWithoutExtension(_name) : nameNode.InnerText;
                                }
                            }
                        }
                        // end of xml transformation

                        _attachments.Add(_name);
                    }
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException("Cannot create a ContentInfo. Path: " + path, e);
            }
        }
コード例 #27
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var TempVitA = TempVitaminARow.Fields;
            var d        = DistrictRow.Fields;
            var r        = RoundRow.Fields;
            var usr      = Administration.Entities.UserRow.Fields;
            var clc      = ClusterRow.Fields;
            var prov     = ProvinceRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 3; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var roundName1   = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    var districtName = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    var clusterName  = Convert.ToString(worksheet.Cells[row, 5].Value ?? "");
                    var provName     = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");

                    if (districtName.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var TempA = uow.Connection.TryFirst <TempVitaminARow>(q => q
                                                                          .Select(TempVitA.TempVitaminAId)
                                                                          .Where(TempVitA.DistrictName == districtName & TempVitA.RoundName == roundName1 & TempVitA.ClusterName == clusterName & TempVitA.ProvinceName == provName));

                    if (TempA == null)
                    {
                        TempA = new TempVitaminARow
                        {
                            DistrictName = districtName,
                            RoundName    = roundName1,
                            ClusterName  = clusterName,
                            ProvinceName = provName
                        }
                    }
                    ;
                    else
                    {
                        // avoid assignment errors
                        TempA.TrackWithChecks = false;
                    }

                    var roundName = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(roundName))
                    {
                        var round = uow.Connection.TryFirst <RoundRow>(q => q
                                                                       .Select(r.RoundId)
                                                                       .Where(r.RoundName == roundName));

                        if (round == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Round with name '" +
                                                   roundName + "' is not found!");
                            continue;
                        }

                        TempA.RoundId = round.RoundId.Value;
                    }
                    else
                    {
                        TempA.RoundId = null;
                    }


                    var dName = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(dName))
                    {
                        var district = uow.Connection.TryFirst <DistrictRow>(q => q
                                                                             .Select(d.DistrictId)
                                                                             .Where(d.Dcode == dName & d.Pname == provName));

                        if (dName == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": District with name '" +
                                                   dName + "' is not found!");
                            continue;
                        }

                        TempA.DistrictId = district.DistrictId.Value;
                    }
                    else
                    {
                        TempA.DistrictId = null;
                    }


                    var Cluster = Convert.ToString(worksheet.Cells[row, 5].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(Cluster))
                    {
                        var round = uow.Connection.TryFirst <ClusterRow>(q => q
                                                                         .Select(clc.ClusterId)
                                                                         .Where(clc.DistrictDcode == districtName & clc.Cname == Cluster));

                        if (Cluster == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Cluster with name '" +
                                                   Cluster + "' is not found!");
                            continue;
                        }

                        TempA.ClusterId = round.ClusterId.Value;
                    }
                    else
                    {
                        TempA.ClusterId = null;
                    }

                    var Province = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(Province))
                    {
                        var round = uow.Connection.TryFirst <ProvinceRow>(q => q
                                                                          .Select(prov.ProvinceId)
                                                                          .Where(prov.Pname == Province));

                        if (TempA == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": Province with name '" +
                                                   Province + "' is not found!");
                            continue;
                        }

                        TempA.ProvinceId = round.ProvinceId.Value;
                    }
                    else
                    {
                        TempA.ProvinceId = null;
                    }

                    TempA.TargetU5Cases   = Convert.ToInt16(worksheet.Cells[row, 6].Value ?? 0);
                    TempA.D1VitADist      = Convert.ToInt16(worksheet.Cells[row, 7].Value ?? 0);
                    TempA.D1VitAUse       = Convert.ToInt16(worksheet.Cells[row, 8].Value ?? 0);
                    TempA.D1C611Months    = Convert.ToInt16(worksheet.Cells[row, 9].Value ?? 0);;
                    TempA.D1C1259Months   = Convert.ToInt16(worksheet.Cells[row, 10].Value ?? 0);
                    TempA.D2VitADist      = Convert.ToInt16(worksheet.Cells[row, 11].Value ?? 0);
                    TempA.D2VitAUse       = Convert.ToInt16(worksheet.Cells[row, 12].Value ?? 0);
                    TempA.D2C611Months    = Convert.ToInt16(worksheet.Cells[row, 13].Value ?? 0);
                    TempA.D2C1259Months   = Convert.ToInt16(worksheet.Cells[row, 14].Value ?? 0);
                    TempA.D3VitADist      = Convert.ToInt16(worksheet.Cells[row, 15].Value ?? 0);
                    TempA.D3VitAUse       = Convert.ToInt16(worksheet.Cells[row, 16].Value ?? 0);
                    TempA.D3C611Months    = Convert.ToInt16(worksheet.Cells[row, 17].Value ?? 0);
                    TempA.D3C1259Months   = Convert.ToInt16(worksheet.Cells[row, 18].Value ?? 0);
                    TempA.D5VitADist      = Convert.ToInt16(worksheet.Cells[row, 19].Value ?? 0);
                    TempA.D5VitAUse       = Convert.ToInt16(worksheet.Cells[row, 20].Value ?? 0);
                    TempA.D5C611Months    = Convert.ToInt16(worksheet.Cells[row, 21].Value ?? 0);
                    TempA.D5C1259Months   = Convert.ToInt16(worksheet.Cells[row, 22].Value ?? 0);
                    TempA.PemtremtManager = Convert.ToString(worksheet.Cells[row, 23].Value ?? "");

                    var user = User.Identity.Name;
                    if (!string.IsNullOrWhiteSpace(user))
                    {
                        var Users = uow.Connection.TryFirst <Administration.Entities.UserRow>(q => q
                                                                                              .Select(usr.TenantId)
                                                                                              .Where(usr.Username == user));

                        if (Users == null)
                        {
                            response.ErrorList.Add("Error On Row " + row + ": TenantID with name '" +
                                                   Users + "' is not found!");
                            continue;
                        }

                        TempA.TenantId = Users.TenantId.Value;
                    }
                    else
                    {
                        TempA.TenantId = null;
                    }


                    if (TempA.TempVitaminAId == null)
                    {
                        new TempVitaminARepository().Create(uow, new SaveRequest <MyRow>
                        {
                            Entity = TempA
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new TempVitaminARepository().Update(uow, new SaveRequest <MyRow>
                        {
                            Entity   = TempA,
                            EntityId = TempA.TempVitaminAId.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }


            return(response);
        }
コード例 #28
0
        public override void OnBeforeSave(ISaveRequestHandler handler)
        {
            var filesToDelete = new FilesToDelete();

            UploadHelper.RegisterFilesToDelete(handler.UnitOfWork, filesToDelete);
            handler.StateBag[this.GetType().FullName + "_FilesToDelete"] = filesToDelete;

            var filename    = (StringField)(handler.Row.FindField(this.fileNameField) ?? handler.Row.FindFieldByPropertyName(fileNameField));
            var oldFilename = handler.IsCreate ? null : filename[handler.Old];
            var newFilename = filename[handler.Row] = filename[handler.Row].TrimToNull();

            if (oldFilename.IsTrimmedSame(newFilename))
            {
                filename[handler.Row] = oldFilename;
                return;
            }

            if (!oldFilename.IsEmptyOrNull())
            {
                var actualOldFile = ((subFolder != null && !storeSubFolderInDB) ? (subFolder + "/") : "") + oldFilename;
                filesToDelete.RegisterOldFile(actualOldFile);

                if (copyFileToHistory)
                {
                    var    oldFilePath = UploadHelper.ToPath(actualOldFile);
                    string date        = DateTime.UtcNow.ToString("yyyyMM", Invariants.DateTimeFormat);
                    string historyFile = "history/" + date + "/" + Path.GetFileName(oldFilePath);
                    if (File.Exists(UploadHelper.DbFilePath(oldFilePath)))
                    {
                        UploadHelper.CopyFileAndRelated(UploadHelper.DbFilePath(oldFilePath), UploadHelper.DbFilePath(historyFile), overwrite: true);
                    }
                }
            }


            if (newFilename == null)
            {
                if (oldFilename.IsTrimmedEmpty())
                {
                    return;
                }

                filename[handler.Row] = null;
                return;
            }

            if (!newFilename.ToLowerInvariant().StartsWith("temporary/"))
            {
                throw new InvalidOperationException("For security reasons, only temporary files can be used in uploads!");
            }

            if (handler.IsUpdate)
            {
                var copyResult = CopyTemporaryFile(handler, filesToDelete);
                filename[handler.Row] = copyResult.DbFileName;
            }
        }
コード例 #29
0
        public ExcelImportResponse ExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var w  = WaresRow.Fields;
            var c  = CategoryRow.Fields;
            var m  = MeasureRow.Fields;
            var cp = CounterpartyRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();

            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 2; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    var waresName = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    if (waresName.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var wares = uow.Connection.TryFirst <WaresRow>(q => q
                                                                   .Select(w.WaresID)
                                                                   .Where(w.WaresName == waresName));

                    if (wares == null)
                    {
                        wares = new WaresRow
                        {
                            WaresName = waresName
                        }
                    }
                    ;
                    else
                    {
                        wares.TrackWithChecks = false;
                    }

                    #region Category

                    var categoryName = Convert.ToString(worksheet.Cells[row, 6].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(categoryName))
                    {
                        var category = uow.Connection.TryFirst <CategoryRow>(q => q
                                                                             .Select(c.CategoryID)
                                                                             .Where(c.CategoryName == categoryName));

                        if (category == null)
                        {
                            response.ErrorList.Add("Error On Row" + row + ": Category with name '" +
                                                   categoryName + "' is not found!");
                            continue;
                        }

                        wares.CategoryID = category.CategoryID.Value;
                    }
                    else
                    {
                        wares.CategoryID = null;
                    }

                    #endregion Category

                    #region Measure

                    var measureName = Convert.ToString(worksheet.Cells[row, 7].Value ?? "");
                    if (!string.IsNullOrWhiteSpace(measureName))
                    {
                        var measure = uow.Connection.TryFirst <MeasureRow>(q => q
                                                                           .Select(m.MeasureID)
                                                                           .Where(m.MeasureName == measureName));

                        if (measure == null)
                        {
                            response.ErrorList.Add("Error On Row" + row + ": Measure with name '" +
                                                   measureName + "' is not found!");
                            continue;
                        }

                        wares.MeasureID = measure.MeasureID.Value;
                    }
                    else
                    {
                        wares.MeasureID = null;
                    }

                    #endregion Measure

                    #region Counterparty

                    //var counterpartyName = Convert.ToString(worksheet.Cells[row, 13].Value ?? 0);
                    //if (!string.IsNullOrWhiteSpace(counterpartyName))
                    //{
                    //    var counterparty = uow.Connection.TryFirst<CounterpartyRow>(q => q
                    //        .Select(cp.CounterpartyID)
                    //        .Where(cp.CompanyName == counterpartyName));

                    //    if(counterparty == null)
                    //    {
                    //        response.ErrorList.Add("Error On Row" + row + ": Counterparty with name '" +
                    //            counterpartyName + "' is not found!");
                    //        continue;
                    //    }

                    //    wares.CounterpartyID = counterparty.CounterpartyID.ToString();
                    //}
                    //else
                    //{
                    //    wares.CounterpartyID = null;
                    //}

                    #endregion Counterparty

                    wares.WaresCode    = Convert.ToString(worksheet.Cells[row, 1].Value ?? "");
                    wares.WaresBarcode = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    wares.WaresLabel   = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    wares.Discontinued = Convert.ToBoolean(worksheet.Cells[row, 5].Value ?? "");

                    wares.QuantityPerUnit = Convert.ToInt32(worksheet.Cells[row, 8].Value ?? "");
                    wares.UnitPrice       = Convert.ToDecimal(worksheet.Cells[row, 9].Value ?? 0);
                    wares.UnitsInStock    = Convert.ToDecimal(worksheet.Cells[row, 10].Value ?? 0);
                    wares.UnitsOnOrder    = Convert.ToDecimal(worksheet.Cells[row, 11].Value ?? 0);

                    wares.CounterpartyID = Convert.ToString(worksheet.Cells[row, 12].Value ?? 0);

                    if (wares.WaresID == null)
                    {
                        new WaresRepository().Create(uow, new SaveWithLocalizationRequest <MyRow>
                        {
                            Entity = wares
                        });

                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new WaresRepository().Update(uow, new SaveWithLocalizationRequest <MyRow>
                        {
                            Entity   = wares,
                            EntityId = wares.WaresID.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }

            return(response);
        }
コード例 #30
0
ファイル: Put.cs プロジェクト: y1027/sensenet
        private void CreateFile(string fileName, Node parentNode)
        {
            string realFileName = fileName;

            _handler.Context.Response.StatusCode = 201; // created

            if ((parentNode == null) || !(parentNode is IFolder))
            {
                _handler.Context.Response.StatusCode = 403;
                _handler.Context.Response.Flush();
                return;
            }
            try
            {
                // search for contents referring to this binary
                foreach (Node existingNode in ((IFolder)parentNode).Children)
                {
                    if (SetBinaryAttachment(existingNode, realFileName))
                    {
                        return;
                    }
                }

                // special filetype, referred in web.config
                string contentType = UploadHelper.GetContentType(realFileName, parentNode.Path);
                if (contentType != null)
                {
                    WebDavProvider.Current.AssertCreateContent(parentNode.Path, fileName, contentType);

                    var nodeType    = ActiveSchema.NodeTypes[contentType];
                    var specialFile = nodeType.CreateInstance(parentNode) as IFile;

                    if (specialFile == null)
                    {
                        _handler.Context.Response.StatusCode = 405;
                    }
                    else
                    {
                        var specialNode = (Node)specialFile;
                        if (specialNode.NodeType.IsInstaceOfOrDerivedFrom("Page"))
                        {
                            throw new NotSupportedException("Creating or ediding a Page through Webdav is not supported.");
                        }

                        specialFile.Binary = new BinaryData();
                        specialNode.Name   = fileName;

                        SetBinaryStream(specialNode, _handler.Context.Request.InputStream, FILEPROPERTYNAME, realFileName);
                    }

                    return;
                }

                WebDavProvider.Current.AssertCreateContent(parentNode.Path, fileName, typeof(SN.File).Name);

                // general file
                var fileContent = Content.CreateNew(typeof(SN.File).Name, parentNode, fileName);
                var fileNode    = (SN.File)fileContent.ContentHandler;
                fileNode.Binary = new BinaryData();
                SetBinaryStream(fileNode, _handler.Context.Request.InputStream, FILEPROPERTYNAME, realFileName);
            }
            catch (SecurityException e) // logged
            {
                SnLog.WriteException(e);
                _handler.Context.Response.StatusCode = 403;
            }
            catch (SenseNetSecurityException ee) // logged
            {
                SnLog.WriteException(ee);
                _handler.Context.Response.StatusCode = 403;
            }

            return;
        }
コード例 #31
0
        public IActionResult UploadIntroduction(IntroductionDTO introduction)
        {
            _loggerManager.Info($"UploadIntroduction was requested");

            var files = HttpContext.Request.Form.Files;

            if (files == null || files.Count != 1)
            {
                ModelState.AddModelError(string.Empty, sharedResource.manageIntroductionInvalidFile);

                _loggerManager.Warn($"UploadIntroduction : A file is invalid");

                return(View("Introduction", introduction));
            }

            //validates step's index
            if (!_planRepository.GetStepList().Contains(introduction.Step))
            {
                _loggerManager.Warn($"UploadIntroduction : Step index is wrong");
                return(BadRequest());
            }

            var uploadlimit = int.Parse(_settingRepository.Get(Settings.FileUploadLimit));

            if (!ValidationHelper.ValidateFileSize(files[0], uploadlimit))
            {
                ModelState.AddModelError(string.Empty, sharedResource.manageIntroductionFileLimitError);

                _loggerManager.Warn($"UploadIntroduction : A file exceed a limit");

                return(View("Introduction", introduction));
            }

            var userId = HttpContext.GetUserId();

            //upload a file in wwwroot directory
            var uploadRelPath = UploadHelper.Upload(files[0]);

            //creates a new file record
            var fileDto = _fileRepository.CreateNewFile(Path.GetFileNameWithoutExtension(files[0].FileName), Path.GetExtension(files[0].FileName), uploadRelPath, userId);

            //boolean that determines a result for updating of an introduction
            var result = false;


            if (fileDto != null)//A file record created, updates an introduction record
            {
                _loggerManager.Info($"UploadIntroduction : A file was created");

                //takes an older video version
                var oldVideo = _planRepository.GetIntroduction(introduction.Step)?.Video;

                //updaates an introduction for a step
                result = _planRepository.UpdateIntroduction(introduction.Step, fileDto.Id, userId);

                if (result && oldVideo != null)//If a update was succeessful and the introduction had a video before, deletes an older video
                {
                    //a result boolean
                    bool oldFileDelete;

                    //Deletes corresponding record in a repository and corresponding file in a directory, If any fails a result boolean is false
                    oldFileDelete = UploadHelper.Delete(oldVideo.Path);
                    oldFileDelete = _fileRepository.Delete(oldVideo.Id) && oldFileDelete;

                    if (oldFileDelete)
                    {
                        _loggerManager.Warn($"UploadIntroduction : An old file was deleted");
                    }
                    else
                    {
                        _loggerManager.Warn($"UploadIntroduction : An old file was not deleted");
                    }
                }
            }

            if (!result)
            {
                ModelState.AddModelError(string.Empty, sharedResource.manageServerError);
                _loggerManager.Warn($"UploadIntroduction was unable to update");

                return(View("Introduction", introduction));
            }
            else
            {
                _loggerManager.Info($"UploadIntroduction successfully updated");
            }

            return(RedirectToAction("GetIntroduction", new { stepIndex = introduction.Step }));
        }
コード例 #32
0
ファイル: RunOnce.cs プロジェクト: vlslavik/SenseNet
            public ContentInfo(string path)
            {
                try
                {
                    _metaDataPath = path;
                    _attachments  = new List <string>();

                    string directoryName = Path.GetDirectoryName(path);
                    _name = Path.GetFileName(path);
                    string extension = Path.GetExtension(_name);
                    if (extension.ToLower() == ".content")
                    {
                        var fileInfo = new FileInfo(path);
                        FileIsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                        _xmlDoc = new XmlDocument();
                        _xmlDoc.Load(path);

                        XmlNode nameNode = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentName");
                        _name = nameNode == null?Path.GetFileNameWithoutExtension(_name) : nameNode.InnerText;

                        _contentTypeName = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentType").InnerText;

                        ClearPermissions    = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Clear") != null;
                        HasBreakPermissions = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Break") != null;
                        HasPermissions      = _xmlDoc.SelectNodes("/ContentMetaData/Permissions/Identity").Count > 0;

                        // /ContentMetaData/Properties/*/@attachment
                        foreach (XmlAttribute attachmentAttr in _xmlDoc.SelectNodes("/ContentMetaData/Fields/*/@attachment"))
                        {
                            string attachment = attachmentAttr.Value;
                            _attachments.Add(attachment);
                            bool isFolder = Directory.Exists(Path.Combine(directoryName, attachment));
                            if (isFolder)
                            {
                                if (_isFolder)
                                {
                                    throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                                }
                                _isFolder       = true;
                                _childrenFolder = Path.Combine(directoryName, attachment);
                            }
                        }
                        //-- default attachment
                        var defaultAttachmentPath = Path.Combine(directoryName, _name);
                        if (!_attachments.Contains(_name))
                        {
                            string[] paths;
                            if (Directory.Exists(defaultAttachmentPath))
                            {
                                paths = new string[] { defaultAttachmentPath }
                            }
                            ;
                            else
                            {
                                paths = new string[0];
                            }

                            //string[] paths = Directory.GetDirectories(directoryName, _name);
                            if (paths.Length == 1)
                            {
                                if (_isFolder)
                                {
                                    throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                                }
                                _isFolder       = true;
                                _childrenFolder = defaultAttachmentPath;
                                _attachments.Add(_name);
                            }
                            else
                            {
                                if (System.IO.File.Exists(defaultAttachmentPath))
                                {
                                    _attachments.Add(_name);
                                }
                            }
                        }
                    }
                    else
                    {
                        _isFolder = Directory.Exists(path);
                        if (_isFolder)
                        {
                            var dirInfo = new DirectoryInfo(path);
                            FileIsHidden = (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                            _contentTypeName = "Folder";
                            _childrenFolder  = path;
                        }
                        else
                        {
                            var fileInfo = new FileInfo(path);
                            FileIsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                            _xmlDoc          = new XmlDocument();
                            _contentTypeName = UploadHelper.GetContentType(path, null) ?? "File";

                            var contentMetaData = String.Concat("<ContentMetaData><ContentType>{0}</ContentType><Fields><Binary attachment='", _name.Replace("'", "&apos;"), "' /></Fields></ContentMetaData>");
                            _xmlDoc.LoadXml(String.Format(contentMetaData, _contentTypeName));
                            _attachments.Add(_name);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new ApplicationException("Cannot create a ContentInfo. Path: " + path, e);
                }
            }
コード例 #33
0
        private ServiceResponse HandleUploadRequest(HttpContextBase context)
        {
            if (context.Request.Form.Files.Count != 1)
            {
                throw new ArgumentOutOfRangeException("files");
            }

            var file = context.Request.Form.Files[0];

            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (file.FileName.IsEmptyOrNull())
            {
                throw new ArgumentNullException("filename");
            }

            var processor = new UploadProcessor
            {
                ThumbWidth  = 128,
                ThumbHeight = 96
            };

            if (processor.ProcessStream(file.OpenReadStream(), Path.GetExtension(file.FileName)))
            {
                var temporaryFile = "temporary/" + Path.GetFileName(processor.FilePath);
                using (var sw = new StreamWriter(System.IO.File.OpenWrite(Path.ChangeExtension(UploadHelper.DbFilePath(temporaryFile), ".orig"))))
                    sw.WriteLine(file.FileName);

                return(new UploadResponse()
                {
                    TemporaryFile = temporaryFile,
                    Size = processor.FileSize,
                    IsImage = processor.IsImage,
                    Width = processor.ImageWidth,
                    Height = processor.ImageHeight
                });
            }
            else
            {
                return(new UploadResponse()
                {
                    Error = new ServiceError()
                    {
                        Code = "Exception",
                        Message = processor.ErrorMessage
                    }
                });
            }
        }
コード例 #34
0
 /// <summary>
 /// 下载导入标签模板
 /// </summary>
 public void DownLoadTemplate()
 {
     UploadHelper.ExportExcel("PushLabelTemplate.xls", "PushLabelTemplate.xls");
 }
コード例 #35
0
        public bool ActivateFor(Row row)
        {
            if (ReferenceEquals(null, Target))
            {
                return(false);
            }

            attr = Target.GetAttribute <ImageUploadEditorAttribute>();
            if (attr == null || attr.DisableDefaultBehavior || attr.EditorType != "ImageUpload")
            {
                return(false);
            }

            if (!(Target is StringField))
            {
                throw new ArgumentException(String.Format(
                                                "Field '{0}' on row type '{1}' has a UploadEditor attribute but it is not a String field!",
                                                Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            if (!(row is IIdRow))
            {
                throw new ArgumentException(String.Format(
                                                "Field '{0}' on row type '{1}' has a UploadEditor attribute but Row type doesn't implement IIdRow!",
                                                Target.PropertyName ?? Target.Name, row.GetType().FullName));
            }

            if (!attr.OriginalNameProperty.IsEmptyOrNull())
            {
                var originalNameField = row.FindFieldByPropertyName(attr.OriginalNameProperty) ??
                                        row.FindField(attr.OriginalNameProperty);

                if (ReferenceEquals(null, originalNameField))
                {
                    throw new ArgumentException(String.Format(
                                                    "Field '{0}' on row type '{1}' has a UploadEditor attribute but " +
                                                    "a field with OriginalNameProperty '{2}' is not found!",
                                                    Target.PropertyName ?? Target.Name,
                                                    row.GetType().FullName,
                                                    attr.OriginalNameProperty));
                }

                this.originalNameField = (StringField)originalNameField;
            }

            var format = attr.FilenameFormat;

            if (format == null)
            {
                format = row.GetType().Name;
                if (format.EndsWith("Row"))
                {
                    format = format.Substring(0, format.Length - 3);
                }
                format += "/~";
            }

            this.fileNameFormat = format.Replace("~", SplittedFormat);
            this.replaceFields  = ParseReplaceFields(fileNameFormat, row, Target);
            this.uploadHelper   = new UploadHelper((attr.SubFolder.IsEmptyOrNull() ? "" : (attr.SubFolder + "/")) + (this.fileNameFormat));

            return(true);
        }
コード例 #36
0
        public override void OnBeforeSave(ISaveRequestHandler handler)
        {
            var field = (StringField)(handler.Row.FindField(this.filesField) ?? handler.Row.FindFieldByPropertyName(filesField));

            if (!handler.Row.IsAssigned(field))
            {
                return;
            }

            var oldFilesJSON = (handler.IsCreate ? null : field[handler.Old]).TrimToNull();
            var newFilesJSON = field[handler.Row] = field[handler.Row].TrimToNull();

            if (oldFilesJSON.IsTrimmedSame(newFilesJSON))
            {
                field[handler.Row] = oldFilesJSON;
                return;
            }

            var oldFileList = ParseAndValidate(oldFilesJSON, "oldFiles");
            var newFileList = ParseAndValidate(newFilesJSON, "newFiles");

            var filesToDelete = new FilesToDelete();

            UploadHelper.RegisterFilesToDelete(handler.UnitOfWork, filesToDelete);
            handler.StateBag[this.GetType().FullName + "_FilesToDelete"] = filesToDelete;

            foreach (var file in oldFileList)
            {
                var filename = file.Filename.Trim();
                if (newFileList.Any(x => String.Compare(x.Filename.Trim(), filename, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    continue;
                }

                var actualOldFile = ((subFolder != null && !storeSubFolderInDB) ? (subFolder + "/") : "") + filename;
                filesToDelete.RegisterOldFile(actualOldFile);

                if (copyFilesToHistory)
                {
                    var    oldFilePath = UploadHelper.ToPath(actualOldFile);
                    string date        = DateTime.UtcNow.ToString("yyyyMM", Invariants.DateTimeFormat);
                    string historyFile = "history/" + date + "/" + Path.GetFileName(oldFilePath);
                    if (File.Exists(UploadHelper.DbFilePath(oldFilePath)))
                    {
                        UploadHelper.CopyFileAndRelated(UploadHelper.DbFilePath(oldFilePath), UploadHelper.DbFilePath(historyFile), overwrite: true);
                    }
                }
            }

            if (newFileList.IsEmptyOrNull())
            {
                field[handler.Row] = null;
                return;
            }

            if (handler.IsUpdate)
            {
                field[handler.Row] = CopyTemporaryFiles(handler, oldFileList, newFileList, filesToDelete);
            }
        }
コード例 #37
0
        public static void CheckUploadedImageAndCreateThumbs(ImageUploadEditorAttribute attr, ref string temporaryFile)
        {
            ImageCheckResult[] supportedFormats = null;

            if (!attr.AllowNonImage)
            {
                supportedFormats = new ImageCheckResult[] {
                    ImageCheckResult.JPEGImage,
                    ImageCheckResult.GIFImage,
                    ImageCheckResult.PNGImage
                }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = attr.MinWidth;
            checker.MaxWidth    = attr.MaxWidth;
            checker.MinHeight   = attr.MinHeight;
            checker.MaxHeight   = attr.MaxHeight;
            checker.MaxDataSize = attr.MaxSize;

            Image image = null;

            try
            {
                var temporaryPath = UploadHelper.DbFilePath(temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (attr.MinSize != 0 && fs.Length < attr.MinSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooSmall,
                                                                UploadHelper.FileSizeDisplay(attr.MinSize)));
                    }

                    if (attr.MaxSize != 0 && fs.Length > attr.MaxSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooBig,
                                                                UploadHelper.FileSizeDisplay(attr.MaxSize)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result == ImageCheckResult.InvalidImage &&
                        attr.AllowNonImage)
                    {
                        return;
                    }

                    if (result > ImageCheckResult.UnsupportedFormat ||
                        (supportedFormats != null && Array.IndexOf(supportedFormats, result) < 0))
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result >= ImageCheckResult.FlashMovie)
                    {
                        return;
                    }

                    string basePath = UploadHelper.TemporaryPath;
                    string baseFile = Path.GetFileNameWithoutExtension(Path.GetFileName(temporaryPath));

                    TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                    if ((attr.ScaleWidth > 0 || attr.ScaleHeight > 0) &&
                        ((attr.ScaleWidth > 0 && (attr.ScaleSmaller || checker.Width > attr.ScaleWidth)) ||
                         (attr.ScaleHeight > 0 && (attr.ScaleSmaller || checker.Height > attr.ScaleHeight))))
                    {
                        using (Image scaledImage = ThumbnailGenerator.Generate(
                                   image, attr.ScaleWidth, attr.ScaleHeight, attr.ScaleMode, Color.Empty))
                        {
                            temporaryFile = baseFile + ".jpg";
                            fs.Close();
                            scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            temporaryFile = "temporary/" + temporaryFile;
                        }
                    }

                    var thumbSizes = attr.ThumbSizes.TrimToNull();
                    if (thumbSizes == null)
                    {
                        return;
                    }

                    foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                    {
                        var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                        int w, h;
                        if (dims.Length != 2 ||
                            !Int32.TryParse(dims[0], out w) ||
                            !Int32.TryParse(dims[1], out h) ||
                            w < 0 ||
                            h < 0 ||
                            (w == 0 && h == 0))
                        {
                            throw new ArgumentOutOfRangeException("thumbSizes");
                        }

                        using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, attr.ThumbMode, Color.Empty))
                        {
                            string thumbFile = Path.Combine(basePath,
                                                            baseFile + "_t" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                            thumbImage.Save(thumbFile);
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
コード例 #38
0
        public ExcelImportResponse TeacherExcelImport(IUnitOfWork uow, ExcelImportRequest request)
        {
            request.CheckNotNull();
            Check.NotNullOrWhiteSpace(request.FileName, "filename");

            UploadHelper.CheckFileNameSecurity(request.FileName);

            if (!request.FileName.StartsWith("temporary/"))
            {
                throw new ArgumentOutOfRangeException("filename");
            }

            ExcelPackage ep = new ExcelPackage();

            using (var fs = new FileStream(UploadHelper.DbFilePath(request.FileName), FileMode.Open, FileAccess.Read))
                ep.Load(fs);

            var t = MyRow.Fields;
            var b = TextbookRow.Fields;
            var c = CourseRow.Fields;

            var response = new ExcelImportResponse();

            response.ErrorList = new List <string>();
            var worksheet = ep.Workbook.Worksheets[1];

            for (var row = 2; row <= worksheet.Dimension.End.Row; row++)
            {
                try
                {
                    //TeacherWholeData
                    var batchId = Convert.ToString(worksheet.Cells[row, 3].Value ?? "");
                    if (batchId.IsTrimmedEmpty())
                    {
                        continue;
                    }
                    var declaration = uow.Connection.TryFirst <MyRow>(q1 => q1
                                                                      .Select(t.DeclarationId)
                                                                      .Where(t.DeclarationId == -1));

                    if (declaration == null)
                    {
                        declaration = new MyRow
                        {
                            BatchId = batchId
                        };
                    }
                    else
                    {
                        declaration.TrackWithChecks = false;
                    }

                    //Textbook
                    var textbookID = Convert.ToString(worksheet.Cells[row, 12].Value ?? "");
                    if (textbookID.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var textbook = uow.Connection.TryFirst <TextbookRow>(q => q
                                                                         .Select(b.TextbookNum2)
                                                                         .Where(b.TextbookId == textbookID));

                    if (textbook == null)
                    {
                        textbook = new TextbookRow
                        {
                            TextbookId = textbookID
                        };
                    }
                    else
                    {
                        textbook.TrackWithChecks = false;
                    }

                    textbook.TextbookName  = Convert.ToString(worksheet.Cells[row, 13].Value ?? "");
                    textbook.Author        = Convert.ToString(worksheet.Cells[row, 14].Value ?? "");
                    textbook.Isbn          = Convert.ToString(worksheet.Cells[row, 15].Value ?? "");
                    textbook.Press         = Convert.ToString(worksheet.Cells[row, 16].Value ?? "");
                    textbook.Edition       = Convert.ToString(worksheet.Cells[row, 17].Value ?? "");
                    textbook.PrintingCount = Convert.ToString(worksheet.Cells[row, 18].Value ?? "");
                    textbook.TextbookType  = Convert.ToString(worksheet.Cells[row, 19].Value ?? "");
                    textbook.Price         = Convert.ToString(worksheet.Cells[row, 20].Value ?? "");
                    textbook.IsSelfCompile = Convert.ToString("0");

                    if (textbook.TextbookNum2 == null)
                    {
                        new TextbookRepository().Create(uow, new SaveRequest <TextbookRow>
                        {
                            Entity = textbook
                        });
                    }
                    else
                    {
                        new TextbookRepository().Update(uow, new SaveRequest <TextbookRow>
                        {
                            Entity   = textbook,
                            EntityId = textbook.TextbookNum2.Value
                        });
                    }

                    //Course
                    var courseId = Convert.ToString(worksheet.Cells[row, 8].Value ?? "");
                    if (courseId.IsTrimmedEmpty())
                    {
                        continue;
                    }

                    var course = uow.Connection.TryFirst <CourseRow>(q => q
                                                                     .Select(c.CourseNum)
                                                                     .Where(c.CourseId == courseId));

                    if (course == null)
                    {
                        course = new CourseRow
                        {
                            CourseId = courseId
                        };
                    }
                    else
                    {
                        course.TrackWithChecks = false;
                    }
                    course.CourseCode = Convert.ToString(worksheet.Cells[row, 10].Value ?? "空");
                    course.CourseName = Convert.ToString(worksheet.Cells[row, 11].Value ?? "");

                    if (course.CourseNum == null)
                    {
                        new CourseRepository().Create(uow, new SaveRequest <CourseRow>
                        {
                            Entity = course
                        });
                    }
                    else
                    {
                        new CourseRepository().Update(uow, new SaveRequest <CourseRow>
                        {
                            Entity   = course,
                            EntityId = course.CourseNum.Value
                        });
                    }

                    declaration.TermCode        = Convert.ToString(worksheet.Cells[row, 1].Value ?? "");
                    declaration.TermName        = Convert.ToString(worksheet.Cells[row, 2].Value ?? "");
                    declaration.SchoolId        = Convert.ToString(worksheet.Cells[row, 4].Value ?? "");
                    declaration.SchoolName      = Convert.ToString(worksheet.Cells[row, 5].Value ?? "");
                    declaration.DepartmentId    = Convert.ToString(worksheet.Cells[row, 6].Value ?? "");
                    declaration.DepartmentName  = Convert.ToString(worksheet.Cells[row, 7].Value ?? "");
                    declaration.EducationalType = Convert.ToString(worksheet.Cells[row, 9].Value ?? "");
                    declaration.ApprovedAmount  = Convert.ToInt32(worksheet.Cells[row, 21].Value ?? 0);
                    declaration.Priority        = Convert.ToString(worksheet.Cells[row, 22].Value ?? "");
                    declaration.Phone           = Convert.ToString(worksheet.Cells[row, 23].Value ?? "");
                    declaration.Remarks         = Convert.ToString(worksheet.Cells[row, 24].Value ?? "");
                    declaration.CheckState      = Convert.ToString(worksheet.Cells[row, 25].Value ?? "");
                    declaration.DataSign        = Convert.ToString(worksheet.Cells[row, 26].Value ?? "");
                    declaration.CourseNum       = course.CourseNum.Value;
                    declaration.TextbookNum2    = textbook.TextbookNum2.Value;

                    if (declaration.DeclarationId == null)
                    {
                        new TeacherWholeDataRepository().Create(uow, new SaveRequest <MyRow>
                        {
                            Entity = declaration
                        });
                        response.Inserted = response.Inserted + 1;
                    }
                    else
                    {
                        new TeacherWholeDataRepository().Update(uow, new SaveRequest <MyRow>
                        {
                            Entity   = declaration,
                            EntityId = declaration.DeclarationId.Value
                        });

                        response.Updated = response.Updated + 1;
                    }
                }
                catch (Exception ex)
                {
                    response.ErrorList.Add("Exception on Row " + row + ": " + ex.Message);
                }
            }
            return(response);
        }