/// <summary> /// Initializes a new instance of the <see cref="DisplayObject"/> class. /// </summary> /// <param name="width">The width of this object, in pixels.</param> /// <param name="height">The height of this object, in pixels.</param> /// <param name="filename">The name of the file representing this object. Example: sonorandesert.jpg</param> /// <param name="parent">The media object to which this display object applies.</param> /// <param name="displayType">The type of the display object.</param> /// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param> private DisplayObject(int width, int height, string filename, IGalleryObject parent, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator) { this._width = width; this._height = height; this._filename = filename; if (!String.IsNullOrEmpty(filename)) { this._mimeType = Business.MimeType.LoadMimeType(parent.GalleryId, this._filename); } if (this._mimeType == null) { this._mimeType = new NullObjects.NullMimeType(); } this._parent = parent; this._displayType = displayType; this._displayObjectCreator = displayObjectCreator; if (this._parent is IAlbum) { this._mediaObjectId = int.MinValue; } else { this._mediaObjectId = parent.Id; } }
/// <summary> /// Initializes a new instance of the <see cref="DisplayObject"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="displayType">The display type.</param> /// <param name="mimeType">Specifies the category to which this mime type belongs. This usually corresponds to the first portion of /// the full mime type description. (e.g. "image" if the full mime type is "image/jpeg").</param> private DisplayObject(IGalleryObject parent, DisplayObjectType displayType, MimeTypeCategory mimeType) { if (displayType != DisplayObjectType.External) { throw new BusinessException(String.Format(CultureInfo.CurrentCulture, "This overload of the DisplayObject constructor can only be called when the displayType parameter is DisplayObjectType.External. Instead, it was {0}.", displayType.ToString())); } this._width = int.MinValue; this._height = int.MinValue; this._filename = String.Empty; this._mimeType = GalleryServerPro.Business.MimeType.CreateInstance(mimeType); this._externalType = this._mimeType.TypeCategory; this._parent = parent; this._displayType = displayType; this._displayObjectCreator = new NullObjects.NullDisplayObjectCreator(); if (this._parent is IAlbum) { this._mediaObjectId = int.MinValue; } else { this._mediaObjectId = parent.Id; } }
/// <summary> /// Initializes a new instance of the <see cref="DisplayObject"/> class. /// </summary> /// <param name="width">The width of this object, in pixels.</param> /// <param name="height">The height of this object, in pixels.</param> /// <param name="filename">The name of the file representing this object. Example: sonorandesert.jpg</param> /// <param name="parent">The media object to which this display object applies.</param> /// <param name="displayType">The type of the display object.</param> /// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param> private DisplayObject(int width, int height, string filename, IGalleryObject parent, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator) { this._width = width; this._height = height; this._filename = filename; if (!String.IsNullOrEmpty(filename)) { this._mimeType = Factory.LoadMimeType(parent.GalleryId, this._filename); } if (this._mimeType == null) { this._mimeType = new NullObjects.NullMimeType(); } this._parent = parent; this._displayType = displayType; this._displayObjectCreator = displayObjectCreator; this._displayObjectCreator.Parent = this; if (this._parent is IAlbum) { this._mediaObjectId = int.MinValue; } else { this._mediaObjectId = parent.Id; } }
private void ProcessMediaObjectWithWatermark() { // Send the specified file to the client with the watermark overlayed on top. IMimeType mimeType = MimeType.LoadInstanceByFilePath(this._filename); this._context.Response.Clear(); this._context.Response.ContentType = mimeType.FullType; Image watermarkedImage = null; try { try { watermarkedImage = ImageHelper.AddWatermark(this._filepath); } catch (Exception ex) { // Can't apply watermark to image. Substitute an error image and send that to the user. AppErrorController.LogError(ex); watermarkedImage = Image.FromFile(this._context.Request.MapPath(String.Concat(Util.GalleryRoot, "/images/error_48x48.png"))); } watermarkedImage.Save(this._context.Response.OutputStream, ImageFormat.Jpeg); } finally { if (watermarkedImage != null) { watermarkedImage.Dispose(); } } }
private bool _hasBeenDisposed; // Used by Dispose() methods #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DisplayObject"/> class. /// </summary> /// <param name="width">The width of this object, in pixels.</param> /// <param name="height">The height of this object, in pixels.</param> /// <param name="filename">The name of the file representing this object. Example: sonorandesert.jpg</param> /// <param name="parent">The media object to which this display object applies.</param> /// <param name="displayType">The type of the display object.</param> /// <param name="displayObjectCreator">The object responsible for generating the file this display object points to.</param> private DisplayObject(int width, int height, string filename, IGalleryObject parent, DisplayObjectType displayType, IDisplayObjectCreator displayObjectCreator) { #if DEBUG tt.Tools.StartingMethod(width, height, filename, parent, displayType, displayObjectCreator); #endif this._width = width; this._height = height; this._filename = filename; if (!String.IsNullOrEmpty(filename)) { this._mimeType = GalleryServerPro.Business.MimeType.LoadInstanceByFilePath(this._filename); } if (this._mimeType == null) { this._mimeType = new NullObjects.NullMimeType(); } this._parent = parent; this._displayType = displayType; this._displayObjectCreator = displayObjectCreator; if (this._parent is IAlbum) { this._mediaObjectId = int.MinValue; } else { this._mediaObjectId = parent.Id; } }
/// <summary> /// Return a MimeType object corresponding to the extension of the specified file. The mapping between file /// extension and MIME type is declared in the configuration file. If no matching MIME type can be found, /// this method returns null. /// </summary> /// <param name="filePath">A string representing the filename or the path to the file /// (e.g. "C:\mypics\myprettypony.jpg", "myprettypony.jpg"). It is not case sensitive.</param> /// <returns>Returns the MIME type corresponding to the specified filepath, or null if no matching MIME /// type is found.</returns> /// <exception cref="System.ArgumentException">Thrown if filepath parameter contains one or more of /// the invalid characters defined in System.IO.Path.InvalidPathChars, or contains a wildcard character.</exception> public static IMimeType LoadInstanceByFilePath(string filePath) { LoadInstances(); if (_mimeTypes == null) { throw new BusinessException("GalleryServerPro.Business.MimeType.LoadInstances() should have assigned an instance to the _mimeTypes member variable, but instead it remained null."); } string extension = System.IO.Path.GetExtension(filePath); IMimeType mimeType = null; if (!(String.IsNullOrEmpty(extension))) { foreach (IMimeType mimeTypeIterator in _mimeTypes) { if (mimeTypeIterator.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase)) { mimeType = mimeTypeIterator; break; } } } return(mimeType); }
/// <summary> /// Gets one or more media templates in the collection that match the <paramref name="mimeType" />. If no item is found, then /// the MIME type that matches the major portion is returned. For example, if the collection does not contain a specific item /// for "image/jpeg", then the MIME type for "image/*" is returned. This method returns multiple items when more than one /// template has been specified for browsers. That is, all returned items will have the same value for /// <see cref="IMediaTemplate.MimeType" /> but the <see cref="IMediaTemplate.BrowserId" /> property will vary. At least one /// item in the collection will have the <see cref="IMediaTemplate.BrowserId" /> property set to "default". Guaranteed to not /// return null. If no items are found (which shouldn't happen), an empty collection is returned. /// </summary> /// <param name="mimeType">The MIME type for which to retrieve matching media templates.</param> /// <returns>Returns a <see cref="IMediaTemplateCollection" /> containing media templates that match the /// <paramref name="mimeType" />. </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception> public IMediaTemplateCollection Find(IMimeType mimeType) { if (mimeType == null) { throw new ArgumentNullException(nameof(mimeType)); } IMediaTemplateCollection copy = new MediaTemplateCollection(); var fullType = mimeType.FullType; foreach (var item in _items) { if (item.MimeType.Equals(fullType, StringComparison.OrdinalIgnoreCase)) { copy.Add(item); } } if (!HasDefaultTemplate(copy)) { // No specific MIME type was found (such as "video/mp4"), or one was found but it // didn't have a default variant. Find the generic ones (such as "video/*"). var genericMimeType = String.Concat(mimeType.MajorType, "/*"); foreach (var item in _items) { if (item.MimeType.Equals(genericMimeType, StringComparison.OrdinalIgnoreCase)) { copy.Add(item); } } } return(copy); }
/// <summary> /// Gets one or more browser templates in the collection that match the <paramref name="mimeType" />. If no item is found, then /// the MIME type that matches the major portion is returned. For example, if the collection does not contain a specific item /// for "image/jpeg", then the MIME type for "image/*" is returned. This method returns multiple items when more than one /// template has been specified for browsers. That is, all returned items will have the same value for /// <see cref="IBrowserTemplate.MimeType" /> but the <see cref="IBrowserTemplate.BrowserId" /> property will vary. At least one /// item in the collection will have the <see cref="IBrowserTemplate.BrowserId" /> property set to "default". Guaranteed to not /// return null. If no items are found (which shouldn't happen), an empty collection is returned. /// </summary> /// <param name="mimeType">The MIME type for which to retrieve matching browser templates.</param> /// <returns>Returns a <see cref="IBrowserTemplateCollection" /> containing browser templates that match the /// <paramref name="mimeType" />. </returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception> public IBrowserTemplateCollection Find(IMimeType mimeType) { if (mimeType == null) { throw new ArgumentNullException("mimeType"); } IBrowserTemplateCollection copy = new BrowserTemplateCollection(); string fullType = mimeType.FullType; foreach (IBrowserTemplate browserTemplate in (List <IBrowserTemplate>)Items) { if (browserTemplate.MimeType.Equals(fullType, StringComparison.OrdinalIgnoreCase)) { copy.Add(browserTemplate); } } if (!HasDefaultTemplate(copy)) { // No specific MIME type was found (such as "video/mp4"), or one was found but it // didn't have a default variant. Find the generic ones (such as "video/*"). string genericMimeType = String.Concat(mimeType.MajorType, "/*"); foreach (IBrowserTemplate browserTemplate in (List <IBrowserTemplate>)Items) { if (browserTemplate.MimeType.Equals(genericMimeType, StringComparison.OrdinalIgnoreCase)) { copy.Add(browserTemplate); } } } return(copy); }
/// <summary> /// Gets one or more browser templates in the collection that match the <paramref name="mimeType" />. If no item is found, then /// the MIME type that matches the major portion is returned. For example, if the collection does not contain a specific item /// for "image/jpeg", then the MIME type for "image/*" is returned. This method returns multiple items when more than one /// template has been specified for browsers. That is, all returned items will have the same value for /// <see cref="IBrowserTemplate.MimeType" /> but the <see cref="IBrowserTemplate.BrowserId" /> property will vary. At least one /// item in the collection will have the <see cref="IBrowserTemplate.BrowserId" /> property set to "default". Guaranteed to not /// return null. If no items are found (which shouldn't happen), an empty collection is returned. /// </summary> /// <param name="mimeType">The MIME type for which to retrieve matching browser templates.</param> /// <returns>Returns a <see cref="IBrowserTemplateCollection" /> containing browser templates that match the /// <paramref name="mimeType" />. </returns> public IBrowserTemplateCollection Get(IMimeType mimeType) { IBrowserTemplateCollection copy = new BrowserTemplateCollection(); string fullType = mimeType.FullType; foreach (IBrowserTemplate browserTemplate in (List <IBrowserTemplate>)Items) { if (browserTemplate.MimeType.Equals(fullType, StringComparison.OrdinalIgnoreCase)) { copy.Add(browserTemplate); } } if (copy.Count == 0) { // No specific MIME type was found (such as "video/mp4"). Find the generic ones (such as "video/*"). string genericMimeType = String.Concat(mimeType.MajorType, "/*"); foreach (IBrowserTemplate browserTemplate in (List <IBrowserTemplate>)Items) { if (browserTemplate.MimeType.Equals(genericMimeType, StringComparison.OrdinalIgnoreCase)) { copy.Add(browserTemplate); } } } return(copy); }
public MediaObjectHtmlBuilder(IGalleryObject mediaObject, IDisplayObject displayObject, Array browsers) { if (mediaObject == null) { throw new ArgumentNullException("mediaObject"); } if (displayObject == null) { throw new ArgumentNullException("displayObject"); } if ((browsers == null) || (browsers.Length < 1)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidBrowsers_Msg)); } this._galleryObject = mediaObject; this._mediaObjectId = mediaObject.Id; this._albumId = mediaObject.Parent.Id; this._mimeType = displayObject.MimeType; this._mediaObjectPhysicalPath = displayObject.FileNamePhysicalPath; this._width = displayObject.Width; this._height = displayObject.Height; this._title = mediaObject.Title; this._browsers = browsers; this._displayType = displayObject.DisplayType; this._isPrivate = mediaObject.IsPrivate; this._galleryId = mediaObject.GalleryId; this._externalHtmlSource = displayObject.ExternalHtmlSource; }
/// <summary> /// Creates a collection of MIME types for the specified <paramref name="galleryId" /> by copying the master list of MIME /// types and updating each copied instance with gallery-specific properties, most notable <see cref="IMimeType.AllowAddToGallery" />. /// The collection is added to the static member variable <see cref="_mimeTypes" /> where <paramref name="galleryId" /> is /// the key and the collection of MIME types is the value. Returns <c>true</c> when this function successfully creates the /// collection and adds it to the static member variable <see cref="_mimeTypes" />; otherwise returns <c>false</c>. /// </summary> /// <param name="galleryId">The gallery ID.</param> /// <returns>Returns <c>true</c> when this function successfully creates the collection and adds it to the static member /// variable <see cref="_mimeTypes" />; otherwise returns <c>false</c>. A value of <c>false</c> indicates no gallery-specific /// MIME type records were found in the data store.</returns> private static bool GenerateMimeTypesForGallery(int galleryId) { IMimeTypeCollection baseMimeTypes = LoadMimeTypes(Int32.MinValue); IMimeTypeCollection newMimeTypes = new MimeTypeCollection(); IBrowserTemplateCollection browserTemplates = Factory.LoadBrowserTemplates(); bool foundRows = false; using (IDataReader dr = Factory.GetDataProvider().MimeType_GetMimeTypeGalleries()) { //SELECT mtg.MimeTypeGalleryId, mtg.FKGalleryId, mt.FileExtension, mtg.IsEnabled //FROM gs_MimeType mt INNER JOIN gs_MimeTypeGallery mtg ON mt.MimeTypeId = mtg.FKMimeTypeId //ORDER BY mt.FileExtension; while (dr.Read()) { int galleryIdInDb = Convert.ToInt32(dr["FKGalleryId"], CultureInfo.InvariantCulture); if (galleryIdInDb != galleryId) { continue; // We only care about loading items for the requested gallery, so skip any others. } foundRows = true; IMimeType mimeType = baseMimeTypes.Find(dr["FileExtension"].ToString()); if (mimeType == null) { throw new BusinessException(String.Format("Could not find a IMimeType with file extension \"{0}\" in the list of base MIME types.", dr["FileExtension"].ToString())); } IMimeType newMimeType = mimeType.Copy(); newMimeType.GalleryId = galleryId; newMimeType.MimeTypeGalleryId = Convert.ToInt32(dr["MimeTypeGalleryId"], CultureInfo.InvariantCulture); newMimeType.AllowAddToGallery = Convert.ToBoolean(dr["IsEnabled"], CultureInfo.InvariantCulture); // Populate the browser collection. newMimeType.BrowserTemplates.AddRange(browserTemplates.Get(newMimeType)); // Validate the browser templates. There may not be any, which is OK (for example, there isn't one defined for 'application/msword'). // But if there *IS* one defined, there must be one with a browser ID of "default". if ((newMimeType.BrowserTemplates.Count > 0) && (newMimeType.BrowserTemplates.Get("default") == null)) { throw new BusinessException(string.Format("No default browser template. Could not find a browser template for MIME type \"{0}\" or \"{1}\" with browser ID = \"default\".", newMimeType.FullType, String.Concat(newMimeType.MajorType, "/*"))); } newMimeTypes.Add(newMimeType); } } if (foundRows) { lock (_sharedLock) { _mimeTypes.Add(galleryId, newMimeTypes); } } return(foundRows); }
private static IOrderedEnumerable <IMediaEncoderSettings> GetEncoderSettings(IMimeType mimeType, int galleryId) { return(Factory.LoadGallerySetting(galleryId).MediaEncoderSettings .Where(es => ( (es.SourceFileExtension == mimeType.Extension) || (es.SourceFileExtension == String.Concat("*", mimeType.MajorType)))) .OrderBy(es => es.Sequence)); }
public Attachment(FileInfo file, string name, string contentType) : this(file, name) { if(contentType == null) throw new ArgumentNullException("contentType"); if(contentType.Length == 0) throw new ArgumentException("Parameter can not be of zero length.", "contentType"); this.contentType = new MimeType(contentType); }
/// <summary> /// Handles the Click event of the btnExportData control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void btnExportData_Click(object sender, EventArgs e) { string backupFilename = "GalleryServerBackup_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss", CultureInfo.InvariantCulture); IBackupFile bak = new BackupFile(); bak.IncludeMembershipData = chkExportMembership.Checked; bak.IncludeGalleryData = chkExportGalleryData.Checked; var galleryData = bak.Create(); IMimeType mimeType = Factory.LoadMimeType("dummy.zip"); int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; Stream stream = null; try { // Create an in-memory ZIP file. stream = ZipUtility.CreateZipStream(galleryData, backupFilename + ".xml"); // Send to user. Response.AddHeader("Content-Disposition", "attachment; filename=" + backupFilename + ".zip"); Response.Clear(); Response.ContentType = (mimeType != null ? mimeType.FullType : "application/octet-stream"); Response.Buffer = false; stream.Position = 0; int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { if (Response.IsClientConnected) { Response.OutputStream.Write(buffer, 0, byteCount); Response.Flush(); } else { return; } } } finally { if (stream != null) { stream.Close(); } Response.End(); } }
public IMimeType GetHighestQuality(IMimeType mimeType, bool exactType) { var acceptedTypes = GetAcceptedTypes(); IMimeType result = null; foreach(var m in acceptedTypes) { if(((exactType && m.EqualsExactType(mimeType)) || m.EqualsType(mimeType)) && (result == null || result.Quality < m.Quality)) { result = m; } } return result; }
/// <summary> /// Initializes a new instance of the <see cref="MediaObjectHtmlBuilder"/> class. /// </summary> /// <param name="mediaObjectId">The media object id.</param> /// <param name="albumId">The album id.</param> /// <param name="mimeType">The MIME type.</param> /// <param name="mediaObjectPhysicalPath">The media object physical path.</param> /// <param name="width">The width of the media object, in pixels.</param> /// <param name="height">The height of the media object, in pixels.</param> /// <param name="title">The title.</param> /// <param name="browsers">An <see cref="System.Array"/> of browser ids for the current browser. This /// is a list of strings that represent the various categories of browsers the current browser belongs /// to. This is typically populated by calling ToArray() on the Request.Browser.Browsers property.</param> /// <param name="displayType">The display type.</param> /// <param name="isPrivate">if set to <c>true</c> the media object is private.</param> /// <param name="galleryId">The value that uniquely identifies the current gallery.</param> public MediaObjectHtmlBuilder(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, int width, int height, string title, Array browsers, DisplayObjectType displayType, bool isPrivate, int galleryId) { #region Validation if (mediaObjectId <= 0) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidMediaObjectId_Msg, mediaObjectId)); } if (albumId <= 0) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidAlbumId_Msg, albumId)); } if (mimeType == null) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidMimeType_Msg)); } if (width < 0) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidWidth_Msg, width)); } if (height < 0) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidHeight_Msg, height)); } if (title == null) { title = String.Empty; } if ((browsers == null) || (browsers.Length < 1)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidBrowsers_Msg)); } #endregion this._mediaObjectId = mediaObjectId; this._albumId = albumId; this._mimeType = mimeType; this._mediaObjectPhysicalPath = mediaObjectPhysicalPath; this._width = width; this._height = height; this._title = title; this._browsers = browsers; this._displayType = displayType; this._cssClasses = new StringCollection(); this._isPrivate = isPrivate; this._galleryId = galleryId; }
private void ProcessMediaObject() { // Send the specified file to the client. try { IMimeType mimeType = MimeType.LoadInstanceByFilePath(this._filename); this._context.Response.Clear(); this._context.Response.ContentType = mimeType.FullType; this._context.Response.Buffer = false; HttpCachePolicy cachePolicy = this._context.Response.Cache; cachePolicy.SetExpires(DateTime.Now.AddSeconds(2592000)); // 30 days cachePolicy.SetCacheability(HttpCacheability.Public); cachePolicy.SetValidUntilExpires(true); FileStream fileStream = null; try { int bufferSize = Config.GetCore().MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; fileStream = File.OpenRead(this._filepath); // Required for Silverlight to properly work this._context.Response.AddHeader("Content-Length", fileStream.Length.ToString()); int byteCount; while ((byteCount = fileStream.Read(buffer, 0, buffer.Length)) > 0) { if (this._context.Response.IsClientConnected) { this._context.Response.OutputStream.Write(buffer, 0, byteCount); this._context.Response.Flush(); } else { return; } } } finally { if (fileStream != null) { fileStream.Close(); } } } catch (Exception ex) { AppErrorController.LogError(ex); } }
private static string GetMediaObjectUrl(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, DisplayObjectType displayType, bool isPrivate) { string queryString = string.Format(CultureInfo.InvariantCulture, "moid={0}&aid={1}&mo={2}&mtc={3}&dt={4}&isp={5}", mediaObjectId, albumId, Uri.EscapeDataString(mediaObjectPhysicalPath), (int)mimeType.TypeCategory, (int)displayType, isPrivate.ToString()); // If necessary, encrypt, then URL encode the query string. if (Config.GetCore().EncryptMediaObjectUrlOnClient) { queryString = Util.UrlEncode(HelperFunctions.Encrypt(queryString)); } return(string.Concat(Util.GalleryRoot, "/handler/getmediaobject.ashx?", queryString)); }
public static bool IsMimeType(byte[] input, IMimeType mimeType) { var isMatch = FindMatch(input, mimeType.ByteHeader, mimeType.Offset); if (isMatch && mimeType.OtherIdentifier != null && mimeType.OtherIdentifier.Length > 0) { var matchingIndices = input.Select((b, i) => b == mimeType.OtherIdentifier[0] ? i : -1).Where(i => i != -1).ToList(); isMatch = matchingIndices.Any(i => FindMatch(input, mimeType.OtherIdentifier, i)); } return(isMatch); }
protected void btnExportData_Click(object sender, EventArgs e) { string backupFilename = "GalleryServerBackup_" + DateTime.Now.ToString("yyyy-MM-dd_HHmmss"); string galleryData = HelperFunctions.ExportGalleryData(chkExportMembership.Checked, chkExportGalleryData.Checked); IMimeType mimeType = MimeType.LoadInstanceByFilePath("dummy.zip"); ZipUtility zip = new ZipUtility(Util.UserName, RoleController.GetGalleryServerRolesForUser()); int bufferSize = Core.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; Stream stream = null; try { // Create an in-memory ZIP file. stream = zip.CreateZipStream(galleryData, backupFilename + ".xml"); // Send to user. Response.AddHeader("Content-Disposition", "attachment; filename=" + backupFilename + ".zip"); Response.Clear(); Response.ContentType = (mimeType != null ? mimeType.FullType : "application/octet-stream"); Response.Buffer = false; stream.Position = 0; int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { if (Response.IsClientConnected) { Response.OutputStream.Write(buffer, 0, byteCount); Response.Flush(); } else { return; } } } finally { if (stream != null) { stream.Close(); } Response.End(); } }
public IFileFormat FromMimeType(IMimeType mimeType) { if (mimeType is null) { throw new ArgumentNullException(nameof(mimeType)); } IFileFormat fileFormat = GetKnownFileFormatsInternal() .Where(format => format.MimeType.Equals(mimeType)) .FirstOrDefault(); return(fileFormat); }
public Attachment(FileInfo file, string name, string contentType) : this(file, name) { if (contentType == null) { throw new ArgumentNullException("contentType"); } if (contentType.Length == 0) { throw new ArgumentException("Parameter can not be of zero length.", "contentType"); } this.contentType = new MimeType(contentType); }
public IMimeType GetHighestQuality(IMimeType mimeType, bool exactType) { var acceptedTypes = GetAcceptedTypes(); IMimeType result = null; foreach (var m in acceptedTypes) { if (((exactType && m.EqualsExactType(mimeType)) || m.EqualsType(mimeType)) && (result == null || result.Quality < m.Quality)) { result = m; } } return(result); }
private void BuildAndSendZipFile(List <int> albumIds, List <int> mediaObjectIds) { IMimeType mimeType = MimeType.LoadInstanceByFilePath("dummy.zip"); string zipFilename = Util.UrlEncode("Media Files".Replace(" ", "_")); ZipUtility zip = new ZipUtility(Util.UserName, Controller.RoleController.GetGalleryServerRolesForUser()); int bufferSize = Core.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; Stream stream = null; try { // Create an in-memory ZIP file. stream = zip.CreateZipStream(this.AlbumId, albumIds, mediaObjectIds, GetImageSize()); // Send to user. Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFilename + ".zip"); Response.Clear(); Response.ContentType = (mimeType != null ? mimeType.FullType : "application/octet-stream"); Response.Buffer = false; stream.Position = 0; int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { if (Response.IsClientConnected) { Response.OutputStream.Write(buffer, 0, byteCount); Response.Flush(); } else { return; } } } finally { if (stream != null) { stream.Close(); } Response.End(); } }
private static Bitmap GetGenericThumbnailBitmap(IMimeType mimeType) { Bitmap thumbnailBitmap = null; switch (mimeType.MajorType.ToUpperInvariant()) { case "AUDIO": thumbnailBitmap = Resources.GenericThumbnailImage_Audio; break; case "VIDEO": thumbnailBitmap = Resources.GenericThumbnailImage_Video; break; case "IMAGE": thumbnailBitmap = Resources.GenericThumbnailImage_Image; break; default: thumbnailBitmap = Resources.GenericThumbnailImage_Unknown; break; } return thumbnailBitmap; }
/// <summary> /// Creates a new map tile file. The file name will be generated based on the zoom level, the column and the row of the map tile. /// </summary> /// <param name="mapTile">the map tile that the file contains</param> /// <param name="rootDirectory">the root directory that will contain the tiles</param> /// <param name="mimeType">the mime type of the map tile</param> public MapTileFile(MapTile mapTile, DirectoryInfo rootDirectory, IMimeType mimeType) { var fileName = string.Format("{0}-{1}-{2}{3}", mapTile.ZoomLevel.Zoom, mapTile.Column, mapTile.Row, mimeType.Extension); var path = rootDirectory.FullName + Path.DirectorySeparatorChar + mapTile.ZoomLevel.Zoom + Path.DirectorySeparatorChar + PrefixDirectoryName(mapTile.Column.ToString()) + Path.DirectorySeparatorChar + PrefixDirectoryName(mapTile.Row.ToString()) + Path.DirectorySeparatorChar + fileName; File = new FileInfo(path); MimeType = mimeType; MapTile = mapTile; }
internal FileFormat(string fileExtension) { if (fileExtension.Equals(".txt", StringComparison.OrdinalIgnoreCase)) { MimeType = new MimeType("text/plain"); } else { MimeType = new MimeType("application/octet-stream"); } Extensions = new string[] { fileExtension }; }
private static string GetGenericThumbnailFilePath(IMimeType mimeType) { var basePath = Path.Combine(AppSetting.Instance.WebRootPath, GlobalConstants.GenericThumbnailDirectory); switch (mimeType.MajorType.ToUpperInvariant()) { case "AUDIO": return(Path.Combine(basePath, GlobalConstants.GenericAudioThumbnailFileName)); case "VIDEO": return(Path.Combine(basePath, GlobalConstants.GenericVideoThumbnailFileName)); case "IMAGE": return(Path.Combine(basePath, GlobalConstants.GenericImageThumbnailFileName)); default: return(Path.Combine(basePath, GlobalConstants.GenericUnknownThumbnailFileName)); } }
public static object FromBase64String(string input, out IMimeType mime) { byte[] result = Convert.FromBase64String(input); if (FinderMimeType.IsString(result)) { mime = new MimeType("#string#", "", null); return(Encoding.UTF8.GetString(result)); } else { var _mime = FinderMimeType.GetMimeType(result); MemoryStream m = new MemoryStream(result); mime = _mime; return(m); } }
private static Bitmap GetGenericThumbnailBitmap(IMimeType mimeType) { Bitmap thumbnailBitmap; switch (mimeType.MajorType.ToUpperInvariant()) { case "AUDIO": thumbnailBitmap = Resources.GenericThumbnailImage_Audio; break; case "VIDEO": thumbnailBitmap = Resources.GenericThumbnailImage_Video; break; case "IMAGE": thumbnailBitmap = Resources.GenericThumbnailImage_Image; break; default: thumbnailBitmap = Resources.GenericThumbnailImage_Unknown; break; } return(thumbnailBitmap); }
/// <summary> /// Persist the gallery-specific properties of the <paramref name="mimeType" /> to the data store. Currently, only the /// <see cref="IMimeType.AllowAddToGallery" /> property is unique to the gallery identified in <see cref="IMimeType.GalleryId" />; /// the other properties are application-wide and at present there is no API to modify them. In other words, this method saves whether a /// particular MIME type is enabled or disabled for a particular gallery. /// </summary> /// <param name="mimeType">The MIME type instance to save.</param> /// <exception cref="ArgumentException">Thrown when the <see cref="IMimeType.MimeTypeGalleryId" /> property is not set to a valid value.</exception> internal static void Save(IMimeType mimeType) { if (mimeType.MimeTypeGalleryId == int.MinValue) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "The MimeTypeGalleryId property must be set to a valid value. Instead, it was {0}.", mimeType.MimeTypeGalleryId), "mimeType"); } using (SqlConnection cn = SqlDataProvider.GetDbConnection()) { using (SqlCommand cmd = GetCommandMimeTypeGalleryUpdate(cn)) { cmd.Parameters["@MimeTypeGalleryId"].Value = mimeType.MimeTypeGalleryId; cmd.Parameters["@IsEnabled"].Value = mimeType.AllowAddToGallery; cn.Open(); cmd.ExecuteNonQuery(); } } }
private void SaveSettings() { bool previousAllowAllValue = CoreConfig.allowUnspecifiedMimeTypes; this.wwDataBinder.Unbind(this); if (CoreConfig.allowUnspecifiedMimeTypes != previousAllowAllValue) { GspConfigController.SaveCore(this.CoreConfig); } if (wwDataBinder.BindingErrors.Count > 0) { this.wwMessage.CssClass = "wwErrorFailure gsp_msgwarning"; this.wwMessage.Text = wwDataBinder.BindingErrors.ToHtml(); return; } // Loop through each record in the grid. For each file extension, find the matching MIME types from the // configuration file. If the value has changed, update it. When done looping, save config file. Dictionary <string, bool> mimeTypesToUpdate = new Dictionary <string, bool>(); foreach (GridItem row in gdMimeTypes.Items) { object[] rowValues = (object[])row.DataItem; bool enabled = Convert.ToBoolean(rowValues[0], CultureInfo.InvariantCulture); string fileExt = rowValues[1].ToString(); IMimeType mimeType = MimeType.LoadInstanceByFilePath(fileExt); if (mimeType.AllowAddToGallery != enabled) { mimeTypesToUpdate.Add(mimeType.Extension, enabled); } } if (mimeTypesToUpdate.Count > 0) { GspConfigController.SaveMimeTypes(mimeTypesToUpdate); } this.wwMessage.CssClass = "wwErrorSuccess gsp_msgfriendly gsp_bold"; this.wwMessage.ShowMessage(Resources.GalleryServerPro.Admin_Save_Success_Text); }
/// <summary> /// Return a MimeType object corresponding to the file's extension. The mapping between file extension and /// MIME type is declared in the configuration file. If no matching MIME type can be found, /// this method returns null. /// </summary> /// <param name="fileExtension">A string representing the file's extension, including the period (e.g. ".jpg", ".avi"). /// It is not case sensitive.</param> /// <returns>Returns the MIME type corresponding to the specified file extension, or null if no matching MIME /// type is found.</returns> public static IMimeType LoadInstance(string fileExtension) { LoadInstances(); if (_mimeTypes == null) { throw new BusinessException("GalleryServerPro.Business.MimeType.LoadInstances() should have assigned an instance to the _mimeTypes member variable, but instead it remained null."); } IMimeType mimeType = null; foreach (IMimeType mimeTypeIterator in _mimeTypes) { if (mimeTypeIterator.Extension.Equals(fileExtension, StringComparison.OrdinalIgnoreCase)) { mimeType = mimeTypeIterator; break; } } return(mimeType); }
/// <summary> /// Initializes a new instance of the <see cref="MediaObjectHtmlBuilder"/> class. /// </summary> /// <param name="mediaObjectId">The media object id.</param> /// <param name="albumId">The album id.</param> /// <param name="mimeType">The MIME type.</param> /// <param name="mediaObjectPhysicalPath">The media object physical path.</param> /// <param name="width">The width of the media object, in pixels.</param> /// <param name="height">The height of the media object, in pixels.</param> /// <param name="title">The title.</param> /// <param name="browsers">An <see cref="System.Array"/> of browser ids for the current browser. This /// is a list of strings that represent the various categories of browsers the current browser belongs /// to. This is typically populated by calling ToArray() on the Request.Browser.Browsers property.</param> /// <param name="displayType">The display type.</param> /// <param name="isPrivate">if set to <c>true</c> the media object is private.</param> /// <param name="galleryId">The value that uniquely identifies the current gallery.</param> public MediaObjectHtmlBuilder(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, int width, int height, string title, Array browsers, DisplayObjectType displayType, bool isPrivate, int galleryId) { #region Validation if (mediaObjectId <= 0) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidMediaObjectId_Msg, mediaObjectId)); if (albumId <= 0) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidAlbumId_Msg, albumId)); if (mimeType == null) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidMimeType_Msg)); if (width < 0) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidWidth_Msg, width)); if (height < 0) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidHeight_Msg, height)); if (title == null) title = String.Empty; if ((browsers == null) || (browsers.Length < 1)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.GalleryServerPro.MediaObjectHtmlBuilder_Ctor_InvalidBrowsers_Msg)); #endregion this._mediaObjectId = mediaObjectId; this._albumId = albumId; this._mimeType = mimeType; this._mediaObjectPhysicalPath = mediaObjectPhysicalPath; this._width = width; this._height = height; this._title = title; this._browsers = browsers; this._displayType = displayType; this._cssClasses = new StringCollection(); this._isPrivate = isPrivate; this._galleryId = galleryId; }
/// <summary> /// Decodifica o base64 para o objeto desejado /// </summary> /// <param name="input">String base64</param> /// <param name="mime">Tipo de objeto resultante da Decodificação</param> /// <returns>Objeto decodificado</returns> public static object FromBase64Object(string input, out IMimeType mime) { if (string.IsNullOrEmpty(input)) { throw new ArgumentException("message", nameof(input)); } byte[] result = Convert.FromBase64String(input); if (FinderMimeType.IsString(result)) { mime = new MimeType("#string#", "", null); return(Encoding.UTF8.GetString(result)); } else { var _mime = FinderMimeType.GetMimeType(result); MemoryStream m = new MemoryStream(result); mime = _mime; return(m); } }
public bool EqualsType(IMimeType mimeType) { return mimeType != null && this.DiscreteType.Equals(mimeType.DiscreteType) && (this.CompositeType.Equals(mimeType.CompositeType) || this.CompositeType.Equals("*") || mimeType.CompositeType.Equals("*")); }
public bool EqualsExactType(IMimeType mimeType) { return mimeType != null && this.DiscreteType.Equals(mimeType.DiscreteType) && this.CompositeType.Equals(mimeType.CompositeType); }
/// <summary> /// Persist the gallery-specific properties of the <paramref name="mimeType"/> to the data store. Currently, only the /// <see cref="IMimeType.AllowAddToGallery"/> property is unique to the gallery identified in <see cref="IMimeType.GalleryId"/>; /// the other properties are application-wide and at present there is no API to modify them. In other words, this method saves whether a /// particular MIME type is enabled or disabled for a particular gallery. /// </summary> /// <param name="mimeType">The MIME type instance to save.</param> /// <exception cref="ArgumentException">Thrown when the <see cref="IMimeType.MimeTypeGalleryId"/> property of the <paramref name="mimeType" /> /// parameter is not set to a valid value.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception> public override void MimeType_Save(IMimeType mimeType) { if (mimeType == null) throw new ArgumentNullException("mimeType"); MimeType.Save(mimeType); }
/// <summary> /// Persist the gallery-specific properties of the <paramref name="mimeType"/> to the data store. Currently, only the /// <see cref="IMimeType.AllowAddToGallery"/> property is unique to the gallery identified in <see cref="IMimeType.GalleryId"/>; /// the other properties are application-wide and at present there is no API to modify them. In other words, this method saves whether a /// particular MIME type is enabled or disabled for a particular gallery. /// </summary> /// <param name="mimeType">The MIME type instance to save.</param> /// <exception cref="ArgumentException">Thrown when the <see cref="IMimeType.MimeTypeGalleryId"/> property of the <paramref name="mimeType" /> /// parameter is not set to a valid value.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception> public abstract void MimeType_Save(IMimeType mimeType);
private static string GetMediaObjectUrl(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, DisplayObjectType displayType, bool isPrivate) { string queryString = string.Format(CultureInfo.CurrentCulture, "moid={0}&aid={1}&mo={2}&mtc={3}&dt={4}&isp={5}", mediaObjectId, albumId, Uri.EscapeDataString(mediaObjectPhysicalPath), (int)mimeType.TypeCategory, (int)displayType, isPrivate.ToString()); // If necessary, encrypt, then URL encode the query string. if (WebsiteController.GetGalleryServerProConfigSection().Core.EncryptMediaObjectUrlOnClient) queryString = HttpUtility.UrlEncode(HelperFunctions.Encrypt(queryString)); return string.Concat(WebsiteController.GetAppRootPathUrl(), "/handler/getmediaobject.ashx?", queryString); }
/// <summary> /// Initializes a new instance of the <see cref="DisplayObject"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="displayType">The display type.</param> /// <param name="mimeType">Specifies the category to which this mime type belongs. This usually corresponds to the first portion of /// the full mime type description. (e.g. "image" if the full mime type is "image/jpeg").</param> private DisplayObject(IGalleryObject parent, DisplayObjectType displayType, MimeTypeCategory mimeType) { #if DEBUG tt.Tools.StartingMethod(parent, displayType, mimeType); #endif if (displayType != DisplayObjectType.External) throw new BusinessException(String.Format("This overload of the DisplayObject constructor can only be called when the displayType parameter is DisplayObjectType.External. Instead, it was {0}.", displayType.ToString())); this._width = int.MinValue; this._height = int.MinValue; this._filename = String.Empty; this._mimeType = GalleryServerPro.Business.MimeType.CreateInstance(mimeType); this._externalType = this._mimeType.TypeCategory; this._parent = parent; this._displayType = displayType; this._displayObjectCreator = new NullObjects.NullDisplayObjectCreator(); if (this._parent is IAlbum) { this._mediaObjectId = int.MinValue; } else { this._mediaObjectId = parent.Id; } }
public IMimeType GetHighestQuality(IMimeType mimeType) { return GetHighestQuality(mimeType, false); }
private static IOrderedEnumerable<IMediaEncoderSettings> GetEncoderSettings(IMimeType mimeType, int galleryId) { return Factory.LoadGallerySetting(galleryId).MediaEncoderSettings .Where(es => ( (es.SourceFileExtension == mimeType.Extension) || (es.SourceFileExtension == String.Concat("*", mimeType.MajorType)))) .OrderBy(es => es.Sequence); }
private static string GetMediaObjectUrl(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, DisplayObjectType displayType, bool isPrivate) { string queryString = string.Format(CultureInfo.InvariantCulture, "moid={0}&aid={1}&mo={2}&mtc={3}&dt={4}&isp={5}", mediaObjectId, albumId, Uri.EscapeDataString(mediaObjectPhysicalPath), (int)mimeType.TypeCategory, (int)displayType, isPrivate.ToString()); // If necessary, encrypt, then URL encode the query string. if (Config.GetCore().EncryptMediaObjectUrlOnClient) queryString = Util.UrlEncode(HelperFunctions.Encrypt(queryString)); return string.Concat(Util.GalleryRoot, "/handler/getmediaobject.ashx?", queryString); }
/// <summary> /// Persist the gallery-specific properties of the <paramref name="mimeType"/> to the data store. Currently, only the /// <see cref="IMimeType.AllowAddToGallery"/> property is unique to the gallery identified in <see cref="IMimeType.GalleryId"/>; /// the other properties are application-wide and at present there is no API to modify them. In other words, this method saves whether a /// particular MIME type is enabled or disabled for a particular gallery. /// </summary> /// <param name="mimeType">The MIME type instance to save.</param> /// <exception cref="ArgumentException">Thrown when the <see cref="IMimeType.MimeTypeGalleryId"/> property of the <paramref name="mimeType" /> /// parameter is not set to a valid value.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="mimeType" /> is null.</exception> public override void MimeType_Save(IMimeType mimeType) { if (mimeType == null) throw new ArgumentNullException("mimeType"); if (mimeType.MimeTypeGalleryId == int.MinValue) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "The MimeTypeGalleryId property must be set to a valid value. Instead, it was {0}.", mimeType.MimeTypeGalleryId), "mimeType"); } using (GspContext ctx = new GspContext()) { MimeTypeGalleryDto mtDto = ctx.MimeTypeGalleries.Find(mimeType.MimeTypeGalleryId); if (mtDto != null) { mtDto.IsEnabled = mimeType.AllowAddToGallery; ctx.SaveChanges(); } } }
public static string GenerateUrl(int mediaObjectId, int albumId, IMimeType mimeType, string mediaObjectPhysicalPath, DisplayObjectType displayType, bool isPrivate) { return GetMediaObjectUrl(mediaObjectId, albumId, mimeType, mediaObjectPhysicalPath, displayType, isPrivate); }