Exemple #1
0
        public FileResult GetImage(string id, string ff)
        {
            try
            {
                if (!String.IsNullOrEmpty(id))
                {
                    byte[] fileBytes = System.IO.File.ReadAllBytes(String.Format(@"{0}/{1}/{2}.jpg", AppConfigManager.HeyFolderPath, ff, id));
                    string fileName = String.Format("{0}.jpg", id);
                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = fileName,
                        Inline = true,
                    };
                    Response.AppendHeader("Content-Disposition", cd.ToString());
                    return File(fileBytes, System.Net.Mime.MediaTypeNames.Image.Jpeg);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                // changed here by yahya
                //throw new Exception(CodeHelper.UnableToFindFile);
            }

            return null;
        }
Exemple #2
0
        public ActionResult Download(string id, int azienda)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var service = new SferaService();
                var info = new UserInfo(0, azienda);

                var documentoFileName = getDocumentoFileName(id, service, info);
                var documento = documentoFileName.Documento;

                var docInfo = getDocumentInfo(documento, service, info);
                if (docInfo.Body != null)
                {
                    var fileName = documento.FileName;
                    if (!fileName.EndsWith(".pdf"))
                        fileName = $"{fileName}.pdf";

                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        // for example foo.bak
                        FileName = fileName,

                        // always prompt the user for downloading, set to true if you want 
                        // the browser to try to show the file inline
                        Inline = true,
                    };

                    Response.AddHeader("set-cookie", "fileDownload=true; path=/");
                    Response.AppendHeader("Content-Disposition", cd.ToString());
                    return File(docInfo.Body, "application/pdf");
                }
            }

            return null;
        }
        public async Task<ActionResult> DownloadDocument(string feedName, string guid)
        {
            var parameters = new { feedName = feedName, guid = guid };

            var attachment = await WebApiService.Instance.GetAsync<AttachmentDto>("/Attachments/Get", UserManager.User.AccessToken, parameters);

            if (attachment != null)
            {
                var blobData = await WebApiService.Instance.GetBlobAsync("/Documents/Get", UserManager.User.AccessToken, parameters);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = attachment.FileName,

                    // Prompt the user for downloading; set to true if you want 
                    // the browser to try to show the file 'inline' (display in-browser
                    // without prompting to download file).  Set to false if you 
                    // want to always prompt them to download the file.
                    Inline = true,
                };
                Response.AppendHeader("Content-Disposition", cd.ToString());

                // View document
                return File(blobData, attachment.ContentType);
            }
            return RedirectToAction("NotFound", "Error");
        }
        public ActionResult ConfirmCart(CartDto cart)
        {
            // check for second submission
            if (Session[CartKey] == null)
            {
                TempData["ErrorMessage"] = "Already submitted this cart; invoice has already been generated";
                return RedirectToAction("DisplayCart");
            }

            // dropping cart reference here to prevent double submission
            Session[CartKey] = null;

            if (cart.Rows == null || cart.Rows.Count == 0)
            {
                TempData["ErrorMessage"] = "Submitted an empty cart";
                return View("EditCart", GetOrInitCartFromSession());
            }

            var invoiceFile = Service.ConfirmCart(cart);

            var encoding = Encoding.UTF8;
            var bytes = invoiceFile.FileRows.SelectMany(row => encoding.GetBytes(row + Environment.NewLine)).ToArray();

            var contentDisposition = new System.Net.Mime.ContentDisposition
            {
                FileName = string.Format("Invoice{0}.csv", invoiceFile.InvoiceNumber),
                Inline = false
            };
            Response.AppendHeader("Content-Disposition", contentDisposition.ToString());

            return File(bytes, contentDisposition.ToString());
        }
        public ActionResult Download(string Name)
        {
            byte[] filedata = { };
            string contentType = string.Empty;
            try
            {
                string fullFilePath = center.GetCertificatePath(Name);
                string filename = Path.GetFileName(fullFilePath);
                string filepath = fullFilePath;
                filedata = System.IO.File.ReadAllBytes(filepath);
                contentType = MimeMapping.GetMimeMapping(filepath);

                System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
            }
            catch (Exception ex)
            {
                Logger.LogManager.Instance.WriteError("Error while trying to download certificate: " + ex.Message);
            }
            return File(filedata, contentType);
        }
        public ActionResult VMT(string id)
        {
            long providedId;
            if (!long.TryParse(id, out providedId))
            {
                return View("Error");
            }

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = id + ".vmt",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());

            string vmt_file = String.Format(@"""UnlitGeneric""
            {{
            ""$basetexture""	""vgui\logos\{0}""
            ""$translucent"" ""1""
            ""$ignorez"" ""1""
            ""$vertexcolor"" ""1""
            ""$vertexalpha"" ""1""
            }} ", id);

            return File(Encoding.UTF8.GetBytes(vmt_file), "application/vnd.valve.vmt");
        }
Exemple #7
0
 public ActionResult Pdf()
 {
     var cd = new System.Net.Mime.ContentDisposition
     {
         FileName = @"thornton-resume.pdf",
         Inline = false,
     };
     Response.AppendHeader("Content-Disposition", cd.ToString());
     return File(@"..\Content\thornton-resume.pdf", "application/pdf");
 }
 // GET: /Sql/Download?
 public ActionResult Download(string id) {
     var result = !string.IsNullOrEmpty(id) ? new SqloogleSearcher(ConfigurationManager.AppSettings.Get("SearchIndexPath")).Find(id) : null;
     if (result != null) {
         var cd = new System.Net.Mime.ContentDisposition {
             FileName = $"{id}.sql",
             Inline = false,
         };
         Response.AppendHeader("Content-Disposition", cd.ToString());
         return File(new MemoryStream(Encoding.ASCII.GetBytes(result["sqlscript"])), "application/x-sql");
     }
     throw new HttpException(404, "NotFound");
 }
 public ActionResult Download(string ISBN)
 {
     WebClient Client = new WebClient();
     Book Download = BooksRepository.GetBookByISBN(ISBN);
     byte[] bookData = Client.DownloadData(ConfigurationManager.AppSettings["MOBI_URL"].ToString() + ISBN + ".mobi");
     var cd = new System.Net.Mime.ContentDisposition
     {
         FileName = Download.Title.Replace("(", String.Empty).Replace(")", String.Empty) + ".mobi",
         Inline = false,
     };
     Response.AppendHeader("Content-Disposition", cd.ToString());
     return File(bookData, "application/x-mobipocket-ebook");
 }
Exemple #10
0
        public ActionResult SpecSheet()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Programming Exercise EYC.docx";
            byte[] filedata = System.IO.File.ReadAllBytes(path);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "Programming Exercise EYC.docx",

                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(filedata, "application/msword");
        }
        public ActionResult Download(string hash)
        {
            var arquivoRules = new ArquivoRules();
            var arquivo = arquivoRules.GetByHash(hash);

            System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
            {
                FileName = arquivo.Nome,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(Application.Path("/Public/files/" + arquivo.Hash), "application/force-download");
        }
        public ActionResult Download(int campanhaId, string nome, string hash)
        {
            var rules = new CampanhaRules();
            var filename = rules.GetPdfFilename(campanhaId, hash);

            System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
            {
                FileName = nome + ".pdf",
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filename, "application/force-download");
        }
        public FileContentResult GetFileContent(string fileName)
        {
            string filepath = Path.Combine(Server.MapPath("~/Resources/PDF"), fileName);
            byte[] filedata = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = fileName,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filedata, contentType);
        }
Exemple #14
0
        // GET: Pigeon
        public ActionResult CV()
        {
            var file = new FileInfo("~/App_Data/cv.docx");
            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = file.Name,

                // always prompt the user for downloading, set to true if you want 
                // the browser to try to show the file inline
                Inline = false,
            };
            //a comprendre
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File ("~/App_Data/cv.docx", "application/ms-word");
        }
        //
        // GET: /RadChart/
        public ActionResult Image(int MarketId = 1)
        {
            RadChart rc = new RadChart();
            rc.CreateChart(MarketId);

            var cd = new System.Net.Mime.ContentDisposition
            {

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = true,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(rc.ChartData, "image/jpg");
        }
Exemple #16
0
        public ActionResult Get(int id)
        {

            var document = Data.Objects.GetStudentDocument(id);

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = document.Name,

                // always prompt the user for downloading, set to true if you want 
                // the browser to try to show the file inline
                Inline = false
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(document.Contents.ToArray(), Helpers.Misc.GetMimeType(document.Name));
        }
        //
        // GET: /File/
        public ActionResult Download(string EMPLOYEE_ID, string YEAR_CHECKUP, string FILE_NAME)
        {
            string filePath = string.Format("{0}\\{1}_{2}\\{3}", ConfigurationManager.AppSettings["FileUpload"], EMPLOYEE_ID, YEAR_CHECKUP, FILE_NAME);

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = FILE_NAME,

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(filePath, Path.GetExtension(filePath));
        }
 public FileResult GetFile(string file)
 {
     var cd = new System.Net.Mime.ContentDisposition
     {
         FileName = GetFile("~/App_Data/DataFromClient/", file),
         Inline = false
     };
     //Response.AppendHeader("Content-Disposition", cd.ToString());
     try
     {
         return base.File(System.IO.File.ReadAllBytes(cd.FileName), System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName(cd.FileName));
     }
     catch (Exception)
     {
         // handle
     }
     return null;
 }
        public ActionResult GetData(string data ="", DataSource source= DataSource.Old)
        {
            string fileName = $"{source}data", filePath = "";
            switch (data) {
                //case "csv": fileName = DataGenerator.GenerateCSVDocument(source, Path.GetTempPath()); fileName += ".csv";  break;
            }

            byte[] filedata = System.IO.File.ReadAllBytes(filePath);
            string contentType = MimeMapping.GetMimeMapping(filePath);

            var cd = new System.Net.Mime.ContentDisposition {
                FileName = fileName,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filedata, contentType);
        }
        public ActionResult GetAttachment(string aid, string attname, string mid)
        {
            ExchangeService service = Connection.ConnectEWS();
            EmailMessage message = EmailMessage.Bind(service, new ItemId(mid), new PropertySet(ItemSchema.Attachments));
            message.Load();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] ContentBytes = null;
            string filename = null;
            string contentType = null;

            foreach (Attachment att in message.Attachments)
            {
                if (aid == att.Id.ToString() && att is FileAttachment)
                {
                    FileAttachment fileAt = att as FileAttachment;
                    fileAt.Load(ms);
                    filename = fileAt.Name;
                    contentType = fileAt.ContentType;
                }
                else if (aid == att.Id.ToString() && att is ItemAttachment)
                {
                    ItemAttachment itemAttachment = att as ItemAttachment;
                    itemAttachment.Load(new PropertySet(EmailMessageSchema.MimeContent));
                    MimeContent mc = itemAttachment.Item.MimeContent;
                    ContentBytes = mc.Content;
                    filename = itemAttachment.Name + ".eml";
                    contentType = itemAttachment.ContentType;

                }
            }

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());

            // return the file
            return File(ms.ToArray() ?? ContentBytes, attname);
        }
        // GET: Files
        public ActionResult DownloadCV(string url)
        {
            if (url != null)
            {
            byte[] filedata = System.IO.File.ReadAllBytes(url);
            string contentType = MimeMapping.GetMimeMapping(url);

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = url,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filedata, contentType);
        }
            TempData["Error"] = "You have to load up your CV! Click Hello in the header.";
            return View("Apply");
        }
        public ActionResult Download(string FileName)
        {
            //byte[] fileBytes = System.IO.File.ReadAllBytes("~/App_Data/CalculatedAddresses.xlsx");
            //var response = new FileContentResult(fileBytes, "application/octet-stream");
            //response.FileDownloadName = "~/App_Data/CalculatedAddresses.xlsx";
            //return response;

            string filepath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/" + FileName;
            byte[] filedata = System.IO.File.ReadAllBytes(filepath);
            string contentType = MimeMapping.GetMimeMapping(filepath);

            System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
            {
                FileName = FileName,
                Inline = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return File(filedata, contentType);
        }
        public ActionResult DetailsDownload(string stringId = "")
        {
            // Attempt to get the matching object
            var o = m.PropertyPhotoGetById(stringId);

            if (o == null)
            {
                return HttpNotFound();
            }
            else
            {
                // Get file extension, assumes the web server is Microsoft IIS based
                // Must get the extension from the Registry (which is a key-value storage structure for configuration settings, for the Windows operating system and apps that opt to use the Registry)

                // Working variables
                string extension;
                RegistryKey key;
                object value;

                // Open the Registry, attempt to locate the key
                key = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + o.ContentType, false);
                // Attempt to read the value of the key
                value = (key == null) ? null : key.GetValue("Extension", null);
                // Build/create the file extension string
                extension = (value == null) ? string.Empty : value.ToString();

                // Create a new Content-Disposition header
                var cd = new System.Net.Mime.ContentDisposition
                {
                    // Assemble the file name + extension
                    FileName = $"img-{stringId}{extension}",
                    // Force the media item to be saved (not viewed)
                    Inline = false
                };
                // Add the header to the response
                Response.AppendHeader("Content-Disposition", cd.ToString());

                return File(o.Content, o.ContentType);
            }
        }
        // GET: Image
        public ActionResult Index(string extension, string imageType)
        {
            if (imageType.IsNullOrWhiteSpace())
            {
                imageType = DefaultFileType;
            }

            if (extension.IsNullOrWhiteSpace())
            {
                return View();
            }

            if (!Types.Contains(imageType.ToLowerInvariant()))
            {
                ViewBag.Message = "Filetype not supported";
                return View("Error");
            }

            var dir = Path.Combine(Server.MapPath("~/Content"), imageType);
            var files = Directory.GetFiles(dir).Select(Path.GetFileNameWithoutExtension).ToArray();
            if (!files.Contains(extension))
            {
                //We don't have an icon for this file type
                return null;
            }
            var file = extension + "." + imageType; 
            var fileLocation = Path.Combine(dir, file);
            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = file,

                // always prompt the user for downloading, set to true if you want 
                // the browser to try to show the file inline
                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(fileLocation, "image/" + imageType);
        }
        // GET: Issue
        public ActionResult Index(int id = 1)
        {
            try
            {
                string filename = id + ".pdf";
                string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Content/Issues/" + filename;
                byte[] filedata = System.IO.File.ReadAllBytes(filepath);
                string contentType = MimeMapping.GetMimeMapping(filepath);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());

                return File(filedata, contentType);
            }
            catch
            {
                return View();
            }
        }
        public ActionResult Download(GeneratedXMLModel generatedViewModel,string filename = null)
        {
            //taken from stackoverflow : http://stackoverflow.com/questions/11260550/calling-save-dialog-box-from-javascript
            var document = generatedViewModel.GeneratedFix;
            string _filename;

            if (filename == null) {
                var y = Enum.Parse(typeof(SunTransactionType), SunTransactionType.CONTRA.ToString());
                _filename = generatedViewModel.PPReference;

                if (generatedViewModel.SunFixType == SunFixType.Sun)
                    _filename =  _filename + "_" +  generatedViewModel.transactionType.ToString();

            }
            else
            {
                _filename = filename;
            }
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = _filename,
                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };
            //Response.AppendHeader("Content-Disposition", cd.ToString());
            if (filename == null)
                if (generatedViewModel.SunFixType == SunFixType.Trader)
                    return File(new System.Text.UTF8Encoding().GetBytes(document), "application/octet-stream", _filename+".sql");
                else
                    return File(new System.Text.UTF8Encoding().GetBytes(document), "application/octet-stream", _filename+".xml");
            else{
                string filePath = Path.Combine(Server.MapPath("~/"), "Temp",filename);
                return File(filePath, "application/octet-stream", DateTime.Now.ToString("yyyyMMddHHmm")+".zip");
            }
        }
        public FileContentResult ReturnBookInPdf(string isbn)
        {
            try
            {

                var bytes = new BookManager().GetPdf(Convert.ToInt64(isbn));

                const string mimeType = "application/pdf";

                var content = new System.Net.Mime.ContentDisposition
                {
                    FileName = "Test.pdf",
                    Inline = true
                };

                Response.AppendHeader("Content-Disposition", content.ToString());
                return File(bytes, mimeType);
            }
            catch (Exception)
            {
                return null;

            }
        }
        public ActionResult Open(int id, string name)
        {
            MidiFile crumbsmodel = crumbsRepository.FindMidiFile(id);

            if (CurrentUser == null)
                return base.Content("Not Authorized");

            Payment payment = crumbsRepository.FindConfirmedPaymentForMIDI(CurrentUser.UserID, id);
            if(payment == null)
                return base.Content("Not Authorized");

            string path = MidiFileHelper.getMidiPath(crumbsmodel);
            string FullPath = HostingEnvironment.ApplicationPhysicalPath + path;

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = crumbsmodel.FileName,

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return base.File(FullPath, "audio/midi");
        }
        public ActionResult GetFile()
        {
            XSSFWorkbook wb    = new XSSFWorkbook();
            ISheet       sheet = wb.CreateSheet("Archivo");

            #region Escribe Archivo
            int col_Actual = 0;
            int row_Actual = 0;
            var row_       = sheet.CreateRow(row_Actual++);
            row_.CreateCell(col_Actual).SetCellValue("IdCliente");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("FechaRegistroEmpresa");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("RazonSocial");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("RFC");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("Sucursal");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("IdEmpleado");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("Nombre");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("Paterno");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("Materno");
            col_Actual++;
            row_.CreateCell(col_Actual).SetCellValue("IdViaje");
            col_Actual = 0;

            InfoCustomer info = GetData();
            if (info.Data != null && info.Data.Count > 0)
            {
                foreach (var elm in info.Data)
                {
                    var row_d = sheet.CreateRow(row_Actual++);
                    row_d.CreateCell(col_Actual).SetCellValue(elm.IdCliente.ToString().Trim());
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.FechaRegistroEmpresa.ToString().Trim());;
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.RazonSocial.Trim());
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.RFC.Trim());
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.Sucursal);
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.IdEmpleado.ToString());
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.Nombre);
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.Paterno);
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.Materno);
                    col_Actual++;
                    row_d.CreateCell(col_Actual).SetCellValue(elm.IdViaje.ToString());
                    col_Actual = 0;
                }
            }


            #endregion

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try
            {
                wb.Write(bos);
            }
            finally
            {
                bos.Close();
            }
            byte[] bytes = bos.ToByteArray();

            string filename = "customers.xlsx";

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return(File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Exemple #30
0
        }         // Index

        public ActionResult DownloadMessagesDocument(string id, bool download = false)
        {
            Guid       guid;
            FileResult fs = null;
            string     fileName;

            if (Guid.TryParse(id, out guid))
            {
                var askville     = _askvilleRepository.GetAskvilleByGuid(id);
                var askvilleData = ConvertFormat(string.IsNullOrEmpty(askville.MessageBody) ? "" : askville.MessageBody, SaveFormat.Pdf, "text");

                fs       = File(askvilleData, "application/pdf");
                fileName = string.Format("Askville({0}).pdf", FormattingUtils.FormatDateTimeToStringWithoutSpaces(askville.CreationDate));
            }
            else
            {
                var f = _exportResultRepository.Get(Convert.ToInt32(id));
                if (f == null)
                {
                    throw new Exception(String.Format("File id={0} not found", id));
                }
                fileName = f.FileName.Replace(",", "").Replace("£", "");
                if (f.FileType == 1)
                {
                    fs = File(f.BinaryBody, "application/pdf");
                }
                else
                {
                    if (f.FileName.EndsWith("html"))
                    {
                        fs = File(f.BinaryBody, "text/html");
                    }
                    else
                    {
                        if (download)
                        {
                            fs = File(f.BinaryBody, "application/msoffice");
                        }
                        else
                        {
                            var pdfDocument = AgreementRenderer.ConvertToPdf(f.BinaryBody, LoadFormat.Docx);
                            fs = File(pdfDocument, "application/pdf");
                            fileName.Replace("docx", "pdf");
                        }
                    }
                }
            }

            if (download)
            {
                fs.FileDownloadName = fileName;
            }
            else
            {
                var cd = new System.Net.Mime.ContentDisposition {
                    FileName = fileName,
                    Inline   = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
            }
            return(fs);
        }
Exemple #31
0
        public ActionResult Download(string fileFolder, string fileName)
        {
            AppLogger.log.Info("Function => Download ==> fileFolder = " + fileFolder);
            AppLogger.log.Info("Function => Download ==> fileName = " + fileName);
            string filePath = string.Empty;
            string fpath    = string.Empty;

            try
            {
                filePath = Path.Combine(Server.MapPath("~/PriorityDocs"), fileFolder + "/" + fileName);
                AppLogger.log.Info("Function => Download ==> filePath = " + filePath);
            }
            catch (Exception ex)
            {
                AppLogger.log.Info("filePath = Exception", ex);
                return(Json(new { status = "error", message = "error creating folder path" }));
            }
            string filename = fileName;

            byte[] filedata = null;

            try
            {
                FileStream fs = System.IO.File.OpenRead(filePath);
                filedata = new byte[fs.Length];
                //return View();
            }
            catch (Exception ex)
            {
                AppLogger.log.Info("Function => Download ==> ReadAllBytes = " + filePath);
                AppLogger.log.Info("filePath ==> ReadAllBytes ==> Exception", ex);
                return(Json(new { status = "error", message = "error reading from folder" }));
            }

            string contentType  = MimeMapping.GetMimeMapping(filePath);
            var    content_type = "";
            var    cd           = new System.Net.Mime.ContentDisposition
            {
                FileName = fileName,
                Inline   = true,
            };

            Response.Clear();
            Response.ClearContent();
            Response.Buffer = true;
            Response.ClearHeaders();

            if (filePath.Contains(".doc"))
            {
                content_type = "application/msword";
            }
            else if (filePath.Contains(".docx"))
            {
                content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            }
            else if (filePath.Contains(".pdf"))
            {
                content_type = "application/pdf";
            }
            else if (filePath.Contains(".xsl"))
            {
                content_type = "application/vnd.ms-excel";
            }
            else if (filePath.Contains(".jpeg") || filePath.Contains(".jpg"))
            {
                content_type = "image/jpeg";
            }
            else if (filePath.Contains(".xsl"))
            {
                content_type = "application/vnd.ms-excel";
            }
            else if (filePath.Contains(".csv"))
            {
                content_type = "text/csv";
            }
            else if (filePath.Contains(".bmp"))
            {
                content_type = "image/x-windows-bmp";
            }
            else if (filePath.Contains(".xlsx"))
            {
                content_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
            else
            {
                content_type = "text/plain";
            }

            Response.ContentType = content_type;
            Response.AppendHeader("Content-Disposition", "attachment; " + cd.ToString());

            Response.TransmitFile(filePath);
            Response.End();

            return(File(filedata, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));
        }
Exemple #32
0
        public ActionResult Download()
        {
            int FileId = Convert.ToInt32(TempData["FileId"]);

            try
            {
                int CurrentUserId = USerConfig.GetUserID();
                if (objFileDataLayer.FileUserAccess(FileId, CurrentUserId))
                {
                    int        RequestId  = objFileDataLayer.GenerateRequest(FileId, CurrentUserId);
                    List <int> PartnerIds = objFileDataLayer.GetPartnerIds(FileId);
                    objFileDataLayer.GenerateOTP(PartnerIds, RequestId);
                    string          AccessStatus = objFileDataLayer.AuthorizeOTP(RequestId);//Until and unless we get NouserPending status the file will not download
                    User_Controller userData     = new User_Controller();


                    foreach (var partnerid in PartnerIds)
                    {
                        int GetOtp = userData.GetOtp(RequestId, partnerid);
                        SMTPProtocol.NotifyPartners("Notification", string.Format("You partners is waiting for the file ,Please find the OTP : {0} .Use the following url to enter your ", GetOtp), userData.GetEmailbyPartnerId(partnerid.ToString()));
                    }

                    if (AccessStatus == "NoUserPending" && AccessStatus != "")
                    {
                        string fileName = objFileDataLayer.GetFileName(FileId);
                        if (fileName != "NIL")
                        {
                            var    filepath    = Path.Combine(Server.MapPath("~/PostImage"), fileName);
                            byte[] filedata    = System.IO.File.ReadAllBytes(filepath);
                            string contentType = MimeMapping.GetMimeMapping(filepath);

                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = fileName,
                                Inline   = true,
                            };

                            Response.AppendHeader("Content-Disposition", cd.ToString());
                            objFileDataLayer.DeleteRequest(RequestId);
                            return(File(filedata, contentType));
                        }
                        else
                        {
                            ViewBag.Title   = "File not found";
                            ViewBag.Message = "The file you are trying to access is deleted";
                            return(View());
                        }
                    }
                    else
                    {
                        return(View());
                    }
                }
                else
                {
                    ViewBag.Title   = "Illegal Entry";
                    ViewBag.Message = "You are not authorized to access this file";
                    return(View());
                }
            }
            catch
            {
                return(View());
            }
        }
        public async Task <ActionResult> ExecuteReport(string name, string frequency)
        {
            var report = (await PortalHelpers.GetReportsAsync(name)).FirstOrDefault();

            if (report == null)
            {
                return(NotFound());
            }
            var paramValueByParamName = new Dictionary <string, string>();

            foreach (string k in Request.Form.Keys)
            {
                if (!k.StartsWith(ReportParameterNamePrefix))
                {
                    continue;
                }
                paramValueByParamName[k.RightOf(ReportParameterNamePrefix)] = Request.Form[k].FirstOrDefault();
            }
            var config   = ConfigOptions.Value;
            var template = PortalHelpers.GetEmailTemplate(config.ReportEmailTemplateId);

            switch (frequency)
            {
            case "":
            case null:
            case ReportFrequencies.Synchronous:
            {
                var res = await ReportRunner.ExecuteAsync(name, paramValueByParamName);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = res.Name,
                    Inline   = false,
                };
                Response.Headers.Add("Content-Disposition", cd.ToString());
                return(File(res.ContentStream, res.ContentType.MediaType));
            }

            case ReportFrequencies.EmailMeOnce:
            {
                if (template == null)
                {
                    throw new UloException(UloExceptionCodes.NoEmailTemplate, $"templateId={config.ReportEmailTemplateId} for report={report.Name}");
                }
                var recipients = new[] { CurrentUser.Email };
                var o          = new ReportEmailViewModel(User.Identity.Name)
                {
                    Report = report
                };
                var jobId = BackgroundJobClient.Enqueue <IBackgroundTasks>(b => b.EmailReport(recipients, template.EmailSubject, template.EmailBody, template.EmailHtmlBody, o, name, paramValueByParamName));
                AddPageAlert(new PageAlert($"Scheduled immediate execution of report \"{report.Title}\" for email to {recipients.FirstOrDefault()} with jobId={jobId}", false));
                return(RedirectToAction(ActionNames.ListReports));
            }

            case ReportFrequencies.Recurring:
            {
                if (template == null)
                {
                    throw new UloException(UloExceptionCodes.NoEmailTemplate, $"templateId={config.ReportEmailTemplateId} for report={report.Name}");
                }
                var domains        = CSV.ParseLine(config.ReportRecipientEmailDomains).ToCaseInsensitiveSet();
                var recipients     = Request.Form["recipients"].FirstOrDefault().Split(';', ',', '\t', ' ', '\r', '\n').Select(z => z.TrimOrNull()).WhereNotNull().Where(z => domains.Contains(z.RightOf("@"))).ToArray();
                var now            = DateTime.UtcNow;
                var recurringJobId = $"{User.Identity.Name}.Report.{report.Name}.{now.ToYYYYMMDD()}.{now.ToHHMMSS()}";
                var o = new ReportEmailViewModel(User.Identity.Name)
                {
                    JobId    = recurringJobId,
                    Report   = report,
                    UserNote = Request.Form["userNote"].FirstOrDefault()
                };
                var job  = Hangfire.Common.Job.FromExpression <IBackgroundTasks>(b => b.EmailReport(recipients, template.EmailSubject, template.EmailBody, template.EmailHtmlBody, o, name, paramValueByParamName));
                var cron = Request.Form["cron"].FirstOrDefault().TrimOrNull();
                if (cron == null)
                {
                    var time = DateTime.Parse(Request.Form["time"]);
                    time = TimeZoneInfo.ConvertTimeToUtc(time, PortalHelpers.DisplayTimeZone);
                    cron = Hangfire.Cron.Daily(time.Hour, time.Minute);
                }
                RJM.AddOrUpdate(recurringJobId, job, cron);
                AddPageAlert(new PageAlert($"Scheduled recurring report \"{report.Title}\" for email to {recipients.Length} recipients with recurringJobId={recurringJobId}", false));
                return(RedirectToAction(ActionNames.ListReports));
            }

            default:
                throw new UnexpectedSwitchValueException(frequency);
            }
        }
Exemple #34
0
        /// <summary>
        /// SendNetMail,多个收件人、抄送人、附件其参数用";"隔开,最后一个不能有";"
        /// </summary>
        /// <param name="mailFrom">发件人</param>
        /// <param name="mailTo">收件人(多个收件人用";"隔开,最后一个不能有";")</param>
        /// <param name="mailSubject">主题</param>
        /// <param name="mailBody">内容</param>
        /// <param name="mailAttch">附件(多个附件用";"隔开,最后一个不能有";")</param>
        /// <param name="mailAccount">用户名(对加密过的)</param>
        /// <param name="mailCode">密码(对加密过的)</param>
        /// <param name="mailPriority">优先级</param>
        /// <param name="mailCC">抄送(多个抄送人用";"隔开,最后一个不能有";")</param>
        /// <param name="resultMessage">输出信息</param>
        public static void SendNetMail(string mailFrom, string mailTo, string mailSubject, string mailBody, string mailAttch, string mailAccount, string mailCode, string mailPriority, string mailCC, out string resultMessage)
        {
            //初始化输出参数
            resultMessage = "";

            //发件人和收件人不为空
            if (string.IsNullOrEmpty(mailFrom) || string.IsNullOrEmpty(mailTo))
            {
                resultMessage = "Please Fill Email Addresser Or Addressee . ";
                return;
            }

            System.Net.Mail.MailMessage email     = new System.Net.Mail.MailMessage();
            System.Net.Mail.MailAddress emailFrom = new System.Net.Mail.MailAddress(mailFrom);

            //发件人
            email.From = emailFrom;
            //收件人
            if (string.IsNullOrEmpty(DebugMail))
            {
                string[] toUsers = mailTo.Split(';');
                foreach (string to in toUsers)
                {
                    if (!string.IsNullOrEmpty(to))
                    {
                        email.To.Add(to);
                    }
                }
            }
            else
            {
                email.To.Add(DebugMail);
                mailSubject += "(MailTo " + mailTo + ")";
            }
            //抄送
            if (string.IsNullOrEmpty(DebugMail))
            {
                if (!string.IsNullOrEmpty(mailCC))
                {
                    string[] ccUsers = mailCC.Split(';');
                    foreach (string cc in ccUsers)
                    {
                        if (!string.IsNullOrEmpty(cc))
                        {
                            email.CC.Add(cc);
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(mailCC))
                {
                    mailSubject += "(MailCC " + mailCC + ")";
                }
            }
            //主题
            email.Subject = mailSubject;
            //内容
            email.Body = mailBody;
            //附件
            if (!string.IsNullOrEmpty(mailAttch))
            {
                string[] attachments = mailAttch.Split(';');
                foreach (string file in attachments)
                {
                    System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
                    //为附件添加发送时间
                    System.Net.Mime.ContentDisposition disposition = attach.ContentDisposition;
                    disposition.CreationDate     = System.IO.File.GetCreationTime(file);
                    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                    disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);
                    //添加附件
                    email.Attachments.Add(attach);
                }
            }
            //优先级
            email.Priority = (mailPriority == "High") ? System.Net.Mail.MailPriority.High : System.Net.Mail.MailPriority.Normal;
            //内容编码、格式
            email.BodyEncoding = System.Text.Encoding.UTF8;
            email.IsBodyHtml   = true;
            //SMTP服务器
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(MailSmtpServer);

            //验证(Credentials 凭证)
            if (!string.IsNullOrEmpty(mailAccount))
            {
                client.Credentials = new System.Net.NetworkCredential(mailAccount, mailCode);
            }

            //处理待发的电子邮件的方法 (Delivery 发送,传输)
            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            try
            {
                //发送邮件
                client.Send(email);
                resultMessage = "Sent Successfully";
            }
            catch (Exception ex)
            {
                resultMessage = "Send Faile,Bring Error :" + ex.Message;
            }
        }
Exemple #35
0
        public async Task <IActionResult> ExportProjectData(long id, string type, long userId = -1)
        {
            FileStreamResult fsr = null;
            var filePath         = "";

            // check for valid project
            var project = await _unitOfWork.Projects.SingleOrDefaultAsync(p => p.Id == id);

            if (project == null)
            {
                return(NotFound());
            }

            // check for valid export type parameter
            switch (type)
            {
            case "text":
            case "numeric":
            case "codebook":
                break;

            default:
                _logger.LogError("Invalid export type parameter = {Type}", type);
                return(BadRequest());
            }
            // check if userid passed,  if yes then export data for the requested user
            ExportResult exportResult;

            exportResult = await _exportService.ExportProjectData(id, type, userId);

            if (exportResult.IsSuccessful())
            {
                filePath = exportResult.FilePath;
            }
            else
            {
                Console.WriteLine("Error in export");
                Response.Headers.Add("Content-Type", "application/json");
                return(Json(exportResult));
            }

            // response...
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = Uri.EscapeUriString(Path.GetFileName(filePath)),
                Inline   = false // false = prompt the user for downloading, true = browser to show the file inline
            };

            Response.Headers.Add("Content-Disposition", cd.ToString());
            Response.Headers.Add("X-Content-Type-Options", "nosniff");

            try
            {
                Stream tempFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                fsr = new FileStreamResult(tempFileStream, "text/csv");
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to read: {0}, exception {1} ", filePath, e);
                return(fsr);
            }

            return(fsr);
        }
Exemple #36
0
        public IActionResult Download(int episode, string fileName)
        {
            string   path          = string.Empty;
            string   contentType   = string.Empty;
            long     contentLength = 0;
            DateTime dateUploaded  = new DateTime(1900, 1, 1);

            // find the podcast specified
            var foundPodcast = _dbContext.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();

            if (foundPodcast != null)
            {
                PodcastFile file = foundPodcast.Files.Where(f => f.FileName == fileName).FirstOrDefault();
                if (file != null)
                {
                    path          = file.Path;
                    contentType   = file.ContentType;
                    contentLength = file.ContentLength;
                    fileName      = file.FileName;
                    dateUploaded  = foundPodcast.DateEdited;
                }
                else
                {
                    return(new StatusCodeResult(StatusCodes.Status404NotFound));
                }
            }
            else
            {
                return(new StatusCodeResult(StatusCodes.Status404NotFound));
            }
            if (System.IO.File.Exists(path))
            {
                // Are they downloading it by range?
                bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]);              // We do not support ranges

                bool isCached = !string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]); // Check to see if they have a cache

                if (isCached)
                {
                    // The file is cached, let's just 304 this
                    Response.StatusCode = 304;
                    Response.Headers.Add("Content-Length", "0");
                    return(Content(string.Empty));
                }
                else
                {
                    long startByte = 0;
                    long endByte   = contentLength - 1;
                    long length    = contentLength;

                    #region Range Calculation
                    // check to see if we need to pass a specified range
                    if (byRange)
                    {
                        long     anotherStart = startByte;
                        long     anotherEnd   = endByte;
                        string[] arr_split    = Request.Headers["Range"].ToString().Split(new char[] { '=' });
                        string   range        = arr_split[1];

                        // Make sure the client hasn't sent us a multibyte range
                        if (range.IndexOf(",") > -1)
                        {
                            // (?) Shoud this be issued here, or should the first
                            // range be used? Or should the header be ignored and
                            // we output the whole content?
                            Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                            return(new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable));
                        }

                        // If the range starts with an '-' we start from the beginning
                        // If not, we forward the file pointer
                        // And make sure to get the end byte if spesified
                        if (range.StartsWith("-"))
                        {
                            // The n-number of the last bytes is requested
                            anotherStart = startByte - Convert.ToInt64(range.Substring(1));
                        }
                        else
                        {
                            arr_split    = range.Split(new char[] { '-' });
                            anotherStart = Convert.ToInt64(arr_split[0]);
                            long temp = 0;
                            anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
                        }

                        /* Check the range and make sure it's treated according to the specs.
                         * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                         */
                        // End bytes can not be larger than $end.
                        anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
                        // Validate the requested range and return an error if it's not correct.
                        if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
                        {
                            Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                            return(new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable));
                        }
                        startByte = anotherStart;
                        endByte   = anotherEnd;

                        length = endByte - startByte + 1; // Calculate new content length

                        // Ranges are response of 206
                        Response.StatusCode = 206;
                    }
                    #endregion

                    // We accept ranges
                    Response.Headers.Add("Accept-Ranges", "0-" + contentLength);

                    // Notify the client the byte range we'll be outputting
                    Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                    // Notify the client the content length we'll be outputting
                    Response.Headers.Add("Content-Length", length.ToString());

                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = fileName,
                        Inline   = true
                    };

                    Response.Headers.Add("Content-Disposition", cd.ToString());

                    FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

                    // Reset file stream to starting position (or start of range)
                    fileStream.Seek(startByte, SeekOrigin.Begin);

                    return(new BufferedFileStreamResult(contentType, (response) => ResponseHelper.StreamToOutput(response, true, fileStream, (int)length, 4 * 1024), false));
                }
            }
            return(new StatusCodeResult(StatusCodes.Status404NotFound));
        }
        public ActionResult DownloadFile(string filePath)
        {
            // string blobPath = Path.GetFullPath(filePath);

            //return new FileStreamResult(new FileStream(new Uri(filePath).AbsolutePath,FileMode.Open),"image/jpeg");
            //string azureFilePath = filePath;
            string relativeDirectoryPath = ConfigurationManager.AppSettings["ImageDirectoryPath"].ToString();

            string directoryPath = HttpContext.Server.MapPath(relativeDirectoryPath);
            //string directoryPath = @"C:\Users\Poonam\Downloads\";


            string imageFullPath = directoryPath + "\\" + filePath.Substring(filePath.LastIndexOf('/') + 1);

            //  Models.User.DownloadImageFromAzure(filePath, imageFullPath, "poonam");

            using (WebClient client = new WebClient())
            {
                //fileName = fileName + extension;

                client.DownloadFile(filePath, imageFullPath);
            }

            FileStream fs = new FileStream(imageFullPath, FileMode.Open);

            byte[] buf         = new byte[fs.Length];
            int    br          = fs.Read(buf, 0, buf.Length);
            string contentType = MimeMapping.GetMimeMapping(imageFullPath);

            // Response.AppendHeader("Content-Disposition", "attachment; filename=" + filePath.Substring(filePath.LastIndexOf('/') + 1));
            //Response.AddHeader("Content-Length", fs.Length.ToString());
            //Response.ContentType = "application/octet-stream";
            // Response.OutputStream.Write(buf, 0, buf.Length);

            //return new FileStreamResult(new FileStream(imageFullPath,FileMode.Open),"image/jpeg");
            //return  File(buf, "application/octet-stream");

            //return File(buf, System.Net.Mime.MediaTypeNames.Application.Octet);
            //return new FileStreamResult(fs, "application/octet-stream");


            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filePath.Substring(filePath.LastIndexOf('/') + 1),
                Inline   = false,
                //DispositionType = System.Net.Mime.ContentDisposition.DispositionType.
            };

            //fs.Close();
            //Response.AppendHeader("Content-Disposition", cd.ToString());

            //Response.Headers.Remove("Content-Disposition");
            //Response.Headers.Add("Content-Disposition", "attachment;filename="+ filePath.Substring(filePath.LastIndexOf('/') + 1));
            // Response.AppendHeader("Content-Disposition", "attachment;filename="+ filePath.Substring(filePath.LastIndexOf('/') + 1));

            //Response.Buffer = true;
            //return File(buf, System.Net.Mime.MediaTypeNames.Application.Octet, filePath.Substring(filePath.LastIndexOf('/') + 1));


            //  return new FileContentResult(buf, contentType);
            return(new FileStreamResult(fs, cd.ToString()));

            //return null;
        }
        public ActionResult DownloadBatchOverviewReport(String _TemplateKey, String _1stBatchKey, String _2ndBatchKey, String _BatchTypeKey, String _MaterialKey, String StartTime, String EndTime, bool CreateLogFile = false)
        {
            const string FILENAME_PREFIX = "BatchOverview_";
            //const string FILENAME_PREFIX = "BatchOverview";
            const string FILENAME_TYPE       = "xlsx";
            const string EXCEL_TEMPLATE_NAME = "ExcelReport_BatchOverview_Template.xlsx";
            const string SSIS_PACKAGE        = "ExcelReport_BatchOverview.dtsx";
            const string FOLDER_BASE_SOURCE  = "Areas\\PlantiT.Web.HeinekenMassafra.MES\\Excel";
            const string FOLDER_BIN          = "bin";
            const string FOLDER_TEMPLATE     = "template";
            const string FOLDER_BASE_OUTPUT  = "Areas\\PlantiT.Web.HeinekenMassafra.MES\\Excel\\output";
            //const string FOLDER_BASE_OUTPUT = "Areas\\PlantiT.Web.HeinekenMassafra.MES\\Excel\\output\\";
            const string LOG_FILE_NAME = "DownloadBatchOverview_Log.txt";


            const int WAITTIME_IN_MS    = 1000;
            const int MAXWAITTIME_IN_MS = 30000;

            String sLocation = Assembly.GetExecutingAssembly().Location; // Get current directory

            Logger logger = null;

            long     nTemplateKey  = 0;
            long     n1stBatchKey  = 0;
            long     n2ndBatchKey  = 0;
            long     nBatchTypeKey = 0;
            long     nMaterialKey  = 0;
            DateTime dtStartTime   = DateTime.MaxValue;
            DateTime dtEndTime     = DateTime.MinValue;

            string sSourcePath          = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FOLDER_BASE_SOURCE);
            string sDestinationPath     = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FOLDER_BASE_OUTPUT);
            string sDestinationFilePath = String.Empty;
            string sFileName            = String.Empty;

            DateTime dtCheckTime = DateTime.Now;

            // Log generieren
            if (CreateLogFile)
            {
                logger = new Logger(Path.Combine(sDestinationPath, LOG_FILE_NAME), true);
            }


            // Parameter ermitteln
            // TemplateKey
            try
            {
                nTemplateKey = Convert.ToInt64(_TemplateKey);
            }
            catch { }

            // 1stBatchKey
            try
            {
                n1stBatchKey = Convert.ToInt64(_1stBatchKey);
            }
            catch { }

            // 2ndBatchKey
            try
            {
                n2ndBatchKey = Convert.ToInt64(_2ndBatchKey);
            }
            catch { }

            // BatchTypeKey
            try
            {
                nBatchTypeKey = Convert.ToInt64(_BatchTypeKey);
            }
            catch { }

            // MaterialKey
            try
            {
                nMaterialKey = Convert.ToInt64(_MaterialKey);
            }
            catch { }

            // StartTime
            try
            {
                dtStartTime = Convert.ToDateTime(StartTime);
            }
            catch { }

            // EndTime
            try
            {
                dtEndTime = Convert.ToDateTime(EndTime);
            }
            catch { }



            // Nach Datei suchen
            sFileName = FILENAME_PREFIX + DateTime.Now.ToString().Replace(":", "").Replace('/', '.').Replace('-', '.');
            //sFileName = FILENAME_PREFIX;

            Microsoft.SqlServer.Dts.Runtime.Application app     = new Microsoft.SqlServer.Dts.Runtime.Application();
            Microsoft.SqlServer.Dts.Runtime.Package     package = null;
            MyEventListener eventListener = new MyEventListener();

            //Load the SSIS Package which will be executed
            app.PackagePassword = "******";

            String sPackageFilePath = Path.Combine(sSourcePath, FOLDER_BIN, SSIS_PACKAGE);

            // Execute
            try
            {
                // Load package
                package = app.LoadPackage(sPackageFilePath, eventListener);


                // Set values
                Variables vars = package.Variables;

                vars["User::InputTemplateKey"].Value  = nTemplateKey;
                vars["User::Input1stBatchKey"].Value  = n1stBatchKey;
                vars["User::Input2ndBatchKey"].Value  = n2ndBatchKey;
                vars["User::InputBatchTypeKey"].Value = nBatchTypeKey;
                vars["User::InputMaterialKey"].Value  = nMaterialKey;
                vars["User::InputStartTime"].Value    = dtStartTime;
                vars["User::InputEndTime"].Value      = dtEndTime;



                vars["User::InputDestinationFile"].Value  = sFileName + "." + FILENAME_TYPE;
                vars["User::InputDestinationPath"].Value  = sDestinationPath;
                vars["User::InputTemplateFilePath"].Value = Path.Combine(sSourcePath, FOLDER_TEMPLATE, EXCEL_TEMPLATE_NAME);
                vars["User::InputCreateLogFile"].Value    = CreateLogFile;
                vars["User::InputLogFilePath"].Value      = (logger != null) ? logger.FilePath : String.Empty;

                // Log erzeugen
                if (logger != null)
                {
                    logger.Log("InputTemplateKey", vars["User::InputTemplateKey"].Value.ToString());
                    logger.Log("Input1stBatchKey", vars["User::Input1stBatchKey"].Value.ToString());
                    logger.Log("Input2ndBatchKey", vars["User::Input2ndBatchKey"].Value.ToString());
                    logger.Log("InputBatchTypeKey", vars["User::InputBatchTypeKey"].Value.ToString());
                    logger.Log("InputMaterialKey", vars["User::InputMaterialKey"].Value.ToString());
                    logger.Log("InputStartTime", vars["User::InputStartTime"].Value.ToString());
                    logger.Log("InputEndTime", vars["User::InputEndTime"].Value.ToString());

                    logger.Log("InputDestinationFile", vars["User::InputDestinationFile"].Value.ToString());
                    logger.Log("InputDestinationPath", vars["User::InputDestinationPath"].Value.ToString());
                    logger.Log("InputTemplateFilePath", vars["User::InputTemplateFilePath"].Value.ToString());
                }


                vars["InputToOverwrite"].Value = true;

                DTSExecResult results = package.Execute(null, null, eventListener, null, null);
            }
            catch (Exception ex)
            {
                if (logger != null)
                {
                    logger.Log("Error", String.Format("Error: {0} // Innermessage: {1}", ex.Message, (ex.InnerException != null) ? ex.InnerException.Message : String.Empty));
                }

                return(new HttpNotFoundResult(String.Format("Error: {0} // Innermessage: {1}", ex.Message, (ex.InnerException != null) ? ex.InnerException.Message : String.Empty)));
            }

            // zyklisch prüfen ob Datei vorhanden ist, maximal  MAXWAITTIME_IN_MS
            for (int i = 0; i < MAXWAITTIME_IN_MS; i += WAITTIME_IN_MS)
            {
                if (package.Errors.Count > 0)
                {
                    foreach (var item in package.Errors)
                    {
                        if (logger != null)
                        {
                            logger.Log("Error", item.Description);
                        }
                    }
                    break;
                }

                // erstmal eine Sekunde zeit geben, zyklisch prüfen
                System.Threading.Thread.Sleep(WAITTIME_IN_MS);

                // alle Dateien des Pfades holen die dem Suchmuster entsprechen
                DirectoryInfo dirInfo     = new DirectoryInfo(Path.Combine(sDestinationPath));
                var           filesInPath = dirInfo.EnumerateFiles(String.Format("{0}*.{1}", sFileName, FILENAME_TYPE));

                var file = filesInPath.Where(x => x.Name.Contains(sFileName)).OrderByDescending(x => x.LastWriteTime).FirstOrDefault();

                // nur welche die eben erstellt wurde
                if (file == null)
                {
                    continue;
                }

                // Falls eben erstellt...
                if (file.LastWriteTime >= dtCheckTime)
                {
                    // gefunden, Abbruch
                    sFileName = file.Name;
                    break;
                }
            }

            // Pfad mit Datei erzeugen
            sDestinationFilePath = Path.Combine(sDestinationPath, sFileName);

            // Datei vorhanden?
            if (!System.IO.File.Exists(sDestinationFilePath))
            {
                return(new HttpNotFoundResult("Excel file could not created!"));
            }

            // Create data return stream
            byte[] fileData    = System.IO.File.ReadAllBytes(sDestinationFilePath);
            string contentType = System.Web.MimeMapping.GetMimeMapping(sDestinationFilePath);

            // Datei entfernen
            System.IO.File.Delete(sDestinationFilePath);

            var cd = new System.Net.Mime.ContentDisposition()
            {
                // for example foo.bak
                FileName = sFileName,

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(fileData, contentType));
        }
        public async Task <IActionResult> DownloadPvData(int year, int month)
        {
            try
            {
                using (IStatelessSession session = peiuGridDataContext.SessionFactory.OpenStatelessSession())
                {
                    DateTime startDt  = new DateTime(year, month, 1);
                    DateTime endDt    = startDt.AddMonths(1).AddDays(-1);
                    var      pv_datas = await session.CreateCriteria <PvData>()
                                        .Add(Restrictions.Eq("siteId", (short)6))
                                        .Add(Restrictions.Where <PvData>(x => x.timestamp.Year == year && x.timestamp.Month == month))
                                        .AddOrder(Order.Asc("timestamp")).ListAsync <PvData>();

                    var groupsData = pv_datas.GroupBy(key => key.siteId, value => value);

                    var weathers = await session.CreateCriteria <Currentweather>()
                                   .Add(Restrictions.Where <Currentweather>(x => x.Timestamp.Year == year && x.Timestamp.Month == month))
                                   .AddOrder(Order.Asc("Timestamp"))
                                   .ListAsync <Currentweather>();

                    var           weather_result = weathers.ToArray();
                    StringBuilder sb             = new StringBuilder();

                    sb.AppendLine("siteid,pv_ts,w_ts,year,month,day,hour,gen,temp,humidity,cloud");
                    Currentweather currentweather = null;
                    foreach (IGrouping <short?, PvData> pvData in groupsData)
                    {
                        var timegroupsData = pvData.GroupBy(x => new DateTime(x.timestamp.Year, x.timestamp.Month, x.timestamp.Day, x.timestamp.Hour, 0, 0), value => value);

                        short siteid = pvData.Key.Value;
                        foreach (IGrouping <DateTime, PvData> row in pvData)
                        {
                            DateTime       pv_ts          = row.Key;
                            Currentweather target_weather = weathers.LastOrDefault(x => x.Timestamp <= pv_ts && x.Timestamp >= pv_ts.AddHours(-1));
                            if (target_weather != null)
                            {
                                currentweather = target_weather;
                            }
                            else if (target_weather == null && currentweather != null)
                            {
                                target_weather = currentweather;
                            }

                            sb.AppendLine($"{siteid},{pv_ts}{target_weather.Timestamp}{pv_ts.ToString("yyyy,MM,dd,HH")},{row.Sum(x => x.TotalActivePower) / 3600},{target_weather.Temp},{target_weather.Humidity},{target_weather.Clouds}");
                        }
                    }
                    string str       = sb.ToString();
                    byte[] dataBytes = Encoding.UTF8.GetBytes(str);
                    string file      = $"PV발전량이력_{year}_{month}.csv";
                    // Response...
                    System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = file,
                        Inline   = false // false = prompt the user for downloading;  true = browser to try to show the file inline
                    };
                    Response.Headers.Add("Content-Disposition", cd.ToString());
                    Response.Headers.Add("X-Content-Type-Options", "nosniff");
                    return(File(dataBytes, "application/octet-stream"));
                }
            }catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return(BadRequest());
            }
        }
Exemple #40
0
        public ActionResult DownloadFile(string generatorName)
        {
            var    date     = DateTime.Now.Date;
            var    time     = DateTime.Now.TimeOfDay;
            string filename = $"Export_Data_{generatorName}";

            filename = $"{filename}_{date.Day}-{date.Month}-{date.Year}";
            filename = $"{filename}_{time.Hours}-{time.Minutes}-{time.Seconds}-{time.Milliseconds}";
            filename = $"{filename}.pdf";

            var path = AppContext.BaseDirectory;
            var gg   = GG_VALUES.Find(g => g.Item1.Equals(generatorName ?? "", StringComparison.OrdinalIgnoreCase));
            List <Temperature> data = new List <Temperature>();

            if (gg != null)
            {
                data = csvHelper.ReadFile($"{path}App_Data\\{gg.Item2}")?.ToList();
            }

            var             helper   = new PdfHelper();
            var             dates    = data.Select(v => v.Date).ToList();
            List <DateTime> datesVal = new List <DateTime>();

            dates?.ForEach(d => datesVal.Add(DateTime.ParseExact(d, "dd.MM.yyyy HH:mm:ss", CultureInfo.InvariantCulture)));
            var startDate    = datesVal?.OrderBy(v => v).First();
            var startDateStr = startDate?.ToShortDateString() ?? "NA";
            var endDate      = datesVal?.OrderByDescending(v => v).First();
            var endDateStr   = endDate?.ToShortDateString() ?? "NA";

            List <double> values = data?.Select(v => {
                double val = 0;
                double.TryParse(v.Value, out val);
                return(val);
            })?.ToList() ?? new List <double>();

            var minVal = (values?.OrderBy(v => v)?.First())?.ToString() ?? "NA";
            var maxVal = (values?.OrderBy(v => v)?.Last())?.ToString() ?? "NA";
            var avgVal = 0f;
            var idx    = 0;

            data?.ForEach(item => {
                float.TryParse(item.Value, out float val);
                avgVal += val;
                idx++;
            });
            if (idx > 0)
            {
                avgVal /= idx;
            }
            var mostFreqVal = data?.GroupBy(v => v)?.Select(x => new { num = x, cnt = x.Count() })?.OrderByDescending(grp => grp.cnt)?.Select(g => g.num)?.First()?.Key?.Value?.ToString() ?? "NA";

            byte[] filedata = helper.ExportPdf(generatorName, data.Count, $"{startDateStr} - {endDateStr}", maxVal.ToString(), minVal.ToString(), avgVal.ToString(), mostFreqVal.ToString());

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = filename,
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());

            return(File(filedata, "pdf/application"));
        }
Exemple #41
0
        public ActionResult XlsDownload(CodeDto search)
        {
            // Data
            var privacys = db.Privacies.Where(p => p.OneKey != null && p.status == Status.PrivacyStatus.GRANTED);

            if (!string.IsNullOrEmpty(search.onekey))
            {
                privacys = privacys.Where(p => p.OneKey.Contains(search.onekey));
            }

            if (!string.IsNullOrEmpty(search.searchname))
            {
                privacys = privacys.Where(p => p.IND_FULL_NAME.Contains(search.searchname));
            }
            privacys = privacys.OrderBy(p => p.OneKey).OrderBy(p => p.NucleusKey);
            // Xls export
            var wb        = new XLWorkbook();
            var sheetname = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
            var ws        = wb.Worksheets.Add("CodeMatch" + sheetname);

            ws.Cell("A1").Value = "NucleusKey";
            ws.Cell("B1").Value = "OneKey";
            ws.Cell("C1").Value = "PCMSID";
            ws.Cell("D1").Value = "근무처(병원명)";
            ws.Cell("E1").Value = "근무처연락처";
            ws.Cell("F1").Value = "우편번호";
            ws.Cell("G1").Value = "주소";
            ws.Cell("H1").Value = "진료과";
            ws.Cell("I1").Value = "직위";
            ws.Cell("J1").Value = "고객명";
            ws.Cell("K1").Value = "이메일";
            ws.Cell("L1").Value = "핸드폰";
            ws.Cell("M1").Value = "수신거부여부";
            ws.Cell("N1").Value = "수집/이용동의";
            ws.Cell("O1").Value = "위탁동의";
            ws.Cell("P1").Value = "국외이전동의";
            ws.Cell("Q1").Value = "서명여부";
            ws.Cell("R1").Value = "동의서 버전";
            ws.Cell("S1").Value = "동의일자";
            ws.Cell("T1").Value = "동의채널";
            List <Privacy> list = privacys.ToList();
            int            row  = 2;

            foreach (Privacy p in list)
            {
                ws.Cell(row, 1).Value  = p.NucleusKey;
                ws.Cell(row, 2).Value  = p.OneKey;
                ws.Cell(row, 3).Value  = p.PCMSID;
                ws.Cell(row, 4).Value  = p.WKP_NAME;
                ws.Cell(row, 5).Value  = p.WKP_TEL;
                ws.Cell(row, 6).Value  = p.ZIP;
                ws.Cell(row, 7).Value  = p.FULL_ADDR;
                ws.Cell(row, 8).Value  = p.IND_SP;
                ws.Cell(row, 9).Value  = p.TITLE;
                ws.Cell(row, 10).Value = p.IND_FULL_NAME;
                ws.Cell(row, 11).Value = p.EMAIL;
                ws.Cell(row, 12).Value = p.MOBILE;
                ws.Cell(row, 13).Value = p.Unsubscribe;
                ws.Cell(row, 14).Value = p.CONSENT_USE;
                ws.Cell(row, 15).Value = p.CONSENT_TRUST;
                ws.Cell(row, 16).Value = p.CONSENT_ABROAD;
                ws.Cell(row, 17).Value = p.CONSENT_SIGN;
                ws.Cell(row, 18).Value = p.CONSENT.CONSENT_VERSION;
                ws.Cell(row, 19).Value = p.CONSENT.CONSENT_DATE_KOREA;
                ws.Cell(row, 20).Value = p.CONSENT.CONSENT_SOURCE;
                row++;
            }
            Stream fs = new MemoryStream();

            wb.SaveAs(fs);
            fs.Position = 0;

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "pcms_code_" + sheetname + ".xlsx",
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(fs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Exemple #42
0
        public ActionResult XlsDownload(ReportDto search)
        {
            var    sheetname   = DateTime.Now.ToString("yyyyMMddHHmmss");
            string currentuser = !string.IsNullOrEmpty(User?.Identity?.Name) ? User.Identity.Name.ToUpper() : "Anonymous";

            // Data
            var privacys = ReportSearch(search, true);
            // Xls export
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("진료과별고객수" + sheetname);

            ws.Cell("A1").Value = "진료과";
            ws.Cell("B1").Value = "고객수";
            ws.Cell("C1").Value = "이메일 보우";
            ws.Cell("D1").Value = "휴대폰번호 보유";

            int row      = 2;
            int cus      = 0;
            int email    = 0;
            int cp       = 0;
            int cusTot   = 0;
            int emailTot = 0;
            int cpTot    = 0;
            int nsCus    = 0;
            int nsEmail  = 0;
            int nsCP     = 0;

            foreach (var item in search.resultTotal)
            {
                if (IND_SP_LIST.Where(p => p.Text.Equals(item.SP)).Count() > 0)
                {
                    ws.Cell(row, 1).Value = item.SP;
                    cus     = item.count;
                    cusTot += cus;

                    ws.Cell(row, 2).Value = cus;

                    var sp = search.resultEmail.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                    if (sp == null)
                    {
                        email = 0;
                    }
                    else
                    {
                        email = sp.count;
                    }
                    emailTot += email;
                    ws.Cell(row, 3).Value = email;

                    sp = search.resultMobile.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                    if (sp == null)
                    {
                        cp = 0;
                    }
                    else
                    {
                        cp = sp.count;
                    }
                    cpTot += cp;
                    ws.Cell(row, 4).Value = cp;
                }
                else
                {
                }


                row++;
            }
            ws.Cell(row, 1).Value = "미분류";
            ws.Cell(row, 2).Value = cusTot;
            ws.Cell(row, 3).Value = emailTot;
            ws.Cell(row, 4).Value = cpTot;
            row++;
            ws.Cell(row, 1).Value = "합계";
            ws.Cell(row, 2).Value = cusTot;
            ws.Cell(row, 3).Value = emailTot;
            ws.Cell(row, 4).Value = cpTot;

            var ws2 = wb.Worksheets.Add("채널별유입고객수" + sheetname);

            ws2.Cell("A1").Value = "월";
            ws2.Cell("B1").Value = "GRV";
            ws2.Cell("C1").Value = "MMS";
            ws2.Cell("D1").Value = "서면동의서";
            ws2.Cell("E1").Value = "PForceRX";
            ws2.Cell("F1").Value = "총합계";

            row = 2;
            int mms, grv, doc, pfrx, mmsTot, grvTot, docTot, pfrxTot, totSum;

            mms = grv = doc = pfrx = mmsTot = grvTot = docTot = pfrxTot = totSum = 0;

            foreach (var item in search.resultTotal)
            {
                var it = search.rsMMS.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (it == null)
                {
                    mms = 0;
                }
                else
                {
                    mms = it.count;
                }
                mmsTot += mms;

                it = search.rsGRV.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (it == null)
                {
                    grv = 0;
                }
                else
                {
                    grv = it.count;
                }
                grvTot += grv;

                it = search.rsDOC.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (it == null)
                {
                    doc = 0;
                }
                else
                {
                    doc = it.count;
                }
                docTot += doc;

                it = search.rsPFRX.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (it == null)
                {
                    pfrx = 0;
                }
                else
                {
                    pfrx = it.count;
                }
                pfrxTot += pfrx;

                totSum += item.count;

                ws2.Cell(row, 1).Value = item.SP;
                ws2.Cell(row, 2).Value = mms;
                ws2.Cell(row, 3).Value = grv;
                ws2.Cell(row, 4).Value = doc;
                ws2.Cell(row, 5).Value = pfrx;
                ws2.Cell(row, 6).Value = item.count;

                row++;
            }

            ws2.Cell(row, 1).Value = "합계";
            ws2.Cell(row, 2).Value = mmsTot;
            ws2.Cell(row, 3).Value = grvTot;
            ws2.Cell(row, 4).Value = docTot;
            ws2.Cell(row, 5).Value = pfrxTot;
            ws2.Cell(row, 6).Value = totSum;

            Stream fs = new MemoryStream();

            wb.SaveAs(fs);
            fs.Position = 0;

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "pcms_" + currentuser + "_" + sheetname + ".xlsx",
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(fs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Exemple #43
0
        public FileResult DownloadFormSubmissions(string alias, string filename)
        {
            string         resultData = "";
            string         fieldNames = "";
            List <dynamic> resultList = GenerateSubmissionData(alias, out fieldNames);

            if ((resultList.Count > 0) && (!string.IsNullOrEmpty(fieldNames)))
            {
                string headerLine = "Date/Time".WrapQuotes() + "," + "IP".WrapQuotes() + ",";
                foreach (string currentFieldName in fieldNames.Split(','))
                {
                    string fieldTitle = WebConfigurationManager.AppSettings["FormStorage:Translation:" + currentFieldName];
                    if (string.IsNullOrEmpty(fieldTitle))
                    {
                        headerLine += currentFieldName.WrapQuotes() + ",";
                    }
                    else
                    {
                        headerLine += fieldTitle.WrapQuotes() + ",";
                    }
                }
                headerLine  = headerLine.Substring(0, headerLine.Length - 1);
                resultData += headerLine + "\n";

                foreach (IDictionary <string, Object> currentRecord in resultList)
                {
                    string currentLine = ((DateTime)currentRecord["datetime"]).ToString("MMM dd, yyyy HH:mm tt").WrapQuotes() + ",";
                    currentLine += currentRecord["IP"].ToString().WrapQuotes() + ",";
                    foreach (string currentFieldName in fieldNames.Split(','))
                    {
                        if (currentRecord.ContainsKey(currentFieldName))
                        {
                            currentLine += currentRecord[currentFieldName].ToString().WrapQuotes() + ",";
                        }
                        else
                        {
                            currentLine += "\"\",";
                        }
                    }
                    currentLine = currentLine.Substring(0, currentLine.Length - 1);
                    resultData += currentLine + "\n";
                }
            }
            string downloadfileName = alias + ".csv";

            if (!string.IsNullOrEmpty(filename))
            {
                downloadfileName = filename + ".csv";
            }

            byte[] byteData     = Encoding.UTF8.GetBytes(resultData);
            byte[] fileContents = Encoding.UTF8.GetPreamble().Concat(byteData).ToArray();

            System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
            {
                FileName = downloadfileName,
                Inline   = false
            };
            Response.Headers.Add("Content-Disposition", cd.ToString());
            Response.Headers.Add("X-Content-Type-Options", "nosniff");

            return(File(fileContents, "text/csv"));
        }
Exemple #44
0
        public ActionResult AdminXlsDownload(ReportDto search)
        {
            var    sheetname   = DateTime.Now.ToString("yyyyMMddHHmmss");
            string currentuser = !string.IsNullOrEmpty(User?.Identity?.Name) ? User.Identity.Name.ToUpper() : "Anonymous";

            // Data
            search = AdminSearch(search, true);
            // Xls export
            var wb = new XLWorkbook();
            var ws = wb.Worksheets.Add("승인반려 " + sheetname);

            ws.Cell("A1").Value = "월";
            ws.Cell("B1").Value = "승인";
            ws.Cell("C1").Value = "반려";
            ws.Cell("D1").Value = "합계";

            int row = 2;
            int aprTot = 0, rejTot = 0, Tot = 0, cnt = 0;

            foreach (var item in search.rsApproved)
            {
                var objRejected = search.rsRejected.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (objRejected != null)
                {
                    cnt = objRejected.count;
                }
                ws.Cell(row, 1).Value = item.SP;
                ws.Cell(row, 2).Value = item.count;
                ws.Cell(row, 3).Value = cnt;
                ws.Cell(row, 4).Value = cnt + item.count;
                aprTot += item.count;
                rejTot += cnt;
                Tot    += item.count + cnt;
                row++;
            }
            ws.Cell(row, 1).Value = "합계";
            ws.Cell(row, 2).Value = aprTot;
            ws.Cell(row, 3).Value = rejTot;
            ws.Cell(row, 4).Value = Tot;

            var ws2 = wb.Worksheets.Add("Code Mapping" + sheetname);

            ws2.Cell("A1").Value = "월";
            ws2.Cell("B1").Value = "Nucleus Code";
            ws2.Cell("C1").Value = "OneKey Code";

            row = 2;
            int nTot = 0, oTot = 0;

            cnt = 0;
            foreach (var item in search.rsN360)
            {
                var obj = search.rsOnekey.Where(p => p.SP.Equals(item.SP)).FirstOrDefault();
                if (obj != null)
                {
                    cnt = obj.count;
                }
                ws2.Cell(row, 1).Value = item.SP;
                ws2.Cell(row, 2).Value = item.count;
                ws2.Cell(row, 3).Value = cnt;
                nTot += item.count;
                oTot += cnt;
                row++;
            }
            ws2.Cell(row, 1).Value = "합계";
            ws2.Cell(row, 2).Value = nTot;
            ws2.Cell(row, 3).Value = oTot;

            var ws3 = wb.Worksheets.Add("고객개인정보" + sheetname);

            ws3.Cell("A1").Value = "전체 PCMS 레코드";
            ws3.Cell("B1").Value = "Nucleus 부여 레코드(중복포함)";
            ws3.Cell("C1").Value = "Nucleus 부여 레코드(중복제외)";

            ws3.Cell("A2").Value = search.pcms_count;
            ws3.Cell("B2").Value = search.n360_count;
            ws3.Cell("C2").Value = search.n360_distinct_count;

            ws3.Cell("A3").Value = "전체 PCMS 레코드";
            ws3.Cell("B3").Value = "Onekey 부여 레코드(중복포함)";
            ws3.Cell("C3").Value = "Onekey 부여 레코드(중복제외)";

            ws3.Cell("A4").Value = search.pcms_count;
            ws3.Cell("B4").Value = search.onekey_count;
            ws3.Cell("C4").Value = search.onekey_distinct_count;

            ws3.Cell("A5").Value = "전체 PCMS 레코드";
            ws3.Cell("B5").Value = "활성화 레코드";
            ws3.Cell("C5").Value = "비활성화 레코드";

            ws3.Cell("A6").Value = search.pcms_count;
            ws3.Cell("B6").Value = search.active_count;
            ws3.Cell("C6").Value = search.inactive_count;

            Stream fs = new MemoryStream();

            wb.SaveAs(fs);
            fs.Position = 0;

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "pcms_admin_report_" + currentuser + "_" + sheetname + ".xlsx",
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(fs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Exemple #45
0
        public async Task <IActionResult> Download(string file)
        {
            if (_config.UploadConfig.DownloadEnabled)
            {
                ViewBag.Title = "Download " + file;
                string   fileName       = string.Empty;
                string   url            = string.Empty;
                string   key            = string.Empty;
                string   iv             = string.Empty;
                string   contentType    = string.Empty;
                long     contentLength  = 0;
                bool     premiumAccount = false;
                DateTime dateUploaded   = new DateTime();

                Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
                if (upload != null)
                {
                    // Check Expiration
                    if (UploadHelper.CheckExpiration(upload))
                    {
                        DeleteFile(upload);
                        return(new StatusCodeResult(StatusCodes.Status404NotFound));
                    }

                    upload.Downloads += 1;
                    _dbContext.Entry(upload).State = EntityState.Modified;
                    _dbContext.SaveChanges();

                    fileName      = upload.FileName;
                    url           = upload.Url;
                    key           = upload.Key;
                    iv            = upload.IV;
                    contentType   = upload.ContentType;
                    contentLength = upload.ContentLength;
                    dateUploaded  = upload.DateUploaded;
                    if (User.Identity.IsAuthenticated)
                    {
                        IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);

                        premiumAccount = userInfo.AccountType == AccountType.Premium;
                    }
                    if (!premiumAccount && upload.User != null)
                    {
                        IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, upload.User.Username);

                        premiumAccount = userInfo.AccountType == AccountType.Premium;
                    }
                }
                else
                {
                    return(new StatusCodeResult(StatusCodes.Status404NotFound));
                }

                // We don't have the key, so we need to decrypt it client side
                if (string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
                {
                    DownloadViewModel model = new DownloadViewModel();
                    model.CurrentSub    = Subdomain;
                    model.FileName      = file;
                    model.ContentType   = contentType;
                    model.ContentLength = contentLength;
                    model.IV            = iv;
                    model.Decrypt       = true;

                    return(View(model));
                }
                else if (!premiumAccount && _config.UploadConfig.MaxDownloadSize < contentLength)
                {
                    // We want to force them to the dl page due to them being over the max download size for embedded content
                    DownloadViewModel model = new DownloadViewModel();
                    model.CurrentSub    = Subdomain;
                    model.FileName      = file;
                    model.ContentType   = contentType;
                    model.ContentLength = contentLength;
                    model.Decrypt       = false;

                    return(View(model));
                }
                else // We have the key, so that means server side decryption
                {
                    // Check for the cache
                    bool   isCached      = false;
                    string modifiedSince = Request.Headers["If-Modified-Since"];
                    if (!string.IsNullOrEmpty(modifiedSince))
                    {
                        DateTime modTime = new DateTime();
                        bool     parsed  = DateTime.TryParse(modifiedSince, out modTime);
                        if (parsed)
                        {
                            if ((modTime - dateUploaded).TotalSeconds <= 1)
                            {
                                isCached = true;
                            }
                        }
                    }

                    if (isCached)
                    {
                        return(new StatusCodeResult(StatusCodes.Status304NotModified));
                    }
                    else
                    {
                        string subDir    = fileName[0].ToString();
                        string filePath  = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, fileName);
                        long   startByte = 0;
                        long   endByte   = contentLength - 1;
                        long   length    = contentLength;
                        if (System.IO.File.Exists(filePath))
                        {
                            #region Range Calculation
                            // Are they downloading it by range?
                            bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]); // We do not support ranges

                            // check to see if we need to pass a specified range
                            if (byRange)
                            {
                                long     anotherStart = startByte;
                                long     anotherEnd   = endByte;
                                string[] arr_split    = Request.Headers["Range"].ToString().Split(new char[] { '=' });
                                string   range        = arr_split[1];

                                // Make sure the client hasn't sent us a multibyte range
                                if (range.IndexOf(",") > -1)
                                {
                                    // (?) Shoud this be issued here, or should the first
                                    // range be used? Or should the header be ignored and
                                    // we output the whole content?
                                    Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                                    return(new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable));
                                }

                                // If the range starts with an '-' we start from the beginning
                                // If not, we forward the file pointer
                                // And make sure to get the end byte if spesified
                                if (range.StartsWith("-"))
                                {
                                    // The n-number of the last bytes is requested
                                    anotherStart = startByte - Convert.ToInt64(range.Substring(1));
                                }
                                else
                                {
                                    arr_split    = range.Split(new char[] { '-' });
                                    anotherStart = Convert.ToInt64(arr_split[0]);
                                    long temp = 0;
                                    anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
                                }

                                /* Check the range and make sure it's treated according to the specs.
                                 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                                 */
                                // End bytes can not be larger than $end.
                                anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
                                // Validate the requested range and return an error if it's not correct.
                                if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
                                {
                                    Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                                    return(new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable));
                                }
                                startByte = anotherStart;
                                endByte   = anotherEnd;

                                length = endByte - startByte + 1; // Calculate new content length

                                // Ranges are response of 206
                                Response.StatusCode = 206;
                            }
                            #endregion

                            // Set Last Modified
                            Response.GetTypedHeaders().LastModified = dateUploaded;

                            // We accept ranges
                            Response.Headers.Add("Accept-Ranges", "0-" + contentLength);

                            // Notify the client the byte range we'll be outputting
                            Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);

                            // Notify the client the content length we'll be outputting
                            Response.Headers.Add("Content-Length", length.ToString());

                            // Set the content type of this response
                            Response.Headers.Add("Content-Type", contentType);

                            // Create content disposition
                            var cd = new System.Net.Mime.ContentDisposition
                            {
                                FileName = url,
                                Inline   = true
                            };

                            Response.Headers.Add("Content-Disposition", cd.ToString());

                            // Read in the file
                            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                            // Reset file stream to starting position (or start of range)
                            fs.Seek(startByte, SeekOrigin.Begin);

                            try
                            {
                                // If the IV is set, and Key is set, then decrypt it while sending
                                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
                                {
                                    byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                                    byte[] ivBytes  = Encoding.UTF8.GetBytes(iv);

                                    return(new BufferedFileStreamResult(contentType, async(response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, _config.UploadConfig.ChunkSize), false));
                                }
                                else // Otherwise just send it
                                {
                                    // Send the file
                                    return(new BufferedFileStreamResult(contentType, async(response) => await ResponseHelper.StreamToOutput(response, true, fs, (int)length, _config.UploadConfig.ChunkSize), false));
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.LogWarning(ex, "Error in Download: {url}", new { url });
                            }
                        }
                    }
                    return(new StatusCodeResult(StatusCodes.Status404NotFound));
                }
            }
            return(new StatusCodeResult(StatusCodes.Status403Forbidden));
        }
Exemple #46
0
        public async Task <ActionResult> ResizeImage(UploadedIMGViewModel model)
        {
            if (ModelState.IsValid)
            {
                //get original image on server
                Operation operation = Task.Run(async() => await _context.GetOperation(new Guid(model.IMG_Guid))).GetAwaiter().GetResult();

                if (operation != null)
                {
                    Image img = Task.Run(async() => await FileConversionMethods.ConvertByteArrayToImage(operation.FileUploaded)).GetAwaiter().GetResult();


                    if (img != null)
                    {
                        MemoryStream zipStream = new MemoryStream();
                        Dictionary <string, MemoryStream> memoryStreams = new Dictionary <string, MemoryStream>();

                        //resize the images by selected profiles and compile in a zip file and send as download
                        foreach (var network in model.CompatibleNetworks)
                        {
                            if (network.IsSelected)
                            {
                                foreach (var profile in network.IMG_Profile_Specs)
                                {
                                    if (profile.IsSelected)
                                    {
                                        var imageResized = await ResizingMethods.ResizeImage(img, profile.Width, profile.Height);

                                        //save img in folder Files_ToZip
                                        //imageResized.Save(Path.Combine(Server.MapPath("~/Files_ToZip/"), network.Name + "-" + profile.ProfileName.Replace(" ", "_") + "__" + model.IMG_Name));
                                        MemoryStream ms          = new MemoryStream();
                                        ImageFormat  imageFormat = Utility.GetImageFormat(operation.ContentType.Split('/')[1]);
                                        imageResized.Save(ms, imageFormat);
                                        memoryStreams.Add(network.Name + "/" + network.Name + "-" + profile.ProfileName.Replace(" ", "_") + "__" + model.IMG_Name, ms);
                                    }
                                }
                            }
                        }


                        //create the zip file to be downloaded
                        using (var archive = ZipArchive.Create())
                        {
                            //archive.AddAllFromDirectory(Server.MapPath("~/Files_ToZip/"));
                            foreach (var ms in memoryStreams)
                            {
                                if (!string.IsNullOrEmpty(ms.Key) && ms.Value != null)
                                {
                                    archive.AddEntry(ms.Key, ms.Value, ms.Value.Length, DateTime.Now);
                                }
                            }



                            //archive.SaveTo(Path.Combine(Server.MapPath("~/File_Zip/") + "ResizedImages.zip"), CompressionType.Deflate);
                            archive.SaveTo(zipStream);
                        }

                        //free img ressource
                        img.Dispose();

                        // delete files and download result
                        //memoryStreams = null;
                        //List<string> filesToDelete = new List<string>(Directory.GetFiles(Server.MapPath("~/Files_ToZip/")));
                        //filesToDelete.AddRange(Directory.GetFiles(Server.MapPath("~/Files_Repo/")));

                        //foreach (string file in filesToDelete)
                        //{
                        //    //if (file.Contains(fileUniqueName.ToString()))
                        //    //{
                        //    FileInfo fi = new FileInfo(file);
                        //    if (fi != null && fi.Exists && fi.FullName != model.IMG_Path)
                        //        fi.Delete();
                        //    //}
                        //}

                        Task.Run(async() => await _context.EmptyByteArray(operation)).GetAwaiter().GetResult();

                        //Response.ClearContent();
                        //Response.ClearHeaders();
                        //Set zip file name

                        //Response.AppendHeader("statusCode", "200");
                        string fileName = "ResizedImages_" + operation.Id.ToString().Substring(5, 5) + "_" + DateTime.Now.ToShortDateString() + "_resizeit.zip";
                        //Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
                        var cd = new System.Net.Mime.ContentDisposition
                        {
                            // for example foo.bak
                            FileName = fileName,

                            // always prompt the user for downloading, set to true if you want
                            // the browser to try to show the file inline
                            Inline = true,
                        };
                        Response.AppendHeader("Content-Disposition", cd.ToString());



                        return(File(zipStream.ToArray(), "application/rar"));//File(Path.Combine(Server.MapPath("~/File_Zip/") + "ResizedImages.zip"), "application/zip");//RedirectToAction("Contact");
                    }
                }
                return(View("Error"));
            }

            return(RedirectToAction("Index"));
        }
        //// POST api/values
        //public void Post([FromBody]string value)
        //{
        //}

        // PUT api/values/
        public async Task <HttpResponseMessage> PostFormData()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            ConverterData converterData = new ConverterData( );

            foreach (var file in provider.Contents)
            {
                if (file.Headers.ContentDisposition.FileName != null)
                {
                    var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    var buffer   = await file.ReadAsByteArrayAsync();

                    if (buffer.Length == 0)
                    {
                        continue;
                    }

                    converterData.Files.Add(new ConvertedFileInfo()
                    {
                        Data = buffer, FileName = filename
                    });
                }
                else
                {
                    var disposition = file.Headers.ContentDisposition;

                    var value = await file.ReadAsStringAsync();

                    if (disposition.Name.Trim('\"') == "format")
                    {
                        converterData.Format = value;
                    }
                    else
                    {
                        converterData.Options.Add(disposition.Name, value);
                    }

                    System.Diagnostics.Trace.WriteLine(value);
                }
            }

            var responseContent = new DicomConverterService().Convert(converterData);

            var response = Request.CreateResponse(responseContent.Status);

            if (responseContent.Content != null)
            {
                var cd = new System.Net.Mime.ContentDisposition
                {
                    // for example foo.bak
                    FileName = responseContent.FileName,

                    // always prompt the user for downloading, set to true if you want
                    // the browser to try to show the file inline
                    Inline = false,
                };

                response.Content = responseContent.Content;
                response.Content.Headers.Add("Content-Disposition", cd.ToString());
            }

            return(response);
        }
        //Rapport de l'appel d'offre
        public ActionResult RapportAppelOffre(int?Id)
        {
            var reportQueryAppel = (from a in db.ToutAppleOffre()
                                    select new
            {
                a.noAppelOffre,
                a.nom,
                a.dateEnvoi,
                a.dateRequis,
                a.description,
                a.noMedia,
                a.noStatut,
                a.noEvenement,
                a.tblEvenement
            }).Where(ap => ap.noAppelOffre == Id);

            var reportQuerySoumi = (from s in db.RetunSoumission(Id)
                                    select new
            {
                s.prix,
                s.commentaire,
                s.statut,
                s.noAgencePub,
                s.noAppelOffre,
                s.noSoumission,
                s.noSoumissionAgence,
                s.dateReponse,
                s.dateEnvoi
            }).ToList();
            var reportMedia = db.ToutMedia().Where(me => me.noMedia == reportQueryAppel.First().noMedia);

            var reportStatut = db.ToutStatutAppel().Where(s => s.noStatut == reportQueryAppel.First().noStatut);

            var reportAgence = (from ag in db.ToutAgencePublicite()
                                select new
            {
                ag.noAgencePub,
                ag.nom,
                noAppelOffre = ag.tblSoumission.Select(s => s.noAppelOffre).FirstOrDefault()
            }).Where(age => age.noAppelOffre == Id).ToList();

            var reportEvent = db.ToutEvenement().Where(e => e.noEvenement == reportQueryAppel.First().noEvenement);

            LocalReport u = new LocalReport();

            u.ReportPath = "Rapport/RapportAppel.rdlc";
            u.DataSources.Clear();
            ReportDataSource datasourceAppel = new ReportDataSource("DataSetAppelOffre", reportQueryAppel);
            ReportDataSource datasourceSoumi = new ReportDataSource("DataSetSoumission", reportQuerySoumi);
            ReportDataSource datasourceMedia = new ReportDataSource("DataSetMedia", reportMedia);
            var dataSourceStatut             = new ReportDataSource("DataSetStatut", reportStatut);
            var dataSourceAgence             = new ReportDataSource("DataSetAgence", reportAgence);
            var dataSourceEvent = new ReportDataSource("DataSetEvent", reportEvent);

            u.DataSources.Add(datasourceAppel);
            u.SubreportProcessing += U_SubreportAppelOffre;
            u.DataSources.Add(datasourceSoumi);
            u.DataSources.Add(datasourceSoumi);
            u.DataSources.Add(datasourceMedia);
            u.DataSources.Add(dataSourceStatut);
            u.DataSources.Add(dataSourceAgence);
            u.DataSources.Add(dataSourceEvent);
            u.SetParameters(new ReportParameter("nbSoumission", reportQuerySoumi.Count.ToString()));
            u.SetParameters(new ReportParameter("auteur", db.ReturnUtilisateur(AbpSession.UserId.Value).UserName));



            //ReportParameter p = new ReportParameter("DeptID", deptID.ToString());
            //u.SetParameters(new[] { p });

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = "Rapport_AppelOffre.pdf",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = true,
            };

            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    filenameExtension;

            byte[] bytes = u.Render(
                "PDF", null, out mimeType, out encoding, out filenameExtension,
                out streamids, out warnings);


            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(bytes, "application/pdf"));
        }
Exemple #49
0
        /// <summary>
        /// 发送SMTP邮件
        /// </summary>
        /// <param name="mailFrom">发件人</param>
        /// <param name="mailTo">收件人(多个收件人用;隔开)</param>
        /// <param name="mailSubject">主题</param>
        /// <param name="mailBody">内容</param>
        /// <param name="mailAttach">附件(多个附件用;隔开)</param>
        /// <param name="mailPriority">优先级</param>
        /// <param name="mailCC">抄送人(多个抄送人用;隔开)</param>
        /// <param name="resultMessage">返回信息</param>
        public void SendSmtpMail(string mailFrom, string mailTo, string mailSubject, string mailBody, string mailAttach, string mailPriority, string mailCC, out string resultMessage)
        {
            try
            {
                if (string.IsNullOrEmpty(mailFrom))
                {
                    resultMessage = "error:mailFrom is null";
                    return;
                }
                if (string.IsNullOrEmpty(mailTo))
                {
                    resultMessage = "error:mailTo is null";
                    return;
                }

                MailMessage email     = new MailMessage();
                MailAddress emailFrom = new MailAddress(mailFrom);
                //指定发件人地址
                email.From = emailFrom;
                //收件人
                string[] toUsers = mailTo.Split(';');
                foreach (string to in toUsers)
                {
                    //用于处理收件人结尾可能有;情况
                    if (!string.IsNullOrEmpty(to))
                    {
                        //邮箱有效性验证
                        if (RegexMatchHelper.RegexEmailAddressMatch(to))
                        {
                            email.To.Add(to);//添加收件人邮箱
                        }
                    }
                }
                //抄送人
                if (!string.IsNullOrEmpty(mailCC))
                {
                    string[] ccUsers = mailCC.Split(';');
                    foreach (string cc in ccUsers)
                    {
                        //用于处理抄送人结尾可能要;情况
                        if (!string.IsNullOrEmpty(cc))
                        {
                            //邮箱有效性验证
                            if (RegexMatchHelper.RegexEmailAddressMatch(cc))
                            {
                                email.CC.Add(cc);//添加抄送人邮箱
                            }
                        }
                    }
                }
                //主题
                email.Subject = mailSubject;
                //内容
                email.Body = mailBody;
                //附件
                if (!string.IsNullOrEmpty(mailAttach))
                {
                    string[] attachments = mailAttach.Split(';');
                    foreach (string file in attachments)
                    {
                        //用于处理多个附件结尾可能存在;情况
                        if (!string.IsNullOrEmpty(file))
                        {
                            Attachment attach = new Attachment(file, System.Net.Mime.MediaTypeNames.Application.Octet);
                            //附件添加发送时间
                            System.Net.Mime.ContentDisposition disposition = attach.ContentDisposition;
                            disposition.CreationDate     = System.IO.File.GetCreationTime(file);
                            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
                            disposition.ReadDate         = System.IO.File.GetLastAccessTime(file);
                            //添加附件
                            email.Attachments.Add(attach);
                        }
                    }
                }
                //优先级
                email.Priority = mailPriority == "High" ? MailPriority.High : MailPriority.Normal;
                //内容编码格式
                email.BodyEncoding = System.Text.Encoding.UTF8;
                //设置正文内容是否为html格式的值
                email.IsBodyHtml = true;
                //SMTP服务器地址
                SmtpClient client = new SmtpClient(_mailSmtpServer);
                //验证(Credentials凭证)
                client.Credentials = new System.Net.NetworkCredential(_mailCredential, _mailCredentialPwd);
                //处理待发的电子邮件方法
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                //发送邮件
                client.Send(email);
                resultMessage = "send your email success";
            }
            catch (Exception ex)
            {
                log.Error(string.Format("SendSmtpMail()发生错误,错误信息如下:{0}", ex));
                resultMessage = "error:" + ex.Message;
            }
        }
        //Rapport Commenditaire
        public ActionResult RapportCommenditaire()
        {
            var EventSelect = Request.QueryString["filtre_unTous"];
            var SousEvent   = Request.QueryString["filtre_SousEvent"];
            int nbComEvent  = 0;

            var reportQueryCom = (from c in db.ToutCommenditaire()
                                  select new
            {
                c.nomCommanditaire,
                c.noCommanditaire,
                c.textePresentation
            }).ToList();

            var reportQuery = (from k in db.ToutEvenement()
                               select new
            {
                k.noEvenement,
                k.nom,
                k.dateDebut,
                k.datefin,
                k.url
            }).ToList();


            if (EventSelect != "ToutEven")
            {
                reportQuery = (from k in db.ToutEvenement()
                               select new
                {
                    k.noEvenement,
                    k.nom,
                    k.dateDebut,
                    k.datefin,
                    k.url
                }).Where(ev => ev.noEvenement == Convert.ToInt32(EventSelect)).ToList();

                reportQueryCom = (from c in db.CommenEvent(Convert.ToInt32(EventSelect))
                                  select new
                {
                    c.nomCommanditaire,
                    c.noCommanditaire,
                    c.textePresentation
                }).ToList();
            }

            var reportQueryComSousEvent = (from c in db.ToutCommenditaire()
                                           select new
            {
                c.nomCommanditaire,
                c.noCommanditaire,
                c.textePresentation
            }).ToList();


            var reportQueryDon = db.ToutDon().Select(d => new
            {
                montant         = d.montant,
                noCommanditaire = d.noCommanditaire,
                d.noSousEvenement
            }).ToList();

            var reportQuerySousEvent = db.ToutSousEvenement().Select(se => new
            {
                se.noSousEvenement,
                se.nom
            }).ToList();

            if (SousEvent != "ToutSousEven")
            {
                reportQuerySousEvent = db.ToutSousEvenement().Select(se => new
                {
                    se.noSousEvenement,
                    se.nom
                }).Where(ss => ss.noSousEvenement == Convert.ToInt32(SousEvent)).ToList();

                reportQueryComSousEvent = (from c in db.CommenSousEvent(Convert.ToInt32(SousEvent))
                                           select new
                {
                    c.nomCommanditaire,
                    c.noCommanditaire,
                    c.textePresentation
                }).ToList();
            }

            LocalReport u = new LocalReport();

            u.ReportPath = "Rapport/ReportComendite_Event.rdlc";
            //On charge tous les commenditaires
            nbComEvent = reportQueryCom.Count;
            foreach (var com in reportQueryComSousEvent)
            {
                if (!reportQueryCom.Contains(com))
                {
                    reportQueryCom.Add(com);
                }
            }
            u.DataSources.Clear();
            ReportDataSource datasourceComSous    = new ReportDataSource("DataSetEvent", reportQuery);
            ReportDataSource datasourceComDon     = new ReportDataSource("DataSetCommenditaire", reportQueryCom);
            ReportDataSource datasourceSouesEvent = new ReportDataSource("DataSetSousEvent", reportQuerySousEvent);
            var dsDons = new ReportDataSource("DataSetDon", reportQueryDon);

            u.DataSources.Add(datasourceComSous);
            u.DataSources.Add(datasourceComDon);
            u.DataSources.Add(dsDons);
            u.DataSources.Add(datasourceSouesEvent);
            u.SubreportProcessing += U_SubreportComEvent;
            u.SetParameters(new ReportParameter("auteur", db.ReturnUtilisateur(AbpSession.UserId.Value).UserName));
            u.SetParameters(new ReportParameter("nbComSousEvent", reportQueryComSousEvent.Count.ToString()));
            u.SetParameters(new ReportParameter("nbComEvent", nbComEvent.ToString()));
            u.SetParameters(new ReportParameter("nbComFinal", reportQueryCom.Count.ToString()));

            //ReportParameter p = new ReportParameter("DeptID", deptID.ToString());
            //u.SetParameters(new[] { p });

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = "Rapport_Commenditaire.pdf",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = true,
            };

            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    filenameExtension;

            byte[] bytes = u.Render(
                "PDF", null, out mimeType, out encoding, out filenameExtension,
                out streamids, out warnings);


            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(bytes, "application/pdf"));
        }
        public ActionResult Report(RequestIssue requestıssue, FormCollection formcollection)
        {
            ReportDocument rptH = new ReportDocument();

            rptH.FileName = Server.MapPath("~/RDLC/SurveyReport.rpt");

            rptH.Refresh();
            //rptH.Load();

            var value = new ParameterDiscreteValue();

            var requests_ = db.RequestIssues.AsNoTracking().Include(p => p.Locations).Include(p => p.Personnels).Include(p => p.CorporateAccounts);

            int x_index = 0;
            foreach (int req_ in requests_.Select(i => i.RequestIssueID).ToList())
            {
                value.Value = req_;

                rptH.ParameterFields["RequestIDs"].CurrentValues.Add(value);
                x_index++;
            }

            if (x_index == 0)
            {
                return RedirectToAction("Index", new { custommerr = "Belirttiğiniz Kriterlere Uygun Kayıt(lar) Bulunamadı" });
            }

            // rptH.SetDataSource([datatable]);
            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = "rapor_klimasanHelpDeskAnketler.pdf",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = false,
            };

            Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
            Response.AppendHeader("Content-Disposition", cd.ToString());
            return File(stream, "application/pdf");
        }
        public ActionResult RapportCalculateur(int?id)
        {
            var reportQueryCalculateur = (from s in db.ReturnListCalculateur().Where(c => c.noSousEvenement == id)
                                          select new
            {
                s.noSousEvenement,
                s.billet,
                s.billetVIP,
                s.prixBillet,
                s.prixBilletVIP,
                s.souperSpectacle,
                s.prixSouper,
                s.jeunePourcent,
                s.adultePourcent,
                s.ainePourcent,
                s.jeuneRatio,
                s.adulteRatio,
                s.aineRatio,
                s.promo,
                s.prevente,
                s.customBillet1,
                s.customBillet2,
                s.customPrix1,
                s.customPrix2,
                s.customNom1,
                s.customNom2,
            }).ToList();

            var reportQuerySSEvent = (from s in db.ToutSousEvenement().Where(sse => sse.noSousEvenement == id)
                                      select new
            {
                s.noSousEvenement,
                s.nom,
                s.description,
                s.noEvenement,
                s.noSalle,
            }).ToList();

            var reportQuerySalle = (from s in db.ReturnListSalle().Where(a => a.noSalle == db.FindSousEvenement((int)id).noSalle)
                                    select new
            {
                s.noSalle,
                s.nomSalle,
                s.prix,
                s.billet,
                s.billetVIP,
                s.photoSalle,
                s.dateSupprime,
                s.urlGoogleMap
            }).ToList();

            var reportQueryNomEvent = (from s in db.ToutEvenement().Where(a => a.noEvenement == db.ReturnEvenement((reportQuerySSEvent.FirstOrDefault().noEvenement)).noEvenement)
                                       select new
            {
                s.noEvenement,
                s.nom,
            }).ToList();


            LocalReport u = new LocalReport();

            u.ReportPath = "Rapport/ReportCalculateur.rdlc";
            u.SetParameters(new ReportParameter("auteur", db.ReturnUtilisateur(AbpSession.UserId.Value).UserName));
            u.DataSources.Clear();
            ReportDataSource datasourceCalcul   = new ReportDataSource("DataSetCalculateur", reportQueryCalculateur);
            ReportDataSource datasourceSSEvent  = new ReportDataSource("DataSetSousEvent", reportQuerySSEvent);
            ReportDataSource datasourceSalle    = new ReportDataSource("DataSetSalle", reportQuerySalle);
            ReportDataSource datasourceNomEvent = new ReportDataSource("DataNomEvent", reportQueryNomEvent);

            u.DataSources.Add(datasourceCalcul);
            u.DataSources.Add(datasourceSSEvent);
            u.DataSources.Add(datasourceSalle);
            u.DataSources.Add(datasourceNomEvent);

            //ReportParameter p = new ReportParameter("DeptID", deptID.ToString());
            //u.SetParameters(new[] { p });

            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = "Rapport_Calculateur.pdf",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = true,
            };

            Warning[] warnings;
            string[]  streamids;
            string    mimeType;
            string    encoding;
            string    filenameExtension;

            byte[] bytes = u.Render(
                "PDF", null, out mimeType, out encoding, out filenameExtension,
                out streamids, out warnings);


            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(bytes, "application/pdf"));
        }
        public bool DownloadFile(string sourceUrl, string targetFolder, long fileTransferTaskID, string sourceName, string certPath = "", string certPassword = "")
        {
            string   tempFilename = sourceName + "_" + fileTransferTaskID + "_downloading.file"; // must specificy filename before download starts, use temp filename
            DateTime startTime    = DateTime.Now;

            try
            {
                using (MyWebClient downloader = new MyWebClient())
                {
                    downloader.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                    if (certPath != "")
                    {   // Create a collection object and populate it using the PFX file
                        if (downloader.Certificate == null)
                        // for ercot and certificate needed
                        {
                            X509Certificate2Collection collection = new X509Certificate2Collection();
                            collection.Import(certPath, certPassword, X509KeyStorageFlags.PersistKeySet);
                            downloader.Certificate = collection[0];
                            // http://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel
                            ServicePointManager.Expect100Continue = true;
                            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Ssl3;
                            //ServicePointManager.DefaultConnectionLimit = 9999;
                            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
                            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
                        }
                    }
                    else
                    {
                        // for pjm and no certificate needed
                        ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                        ServicePointManager.Expect100Continue = true;
                    }
                    downloader.UseDefaultCredentials = false;
                    downloader.DownloadFile(new Uri(sourceUrl), targetFolder + tempFilename);

                    string header_contentDisposition = downloader.ResponseHeaders["content-disposition"];
                    string filename;

                    if (String.IsNullOrEmpty(header_contentDisposition))
                    {
                        filename = "null.csv";
                    }
                    else
                    {
                        if (header_contentDisposition.Contains("("))
                        {
                            filename = header_contentDisposition.Substring(header_contentDisposition.IndexOf("filename=") + 9);
                        }
                        else
                        {
                            filename = new System.Net.Mime.ContentDisposition(header_contentDisposition).FileName;
                        }
                    }
                    string destinationFilename = sourceName + "_" + fileTransferTaskID + "_" + filename;
                    //long fileSize = new System.Net.Mime.ContentDisposition(header_contentDisposition).Size;  // this didn't work, returns -1
                    long fileSize = new System.IO.FileInfo(targetFolder + tempFilename).Length;

                    File.Delete(targetFolder + destinationFilename);
                    var sources = new List <string>()
                    {
                        "monthlybillingstatement", "weeklybillingstatement"
                    };
                    if (sources.Contains(sourceName))
                    {
                        if (fileSize <= (25 * 1024))
                        {
                            // PJM returns an empty PDF when the dates in the request have no statement that day
                            Console.WriteLine("Skipped PJM PDF Statement due to size:" + destinationFilename);
                            //File.Move(targetFolder + tempFilename, targetFolder + destinationFilename + ".delete");
                            File.Delete(targetFolder + tempFilename);
                        }
                        // mark the PDF document as "skipped", because it will not be loaded into the database, just dropped in a folder
                        Program.UpdateTaskStatus(fileTransferTaskID, downloadStatusCode: "FTTD_DOWNLOADED", loadStatusCode: "FTTD_SKIP", sourceFileName: filename, destinationFileName: destinationFilename, fileSize: fileSize);
                    }
                    else
                    {
                        File.Move(targetFolder + tempFilename, targetFolder + destinationFilename);     // actual filename is not known until after the download starts

                        if (destinationFilename.ToLower().Contains(".zip"))
                        {
                            Console.WriteLine("Download zipped file completed:" + destinationFilename);
                            Program.UpdateTaskStatus(fileTransferTaskID, downloadStatusCode: "FTTD_DOWNLOADED_ZIP", sourceFileName: filename, destinationFileName: destinationFilename, fileSize: fileSize);
                        }
                        else
                        {
                            Console.WriteLine("Download Completed:" + destinationFilename);
                            Program.UpdateTaskStatus(fileTransferTaskID, downloadStatusCode: "FTTD_DOWNLOADED", sourceFileName: filename, destinationFileName: destinationFilename, fileSize: fileSize);
                        }
                    }
                    Program.LogSession(Properties.Settings.Default.TaskName + ":DownloadFile", destinationFilename, startTime);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.Message);
                Program.LogError(Properties.Settings.Default.TaskName + ":DownloadFile", tempFilename, ex);
                return(false);
            }
        }
        //Rapport de sécurité
        public ActionResult RapportAcces()
        {
            LocalReport rapport_acces = new LocalReport();

            rapport_acces.SubreportProcessing += Rapport_acces_SubreportProcessing;
            rapport_acces.ReportPath           = "Rapport/RapportAcces.rdlc";
            var requete_logs = db.ToutLogs().Where(l => l.UserId != null).AsQueryable();
            var date_debut   = Request.QueryString["filtre_debut"];

            if (!string.IsNullOrWhiteSpace(date_debut))
            {
                DateTime date_debut_dt = DateTime.Parse(date_debut);
                rapport_acces.SetParameters(new ReportParameter("date_debut", date_debut_dt.ToString("yyyy-MM-dd")));
                requete_logs = requete_logs.Where(l => l.ExecutionTime >= date_debut_dt);
            }
            var date_fin = Request.QueryString["filtre_fin"];

            if (!string.IsNullOrWhiteSpace(date_fin))
            {
                DateTime date_fin_dt = DateTime.Parse(date_fin);
                rapport_acces.SetParameters(new ReportParameter("date_fin", date_fin_dt.ToString("yyyy-MM-dd")));
                requete_logs = requete_logs.Where(l => l.ExecutionTime <= date_fin_dt);
            }

            var filtre_periode = Request.QueryString["filtre_periode"];

            var filtre_profil = Request.QueryString["filtre_profil"];

            if (filtre_profil != "tous")
            {
                requete_logs = requete_logs.Where(r => db.GetRoleUtilisateur(db.ReturnUtilisateur(r.UserId.Value)) == filtre_profil);
            }
            var groupByProfil = GroupByProfil(requete_logs);

            var filtre_utilisateur = Request.QueryString["filtre_utilisateur"];

            if (filtre_utilisateur != "tous")
            {
                requete_logs = requete_logs.Where(r => r.UserId.Value.ToString() == filtre_utilisateur);
            }
            var total_jour = requete_logs.GroupBy(r => r.ExecutionTime.ToShortDateString());

            rapport_acces.SetParameters(new ReportParameter("periode", filtre_periode));
            rapport_acces.SetParameters(new ReportParameter("profil_nom", filtre_profil));
            rapport_acces.SetParameters(new ReportParameter("role_id", "1"));
            rapport_acces.SetParameters(new ReportParameter("total_jours", total_jour.Count().ToString()));
            rapport_acces.SetParameters(new ReportParameter("auteur", db.ReturnUtilisateur(AbpSession.UserId.Value).UserName));
            rapport_acces.DataSources.Clear();
            rapport_acces.DataSources.Add(new ReportDataSource("Users", db.ToutUtilisateurs()));
            rapport_acces.DataSources.Add(new ReportDataSource("Logs", requete_logs));
            rapport_acces.DataSources.Add(new ReportDataSource("ToutLogs", db.ToutLogs().Where(l => l.UserId != null)));
            rapport_acces.DataSources.Add(new ReportDataSource("UserRoles", db.ToutRoleUtilisateur()));
            rapport_acces.DataSources.Add(new ReportDataSource("Roles", db.ToutRoles()));
            var cd = new System.Net.Mime.ContentDisposition
            {
                // for example foo.bak
                FileName = "Rapport_Securite.pdf",

                // always prompt the user for downloading, set to true if you want
                // the browser to try to show the file inline
                Inline = true,
            };

            byte[] bytes = rapport_acces.Render("PDF");


            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(bytes, "application/pdf"));
        }
        public ActionResult DownloadMIDI(string userKey, int midiID)
        {
            User user = usersRepository.FindUser(userKey);
            if (user != null)
            {
                MidiFile crumbsmodel = crumbsRepository.FindMidiFile(midiID);
                if (crumbsmodel != null)
                {
                    Payment payment = crumbsRepository.FindConfirmedPaymentForMIDI(user.UserID, midiID);
                    if (payment != null)
                    {
                        string path = MidiFileHelper.getMidiPath(crumbsmodel);
                        string FullPath = HostingEnvironment.ApplicationPhysicalPath + path;

                        var cd = new System.Net.Mime.ContentDisposition
                        {
                            // for example foo.bak
                            FileName = crumbsmodel.FileName,

                            // always prompt the user for downloading, set to true if you want
                            // the browser to try to show the file inline
                            Inline = false,
                        };
                        Response.AppendHeader("Content-Disposition", cd.ToString());
                        Response.AppendHeader("Access-Control-Allow-Origin", "*");
                        return File(FullPath, "audio/midi");
                    }
                }
            }

            return base.Content("Not Authorized");
        }
        public bool EnviaEmail(SPWeb Web)
        {
            //Armazena o endereço email do configurando no serviço de Email do Farm SharePoint
            string SharePointSmtp;
            string SharePointDe;

            try
            {
                SharePointSmtp = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
                SharePointDe   = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
            }
            catch
            {
                return(false);
            }

            //Instância para criação de um novo email
            MailMessage eMail = new MailMessage();

            //Propriedades do email
            eMail.Subject    = this.Assunto;
            eMail.Body       = this.Corpo;
            eMail.IsBodyHtml = true;
            eMail.From       = new MailAddress(SharePointDe, NomePortal);

            //Carrega os anexos
            foreach (string anexo in this.Anexos)
            {
                SPFile     file   = Web.GetFile(anexo);
                Attachment attach = new Attachment(file.OpenBinaryStream(), System.Net.Mime.MediaTypeNames.Application.Octet);
                attach.Name = file.Name;
                System.Net.Mime.ContentDisposition disposition = attach.ContentDisposition;
                disposition.CreationDate     = file.TimeCreated;
                disposition.ModificationDate = file.TimeLastModified;
                disposition.ReadDate         = file.TimeLastModified;
                eMail.Attachments.Add(attach);
            }

            //Verifique se existe destinário para o email
            if (!String.IsNullOrEmpty(this.Para))
            {
                string[] destinatariosPara = this.Para.Split(';');

                foreach (string destinatarioPara in destinatariosPara)
                {
                    if (!String.IsNullOrEmpty(destinatarioPara))
                    {
                        MailAddress DestinatarioPara = new MailAddress(destinatarioPara);
                        eMail.To.Add(DestinatarioPara);
                    }
                }
            }

            //Verifique se existe cópia para o email
            if (!String.IsNullOrEmpty(this.CC))
            {
                string[] destinatariosCC = this.CC.Split(';');

                foreach (string destinatarioCC in destinatariosCC)
                {
                    if (!String.IsNullOrEmpty(destinatarioCC))
                    {
                        MailAddress DestinatarioCC = new MailAddress(destinatarioCC);
                        eMail.CC.Add(DestinatarioCC);
                    }
                }
            }

            //Verifique se existe cópia oculta para o email
            if (!String.IsNullOrEmpty(this.CCO))
            {
                string[] destinatariosCCO = this.CCO.Split(';');

                foreach (string destinatarioCCO in destinatariosCCO)
                {
                    if (!String.IsNullOrEmpty(destinatarioCCO))
                    {
                        MailAddress DestinatarioCCO = new MailAddress(destinatarioCCO);
                        eMail.Bcc.Add(DestinatarioCCO);
                    }
                }
            }

            //Instância de smpt do SharePoint
            SmtpClient smtpClient = new SmtpClient(SharePointSmtp);

            //Envia email com as informações do objeto email
            smtpClient.Send(eMail);

            return(true);
        }
Exemple #57
0
        public void Export(int customerId)
        {
            if (isAuthorized(1) != AuthStates.ElitewebAuth)
            {
                return;
            }
            Customer        c         = dbc.Read(customerId);
            List <Asset>    assets    = db.ReadAllWithFk(customerId);
            List <Firewall> firewalls = dbf.ReadAllWithFk(customerId);
            List <Lan>      lans      = dbl.ReadAllWithFk(customerId);
            List <User>     users     = dbu.ReadAllWithFk(customerId);
            List <Port>     ports     = dbp.ReadAllWithFk(customerId);

            HSSFWorkbook hssfwb = new HSSFWorkbook();
            ICellStyle   style  = hssfwb.CreateCellStyle();

            style.BorderBottom      = BorderStyle.Medium;
            style.BottomBorderColor = HSSFColor.Red.Index;
            IFont font = hssfwb.CreateFont();

            font.IsBold = true;
            style.SetFont(font);

            ISheet sheet    = hssfwb.CreateSheet("Udstyr");
            ISheet firewall = hssfwb.CreateSheet("Firewall");
            ISheet lan      = hssfwb.CreateSheet("Lan");
            ISheet user     = hssfwb.CreateSheet("User");
            ISheet port     = hssfwb.CreateSheet("Port");

            IRow row1 = sheet.CreateRow(0);

            row1.CreateCell(0).SetCellValue("Kunde");
            row1.CreateCell(1).SetCellValue("Adresse");
            row1.CreateCell(2).SetCellValue("Dato");
            for (int i = 0; i < 3; i++)
            {
                row1.GetCell(i).CellStyle = style;
            }
            row1 = sheet.CreateRow(1);
            row1.CreateCell(0).SetCellValue(c.Firm);
            row1.CreateCell(1).SetCellValue(c.Address);
            row1.CreateCell(2).SetCellValue(c.Date.ToShortDateString());

            try
            {
                // Create an array to multiple values at once.
                row1 = sheet.CreateRow(3);
                row1.CreateCell(0).SetCellValue("Navn");
                row1.CreateCell(1).SetCellValue("Beskrivelse");
                row1.CreateCell(2).SetCellValue("Adresse");
                row1.CreateCell(3).SetCellValue("Lokation");
                row1.CreateCell(4).SetCellValue("Login");
                row1.CreateCell(5).SetCellValue("Password");
                row1.CreateCell(6).SetCellValue("Note");
                row1.CreateCell(7).SetCellValue("RAM");
                row1.CreateCell(8).SetCellValue("HDD");
                row1.CreateCell(9).SetCellValue("Type");
                row1.CreateCell(10).SetCellValue("Bruger");
                row1.CreateCell(11).SetCellValue("IP");
                row1.CreateCell(12).SetCellValue("OS");
                row1.CreateCell(13).SetCellValue("Dato");
                for (int i = 0; i < 14; i++)
                {
                    row1.GetCell(i).CellStyle = style;
                }

                for (int row = 0; row < assets.Count; row++)
                {
                    var a         = assets[row];
                    int rowtofill = row + 4;
                    row1 = sheet.CreateRow(rowtofill);
                    row1.CreateCell(0).SetCellValue(a.Name);
                    row1.CreateCell(1).SetCellValue(a.Description);
                    row1.CreateCell(2).SetCellValue(a.Address);
                    row1.CreateCell(3).SetCellValue(a.Location);
                    row1.CreateCell(4).SetCellValue(a.Login);
                    row1.CreateCell(5).SetCellValue(a.Password);
                    row1.CreateCell(6).SetCellValue(a.Note);
                    row1.CreateCell(7).SetCellValue(a.RAM);
                    row1.CreateCell(8).SetCellValue(a.HDD);
                    row1.CreateCell(9).SetCellValue(a.Type.Description);
                    row1.CreateCell(10).SetCellValue(a.Usedby);
                    row1.CreateCell(11).SetCellValue(a.IpAddress);
                    row1.CreateCell(12).SetCellValue(a.OS);
                    row1.CreateCell(13).SetCellValue(a.InstallationDate.ToShortDateString());
                }

                IRow firewallRow = firewall.CreateRow(0);
                firewallRow.CreateCell(0).SetCellValue("Protokol");
                firewallRow.CreateCell(1).SetCellValue("Tilladt fra");
                firewallRow.CreateCell(2).SetCellValue("Interface");
                firewallRow.CreateCell(3).SetCellValue("Destination");
                try
                {
                    for (int i = 0; i < 4; i++)
                    {
                        firewallRow.GetCell(i).CellStyle = style;
                    }
                    for (int row = 0; row < firewalls.Count; row++)
                    {
                        var a         = firewalls[row];
                        int rowtofill = row + 1;
                        firewallRow = firewall.CreateRow(rowtofill);
                        firewallRow.CreateCell(0).SetCellValue(a.Protocol);
                        firewallRow.CreateCell(0).SetCellValue(a.AllowedIps);
                        firewallRow.CreateCell(0).SetCellValue(a.Interface);
                        firewallRow.CreateCell(0).SetCellValue(a.Destination);
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                IRow lanRow = lan.CreateRow(0);
                lanRow.CreateCell(0).SetCellValue("Navn");
                lanRow.CreateCell(1).SetCellValue("Netværk");
                lanRow.CreateCell(2).SetCellValue("DHCP Server");
                lanRow.CreateCell(3).SetCellValue("DNS");
                lanRow.CreateCell(4).SetCellValue("VLAN");
                try
                {
                    for (int i = 0; i < 5; i++)
                    {
                        lanRow.GetCell(i).CellStyle = style;
                    }
                    for (int row = 0; row < lans.Count; row++)
                    {
                        var a         = lans[row];
                        int rowtofill = row + 1;
                        lanRow = lan.CreateRow(rowtofill);
                        lanRow.CreateCell(0).SetCellValue(a.Name);
                        lanRow.CreateCell(1).SetCellValue(a.Network);
                        lanRow.CreateCell(2).SetCellValue(a.DhcpServer);
                        lanRow.CreateCell(3).SetCellValue(a.Dns);
                        lanRow.CreateCell(4).SetCellValue(a.VLan);
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                IRow userRow = user.CreateRow(0);
                userRow.CreateCell(0).SetCellValue("Email");
                userRow.CreateCell(1).SetCellValue("Fornavn");
                userRow.CreateCell(2).SetCellValue("Efternavn");
                userRow.CreateCell(3).SetCellValue("Telefon nr.");
                userRow.CreateCell(4).SetCellValue("Password");
                try
                {
                    for (int i = 0; i < 5; i++)
                    {
                        userRow.GetCell(i).CellStyle = style;
                    }
                    for (int row = 0; row < users.Count; row++)
                    {
                        var a         = users[row];
                        int rowtofill = row + 1;
                        userRow = user.CreateRow(rowtofill);
                        userRow.CreateCell(0).SetCellValue(a.Email);
                        userRow.CreateCell(1).SetCellValue(a.FirstName);
                        userRow.CreateCell(2).SetCellValue(a.LastName);
                        userRow.CreateCell(3).SetCellValue(a.Password);
                        userRow.CreateCell(4).SetCellValue(a.Password);
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                IRow portRow = port.CreateRow(0);
                portRow.CreateCell(0).SetCellValue("Port nr.");
                portRow.CreateCell(1).SetCellValue("Udstyr");
                portRow.CreateCell(1).SetCellValue("Trunk");
                portRow.CreateCell(2).SetCellValue("VLAN");
                portRow.CreateCell(3).SetCellValue("Note");
                try
                {
                    for (int i = 0; i < 4; i++)
                    {
                        portRow.GetCell(i).CellStyle = style;
                    }
                    for (int row = 0; row < ports.Count; row++)
                    {
                        var a         = ports[row];
                        int rowtofill = row + 1;
                        portRow = port.CreateRow(rowtofill);
                        portRow.CreateCell(0).SetCellValue(a.PortNumber);
                        portRow.CreateCell(1).SetCellValue(a.Asset);
                        portRow.CreateCell(2).SetCellValue(a.Trunk);
                        portRow.CreateCell(3).SetCellValue(a.VLAN);
                        portRow.CreateCell(4).SetCellValue(a.Note);
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                for (int i = 0; i <= 13; i++)
                {
                    sheet.AutoSizeColumn(i);
                }
                string filename = "Export.xls";
                var    cd       = new System.Net.Mime.ContentDisposition
                {
                    FileName = filename,
                    Inline   = true,
                };
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", cd.ToString());
                Response.Clear();
                MemoryStream file = new MemoryStream();
                hssfwb.Write(file);
                Response.BinaryWrite(file.GetBuffer());
                Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #58
0
        public ActionResult XlsDownload(ApprovalSearch search)
        {
            IEnumerable <Approval> list = db.Approvals.Where(a => a.status != ApprovalStatus.Request);

            if (search.sp != null)
            {
                list = list.Where(p => p.privacy.IND_SP.Contains(search.sp));
            }
            if (search.hospital != null)
            {
                list = list.Where(p => p.privacy.WKP_NAME.Contains(search.hospital));
            }

            if (search.status != null && !search.status.Equals("total"))
            {
                if (search.status.Equals("approved"))
                {
                    list = list.Where(p => p.status.Equals(ApprovalStatus.Approved));
                }
                else if (search.status.Equals("rejected"))
                {
                    list = list.Where(p => p.status.Equals(ApprovalStatus.Rejected));
                }
            }
            if (search.requestbegindt != null)
            {
                list = list.Where(a => a.createdate >= search.requestbegindt);
            }
            if (search.requestenddt != null)
            {
                list = list.Where(a => a.createdate <= search.requestenddt);
            }

            if (search.approvalbegindt != null)
            {
                list = list.Where(a => a.modifieddate >= search.approvalbegindt);
            }
            if (search.approvalenddt != null)
            {
                list = list.Where(a => a.modifieddate <= search.approvalenddt);
            }

            if (!string.IsNullOrEmpty(search.owner))
            {
                list = list.Where(a => a.creater.Contains(search.owner));
            }
            if (!string.IsNullOrEmpty(search.name))
            {
                list = list.Where(a => a.privacy.IND_FULL_NAME.Contains(search.name));
            }

            // Xls export
            var wb        = new XLWorkbook();
            var sheetname = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
            var ws        = wb.Worksheets.Add("ApprovalHistory" + sheetname);

            ws.Cell("A1").Value = "NucleusKey";
            ws.Cell("B1").Value = "OneKey";
            ws.Cell("C1").Value = "PCMSID";
            ws.Cell("D1").Value = "근무처(병원명)";
            ws.Cell("E1").Value = "근무처연락처";
            ws.Cell("F1").Value = "우편번호";
            ws.Cell("G1").Value = "주소";
            ws.Cell("H1").Value = "진료과";
            ws.Cell("I1").Value = "직위";
            ws.Cell("J1").Value = "고객명";
            ws.Cell("K1").Value = "이메일";
            ws.Cell("L1").Value = "핸드폰";
            ws.Cell("M1").Value = "수신거부여부";
            ws.Cell("N1").Value = "수집/이용동의";
            ws.Cell("O1").Value = "위탁동의";
            ws.Cell("P1").Value = "국외이전동의";
            ws.Cell("Q1").Value = "서명여부";
            ws.Cell("R1").Value = "동의서 버전";
            ws.Cell("S1").Value = "동의일자";
            ws.Cell("T1").Value = "동의채널";
            ws.Cell("U1").Value = "담당자";
            ws.Cell("V1").Value = "승인상태";
            ws.Cell("W1").Value = "요청일자(KST)";
            ws.Cell("X1").Value = "승인자";
            ws.Cell("Y1").Value = "승인일자(KST)";

            int row = 2;

            foreach (Approval p in list)
            {
                ws.Cell(row, 1).Value  = p.privacy.NucleusKey;
                ws.Cell(row, 2).Value  = p.privacy.OneKey;
                ws.Cell(row, 3).Value  = p.privacy.PCMSID;
                ws.Cell(row, 4).Value  = p.privacy.WKP_NAME;
                ws.Cell(row, 5).Value  = p.privacy.WKP_TEL;
                ws.Cell(row, 6).Value  = p.privacy.ZIP;
                ws.Cell(row, 7).Value  = p.privacy.FULL_ADDR;
                ws.Cell(row, 8).Value  = p.privacy.IND_SP;
                ws.Cell(row, 9).Value  = p.privacy.TITLE;
                ws.Cell(row, 10).Value = p.privacy.IND_FULL_NAME;
                ws.Cell(row, 11).Value = p.privacy.EMAIL;
                ws.Cell(row, 12).Value = p.privacy.MOBILE;
                ws.Cell(row, 13).Value = p.privacy.Unsubscribe;
                ws.Cell(row, 14).Value = p.privacy.CONSENT_USE;
                ws.Cell(row, 15).Value = p.privacy.CONSENT_TRUST;
                ws.Cell(row, 16).Value = p.privacy.CONSENT_ABROAD;
                ws.Cell(row, 17).Value = p.privacy.CONSENT_SIGN;
                ws.Cell(row, 18).Value = p.privacy.CONSENT.CONSENT_VERSION;
                ws.Cell(row, 19).Value = p.privacy.CONSENT.CONSENT_DATE_KOREA;
                ws.Cell(row, 20).Value = p.privacy.CONSENT.CONSENT_SOURCE;
                ws.Cell(row, 21).Value = p.privacy.creater;
                ws.Cell(row, 22).Value = p.status == ApprovalStatus.Request ? "요청" : p.status == ApprovalStatus.Rejected ? "반려" : "승인";
                ws.Cell(row, 23).Value = TimeZoneInfo.ConvertTime(p.createdate, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Korea Standard Time")).ToString();
                ws.Cell(row, 24).Value = p.modifier;
                ws.Cell(row, 25).Value = TimeZoneInfo.ConvertTime(p.modifieddate, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Korea Standard Time")).ToString();
                row++;
            }
            Stream fs = new MemoryStream();

            wb.SaveAs(fs);
            fs.Position = 0;

            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = "approval_history" + sheetname + ".xlsx",
                Inline   = true,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(fs, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }