Exemple #1
0
        /// <summary>
        /// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
        /// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
        /// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
        /// </summary>
        /// <param name="metadataItems">The collection of IGalleryObjectMetadataItem objects to add to.</param>
        /// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
        /// throw a security exception if it doesn't have it.</exception>
        private void AddWpfBitmapMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("GalleryServerPro.Business.Wpf");

            // Get reference to static WpfMetadataExtractor.AddWpfBitmapMetadata() method.
            Type[] parmTypes = new Type[2];
            parmTypes[0] = typeof(string);
            parmTypes[1] = typeof(IGalleryObjectMetadataItemCollection);
            Type metadataExtractor = assembly.GetType("GalleryServerPro.Business.Wpf.WpfMetadataExtractor");

            System.Reflection.MethodInfo addMetadataMethod = metadataExtractor.GetMethod("AddWpfBitmapMetadata", parmTypes);

            // Prepare parameters to pass to BitmapDecoder.Create() method.
            object[] parameters = new object[2];
            parameters[0] = this._imageFilePath;
            parameters[1] = metadataItems;

            try
            {
                addMetadataMethod.Invoke(null, parameters);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                LogError(ex);
            }
        }
Exemple #2
0
        /// <summary>
        /// Adds GPS destination location URL metadata item to the <see cref="IGalleryObject.MetadataItems" />
        /// collection of <paramref name="galleryObject" />. If the gallery object's metadata does not contain GPS data or the
        /// visibility of the GPS map link is turned off, no action is taken.
        /// </summary>
        /// <param name="galleryObject">The gallery object.</param>
        /// <param name="metadataDisplaySettings">The metadata display settings.</param>
        /// <remarks>The metadata item is added with <see cref="IGalleryObjectMetadataItem.HasChanges" /> = <c>false</c> to prevent it
        /// from getting persisted to the database. This allows the hyperlink to be regenerated from the template, thus incorporating the
        /// most recent template and other media object properties (such as title). Because the item is linked to the media object, it is
        /// automatically included in the cache of media objects.
        /// This function is identical to <see cref="AddGpsLocationWithMapLink" /> except it uses the primary (not destination) GPS settings.</remarks>
        private static void AddGpsDestLocationWithMapLink(IGalleryObject galleryObject, IMetadataDefinitionCollection metadataDisplaySettings)
        {
            if (!metadataDisplaySettings.Find(FormattedMetadataItemName.GpsDestLocationWithMapLink).IsVisible)
            {
                return;                 // The map link is disabled, so there is nothing to do.
            }
            IGalleryObjectMetadataItemCollection metadata = galleryObject.MetadataItems;
            IGalleryObjectMetadataItem           gpsLocation;

            if (metadata.TryGetMetadataItem(FormattedMetadataItemName.GpsDestLocation, out gpsLocation) && (!metadata.Contains(FormattedMetadataItemName.GpsDestLocationWithMapLink)))
            {
                // We have a GPS location but have not yet created the URL'd version. Do so now and add it to the collection.
                IGalleryObjectMetadataItem latitude;
                IGalleryObjectMetadataItem longitude;
                bool foundLatitude  = metadata.TryGetMetadataItem(FormattedMetadataItemName.GpsDestLatitude, out latitude);
                bool foundLongitude = metadata.TryGetMetadataItem(FormattedMetadataItemName.GpsDestLongitude, out longitude);

                if (foundLatitude && foundLongitude)
                {
                    string url = GetGpsMapUrl(galleryObject, latitude.Value, longitude.Value, gpsLocation.Value);

                    if (!String.IsNullOrEmpty(url))
                    {
                        // Add to meta collection. Specify false for HasChanges to prevent it from getting persisted back to the database.
                        galleryObject.MetadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLocationWithMapLink, Resources.GalleryServerPro.Metadata_GpsDestLocationWithMapLink, url, false);
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// If any of the metadata items for this media object has its <see cref="IGalleryObject.ExtractMetadataOnSave" /> property
        /// set to true, then open the original file, extract the items, and update the <see cref="IGalleryObject.MetadataItems" />
        /// property on our media object. The <see cref="IGalleryObject.ExtractMetadataOnSave" /> property is not changed to false
        /// at this time, since the Save method uses it to know which items to persist to the data store.
        /// </summary>
        private void UpdateMetadata()
        {
            if (this._galleryObject.ExtractMetadataOnSave)
            {
                // Replace all metadata with the metadata found in the original file.
                Metadata.MediaObjectMetadataExtractor metadata;
                try
                {
                    metadata = new Metadata.MediaObjectMetadataExtractor(this._galleryObject.Original.FileNamePhysicalPath, this._galleryObject.GalleryId);
                }
                catch (OutOfMemoryException)
                {
                    // Normally, the Dispose method is called during the Image_Saved event. But when we get this exception, it
                    // never executes and therefore doesn't release the file lock. So we explicitly do so here and then
                    // re-throw the exception.
                    this._galleryObject.Original.Dispose();
                    throw new UnsupportedImageTypeException();
                }

                this._galleryObject.MetadataItems.Clear();
                this._galleryObject.MetadataItems.AddRange(metadata.GetGalleryObjectMetadataItemCollection());
                this._galleryObject.ExtractMetadataOnSave = true;
            }
            else
            {
                // If any individual metadata items have been set to ExtractFromFileOnSave = true, then update those selected ones with
                // the latest metadata from the file. If the metadata item is not found in the file, then set the value to an empty string.
                // The data layer will delete any items with an empty or null string.
                IGalleryObjectMetadataItemCollection metadataItemsToUpdate = this._galleryObject.MetadataItems.GetItemsToUpdate();
                if (metadataItemsToUpdate.Count > 0)
                {
                    Metadata.MediaObjectMetadataExtractor metadata;
                    try
                    {
                        metadata = new Metadata.MediaObjectMetadataExtractor(this._galleryObject.Original.FileNamePhysicalPath, this._galleryObject.GalleryId);
                    }
                    catch (OutOfMemoryException)
                    {
                        // Normally, the Dispose method is called during the Image_Saved event. But when we get this exception, it
                        // never executes and therefore doesn't release the file lock. So we explicitly do so here and then
                        // re-throw the exception.
                        this._galleryObject.Original.Dispose();
                        throw new UnsupportedImageTypeException();
                    }

                    foreach (IGalleryObjectMetadataItem metadataItem in metadataItemsToUpdate)
                    {
                        IGalleryObjectMetadataItem extractedMetadataItem;
                        if (metadata.GetGalleryObjectMetadataItemCollection().TryGetMetadataItem(metadataItem.MetadataItemName, out extractedMetadataItem))
                        {
                            metadataItem.Value = extractedMetadataItem.Value;
                        }
                        else
                        {
                            metadataItem.Value = String.Empty;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Adds GPS data from the <paramref name="bmpMetadata" /> to the <paramref name="metadataItems" /> collection.
        /// </summary>
        /// <param name="bmpMetadata">An object containing the metadata.</param>
        /// <param name="metadataItems">The metadata items.</param>
        private static void AddGpsMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems)
        {
            GpsLocation gps = GpsLocation.Parse(bmpMetadata);

            if (!String.IsNullOrEmpty(gps.Version))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsVersion, GetResource(FormattedMetadataItemName.GpsVersion), gps.Version, true);
            }

            if ((gps.Latitude != null) && (gps.Longitude != null))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLocation, GetResource(FormattedMetadataItemName.GpsLocation), gps.ToLatitudeLongitudeDecimalString(), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLatitude, GetResource(FormattedMetadataItemName.GpsLatitude), gps.Latitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLongitude, GetResource(FormattedMetadataItemName.GpsLongitude), gps.Longitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
            }

            if (gps.Altitude.HasValue)
            {
                string altitude = String.Concat(gps.Altitude.Value.ToString("N0", CultureInfo.CurrentCulture), " ", Resources.Metadata_meters);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsAltitude, GetResource(FormattedMetadataItemName.GpsAltitude), altitude, true);
            }

            if ((gps.DestLatitude != null) && (gps.DestLongitude != null))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLocation, GetResource(FormattedMetadataItemName.GpsDestLocation), gps.ToDestLatitudeLongitudeDecimalString(), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLatitude, GetResource(FormattedMetadataItemName.GpsDestLatitude), gps.DestLatitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLongitude, GetResource(FormattedMetadataItemName.GpsDestLongitude), gps.DestLongitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
            }
        }
 /// <summary>
 /// Adds the metadata items to the current collection.
 /// </summary>
 /// <param name="galleryObjectMetadataItems">The metadata items to add to the collection.</param>
 public void AddRange(IGalleryObjectMetadataItemCollection galleryObjectMetadataItems)
 {
     foreach (IGalleryObjectMetadataItem metadataItem in galleryObjectMetadataItems)
     {
         Items.Add(metadataItem);
     }
 }
Exemple #6
0
        public static MetaItem[] ToMetaItems(IGalleryObjectMetadataItemCollection metadataItems, IGalleryObject galleryObject)
        {
            var metaItems  = new MetaItem[metadataItems.Count];
            var metaDefs   = Factory.LoadGallerySetting(galleryObject.GalleryId).MetadataDisplaySettings;
            var moProfiles = ProfileController.GetProfile().MediaObjectProfiles;

            for (int i = 0; i < metaItems.Length; i++)
            {
                IGalleryObjectMetadataItem md = metadataItems[i];

                metaItems[i] = new MetaItem
                {
                    Id         = md.MediaObjectMetadataId,
                    MediaId    = galleryObject.Id,
                    MTypeId    = (int)md.MetadataItemName,
                    GTypeId    = (int)galleryObject.GalleryObjectType,
                    Desc       = md.Description,
                    Value      = md.Value,
                    IsEditable = metaDefs.Find(md.MetadataItemName).IsEditable
                };

                if (md.MetadataItemName == MetadataItemName.Rating)
                {
                    ReplaceAvgRatingWithUserRating(metaItems[i], moProfiles);
                }
            }

            return(metaItems);
        }
        /// <summary>
        /// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
        /// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
        /// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
        /// </summary>
        /// <param name="imageFilePath">The image file path.</param>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        /// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
        /// throw a security exception if it doesn't have it.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="metadataItems" /> is null.</exception>
        public static void AddWpfBitmapMetadata(string imageFilePath, IGalleryObjectMetadataItemCollection metadataItems)
        {
            if (metadataItems == null)
                throw new ArgumentNullException("metadataItems");

            BitmapMetadata bmpMetadata = GetBitmapMetadata(imageFilePath);

            if (bmpMetadata != null)
            {
                AddGpsMetadata(bmpMetadata, metadataItems);

                AddIptcMetadata(bmpMetadata, metadataItems);

                try
                {
                    if ((bmpMetadata.Title != null) && (!String.IsNullOrEmpty(bmpMetadata.Title.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Title, Resources.Metadata_Title, bmpMetadata.Title.Trim(), true);

                    if (bmpMetadata.Author != null)
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Author, Resources.Metadata_Author, ConvertStringCollectionToDelimitedString(bmpMetadata.Author), true);

                    if (bmpMetadata.DateTaken != null)
                    {
                        DateTime dateTaken = TryParseDate(bmpMetadata.DateTaken);
                        if (dateTaken.Year > DateTime.MinValue.Year)
                        {
                            metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.DatePictureTaken, Resources.Metadata_DatePictureTaken, dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true);
                        }
                    }

                    if ((bmpMetadata.CameraModel != null) && (!String.IsNullOrEmpty(bmpMetadata.CameraModel.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel, bmpMetadata.CameraModel.Trim(), true);

                    if ((bmpMetadata.CameraManufacturer != null) && (!String.IsNullOrEmpty(bmpMetadata.CameraManufacturer.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer, bmpMetadata.CameraManufacturer.Trim(), true);

                    if (bmpMetadata.Keywords != null)
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Keywords, Resources.Metadata_Keywords, ConvertStringCollectionToDelimitedString(bmpMetadata.Keywords), true);

                    if (bmpMetadata.Rating > 0)
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Rating, Resources.Metadata_Rating, bmpMetadata.Rating.ToString(CultureInfo.InvariantCulture), true);

                    if ((bmpMetadata.Comment != null) && (!String.IsNullOrEmpty(bmpMetadata.Comment.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Comment, Resources.Metadata_Comment, bmpMetadata.Comment.Trim(), true);

                    if ((bmpMetadata.Copyright != null) && (!String.IsNullOrEmpty(bmpMetadata.Copyright.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright, bmpMetadata.Copyright.Trim(), true);

                    if ((bmpMetadata.Subject != null) && (!String.IsNullOrEmpty(bmpMetadata.Subject.Trim())))
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Subject, Resources.Metadata_Subject, bmpMetadata.Subject.Trim(), true);
                }
                catch (NotSupportedException) { } // Some image types, such as png, throw a NotSupportedException. Let's swallow them and move on.
            }
        }
Exemple #8
0
        /// <summary>
        /// Adds the metadata items to the current collection.
        /// </summary>
        /// <param name="galleryObjectMetadataItems">The metadata items to add to the collection.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="galleryObjectMetadataItems" /> is null.</exception>
        public void AddRange(IGalleryObjectMetadataItemCollection galleryObjectMetadataItems)
        {
            if (galleryObjectMetadataItems == null)
            {
                throw new ArgumentNullException("galleryObjectMetadataItems");
            }

            foreach (IGalleryObjectMetadataItem metadataItem in galleryObjectMetadataItems)
            {
                Items.Add(metadataItem);
            }
        }
        /// <summary>
        /// Creates a collection of <see cref="CacheItemMetaItem" /> instances from <paramref name="metadataItems" />. This instance is suitable for storing in cache.
        /// </summary>
        /// <param name="metadataItems">The metadata items.</param>
        /// <param name="galleryObjectId">The ID of the gallery object the <paramref name="metadataItems" /> belong to.</param>
        /// <param name="goType">The type of the gallery object the <paramref name="metadataItems" /> belong to. Any value other than <see cref="GalleryObjectType.Album" />
        /// is assumed to be a media object.</param>
        /// <returns>List&lt;CacheItemMetaItem&gt;.</returns>
        public static List <CacheItemMetaItem> FromMetaItems(IGalleryObjectMetadataItemCollection metadataItems, int galleryObjectId, GalleryObjectType goType)
        {
            var items = new List <CacheItemMetaItem>(metadataItems.Count);

            var albumId = (goType == GalleryObjectType.Album ? new int?(galleryObjectId) : null);
            var moId    = (goType == GalleryObjectType.Album ? null : new int?(galleryObjectId));

            foreach (var mi in metadataItems)
            {
                items.Add(new CacheItemMetaItem(mi.MediaObjectMetadataId, mi.MetadataItemName, moId, albumId, mi.RawValue, mi.Value));
            }

            return(items);
        }
		/// <summary>
		/// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
		/// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
		/// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
		/// </summary>
		/// <param name="imageFilePath">The image file path.</param>
		/// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
		/// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
		/// throw a security exception if it doesn't have it.</exception>
		public static void AddWpfBitmapMetadata(string imageFilePath, IGalleryObjectMetadataItemCollection metadataItems)
		{
			//return;
			BitmapMetadata bmpMetadata = GetBitmapMetadata(imageFilePath);

			if (bmpMetadata != null)
			{
				try
				{
					if (bmpMetadata.Title != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Title, Resources.Metadata_Title, bmpMetadata.Title, true);

					if (bmpMetadata.Author != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Author, Resources.Metadata_Author, ConvertStringCollectionToDelimitedString(bmpMetadata.Author), true);

					if (bmpMetadata.DateTaken != null)
					{
						DateTime dateTaken;
						if (DateTime.TryParse(bmpMetadata.DateTaken, out dateTaken))
						{
							metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.DatePictureTaken, Resources.Metadata_DatePictureTaken, dateTaken.ToString("R", CultureInfo.InvariantCulture), true);
						}
					}

					if (bmpMetadata.CameraModel != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel, bmpMetadata.CameraModel, true);

					if (bmpMetadata.CameraManufacturer != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer, bmpMetadata.CameraManufacturer, true);

					if (bmpMetadata.Keywords != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Keywords, Resources.Metadata_Keywords, ConvertStringCollectionToDelimitedString(bmpMetadata.Keywords), true);

					// Rating is an int, so we can't check for null.
					metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Rating, Resources.Metadata_Rating, bmpMetadata.Rating.ToString(CultureInfo.InvariantCulture), true);

					if (bmpMetadata.Comment != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Comment, Resources.Metadata_Comment, bmpMetadata.Comment, true);

					if (bmpMetadata.Copyright != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright, bmpMetadata.Copyright, true);

					if (bmpMetadata.Subject != null)
						metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Subject, Resources.Metadata_Subject, bmpMetadata.Subject, true);
				}
				catch (NotSupportedException) { } // Some image types, such as png, throw a NotSupportedException. Let's swallow them and move on.
			}

		}
        private static void AddIptcMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems)
        {
            foreach (KeyValuePair <FormattedMetadataItemName, string> iptcQueryParm in GetIptcQueryParameters())
            {
                string iptcValue;
                try
                {
                    iptcValue = bmpMetadata.GetQuery(String.Format(CultureInfo.InvariantCulture, IptcQueryFormatString, iptcQueryParm.Value)) as string;
                }
                catch (InvalidOperationException)
                {
                    // Some images throw this exception. When this happens, just exit.
                    break;
                }

                if (!String.IsNullOrEmpty(iptcValue))
                {
                    switch (iptcQueryParm.Key)
                    {
                    case FormattedMetadataItemName.IptcDateCreated:
                    {
                        DateTime dateTaken = TryParseDate(iptcValue);

                        if (dateTaken.Year > DateTime.MinValue.Year)
                        {
                            metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true);
                        }
                        break;
                    }

                    default:
                    {
                        metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), iptcValue, true);
                        break;
                    }
                    }
                }
            }
        }
		/// <summary>
		/// Gets a collection of <see cref="IGalleryObjectMetadataItem" /> objects. The collection includes one item for each
		/// <see cref="FormattedMetadataItemName" /> value, unless that metadata item does not exist in the image's metadata. In that case, no item
		/// is generated. 
		/// </summary>
		/// <returns>Returns a <see cref="IGalleryObjectMetadataItemCollection" /> object.</returns>
		/// <remarks>The collection is created the first time this method is called. Subsequent calls return the cached collection
		/// rather than regenerating it from the image file.</remarks>
		public IGalleryObjectMetadataItemCollection GetGalleryObjectMetadataItemCollection()
		{
			if (this._metadataItems == null)
			{
				this._metadataItems = new GalleryObjectMetadataItemCollection();

				// The AddWpfBitmapMetadata function requires .NET Framework 3.0 and running under Full Trust, so only call if 
				// these conditions are satisfied. There is also a config setting that enables this functionality, so query that
				// as well. (The config setting allows it to be disabled due to the reliability issues found with the WPF classes.)
				if ((AppSetting.Instance.AppTrustLevel == ApplicationTrustLevel.Full)
						&& (AppSetting.Instance.IsDotNet3Installed)
						&& (Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.EnableWpfMetadataExtraction))
				{
					AddWpfBitmapMetadata(_metadataItems);
				}

				AddExifMetadata(_metadataItems);
			}

			RemoveInvalidHtmlAndScripts(_metadataItems);

			return _metadataItems;
		}
Exemple #13
0
        /// <summary>
        /// Gets a collection of <see cref="IGalleryObjectMetadataItem" /> objects. The collection includes one item for each
        /// <see cref="FormattedMetadataItemName" /> value, unless that metadata item does not exist in the image's metadata. In that case, no item
        /// is generated.
        /// </summary>
        /// <returns>Returns a <see cref="IGalleryObjectMetadataItemCollection" /> object.</returns>
        /// <remarks>The collection is created the first time this method is called. Subsequent calls return the cached collection
        /// rather than regenerating it from the image file.</remarks>
        public IGalleryObjectMetadataItemCollection GetGalleryObjectMetadataItemCollection()
        {
            if (this._metadataItems == null)
            {
                this._metadataItems = new GalleryObjectMetadataItemCollection();

                // The AddWpfBitmapMetadata function requires .NET Framework 3.0 and running under Full Trust, so only call if
                // these conditions are satisfied. There is also a config setting that enables this functionality, so query that
                // as well. (The config setting allows it to be disabled due to the reliability issues found with the WPF classes.)
                if ((AppSetting.Instance.AppTrustLevel == ApplicationTrustLevel.Full) &&
                    (AppSetting.Instance.IsDotNet3Installed) &&
                    (Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.EnableWpfMetadataExtraction))
                {
                    AddWpfBitmapMetadata(_metadataItems);
                }

                AddExifMetadata(_metadataItems);
            }

            RemoveInvalidHtmlAndScripts(_metadataItems);

            return(_metadataItems);
        }
        public void Save(IGalleryObjectMetadataItemCollection metadata)
        {
            IGalleryObjectMetadataItemCollection metadataItemsToSave = metadata.GetItemsToSave();

            if (metadataItemsToSave.Count == 0)
            {
                return;                 // Nothing to save
            }

            int tmpId = 0;
            var mDtos = new Dictionary <int, MetadataDto>();
            var metas = new Dictionary <int, IGalleryObjectMetadataItem>();

            // There is at least one item to persist to the data store.
            foreach (IGalleryObjectMetadataItem metaDataItem in metadataItemsToSave)
            {
                MetadataDto mDto;
                if (SaveInternal(metaDataItem, out mDto) == SaveAction.Inserted)
                {
                    metas.Add(++tmpId, metaDataItem);
                    mDtos.Add(tmpId, mDto);
                }
            }

            Save();

            // Loop through each metadata item again, find the matching DTO object, and update
            // the newly assigned ID.
            foreach (var kvp in metas)
            {
                MetadataDto mDto;
                if (mDtos.TryGetValue(kvp.Key, out mDto))
                {
                    kvp.Value.MediaObjectMetadataId = mDto.MetadataId;
                }
            }
        }
        /// <summary>
        /// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
        /// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
        /// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
        /// </summary>
        /// <param name="imageFilePath">The image file path.</param>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        /// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
        /// throw a security exception if it doesn't have it.</exception>
        public static void AddWpfBitmapMetadata(string imageFilePath, IGalleryObjectMetadataItemCollection metadataItems)
        {
            //return;
            BitmapMetadata bmpMetadata = GetBitmapMetadata(imageFilePath);

            if (bmpMetadata != null)
            {
                try
                {
                    if (bmpMetadata.Title != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Title, Resources.Metadata_Title, bmpMetadata.Title, true);
                    }

                    if (bmpMetadata.Author != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Author, Resources.Metadata_Author, ConvertStringCollectionToDelimitedString(bmpMetadata.Author), true);
                    }

                    if (bmpMetadata.DateTaken != null)
                    {
                        DateTime dateTaken;
                        if (DateTime.TryParse(bmpMetadata.DateTaken, out dateTaken) && (dateTaken.Year > DateTime.MinValue.Year))
                        {
                            metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.DatePictureTaken, Resources.Metadata_DatePictureTaken, dateTaken.ToString("R", CultureInfo.InvariantCulture), true);
                        }
                    }

                    if (bmpMetadata.CameraModel != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel, bmpMetadata.CameraModel, true);
                    }

                    if (bmpMetadata.CameraManufacturer != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer, bmpMetadata.CameraManufacturer, true);
                    }

                    if (bmpMetadata.Keywords != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Keywords, Resources.Metadata_Keywords, ConvertStringCollectionToDelimitedString(bmpMetadata.Keywords), true);
                    }

                    // Rating is an int, so we can't check for null.
                    metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Rating, Resources.Metadata_Rating, bmpMetadata.Rating.ToString(CultureInfo.InvariantCulture), true);

                    if (bmpMetadata.Comment != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Comment, Resources.Metadata_Comment, bmpMetadata.Comment, true);
                    }

                    if (bmpMetadata.Copyright != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright, bmpMetadata.Copyright, true);
                    }

                    if (bmpMetadata.Subject != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Subject, Resources.Metadata_Subject, bmpMetadata.Subject, true);
                    }
                }
                catch (NotSupportedException) { }                 // Some image types, such as png, throw a NotSupportedException. Let's swallow them and move on.
            }
        }
        private static void AddIptcMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems)
        {
            foreach (KeyValuePair<FormattedMetadataItemName, string> iptcQueryParm in GetIptcQueryParameters())
            {
                string iptcValue = bmpMetadata.GetQuery(String.Format(CultureInfo.InvariantCulture, IptcQueryFormatString, iptcQueryParm.Value)) as string;

                if (!String.IsNullOrEmpty(iptcValue))
                {
                    switch (iptcQueryParm.Key)
                    {
                        case FormattedMetadataItemName.IptcDateCreated:
                            {
                                DateTime dateTaken = TryParseDate(iptcValue);

                                if (dateTaken.Year > DateTime.MinValue.Year)
                                {
                                    metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true);
                                }
                                break;
                            }
                        default:
                            {
                                metadataItems.AddNew(int.MinValue, iptcQueryParm.Key, GetResource(iptcQueryParm.Key), iptcValue, true);
                                break;
                            }
                    }
                }
            }
        }
        //private void OutputToDebugWindow()
        //{
        //  foreach (RawMetadataItemName metadataItemName in Enum.GetValues(typeof(RawMetadataItemName)))
        //  {
        //    MetadataItem rawMdi;
        //    if (RawMetadata.TryGetValue(metadataItemName, out rawMdi))
        //    {
        //      string rawValue = rawMdi.Value.ToString().Trim().TrimEnd(new char[] {'\0'});
        //      string msg = String.Format(CultureInfo.CurrentCulture, "{0}: {1} (ID {2}, {3}, {4})", metadataItemName, rawValue, rawMdi.PropertyItem.Id, rawMdi.ExtractedValueType, rawMdi.PropertyTagType);
        //      System.Diagnostics.Trace.WriteLine(msg);
        //    }
        //  }
        //}
        private void AddExifMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            //OutputToDebugWindow();

            foreach (FormattedMetadataItemName metadataItemName in Enum.GetValues(typeof(FormattedMetadataItemName)))
            {
                IGalleryObjectMetadataItem mdi = null;
                switch (metadataItemName)
                {
                    case FormattedMetadataItemName.Author: mdi = GetStringMetadataItem(RawMetadataItemName.Artist, FormattedMetadataItemName.Author, Resources.Metadata_Author); break;
                    case FormattedMetadataItemName.CameraModel: mdi = GetStringMetadataItem(RawMetadataItemName.EquipModel, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel); break;
                    case FormattedMetadataItemName.ColorRepresentation: mdi = GetColorRepresentationMetadataItem(); break;
                    case FormattedMetadataItemName.Comment: mdi = GetStringMetadataItem(RawMetadataItemName.ExifUserComment, FormattedMetadataItemName.Comment, Resources.Metadata_Comment); break;
                    case FormattedMetadataItemName.Copyright: mdi = GetStringMetadataItem(RawMetadataItemName.Copyright, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright); break;
                    case FormattedMetadataItemName.DatePictureTaken: mdi = GetDatePictureTakenMetadataItem(); break;
                    case FormattedMetadataItemName.Description: mdi = GetStringMetadataItem(RawMetadataItemName.ImageDescription, FormattedMetadataItemName.Description, Resources.Metadata_Description); break;
                    case FormattedMetadataItemName.Dimensions: mdi = GetDimensionsMetadataItem(); break;
                    case FormattedMetadataItemName.EquipmentManufacturer: mdi = GetStringMetadataItem(RawMetadataItemName.EquipMake, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer); break;
                    case FormattedMetadataItemName.ExposureCompensation: mdi = GetExposureCompensationMetadataItem(); break;
                    case FormattedMetadataItemName.ExposureProgram: mdi = GetExposureProgramMetadataItem(); break;
                    case FormattedMetadataItemName.ExposureTime: mdi = GetExposureTimeMetadataItem(); break;
                    case FormattedMetadataItemName.FlashMode: mdi = GetFlashModeMetadataItem(); break;
                    case FormattedMetadataItemName.FNumber: mdi = GetFNumberMetadataItem(); break;
                    case FormattedMetadataItemName.FocalLength: mdi = GetFocalLengthMetadataItem(); break;
                    case FormattedMetadataItemName.Height: mdi = GetHeightMetadataItem(); break;
                    case FormattedMetadataItemName.HorizontalResolution: mdi = GetXResolutionMetadataItem(); break;
                    case FormattedMetadataItemName.IsoSpeed: mdi = GetStringMetadataItem(RawMetadataItemName.ExifISOSpeed, FormattedMetadataItemName.IsoSpeed, Resources.Metadata_IsoSpeed); break;
                    case FormattedMetadataItemName.Keywords: break; // No way to access keywords through Exif, so just skip this one
                    case FormattedMetadataItemName.LensAperture: mdi = GetApertureMetadataItem(); break;
                    case FormattedMetadataItemName.LightSource: mdi = GetLightSourceMetadataItem(); break;
                    case FormattedMetadataItemName.MeteringMode: mdi = GetMeteringModeMetadataItem(); break;
                    case FormattedMetadataItemName.Rating: break; // No way to access rating through Exif, so just skip this one
                    case FormattedMetadataItemName.Subject: break; // No way to access rating through Exif, so just skip this one
                    case FormattedMetadataItemName.SubjectDistance: mdi = GetSubjectDistanceMetadataItem(); break;
                    case FormattedMetadataItemName.Title: mdi = GetStringMetadataItem(RawMetadataItemName.ImageTitle, FormattedMetadataItemName.Title, Resources.Metadata_Title); break;
                    case FormattedMetadataItemName.VerticalResolution: mdi = GetYResolutionMetadataItem(); break;
                    case FormattedMetadataItemName.Width: mdi = GetWidthMetadataItem(); break;
                }
                if ((mdi != null) && (!metadataItems.Contains(mdi)))
                {
                    metadataItems.Add(mdi);
                }
            }
        }
Exemple #18
0
        private void AddExifMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            foreach (FormattedMetadataItemName metadataItemName in Enum.GetValues(typeof(FormattedMetadataItemName)))
            {
                IGalleryObjectMetadataItem mdi = null;
                switch (metadataItemName)
                {
                case FormattedMetadataItemName.Author: mdi = GetStringMetadataItem(RawMetadataItemName.Artist, FormattedMetadataItemName.Author, Resources.Metadata_Author); break;

                case FormattedMetadataItemName.CameraModel: mdi = GetStringMetadataItem(RawMetadataItemName.EquipModel, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel); break;

                case FormattedMetadataItemName.ColorRepresentation: mdi = GetColorRepresentationMetadataItem(); break;

                case FormattedMetadataItemName.Comment: mdi = GetStringMetadataItem(RawMetadataItemName.ExifUserComment, FormattedMetadataItemName.Comment, Resources.Metadata_Comment); break;

                case FormattedMetadataItemName.Copyright: mdi = GetStringMetadataItem(RawMetadataItemName.Copyright, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright); break;

                case FormattedMetadataItemName.DatePictureTaken: mdi = GetDatePictureTakenMetadataItem(); break;

                case FormattedMetadataItemName.Description: mdi = GetStringMetadataItem(RawMetadataItemName.ImageDescription, FormattedMetadataItemName.Description, Resources.Metadata_Description); break;

                case FormattedMetadataItemName.Dimensions: mdi = GetDimensionsMetadataItem(); break;

                case FormattedMetadataItemName.EquipmentManufacturer: mdi = GetStringMetadataItem(RawMetadataItemName.EquipMake, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer); break;

                case FormattedMetadataItemName.ExposureCompensation: mdi = GetExposureCompensationMetadataItem(); break;

                case FormattedMetadataItemName.ExposureProgram: mdi = GetExposureProgramMetadataItem(); break;

                case FormattedMetadataItemName.ExposureTime: mdi = GetExposureTimeMetadataItem(); break;

                case FormattedMetadataItemName.FlashMode: mdi = GetFlashModeMetadataItem(); break;

                case FormattedMetadataItemName.FNumber: mdi = GetFNumberMetadataItem(); break;

                case FormattedMetadataItemName.FocalLength: mdi = GetFocalLengthMetadataItem(); break;

                case FormattedMetadataItemName.Height: mdi = GetHeightMetadataItem(); break;

                case FormattedMetadataItemName.HorizontalResolution: mdi = GetXResolutionMetadataItem(); break;

                case FormattedMetadataItemName.IsoSpeed: mdi = GetStringMetadataItem(RawMetadataItemName.ExifISOSpeed, FormattedMetadataItemName.IsoSpeed, Resources.Metadata_IsoSpeed); break;

                case FormattedMetadataItemName.Keywords: break;                         // No way to access keywords through Exif, so just skip this one

                case FormattedMetadataItemName.LensAperture: mdi = GetApertureMetadataItem(); break;

                case FormattedMetadataItemName.LightSource: mdi = GetLightSourceMetadataItem(); break;

                case FormattedMetadataItemName.MeteringMode: mdi = GetMeteringModeMetadataItem(); break;

                case FormattedMetadataItemName.Rating: break;                         // No way to access rating through Exif, so just skip this one

                case FormattedMetadataItemName.Subject: break;                        // No way to access rating through Exif, so just skip this one

                case FormattedMetadataItemName.SubjectDistance: mdi = GetStringMetadataItem(RawMetadataItemName.ExifSubjectDist, FormattedMetadataItemName.SubjectDistance, Resources.Metadata_SubjectDistance, String.Concat("{0} ", Resources.Metadata_SubjectDistance_Units)); break;

                case FormattedMetadataItemName.Title: mdi = GetStringMetadataItem(RawMetadataItemName.ImageTitle, FormattedMetadataItemName.Title, Resources.Metadata_Title); break;

                case FormattedMetadataItemName.VerticalResolution: mdi = GetYResolutionMetadataItem(); break;

                case FormattedMetadataItemName.Width: mdi = GetWidthMetadataItem(); break;

                default: throw new System.ComponentModel.InvalidEnumArgumentException(string.Format(CultureInfo.CurrentCulture, "The FormattedMetadataItemName enumeration value {0} is not being processed in MediaObjectMetadataExtractor.AddExifMetadata().", metadataItemName.ToString()));
                }
                if ((mdi != null) && (!metadataItems.Contains(mdi)))
                {
                    metadataItems.Add(mdi);
                }
            }
        }
        /// <summary>
        /// Adds items to <paramref name="metadataItems" /> containing information about the current media object using the FFmpeg utility.
        /// </summary>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        private void AddVideoMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            if (String.IsNullOrEmpty(this._ffmpegOutput))
            {
                this._ffmpegOutput = FFmpeg.GetOutput(this._mediaObjectFilePath, this._galleryId);
            }

            if (!String.IsNullOrEmpty(this._ffmpegOutput))
            {
                ParseVideoMetadata(this._ffmpegOutput, metadataItems);
            }
        }
        /// <summary>
        /// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
        /// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
        /// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
        /// </summary>
        /// <param name="imageFilePath">The image file path.</param>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        /// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
        /// throw a security exception if it doesn't have it.</exception>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="metadataItems" /> is null.</exception>
        public static void AddWpfBitmapMetadata(string imageFilePath, IGalleryObjectMetadataItemCollection metadataItems)
        {
            if (metadataItems == null)
            {
                throw new ArgumentNullException("metadataItems");
            }

            BitmapMetadata bmpMetadata = GetBitmapMetadata(imageFilePath);

            if (bmpMetadata != null)
            {
                AddGpsMetadata(bmpMetadata, metadataItems);

                AddIptcMetadata(bmpMetadata, metadataItems);

                try
                {
                    if ((bmpMetadata.Title != null) && (!String.IsNullOrEmpty(bmpMetadata.Title.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Title, Resources.Metadata_Title, bmpMetadata.Title.Trim(), true);
                    }

                    if (bmpMetadata.Author != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Author, Resources.Metadata_Author, ConvertStringCollectionToDelimitedString(bmpMetadata.Author), true);
                    }

                    if (bmpMetadata.DateTaken != null)
                    {
                        DateTime dateTaken = TryParseDate(bmpMetadata.DateTaken);
                        if (dateTaken.Year > DateTime.MinValue.Year)
                        {
                            metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.DatePictureTaken, Resources.Metadata_DatePictureTaken, dateTaken.ToString(DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true);
                        }
                    }

                    if ((bmpMetadata.CameraModel != null) && (!String.IsNullOrEmpty(bmpMetadata.CameraModel.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel, bmpMetadata.CameraModel.Trim(), true);
                    }

                    if ((bmpMetadata.CameraManufacturer != null) && (!String.IsNullOrEmpty(bmpMetadata.CameraManufacturer.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer, bmpMetadata.CameraManufacturer.Trim(), true);
                    }

                    if (bmpMetadata.Keywords != null)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Keywords, Resources.Metadata_Keywords, ConvertStringCollectionToDelimitedString(bmpMetadata.Keywords), true);
                    }

                    if (bmpMetadata.Rating > 0)
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Rating, Resources.Metadata_Rating, bmpMetadata.Rating.ToString(CultureInfo.InvariantCulture), true);
                    }

                    if ((bmpMetadata.Comment != null) && (!String.IsNullOrEmpty(bmpMetadata.Comment.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Comment, Resources.Metadata_Comment, bmpMetadata.Comment.Trim(), true);
                    }

                    if ((bmpMetadata.Copyright != null) && (!String.IsNullOrEmpty(bmpMetadata.Copyright.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright, bmpMetadata.Copyright.Trim(), true);
                    }

                    if ((bmpMetadata.Subject != null) && (!String.IsNullOrEmpty(bmpMetadata.Subject.Trim())))
                    {
                        metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.Subject, Resources.Metadata_Subject, bmpMetadata.Subject.Trim(), true);
                    }
                }
                catch (NotSupportedException) { }                 // Some image types, such as png, throw a NotSupportedException. Let's swallow them and move on.
                catch (ArgumentException) { }
                catch (InvalidOperationException) { }
            }
        }
 /// <summary>
 /// Gets the collection of tag values having the specified <paramref name="tagName" />.
 /// </summary>
 /// <param name="metas">The metadata items.</param>
 /// <param name="tagName">Name of the tag.</param>
 /// <returns>Returns a collection of strings.</returns>
 private static IEnumerable<string> GetTagList(IGalleryObjectMetadataItemCollection metas, MetadataItemName tagName)
 {
     IGalleryObjectMetadataItem mdTag;
     if (metas.TryGetMetadataItem(tagName, out mdTag))
     {
         return mdTag.Value.ToListFromCommaDelimited();
     }
     else
         return new string[] { };
 }
		private void AddExifMetadata(IGalleryObjectMetadataItemCollection metadataItems)
		{
			foreach (FormattedMetadataItemName metadataItemName in Enum.GetValues(typeof(FormattedMetadataItemName)))
			{
				IGalleryObjectMetadataItem mdi = null;
				switch (metadataItemName)
				{
					case FormattedMetadataItemName.Author: mdi = GetStringMetadataItem(RawMetadataItemName.Artist, FormattedMetadataItemName.Author, Resources.Metadata_Author); break;
					case FormattedMetadataItemName.CameraModel: mdi = GetStringMetadataItem(RawMetadataItemName.EquipModel, FormattedMetadataItemName.CameraModel, Resources.Metadata_CameraModel); break;
					case FormattedMetadataItemName.ColorRepresentation: mdi = GetColorRepresentationMetadataItem(); break;
					case FormattedMetadataItemName.Comment: mdi = GetStringMetadataItem(RawMetadataItemName.ExifUserComment, FormattedMetadataItemName.Comment, Resources.Metadata_Comment); break;
					case FormattedMetadataItemName.Copyright: mdi = GetStringMetadataItem(RawMetadataItemName.Copyright, FormattedMetadataItemName.Copyright, Resources.Metadata_Copyright); break;
					case FormattedMetadataItemName.DatePictureTaken: mdi = GetDatePictureTakenMetadataItem(); break;
					case FormattedMetadataItemName.Description: mdi = GetStringMetadataItem(RawMetadataItemName.ImageDescription, FormattedMetadataItemName.Description, Resources.Metadata_Description); break;
					case FormattedMetadataItemName.Dimensions: mdi = GetDimensionsMetadataItem(); break;
					case FormattedMetadataItemName.EquipmentManufacturer: mdi = GetStringMetadataItem(RawMetadataItemName.EquipMake, FormattedMetadataItemName.EquipmentManufacturer, Resources.Metadata_EquipmentManufacturer); break;
					case FormattedMetadataItemName.ExposureCompensation: mdi = GetExposureCompensationMetadataItem(); break;
					case FormattedMetadataItemName.ExposureProgram: mdi = GetExposureProgramMetadataItem(); break;
					case FormattedMetadataItemName.ExposureTime: mdi = GetExposureTimeMetadataItem(); break;
					case FormattedMetadataItemName.FlashMode: mdi = GetFlashModeMetadataItem(); break;
					case FormattedMetadataItemName.FNumber: mdi = GetFNumberMetadataItem(); break;
					case FormattedMetadataItemName.FocalLength: mdi = GetFocalLengthMetadataItem(); break;
					case FormattedMetadataItemName.Height: mdi = GetHeightMetadataItem(); break;
					case FormattedMetadataItemName.HorizontalResolution: mdi = GetXResolutionMetadataItem(); break;
					case FormattedMetadataItemName.IsoSpeed: mdi = GetStringMetadataItem(RawMetadataItemName.ExifISOSpeed, FormattedMetadataItemName.IsoSpeed, Resources.Metadata_IsoSpeed); break;
					case FormattedMetadataItemName.Keywords: break; // No way to access keywords through Exif, so just skip this one
					case FormattedMetadataItemName.LensAperture: mdi = GetApertureMetadataItem(); break;
					case FormattedMetadataItemName.LightSource: mdi = GetLightSourceMetadataItem(); break;
					case FormattedMetadataItemName.MeteringMode: mdi = GetMeteringModeMetadataItem(); break;
					case FormattedMetadataItemName.Rating: break; // No way to access rating through Exif, so just skip this one
					case FormattedMetadataItemName.Subject: break; // No way to access rating through Exif, so just skip this one
					case FormattedMetadataItemName.SubjectDistance: mdi = GetStringMetadataItem(RawMetadataItemName.ExifSubjectDist, FormattedMetadataItemName.SubjectDistance, Resources.Metadata_SubjectDistance, String.Concat("{0} ", Resources.Metadata_SubjectDistance_Units)); break;
					case FormattedMetadataItemName.Title: mdi = GetStringMetadataItem(RawMetadataItemName.ImageTitle, FormattedMetadataItemName.Title, Resources.Metadata_Title); break;
					case FormattedMetadataItemName.VerticalResolution: mdi = GetYResolutionMetadataItem(); break;
					case FormattedMetadataItemName.Width: mdi = GetWidthMetadataItem(); break;

					default: throw new System.ComponentModel.InvalidEnumArgumentException(string.Format(CultureInfo.CurrentCulture, "The FormattedMetadataItemName enumeration value {0} is not being processed in MediaObjectMetadataExtractor.AddExifMetadata().", metadataItemName.ToString()));
				}
				if ((mdi != null) && (!metadataItems.Contains(mdi)))
				{
					metadataItems.Add(mdi);
				}
			}
		}
        /// <summary>
        /// Gets a collection of <see cref="IGalleryObjectMetadataItem" /> objects. The collection includes one item for each
        /// <see cref="FormattedMetadataItemName" /> value, unless that metadata item does not exist in the image's metadata. In that case, no item
        /// is generated. 
        /// </summary>
        /// <returns>Returns a <see cref="IGalleryObjectMetadataItemCollection" /> object.</returns>
        /// <remarks>The collection is created the first time this method is called. Subsequent calls return the cached collection
        /// rather than regenerating it from the image file.</remarks>
        public IGalleryObjectMetadataItemCollection GetGalleryObjectMetadataItemCollection()
        {
            if (this._metadataItems == null)
            {
                this._metadataItems = new GalleryObjectMetadataItemCollection();

                AddFileMetadata(_metadataItems);

                if (this._mimeTypeCategory == MimeTypeCategory.Image)
                {
                    // The AddWpfBitmapMetadata function requires .NET Framework 3.0 and running under Full Trust, so only call if
                    // these conditions are satisfied. There is also a config setting that enables this functionality, so query that
                    // as well. (The config setting allows it to be disabled due to the reliability issues found with the WPF classes.)
                    if ((AppSetting.Instance.AppTrustLevel == ApplicationTrustLevel.Full)
                            && (AppSetting.Instance.DotNetFrameworkVersion > new Version("2.0"))
                            && (Factory.LoadGallerySetting(_galleryId).ExtractMetadataUsingWpf))
                    {
                        AddWpfBitmapMetadata(_metadataItems);
                    }

                    AddExifMetadata(_metadataItems);
                }

                if (this._mimeTypeCategory == MimeTypeCategory.Video || (this._mimeTypeCategory == MimeTypeCategory.Audio))
                {
                    AddVideoMetadata(_metadataItems);
                }
            }

            RemoveInvalidHtmlAndScripts(_metadataItems, _galleryId);

            return _metadataItems;
        }
        public static MetaItem[] ToMetaItems(IGalleryObjectMetadataItemCollection metadataItems, IGalleryObject galleryObject)
        {
            var metaItems = new MetaItem[metadataItems.Count];
            var metaDefs = Factory.LoadGallerySetting(galleryObject.GalleryId).MetadataDisplaySettings;
            var moProfiles = ProfileController.GetProfile().MediaObjectProfiles;

            for (int i = 0; i < metaItems.Length; i++)
            {
                IGalleryObjectMetadataItem md = metadataItems[i];

                metaItems[i] = new MetaItem
                    {
                        Id = md.MediaObjectMetadataId,
                        MediaId = galleryObject.Id,
                        MTypeId = (int)md.MetadataItemName,
                        GTypeId = (int)galleryObject.GalleryObjectType,
                        Desc = md.Description,
                        Value = md.Value,
                        IsEditable = metaDefs.Find(md.MetadataItemName).IsEditable
                    };

                if (md.MetadataItemName == MetadataItemName.Rating)
                {
                    ReplaceAvgRatingWithUserRating(metaItems[i], moProfiles);
                }
            }

            return metaItems;
        }
Exemple #25
0
        /// <summary>
        /// Persist each each metadata item that has HasChanges = true to the data store. If all items are marked for updating
        /// (mediaObject.RegenerateMetadataOnSave = true), then all metadata items are deleted from the data store and then inserted based
        /// on the current metadata items. If one or more items has HasChanges = false, then each item with HasChanges = true is
        /// processed according to the following rules: (1) If the metadata value is null or an empty string, it is deleted from the
        /// data store and removed from the MetadataItems collection. (2) If the item's MediaObjectMetadataId = int.MinValue, the
        /// item is assumed to be new and is inserted. (3) Any item not falling into the previous two categories, but HasChanges = true,
        /// is assumed to be pre-existing and an update stored procedure is executed.
        /// </summary>
        /// <param name="mediaObject">The media object for which to update metadata items in the data store.</param>
        private static void UpdateMetadataItems(IGalleryObject mediaObject)
        {
            if (mediaObject.RegenerateMetadataOnSave)
            {
                // User wants to replace all metadata items. Delete them all from the data store, then insert the ones we have.
                DeleteMetadataItems(mediaObject);

                InsertMetadataItems(mediaObject);
            }
            else
            {
                IGalleryObjectMetadataItemCollection metadataItemsToSave = mediaObject.MetadataItems.GetItemsToSave();
                if (metadataItemsToSave.Count == 0)
                {
                    return;                     // Nothing to save
                }

                // There is at least one item to persist to the data store.
                SqlCommand cmdUpdate = GetCommandMediaObjectMetadataUpdate();
                cmdUpdate.Parameters["@FKMediaObjectId"].Value = mediaObject.Id;

                SqlCommand cmdInsert = GetCommandMediaObjectMetadataInsert();
                cmdInsert.Parameters["@FKMediaObjectId"].Value = mediaObject.Id;

                cmdUpdate.Connection.Open();
                cmdInsert.Connection.Open();

                foreach (IGalleryObjectMetadataItem metaDataItem in metadataItemsToSave)
                {
                    if (String.IsNullOrEmpty(metaDataItem.Value))
                    {
                        // There is no value, so let's delete this item.
                        DeleteMetadataItem(metaDataItem);

                        // Remove it from the collection.
                        mediaObject.MetadataItems.Remove(metaDataItem);
                    }
                    else if (metaDataItem.MediaObjectMetadataId == int.MinValue)
                    {
                        // Insert the item.
                        cmdInsert.Parameters["@MetadataNameIdentifier"].Value = (int)metaDataItem.MetadataItemName;
                        cmdInsert.Parameters["@Description"].Value            = metaDataItem.Description;
                        cmdInsert.Parameters["@Value"].Value = metaDataItem.Value;

                        cmdInsert.ExecuteNonQuery();

                        // Assign newly assigned ID to the metadata ID property.
                        metaDataItem.MediaObjectMetadataId = Convert.ToInt32(cmdInsert.Parameters["@Identity"].Value, System.Globalization.NumberFormatInfo.InvariantInfo);
                    }
                    else
                    {
                        // Update the item.
                        cmdUpdate.Parameters["@MetadataNameIdentifier"].Value = (int)metaDataItem.MetadataItemName;
                        cmdUpdate.Parameters["@Description"].Value            = metaDataItem.Description;
                        cmdUpdate.Parameters["@Value"].Value = metaDataItem.Value;
                        cmdUpdate.Parameters["@MediaObjectMetadataId"].Value = metaDataItem.MediaObjectMetadataId;

                        cmdUpdate.ExecuteNonQuery();
                    }
                }
                cmdUpdate.Connection.Close();
                cmdInsert.Connection.Close();
            }
        }
 public void AddMeta(IGalleryObjectMetadataItemCollection metaItems)
 {
 }
        /// <summary>
        /// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
        /// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
        /// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
        /// </summary>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        /// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
        /// throw a security exception if it doesn't have it.</exception>
        private void AddWpfBitmapMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            WpfMetadataExtractor.AddWpfBitmapMetadata(this._mediaObjectFilePath, metadataItems);

            //System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("GalleryServerPro.Business.Wpf");

            //// Get reference to static WpfMetadataExtractor.AddWpfBitmapMetadata() method.
            //Type[] parmTypes = new Type[2];
            //parmTypes[0] = typeof(string);
            //parmTypes[1] = typeof(IGalleryObjectMetadataItemCollection);
            //Type metadataExtractor = assembly.GetType("GalleryServerPro.Business.Wpf.WpfMetadataExtractor");
            //System.Reflection.MethodInfo addMetadataMethod = metadataExtractor.GetMethod("AddWpfBitmapMetadata", parmTypes);

            //// Prepare parameters to pass to BitmapDecoder.Create() method.
            //object[] parameters = new object[2];
            //parameters[0] = this._mediaObjectFilePath;
            //parameters[1] = metadataItems;

            //try
            //{
            //  addMetadataMethod.Invoke(null, parameters);
            //}
            //catch (System.Reflection.TargetInvocationException ex)
            //{
            //  LogError(ex, this._galleryId);
            //}
        }
        /// <summary>
        /// Adds GPS data from the <paramref name="bmpMetadata" /> to the <paramref name="metadataItems" /> collection.
        /// </summary>
        /// <param name="bmpMetadata">An object containing the metadata.</param>
        /// <param name="metadataItems">The metadata items.</param>
        private static void AddGpsMetadata(BitmapMetadata bmpMetadata, IGalleryObjectMetadataItemCollection metadataItems)
        {
            GpsLocation gps = GpsLocation.Parse(bmpMetadata);

            if (!String.IsNullOrEmpty(gps.Version))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsVersion, GetResource(FormattedMetadataItemName.GpsVersion), gps.Version, true);
            }

            if ((gps.Latitude != null) && (gps.Longitude != null))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLocation, GetResource(FormattedMetadataItemName.GpsLocation), gps.ToLatitudeLongitudeDecimalString(), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLatitude, GetResource(FormattedMetadataItemName.GpsLatitude), gps.Latitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsLongitude, GetResource(FormattedMetadataItemName.GpsLongitude), gps.Longitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
            }

            if (gps.Altitude.HasValue)
            {
                string altitude = String.Concat(gps.Altitude.Value.ToString("N0", CultureInfo.CurrentCulture), " ", Resources.Metadata_meters);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsAltitude, GetResource(FormattedMetadataItemName.GpsAltitude), altitude, true);
            }

            if ((gps.DestLatitude != null) && (gps.DestLongitude != null))
            {
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLocation, GetResource(FormattedMetadataItemName.GpsDestLocation), gps.ToDestLatitudeLongitudeDecimalString(), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLatitude, GetResource(FormattedMetadataItemName.GpsDestLatitude), gps.DestLatitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
                metadataItems.AddNew(int.MinValue, FormattedMetadataItemName.GpsDestLongitude, GetResource(FormattedMetadataItemName.GpsDestLongitude), gps.DestLongitude.ToDouble().ToString("F6", CultureInfo.InvariantCulture), true);
            }
        }
        /// <summary>
        /// Parses the <paramref name="ffmpegOutput" /> data and adds useful metadata items to the <paramref name="metadataItems" />
        /// collection.
        /// </summary>
        /// <param name="ffmpegOutput">The text output from the execution of the FFmpeg utility against a media file.</param>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        private static void ParseVideoMetadata(string ffmpegOutput, IGalleryObjectMetadataItemCollection metadataItems)
        {
            //Use a regular expression to get the different properties from the video parsed out.
            Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
            Match m = re.Match(ffmpegOutput);

            if (m.Success)
            {
                //string dur = m.Groups[1].Value;
                //string[] timepieces = dur.Split(new char[] { ':', '.' });
                //if (timepieces.Length == 4)
                //{
                //TimeSpan duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
                GalleryObjectMetadataItem mdi = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.Duration, Resources.Metadata_Duration, m.Groups[1].Value.Trim(), true);
                AddMetadataItem(metadataItems, mdi);
                //}
            }

            //get bit rate
            re = new Regex("[B|b]itrate:.((\\d|:)*)");
            m = re.Match(ffmpegOutput);
            double kb;
            if (m.Success && Double.TryParse(m.Groups[1].Value, out kb))
            {
                //TODO: Parse bitrate units instead of assuming they are kb/s
                // Line we are parsing looks like this: Duration: 00:00:25.27, start: 0.000000, bitrate: 932 kb/s
                GalleryObjectMetadataItem mdi = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.BitRate, Resources.Metadata_BitRate, String.Concat(kb, " kb/s"), true);
                AddMetadataItem(metadataItems, mdi);
            }

            //get the audio format
            re = new Regex("[A|a]udio:.*");
            m = re.Match(ffmpegOutput);
            if (m.Success)
            {
                GalleryObjectMetadataItem mdi = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.AudioFormat, Resources.Metadata_AudioFormat, m.Value.Trim(), true);
                AddMetadataItem(metadataItems, mdi);
            }

            //get the video format
            re = new Regex("[V|v]ideo:.*");
            m = re.Match(ffmpegOutput);
            if (m.Success)
            {
                GalleryObjectMetadataItem mdi = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.VideoFormat, Resources.Metadata_VideoFormat, m.Value.Trim(), true);
                AddMetadataItem(metadataItems, mdi);
            }

            //get the video width and height
            // TODO: Get width and height from the metadata lines rather than looking for "200x300"
            re = new Regex("(\\d{2,4})x(\\d{2,4})");
            m = re.Match(ffmpegOutput);
            if (m.Success)
            {
                int width; int height;
                int.TryParse(m.Groups[1].Value, out width);
                int.TryParse(m.Groups[2].Value, out height);

                GalleryObjectMetadataItem mdiWidth = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.Width, Resources.Metadata_Width, String.Concat(width, " ", Resources.Metadata_Width_Units), true);
                GalleryObjectMetadataItem mdiHeight = new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.Height, Resources.Metadata_Height, String.Concat(height, " ", Resources.Metadata_Height_Units), true);

                AddMetadataItem(metadataItems, mdiWidth);
                AddMetadataItem(metadataItems, mdiHeight);
            }
        }
        /// <summary>
        /// Adds the specified metadata item to this gallery object.
        /// </summary>
        /// <param name="metaItems">An instance of <see cref="IGalleryObjectMetadataItemCollection" /> 
        /// containing the items to add to this gallery object.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="metaItems" /> is null.</exception>
        public void AddMeta(IGalleryObjectMetadataItemCollection metaItems)
        {
            if (metaItems == null)
                throw new ArgumentNullException("metaItems");

            if (_metadataItems == null)
                _metadataItems = metaItems;
            else
                _metadataItems.AddRange(metaItems);

            _metadataItems.ApplyDisplayOptions(MetaDefinitions);
        }
		/// <summary>
		/// Add items to the specified collection from metadata accessed through the Windows Presentation Foundation (WPF)
		/// classes. This includes the following items: Title, Author, Data taken, Camera model, Camera manufacturer, Keywords,
		/// Rating, Comment, Copyright, Subject. If any of these items are null, they are not added.
		/// </summary>
		/// <param name="metadataItems">The collection of IGalleryObjectMetadataItem objects to add to.</param>
		/// <exception cref="System.Security.SecurityException">This function requires running under Full Trust, and will
		/// throw a security exception if it doesn't have it.</exception>
		private void AddWpfBitmapMetadata(IGalleryObjectMetadataItemCollection metadataItems)
		{
			System.Reflection.Assembly assembly = System.Reflection.Assembly.Load("GalleryServerPro.Business.Wpf");

			// Get reference to static WpfMetadataExtractor.AddWpfBitmapMetadata() method.
			Type[] parmTypes = new Type[2];
			parmTypes[0] = typeof(string);
			parmTypes[1] = typeof(IGalleryObjectMetadataItemCollection);
			Type metadataExtractor = assembly.GetType("GalleryServerPro.Business.Wpf.WpfMetadataExtractor");
			System.Reflection.MethodInfo addMetadataMethod = metadataExtractor.GetMethod("AddWpfBitmapMetadata", parmTypes);

			// Prepare parameters to pass to BitmapDecoder.Create() method.
			object[] parameters = new object[2];
			parameters[0] = this._imageFilePath;
			parameters[1] = metadataItems;

			try
			{
				addMetadataMethod.Invoke(null, parameters);
			}
			catch (System.Reflection.TargetInvocationException ex)
			{
				LogError(ex);
			}
		}
        /// <summary>
        /// Adds file-specific information, such as file name, file size, etc, to the <paramref name="metadataItems" />.
        /// </summary>
        /// <param name="metadataItems">The collection of <see cref="IGalleryObjectMetadataItem" /> objects to add to.</param>
        private void AddFileMetadata(IGalleryObjectMetadataItemCollection metadataItems)
        {
            FileInfo file = new FileInfo(this._mediaObjectFilePath);

            int fileSize = (int)(file.Length / 1024);
            fileSize = (fileSize < 1 ? 1 : fileSize); // Very small files should be 1, not 0.

            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.FileName, Resources.Metadata_FileName, file.Name, true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.FileNameWithoutExtension, Resources.Metadata_FileName, Path.GetFileNameWithoutExtension(file.Name), true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.FileSizeKb, Resources.Metadata_FileSize, String.Concat(fileSize.ToString("N0", CultureInfo.CurrentCulture), " ", Resources.Metadata_KB), true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.DateFileCreated, Resources.Metadata_DateFileCreated, file.CreationTime.ToString(GlobalConstants.DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.DateFileCreatedUtc, Resources.Metadata_DateFileCreatedUtc, file.CreationTimeUtc.ToString(GlobalConstants.DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.DateFileLastModified, Resources.Metadata_DateFileLastModified, file.LastWriteTime.ToString(GlobalConstants.DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true));
            metadataItems.Add(new GalleryObjectMetadataItem(int.MinValue, FormattedMetadataItemName.DateFileLastModifiedUtc, Resources.Metadata_DateFileLastModifiedUtc, file.LastWriteTimeUtc.ToString(GlobalConstants.DateTimeFormatStringForMetadata, CultureInfo.InvariantCulture), true));
        }
 public void AddMeta(IGalleryObjectMetadataItemCollection metaItems)
 {
 }
 private static void AddMetadataItem(IGalleryObjectMetadataItemCollection metadataItems, GalleryObjectMetadataItem metadataItem)
 {
     if ((metadataItem != null) && (!metadataItems.Contains(metadataItem)))
     {
         metadataItems.Add(metadataItem);
     }
 }