/// <summary>
        /// Downloads the report.
        /// </summary>
        /// <param name="reportFileName">Name of the report file.</param>
        /// <param name="fileType">Type of the file.</param>
        /// <param name="reportType">Type of the report.</param>
        /// <param name="currentDateTime">The time zone information.</param>
        /// <returns></returns>
        public ActionResult DownloadReport(string reportFileName, int fileType, int reportType, string currentDateTime)
        {
            string contentType;
            string fileName;

            string path     = GlobalConfigVariable.ReportsFilePath;
            string filePath = Path.Combine(path, reportFileName);

            string fileNameWithoutExtension = string.Format("{0}-{1}.{2}",
                                                            reportType ==
                                                            Constants.ReportLevelClaim
                    ? Constants.ClaimVarianceReportFileBaseName
                    : Constants.ContractVarianceReportFileBaseName, currentDateTime, "{0}");

            if (fileType == Constants.DownloadFileTypeExcel)
            {
                var    fileExtension = Path.GetExtension(reportFileName);
                string newExtenstion = string.Empty;
                if (fileExtension != null)
                {
                    newExtenstion = fileExtension.Replace(".", "");
                }
                contentType = MimeAssistant.GetMimeTypeByExtension(newExtenstion);
                fileName    = string.Format(fileNameWithoutExtension, newExtenstion);
            }
            else
            {
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Pdf.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Pdf);
            }
            return(File(filePath, contentType, fileName));
        }
        /// <summary>
        /// Downloads the user manual.
        /// </summary>
        /// <returns></returns>
        public ActionResult DownloadUserManual()
        {
            string userManualDocumentpath = Server.MapPath(GlobalConfigVariable.UserManualFilePath);
            string fileName = new FileInfo(userManualDocumentpath).Name;

            return(File(userManualDocumentpath, MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Pdf.ToString()), fileName));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets the document.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public FileContentResult GetDocument(long id)
        {
            ContractDoc document = GetApiResponse <ContractDoc>("ContractDoc", "GetContractDocById", id);

            if (document != null)
            {
                if (document.ContractContent == null)
                {
                    string fileNameWithExtension = Path.GetFileName(document.DocumentId.ToString());
                    string extentionOnly         = Path.GetExtension(document.FileName);
                    string mimeType = MimeAssistant.GetMimeTypeByFileName(fileNameWithExtension + extentionOnly);
                    return
                        (File(
                             System.IO.File.ReadAllBytes(Path.Combine(
                                                             GlobalConfigVariable.ContractDocumentsPath, fileNameWithExtension + extentionOnly)),
                             mimeType, document.FileName));
                }
                else
                {
                    byte[] fileContent = document.ContractContent;
                    string mimeType    = MimeAssistant.GetMimeTypeByFileName(document.FileName);
                    return(File(fileContent, mimeType, document.FileName));
                }
            }
            return(null);
        }
Exemplo n.º 4
0
        public ActionResult Download(string id, string returnUrl, bool z = false)
        {
            id = !z?_idDataProtection.Decode(id) : id;

            int offset = int.Parse(Get("Offset"));
            int count  = int.Parse(Get("Count"));

            try{
                if (!string.IsNullOrEmpty(id))
                {
                    var fileInfo = _fileService.RetrieveFileInfoFromAbsolutePath(id);
                    var path     = fileInfo.PhysicalPath;
                    Log.Information($"Decoded path: {path}");
                    if (!fileInfo.Exists)
                    {
                        ReturnMessage = "File doesn't exist on server's filesystem.";
                        return(RedirectToAction(nameof(Browse), new { @path = returnUrl }));
                    }

                    if (Directory.Exists(path))
                    {
                        ReturnMessage = "This is a folder, cannot download it directly.";
                        return(RedirectToAction(nameof(Browse), new { @path = returnUrl }));
                    }

                    var fs   = _fileService.AsStreamAsync(path);
                    var mime = MimeAssistant.GetMimeType(path);
                    return(File(fs, mime, fileInfo.Name));
                }
            }catch (Exception e) {
                Log.Error(e, "StorageController#Download");
            }
            ReturnMessage = "Resource id cannot be null.";
            return(RedirectToAction(nameof(Browse), new { @path = returnUrl, offset, count }));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets the report file details to download.
        /// </summary>
        /// <param name="reportFileBaseName">Name of the report file base.</param>
        /// <param name="reportFileName">Name of the report file.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileContentType">Type of the file content.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="currentDateTime"></param>
        /// <returns></returns>
        public static string GetReportFileDetailsToDownload(string reportFileBaseName, string reportFileName, out string fileName,
                                                            Enums.DownloadFileType fileContentType, out string contentType, string currentDateTime)
        {
            string reportLocation = GlobalConfigVariable.ReportsFilePath;

            string filePath = Path.Combine(reportLocation, reportFileName);
            string fileNameWithoutExtension = string.Format("{0}-{1}.{2}", reportFileBaseName, currentDateTime, "{0}");

            switch (fileContentType)
            {
            case Enums.DownloadFileType.Xls:
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Xls.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Xls);
                break;

            case Enums.DownloadFileType.Csv:
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Csv.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Csv);
                break;

            case Enums.DownloadFileType.Rtf:
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Rtf.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Rtf);
                break;

            default:
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Pdf.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Pdf);
                break;
            }
            return(filePath);
        }
Exemplo n.º 6
0
        public async Task <string> CreateThumb(string path, string guid, int size = 0)
        {
            var physicalPath = _fileService.RetrieveAbsoluteFromSystemPath(path);
            var mime         = MimeAssistant.GetMimeType(physicalPath);
            var mediaType    = DetectType(mime);

            return(mediaType switch
            {
                MediaType.Image => await CreateThumbFromImageAsync(physicalPath, guid, size),
                MediaType.Video => await CreateThumbFromVideoAsync(physicalPath, guid, size),
                _ => string.Empty
            });
Exemplo n.º 7
0
        private IFileResult Build(IContent content, string extension, bool recursive)
        {
            var filePath = CacheFolderPath + content.ContentItem.Id + "-" + recursive + "." + extension;
            var mimeType = MimeAssistant.GetMimeType(filePath);

            if (_storageProvider.FileExists(filePath))
            {
                var file = _storageProvider.GetFile(filePath);
                if (file.GetLastUpdated().ToUniversalTime().Add(_siteService.GetSiteSettings().As <DownloadAsSettingsPart>().CacheTimeout) >= _clock.UtcNow)
                {
                    return(new FileResult(() => file.OpenRead(), mimeType));
                }
                else
                {
                    _storageProvider.DeleteFile(filePath);
                }
            }

            IEnumerable <IContent> contents;

            if (recursive)
            {
                contents = _flattener.Flatten(content);
            }
            else
            {
                contents = new[] { content }
            };

            var worker = _fileBuilderWorkers.Where(w => string.Equals(w.Descriptor.SupportedFileExtension, extension, StringComparison.OrdinalIgnoreCase)).LastOrDefault();

            if (worker == null)
            {
                throw new NotSupportedException("There is no worker for building a file of type " + extension + ".");
            }

            var stream = worker.Build(contents);

            var newFile = _storageProvider.CreateFile(filePath);

            using (var writeStream = newFile.OpenWrite())
            {
                stream.CopyTo(writeStream);
            }

            return(new FileResult(() =>
            {
                stream.Position = 0;
                return stream;
            }, mimeType));
        }
Exemplo n.º 8
0
        private static bool IsValidFileExtensionAndMime(string originalEncodedName,
                                                        FileStream data,
                                                        ICollection <string> permittedExtensions,
                                                        ICollection <string> permittedMimes)
        {
            if (string.IsNullOrEmpty(originalEncodedName) || data.Length == 0)
            {
                return(false);
            }

            var ext  = Path.GetExtension(originalEncodedName);
            var mime = MimeAssistant.GetMimeType(data.Name);

            return(!string.IsNullOrEmpty(ext) && (permittedExtensions.Contains(ext) && permittedMimes.Contains(mime)));
        }
Exemplo n.º 9
0
        public ActionResult PermanentDownload(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                StorageIndexRecord?s = null;
                try
                {
                    s = _storageIndexContext.IndexStorage.SingleOrDefault(record => record.Urlhash.Equals(id));

                    if (s != null)
                    {
                        if (!s.Expires || (s.ExpireDate != DateTime.Now && s.ExpireDate > DateTime.Now))
                        {
                            var fileBytes = _fileService.AsStreamAsync(s.AbsolutePath);
                            var name      = Path.GetFileName(s.AbsolutePath);
                            if (fileBytes != null)
                            {
                                return(File(fileBytes, MimeAssistant.GetMimeType(name), name, true));
                            }

                            ReturnMessage = "Couldn't read requested resource: " + s.Urlid;
                            Log.Warning(ReturnMessage);
                            return(RedirectToAction(nameof(Browse)));
                        }
                        ReturnMessage = "It seems that this url expired, you need to generate a new one.";
                        return(RedirectToAction(nameof(Browse)));
                    }
                    ReturnMessage = "It seems that given token doesn't exist in the database.";
                    return(RedirectToAction(nameof(Browse)));
                }
                catch (InvalidOperationException ex)
                {
                    ReturnMessage = s != null
                        ? "Couldn't read requested resource: " + s.Urlid
                        : "Database error occured.";
                    Log.Error(ex, string.Concat(ReturnMessage, "StorageController#PermanentDownload"));
                    return(RedirectToAction(nameof(Browse)));
                }
            }
            ReturnMessage = "No id given or database is down.";
            return(RedirectToAction(nameof(Browse)));
        }
        /// <summary>
        /// Downloads the report.
        /// </summary>
        /// <param name="reportFileName">Name of the report file.</param>
        /// <param name="fileType">Type of the file.</param>
        /// <param name="isActive">if set to <c>true</c> [is active].</param>
        /// <param name="currentDateTime">The time zone information.</param>
        /// <returns></returns>
        public ActionResult DownloadReport(string reportFileName, int?fileType, bool isActive, string currentDateTime)
        {
            string contentType;
            string fileName;

            string path     = GlobalConfigVariable.ReportsFilePath;
            string filePath = Path.Combine(path, reportFileName);
            string fileNameWithoutExtension = string.Format("{0}-{1}{2}.{3}", Constants.ModelingReportFileBaseName,
                                                            isActive ? Constants.ActiveReport : Constants.InActiveReport, currentDateTime, "{0}");

            if (fileType == 1)
            {
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Pdf.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Pdf);
            }
            else
            {
                contentType = MimeAssistant.GetMimeTypeByExtension(Enums.DownloadFileType.Xls.ToString());
                fileName    = string.Format(fileNameWithoutExtension, Enums.DownloadFileType.Xls);
            }
            return(File(filePath, contentType, fileName));
        }
Exemplo n.º 11
0
        protected override DriverResult Editor(ContentPart part, MediaLibraryUploadField field, IUpdateModel updater, dynamic shapeHelper)
        {
            var model = new MediaLibraryUploadFieldViewModel {
                SelectedIds = string.Join(",", field.Ids)
            };
            var settings = field.PartFieldDefinition.Settings.GetModel <MediaLibraryUploadFieldSettings>();

            if (updater.TryUpdateModel(model, GetPrefix(field, part), null, null))
            {
                field.Ids = String.IsNullOrEmpty(model.SelectedIds) ? new int[0] : model.SelectedIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

                var files             = ((Controller)updater).Request.Files;
                var mediaPartsCreated = new List <MediaPart>();
                for (int i = 0; i < files.Count; i++)
                {
                    // To make sure that we only process those files that are uploaded using this field's UI control.
                    if (files.AllKeys[i].Equals(string.Format("MediaLibraryUploadField-{0}-{1}[]", part.PartDefinition.Name, field.Name)))
                    {
                        var file = files[i];

                        if (file.ContentLength == 0)
                        {
                            continue;
                        }

                        var allowedExtensions = (settings.AllowedExtensions ?? "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => string.Format(".{0}", s));
                        if (allowedExtensions.Any() && !allowedExtensions.Contains(Path.GetExtension(file.FileName).ToLowerInvariant()))
                        {
                            _notifier.Warning(T("The file \"{0}\" was not uploaded, because its extension is not among the accepted ones. The accepted file extensions are: {1}.",
                                                file.FileName, string.Join(", ", allowedExtensions)));
                            continue;
                        }

                        if (settings.MaximumSizeKB > 0 && file.ContentLength > settings.MaximumSizeKB * 1024)
                        {
                            _notifier.Warning(T("The file \"{0}\" was not uploaded, because its size exceeds the {1} KB limitation.", file.FileName, settings.MaximumSizeKB));
                            continue;
                        }

                        // Checking against image-specific settings.
                        if (MimeAssistant.GetMimeType(file.FileName.ToLowerInvariant()).StartsWith("image"))
                        {
                            using (var image = Image.FromStream(file.InputStream))
                            {
                                if ((settings.ImageMaximumWidth > 0 && image.Width > settings.ImageMaximumWidth) || (settings.ImageMaximumHeight > 0 && image.Height > settings.ImageMaximumHeight))
                                {
                                    _notifier.Warning(T("The image \"{0}\" was not uploaded, because its dimensions exceed the limitations. The maximum allowed file dimensions are {1}x{2} pixels.",
                                                        file.FileName, settings.ImageMaximumWidth, settings.ImageMaximumHeight));
                                    continue;
                                }
                            }

                            file.InputStream.Position = 0;
                        }

                        // At this point we can be sure that the files comply with the settings and limitations, so we can import them.
                        var user       = _wca.GetContext().CurrentUser;
                        var folderPath = _tokenizer.Replace(settings.FolderPath, new Dictionary <string, object>
                        {
                            { "Content", part.ContentItem },
                            { "User", user }
                        });

                        folderPath = string.IsNullOrEmpty(folderPath) ? "UserUploads/" + user.Id : folderPath;

                        var mediaPart = _mediaLibraryService.ImportMedia(file.InputStream, folderPath, file.FileName);
                        _contentManager.Create(mediaPart);
                        mediaPartsCreated.Add(mediaPart);
                    }
                }

                if (mediaPartsCreated.Any())
                {
                    field.Ids = field.Ids.Union(mediaPartsCreated.Select(m => m.ContentItem.Id)).ToArray();
                    _notifier.Information(T("The following items were successfully uploaded: {0}.", string.Join(", ", mediaPartsCreated.Select(mp => mp.FileName))));
                }
            }

            if (settings.Required && field.Ids.Length == 0)
            {
                updater.AddModelError("Id", T("You need to have or upload at least one file for the field {0}.", field.Name.CamelFriendly()));
            }

            return(Editor(part, field, shapeHelper));
        }
Exemplo n.º 12
0
        private async Task <IFileResult> Build(ContentItem content, string extension, bool recursive, DisplayContext displayContext)
        {
            // var filePath = CacheFolderPath + content.ContentItem.Id + "-" + recursive + "." + extension;
            var mimeType = MimeAssistant.GetMimeType(extension);

            //if (_storageProvider.FileExists(filePath))
            //{
            //    var file = _storageProvider.GetFile(filePath);
            //    if (file.GetLastUpdated().ToUniversalTime().Add(_siteService.GetSiteSettings().As<DownloadAsSettingsPart>().CacheTimeout) >= _clock.UtcNow)
            //    {
            //        return new FileResult(() => file.OpenRead(), mimeType);
            //    }
            //    else
            //    {
            //        _storageProvider.DeleteFile(filePath);
            //    }
            //}

            IEnumerable <ContentItem> contents;

            if (recursive)
            {
                contents = await _flattener.Flatten(content, displayContext);
            }
            else
            {
                contents = new[] { content }
            };

            var worker = _fileBuilderWorkers.LastOrDefault(w => string.Equals(w.Descriptor.SupportedFileExtension, extension, StringComparison.OrdinalIgnoreCase));

            if (worker == null)
            {
                throw new NotSupportedException("There is no worker for building a file of type " + extension + ".");
            }

            var stream = await worker.Build(contents, displayContext);

            //
            //if (string.IsNullOrEmpty(directoryName))
            //{
            //    directoryName = "";
            //}

            var mediaDiredtory = await CreateTempFolder("", "DownloadAsDirectoryTemp");

            string name = content.ContentItem.Id.ToString() + "." + mimeType;
            //   string directoryName = "";//Path.GetDirectoryName(name);
            string mediaFilename = _storageProvider.Combine(mediaDiredtory.DirectoryPath, name);
            var    memoryStream  = new MemoryStream();
            await stream.CopyToAsync(memoryStream);

            memoryStream.Position = 0;
            //Create file.
            await _storageProvider.CreateFileFromStreamAsync(mediaFilename, memoryStream, true);


//            string directoryName = Path.GetDirectoryName(name);
//            string filePath = _mediaFileStore.Combine(directoryName, Path.GetFileName(name));
//            await _mediaFileStore.CreateFileFromStream(filePath, new MemoryStream(bits));
//
//            string publicUrl = _mediaFileStore.MapPathToPublicUrl(filePath);


            //Get File
            var newFile = await _storageProvider.GetFileInfoAsync(mediaFilename);

            if (newFile == null)
            {
                return(null);
            }
            //convert to donloadadble file
            var newfileAsStream = await _storageProvider.GetFileStreamAsync(mediaFilename);

            // var newfileAsStream = await _storageProvider.GetFileStreamAsync(newFile.DirectoryPath);

            //  string publicUrl = _storageProvider.MapPathToPublicUrl(filePath);


            //todo
            // var newFile = _storageProvider.CreateFile(filePath);
            // var newFile = await _storageProvider.CreateFileFromStream(filePath);

            //var mediaFilePath = _storageProvider.Combine(filePath, file.FileName);

            //using (var stream1 = file.OpenReadStream())
            //{
            //    await _storageProvider.CreateFileFromStream(mediaFilePath, stream1);
            //}

            //using (var writeStream = newFile.OpenWrite())
            //{
            //    stream.CopyTo(writeStream);
            //}



            //also see :
            //https://www.codeproject.com/Articles/1203408/Upload-Download-Files-in-ASP-NET-Core

            return(new FileResult(() =>
            {
                newfileAsStream.Position = 0;
                return newfileAsStream;
            }, mimeType));

            // return null;
        }