private static void WriteResponse(HttpContentType?mimeType, byte[] content, HttpStatusCode httpStatusCode, IOutputStream outputStream) { var stream = outputStream.AsStreamForWrite(); var responseHeader = new StringBuilder(); responseHeader.Append($"{HttpStatusCodeHelper.GetHttpStatusCodeForHttpHeader(httpStatusCode)}\r\n"); if (httpStatusCode != HttpStatusCode.HttpCode204) { responseHeader.Append($"Content-Type: {MimeTypeHelper.GetHttpContentType(mimeType.Value)}\r\n"); responseHeader.Append($"Content-Length: {content.Length}\r\n"); } responseHeader.Append("Connection: Close\r\n\r\n"); var responsHeaderBytes = Encoding.UTF8.GetBytes(responseHeader.ToString()); stream.Write(responsHeaderBytes, 0, responsHeaderBytes.Length); if (content != null) { stream.Write(content, 0, content.Length); } stream.Flush(); stream.Dispose(); }
public HttpResponseMessage Download(Guid id) { try { FileDto fileDto = _service.GetFileById(id, base.GetUserDto()); if (fileDto != null) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(fileDto.Data) }; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileDto.FileName }; result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeTypeHelper.GetMimeType(Path.GetExtension(fileDto.FileName))); return(result); } else { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } } catch (PermissionException e) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (Exception e) { Logger.e("Download", e); return(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(e.Message) }); } }
public async Task <ActionResult> Download(Guid id, Guid fileId) { var result = await mediator.SendAsync(new GetFile(id, fileId)); return(File(result.Content, MimeTypeHelper.GetMimeType(result.Type), string.Format("{0}.{1}", result.Name, result.Type))); }
public async Task <ActionResult> GenerateMovementDocument(Guid id) { var result = await mediator.SendAsync(new GenerateMovementDocument(id)); return(File(result.Content, MimeTypeHelper.GetMimeType(result.FileNameWithExtension), result.FileNameWithExtension)); }
public override async Task <OriginalData?> GetAsync(string source, ICachedImage?existingCachedImage) { IFileInfo fileInfo = FileProvider.GetFileInfo(source); if (fileInfo.Exists == false) { throw new Exception("file not found: " + source); } string etag = (fileInfo.Length ^ fileInfo.LastModified.UtcTicks).ToString(); if (existingCachedImage != null) { if (existingCachedImage.Metadata.Cache.ETag == etag) { return(null); } } MemoryStream mem = new MemoryStream((int)fileInfo.Length); using (Stream stream = fileInfo.CreateReadStream()) { await stream.CopyToAsync(mem); } string mimeType = MimeTypeHelper.GetMimeTypeByExtension(fileInfo.Name); return(new OriginalData(mimeType, mem.ToArray(), new CacheSettings() { ETag = etag })); }
/// <summary> /// Create Media entity with attachment /// </summary> /// <param name="filePath">Local Path to file</param> /// <param name="filename">Name of file in WP Media Library</param> /// <returns>Created media object</returns> /// <param name="mimeType">Override for automatic mime type detection</param> public async Task <MediaItem> Create(string filePath, string filename, string mimeType = null) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(filename)); } if (File.Exists(filePath)) { using (StreamContent content = new StreamContent(File.OpenRead(filePath))) { if (string.IsNullOrEmpty(mimeType)) { string extension = filename.Split('.').Last(); content.Headers.TryAddWithoutValidation("Content-Type", MimeTypeHelper.GetMIMETypeFromExtension(extension)); } else { content.Headers.TryAddWithoutValidation("Content-Type", mimeType); } content.Headers.TryAddWithoutValidation("Content-Disposition", $"attachment; filename={filename}"); return((await _httpHelper.PostRequest <MediaItem>($"{_defaultPath}{_methodPath}", content).ConfigureAwait(false)).Item1); } } else { throw new FileNotFoundException($"{filePath} was not found"); } }
protected void Page_Load(object sender, EventArgs e) { // Check 'ReadData' permission if (CurrentUser != null && CurrentUser.IsAuthorizedPerResource("cms.form", "ReadData")) { // Get file name from querystring string fileName = QueryHelper.GetString("filename", String.Empty); string siteName = QueryHelper.GetString("sitename", CurrentSiteName); if ((ValidationHelper.IsFileName(fileName)) && (siteName != null)) { // Get physical path to the file string filePath = FormHelper.GetFilePhysicalPath(siteName, fileName); if (File.Exists(filePath)) { // Clear response CookieHelper.ClearResponseCookies(); Response.Clear(); // Prepare response string extension = Path.GetExtension(filePath); Response.ContentType = MimeTypeHelper.GetMimetype(extension); // Set the file disposition SetDisposition(fileName, extension); // Get file binary from file system WriteFile(filePath); CompleteRequest(); } } } }
public IActionResult CreateWord() { var fileName = _context.DataFile .Select(i => i.FileName) .First(); var previousExtension = fileName.Split('.')[1]; var wordFile = fileName.Replace(previousExtension, "docx"); var targetFileDirectory = Path.Combine(_hostingEnvironment.ContentRootPath, "Uploads"); if (!Directory.Exists(targetFileDirectory)) { Directory.CreateDirectory(targetFileDirectory); } var filePath = Path.Combine(targetFileDirectory, wordFile); WordHelper.CreateWordprocessingDocument(filePath); var run = new RunFonts { Ascii = "Calibri" }; var wp = new WordHelper("14.1%", "26.7%", "59.1%", "24", run); var lineItems = (from tempData in _context.TempData join category in _context.Category on tempData.Category equals category.Name join lineItem in _context.LineItem on tempData.Name equals lineItem.Name join mapping in _context.Mapping on new { CategoryId = category.Id, LineItemId = lineItem.Id } equals new { mapping.CategoryId, mapping.LineItemId } orderby mapping.LineItemId, lineItem.LineNumber select new { Category = category.Name, mapping.LineItem.Name, mapping.Description, mapping.LineItem.LineNumber, mapping.Id }) .ToList(); var model = (from lineItem in lineItems.GroupBy(i => new { i.Category, i.Description }) let lineNumbers = lineItem.Select(i => i.LineNumber) let lineNames = lineItem.Select(i => i.Name) select new LineItemViewModel { Category = lineItem.Key.Category, Description = lineItem.Key.Description, WordLineNumbers = string.Join(',', lineNumbers), Name = string.Join(Environment.NewLine + Environment.NewLine, lineNames) }).ToList(); wp.AddTable(filePath, model); var fileBytes = System.IO.File.ReadAllBytes(filePath); return(File(fileBytes, MimeTypeHelper.GetContentType(filePath), wordFile)); }
/// <summary> /// Gets the mime type of the file. /// </summary> /// <returns></returns> public string GetContentType() { if (String.IsNullOrEmpty(Name)) { return(""); } return(MimeTypeHelper.GetMimeType(Name)); }
public static CloudBlockBlob StoreFile(string containerName, string virtualFilename, FileInfo file, StorageFileConfig config) { using (var fs = file.OpenRead()) { config.ContentType = MimeTypeHelper.GetMimeType(file.FullName); return(StoreFile(containerName, virtualFilename, fs, config)); } }
private static void UpgradeApplication(Func <bool> versionSpecificMethod, string newVersion, string packageName) { // Increase the timeout for upgrade request due to expensive operations like macro signing and conversion (needed for large DBs) HttpContext.Current.Server.ScriptTimeout = 14400; EventLogProvider.LogInformation(EVENT_LOG_INFO, "Upgrade - Start"); // Set the path to the upgrade package (this has to be done here, not in the Import method, because it's an async procedure without HttpContext) mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/" + packageName); mWebsitePath = HttpContext.Current.Server.MapPath("~/"); using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; UpdateClasses(); UpdateAlternativeForms(); } // Update all views var dtm = new TableManager(null); dtm.RefreshDocumentViews(); RefreshCustomViews(dtm); // Set data version SettingsKeyInfoProvider.SetValue("CMSDataVersion", newVersion); SettingsKeyInfoProvider.SetValue("CMSDBVersion", newVersion); // Clear hashtables ModuleManager.ClearHashtables(); // Clear the cache CacheHelper.ClearCache(null, true); // Drop the routes CMSDocumentRouteHelper.DropAllRoutes(); // Init the Mimetype helper (required for the Import) MimeTypeHelper.LoadMimeTypes(); // Call version specific operations if (versionSpecificMethod != null) { using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; versionSpecificMethod.Invoke(); } } UpgradeImportPackage(); }
/// <summary> /// Fill more information based on File is Image or not /// </summary> /// <param name="imageInfo"></param> /// <param name="fileEntity"></param> public static void FillInformation(ImageModel imageInfo, FileEntity fileEntity) { fileEntity.IsImage = false; fileEntity.IsCompressedImage = false; fileEntity.MimeType = string.IsNullOrWhiteSpace(fileEntity.Extension) ? "application/octet-stream" : MimeTypeHelper.GetMimeType(fileEntity.Extension); if (imageInfo != null) { // Image File fileEntity.IsImage = true; fileEntity.ImageDominantHexColor = imageInfo.DominantHexColor.ToLowerInvariant(); fileEntity.ImageWidthPx = imageInfo.WidthPx; fileEntity.ImageHeightPx = imageInfo.HeightPx; fileEntity.MimeType = imageInfo.MimeType; fileEntity.Extension = imageInfo.Extension; } else { fileEntity.Extension = Path.GetExtension(fileEntity.Name); } // Handle file extension if (string.IsNullOrWhiteSpace(fileEntity.Extension)) { fileEntity.Extension = MimeTypeHelper.GetExtension(fileEntity.MimeType); } // Handle file name if (!string.IsNullOrWhiteSpace(fileEntity.Name)) { fileEntity.Name = FileHelper.MakeValidFileName(fileEntity.Name); if (!string.IsNullOrWhiteSpace(fileEntity.Extension) && fileEntity.Name.EndsWith(fileEntity.Extension)) { // Get File Name Only fileEntity.Name = fileEntity.Name.Substring(0, fileEntity.Name.Length - fileEntity.Extension.Length); } } else { fileEntity.Name = Elect.Core.StringUtils.StringHelper.Generate(4, false); } }
/// <summary> /// Create Media entity with attachment /// </summary> /// <param name="fileStream">stream with file content</param> /// <param name="filename">Name of file in WP Media Library</param> /// <returns>Created media object</returns> public async Task <MediaItem> Create(Stream fileStream, string filename) { StreamContent content = new StreamContent(fileStream); string extension = filename.Split('.').Last(); content.Headers.TryAddWithoutValidation("Content-Type", MimeTypeHelper.GetMIMETypeFromExtension(extension)); content.Headers.TryAddWithoutValidation("Content-Disposition", $"attachment; filename={filename}"); return((await _httpHelper.PostRequest <MediaItem>($"{_defaultPath}{_methodPath}", content)).Item1); }
public async Task <ActionResult> Download(Guid notificationId, Guid fileId) { var result = await mediator.SendAsync(new GetFile(notificationId, fileId)); var fileExtension = result.Type.Replace(".", string.Empty); return(File(result.Content, MimeTypeHelper.GetMimeType(result.Type), string.Format("{0}.{1}", result.Name, fileExtension))); }
/// <summary> /// <para> Get image info. </para> /// <para> If not know mime type but valid image then return <see cref="ImageConstants.ImageMimeTypeUnknown" /> </para> /// <para> Invalid image will be return <c> NULL </c> </para> /// </summary> /// <param name="imageStream"></param> public static ImageModel GetImageInfo(MemoryStream imageStream) { try { ImageModel imageModel = new ImageModel(); // Check Vector image first, if image is vector then no info for width and height if (IsSvgImage(imageStream)) { imageModel.MimeType = "image/svg+xml"; } else { // Raster check (jpg, png, etc.) using (var image = Image.FromStream(imageStream)) { // Get image mime type bool isUnknownMimeType = true; foreach (var imageCodecInfo in ImageCodecInfo.GetImageDecoders()) { if (imageCodecInfo.FormatID == image.RawFormat.Guid) { imageModel.MimeType = imageCodecInfo.MimeType; isUnknownMimeType = false; break; } } if (isUnknownMimeType) { imageModel.MimeType = ImageConstants.ImageMimeTypeUnknown; } // Get width and height in pixel info imageModel.WidthPx = image.Width; imageModel.HeightPx = image.Height; } } // Get others info imageModel.Extension = MimeTypeHelper.GetExtension(imageModel.MimeType); // Get image dominant color using (var bitmap = new Bitmap(imageStream)) { imageModel.DominantHexColor = ImageDominantColorHelper.GetHexCode(bitmap); } return(imageModel); } catch { return(null); } }
public FileDataDTO GetFileData(string path) { string fileName = Path.GetFileName(path); string ext = Path.GetExtension(path); var stream = File.OpenRead(path); string mimeType = MimeTypeHelper.GetMimeType(ext); return(new FileDataDTO { FileStream = stream, Extension = ext, FileName = fileName, MimeType = mimeType }); }
protected void Page_Load(object sender, EventArgs e) { string hash = QueryHelper.GetString("hash", string.Empty); string path = QueryHelper.GetString("path", string.Empty); // Validate hash if (ValidationHelper.ValidateHash("?path=" + path, hash, false)) { if (path.StartsWith("~")) { path = Server.MapPath(path); } // Get file content from Amazon S3 IS3ObjectInfo obj = S3ObjectFactory.GetInfo(path); // Check if blob exists if (Provider.ObjectExists(obj)) { Stream stream = Provider.GetObjectContent(obj); // Set right content type Response.ContentType = MimeTypeHelper.GetMimetype(Path.GetExtension(path)); SetDisposition(Path.GetFileName(path), Path.GetExtension(path)); // Send headers Response.Flush(); Byte[] buffer = new Byte[DataHelper.BUFFER_SIZE]; int bytesRead = stream.Read(buffer, 0, DataHelper.BUFFER_SIZE); // Copy data from blob stream to cache while (bytesRead > 0) { // Write the data to the current output stream Response.OutputStream.Write(buffer, 0, bytesRead); // Flush the data to the output Response.Flush(); // Read next part of data bytesRead = stream.Read(buffer, 0, DataHelper.BUFFER_SIZE); } stream.Close(); CompleteRequest(); } } else { URLHelper.Redirect(ResolveUrl("~/CMSMessages/Error.aspx?title=" + ResHelper.GetString("general.badhashtitle") + "&text=" + ResHelper.GetString("general.badhashtext"))); } }
public Form1() { InitializeComponent(); this.btnStop.Enabled = false; this.basePath = AppDomain.CurrentDomain.BaseDirectory; this.basePath = this.basePath.Substring(0, this.basePath.IndexOf("\\Sandbox")); this.basePath = Path.Combine(this.basePath, "Peek.WebService"); MimeTypeHelper.GetInstance().Load(Path.Combine(this.basePath, "Configuration.xml")); }
/// <summary> /// Processes the specified file. /// </summary> /// <param name="fileGuid">File guid</param> /// <param name="preview">Use preview</param> protected void ProcessFile(Guid fileGuid, bool preview) { // Get the file info if doesn't retrieved yet fileInfo = (fileInfo ?? MediaFileInfoProvider.GetMediaFileInfo(fileGuid, CurrentSiteName)); if (fileInfo != null) { if (preview) { // Get file path string path = MediaFileInfoProvider.GetMediaFilePath(fileInfo.FileLibraryID, fileInfo.FilePath); string pathDirectory = Path.GetDirectoryName(path); string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName); string folderPath = DirectoryHelper.CombinePath(pathDirectory, hiddenFolderPath); // Ensure hidden folder exists DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory); // Get preview file string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(fileInfo.FileName, fileInfo.FileExtension, ".*", CurrentSiteName)); if (files.Length > 0) { bool resizeImage = (ImageHelper.IsImage(Path.GetExtension(files[0])) && MediaFileInfoProvider.CanResizeImage(files[0], Width, Height, MaxSideSize)); // Get the data if ((outputFile == null) || (outputFile.MediaFile == null)) { outputFile = NewOutputFile(fileInfo, null); outputFile.UsePreview = true; outputFile.Width = Width; outputFile.Height = Height; outputFile.MaxSideSize = MaxSideSize; outputFile.Resized = resizeImage; outputFile.FileExtension = Path.GetExtension(files[0]); outputFile.MimeType = MimeTypeHelper.GetMimetype(outputFile.FileExtension); } } } else { bool resizeImage = (ImageHelper.IsImage(fileInfo.FileExtension) && MediaFileInfoProvider.CanResizeImage(fileInfo, Width, Height, MaxSideSize)); // Get the data if ((outputFile == null) || (outputFile.MediaFile == null)) { outputFile = NewOutputFile(fileInfo, null); outputFile.Width = Width; outputFile.Height = Height; outputFile.MaxSideSize = MaxSideSize; outputFile.Resized = resizeImage; } } } }
public static string MapType(string path) { var type = MimeTypeHelper.GetMimeType(path); if (type == null) { return("icons/IcType-onbekend"); } else if (type.StartsWith("image")) { return("icons/IcType-Foto"); } else if (type.StartsWith("video")) { return("icons/IcType-Film"); } else if (type.Equals("application/pdf")) { return("icons/IcType-PDF"); } else if (type.Equals("application/vnd.ms-powerpoint") || type.Equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")) { return("icons/IcType-Presentatie"); } else if (type.Equals("application/vnd.ms-excel") || type.Equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) { return("icons/IcType-Berekeningen"); } else if (type.Equals("application/msword") || type.Equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) { return("icons/IcType-Tekstdocumenten"); } else if (type.Equals("application/zip")) { return("icons/IcType-gecompileerd"); } else if (type.Equals("application/mp4")) { return("icons/IcType-Film"); } else if (type.StartsWith("audio")) { return("icons/IcType-Muziek"); } else { return("icons/IcType-onbekend"); } }
private void btnOk_Click(object sender, EventArgs e) { // Init the Mimetype helper (required for the export) MimeTypeHelper.LoadMimeTypes(); // Prepare the settings ExportSettings = new SiteExportSettings(CMSContext.CurrentUser); ExportSettings.WebsitePath = Server.MapPath("~/"); ExportSettings.TargetPath = targetFolder; // Initialize ImportExportHelper.InitSingleObjectExportSettings(ExportSettings, exportObj); string result = ImportExportHelper.ValidateExportFileName(ExportSettings, txtFileName.Text); // Filename is valid if (!string.IsNullOrEmpty(result)) { lblError.Text = result; } else { txtFileName.Text = txtFileName.Text.Trim(); // Add extension if (Path.GetExtension(txtFileName.Text).ToLowerCSafe() != ".zip") { txtFileName.Text = txtFileName.Text.TrimEnd('.') + ".zip"; } // Set the filename lblProgress.Text = string.Format(GetString("ExportObject.ExportProgress"), ResHelper.LocalizeString(exportObjectDisplayName)); ExportSettings.TargetFileName = txtFileName.Text; pnlContent.Visible = false; pnlDetails.Visible = false; btnOk.Enabled = false; pnlProgress.Visible = true; try { // Export the data ltlScript.Text = ScriptHelper.GetScript("StartTimer();"); ucAsyncControl.RunAsync(ExportSingleObject, WindowsIdentity.GetCurrent()); } catch (Exception ex) { DisplayError(ex); } } }
public ActionResult Show(string id) { System.IO.Stream stream; id = id.Replace("\\\\", "\\"); if (MimeTypeHelper.IsImage(id) && (stream = _FileManager.GetImage(id)) != null) { return(File(stream, MimeTypeHelper.GetMimeType(id))); } else { return(HttpNotFound("file not exists")); } }
public static CloudBlockBlob StoreFile(string containerName, string virtualFilename, FileInfo file, bool replace = true) { using (var fs = file.OpenRead()) { var contenttype = MimeTypeHelper.GetMimeType(file.FullName); return(StoreFile(containerName, virtualFilename, fs, new StorageFileConfig() { Replace = replace, ContentType = contenttype })); } }
public IActionResult DownloadImage(string fileName) { string contentPath = PathHelper.GetViewerImagesFolder(); string targetFullFileName = Path.Combine(contentPath, fileName); if (!IOFile.Exists(targetFullFileName)) { return(NotFound()); } string mimeType = MimeTypeHelper.GetMimeType(Path.GetExtension(fileName)); return(PhysicalFile(targetFullFileName, mimeType, fileName)); }
protected MediaFileInfo CreateMediafileInfo(int mediaLibraryId, FileInfo fileInfo) { var mediaFile = new MediaFileInfo(fileInfo?.FullName, mediaLibraryId) { FileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - fileInfo.Extension.Length), FileExtension = fileInfo.Extension, FileMimeType = MimeTypeHelper.GetMimetype(fileInfo.Extension), FileSiteID = SiteContext.CurrentSiteID, FileLibraryID = mediaLibraryId, FileSize = fileInfo.Length }; MediaFileInfoProvider.SetMediaFileInfo(mediaFile); return(mediaFile); }
/// <summary> /// Create Media entity with attachment /// </summary> /// <param name="filePath">Local Path to file</param> /// <param name="filename">Name of file in WP Media Library</param> /// <returns>Created media object</returns> public async Task <MediaItem> Create(string filePath, string filename) { if (File.Exists(filePath)) { StreamContent content = new StreamContent(File.OpenRead(filePath)); string extension = filename.Split('.').Last(); content.Headers.TryAddWithoutValidation("Content-Type", MimeTypeHelper.GetMIMETypeFromExtension(extension)); content.Headers.TryAddWithoutValidation("Content-Disposition", $"attachment; filename={filename}"); return((await _httpHelper.PostRequest <MediaItem>($"{_defaultPath}{_methodPath}", content)).Item1); } else { throw new FileNotFoundException($"{filePath} was not found"); } }
/// <summary> /// Sets content type of the response based on file MIME type /// </summary> /// <param name="filePath">File path</param> private void SetResponseContentType(string filePath) { string extension = Path.GetExtension(filePath); string mimeType = MimeTypeHelper.GetMimetype(extension); switch (extension.ToLowerCSafe()) { case ".flv": // Correct MIME type mimeType = "video/x-flv"; break; } // Set content type Response.ContentType = mimeType; }
public async Task <Guid> AddMediaFileAsync(string filePath, string mediaLibraryName, string?libraryFolderPath = default, bool checkPermissions = default) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("File path was not specified.", nameof(filePath)); } return(await AddMediaFileAsyncImplementation()); async Task <Guid> AddMediaFileAsyncImplementation() { var siteId = _siteService.CurrentSite.SiteID; var siteName = _siteService.CurrentSite.SiteName; MediaLibraryInfo mediaLibraryInfo; try { mediaLibraryInfo = await _mediaLibraryInfoProvider.GetAsync(mediaLibraryName, siteId); } catch (Exception) { throw new Exception($"The {mediaLibraryName} library was not found on the {siteName} site."); } if (checkPermissions && !mediaLibraryInfo.CheckPermissions(PermissionsEnum.Create, siteName, MembershipContext.AuthenticatedUser)) { throw new PermissionException( $"The user {MembershipContext.AuthenticatedUser.FullName} lacks permissions to the {mediaLibraryName} library."); } MediaFileInfo mediaFile = !string.IsNullOrEmpty(libraryFolderPath) ? new MediaFileInfo(filePath, mediaLibraryInfo.LibraryID, libraryFolderPath) : new MediaFileInfo(filePath, mediaLibraryInfo.LibraryID); var fileInfo = FileInfo.New(filePath); mediaFile.FileName = fileInfo.Name.Substring(0, fileInfo.Name.Length - fileInfo.Extension.Length); mediaFile.FileExtension = fileInfo.Extension; mediaFile.FileMimeType = MimeTypeHelper.GetMimetype(fileInfo.Extension); mediaFile.FileSiteID = siteId; mediaFile.FileLibraryID = mediaLibraryInfo.LibraryID; mediaFile.FileSize = fileInfo.Length; _mediaFileInfoProvider.Set(mediaFile); return(mediaFile.FileGUID); } }
/// <summary> /// Método que devuelve los atributos que deberán ser firmados /// </summary> /// <param name="parameters"></param> /// <returns></returns> private Dictionary <DerObjectIdentifier, Asn1Encodable> GetSignedAttributes(SignatureParameters parameters) { Dictionary <DerObjectIdentifier, Asn1Encodable> signedAttrs = new Dictionary <DerObjectIdentifier, Asn1Encodable>(); BcCms.Attribute signingCertificateReference = MakeSigningCertificateAttribute(parameters); signedAttrs.Add((DerObjectIdentifier)signingCertificateReference.AttrType, signingCertificateReference); signedAttrs.Add(PkcsObjectIdentifiers.Pkcs9AtSigningTime, MakeSigningTimeAttribute (parameters)); if (parameters.SignaturePolicyInfo != null) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, MakeSignaturePolicyAttribute(parameters)); } if (!string.IsNullOrEmpty(parameters.SignerRole)) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSignerAttr, MakeSignerAttrAttribute(parameters)); } if (parameters.SignatureProductionPlace != null) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSignerLocation, MakeSignerLocationAttribute(parameters)); } if (parameters.SignatureCommitments.Count > 0) { var commitments = MakeCommitmentTypeIndicationAttributes(parameters); foreach (var item in commitments) { signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCommitmentType, item); } } if (!string.IsNullOrEmpty(parameters.MimeType)) { ContentHints contentHints = new ContentHints(new DerObjectIdentifier(MimeTypeHelper.GetMimeTypeOid(parameters.MimeType))); BcCms.Attribute contentAttr = new BcCms.Attribute(PkcsObjectIdentifiers.IdAAContentHint, new DerSet(contentHints)); signedAttrs.Add(PkcsObjectIdentifiers.IdAAContentHint, contentAttr); } return(signedAttrs); }
private static MediaTypeHeaderValue GetMediaType(DigitalResource resource) { String ext = String.Empty; if (resource.OriginalFileName.Contains(".")) { ext = resource.OriginalFileName.Substring(resource.OriginalFileName.IndexOf(".") + 1); } if (String.IsNullOrEmpty(ext)) { ext = "application/octet-stream"; } string mimeType = MimeTypeHelper.GetMimeType(ext); MediaTypeHeaderValue _mediaType = MediaTypeHeaderValue.Parse(mimeType); return(_mediaType); }