public static void MapToImage(Image img, ImageField field)
        {
            int height = 0;
            int.TryParse(field.Height, out height);
            int width = 0;
            int.TryParse(field.Width, out width);
            int hSpace = 0;
            int.TryParse(field.HSpace, out hSpace);
            int vSpace = 0;
            int.TryParse(field.VSpace, out vSpace);

            img.Alt = field.Alt;
            img.Border = field.Border;
            img.Class = field.Class;
            img.Height = height;
            img.HSpace = hSpace;
            img.MediaId = field.MediaID.Guid;
            if (field.MediaItem != null)
            {
                img.Src = MediaManager.GetMediaUrl(field.MediaItem);
                var fieldTitle = field.MediaItem.Fields["Title"];
                if (fieldTitle != null)
                    img.Title = fieldTitle.Value;
            }
            img.VSpace = vSpace;
            img.Width = width;
            img.Language = field.MediaLanguage;
        }
        public override object GetValue(global::Sitecore.Data.Items.Item item,  ISitecoreService service)
        {
            var itemField = item.Fields[FieldName];

            if (itemField == null) return null;

            Image img = new Image();
            ImageField scImg = new ImageField(itemField);

            int height = 0;
            int.TryParse(scImg.Height, out height);
            int width = 0;
            int.TryParse(scImg.Width, out width);
            int hSpace = 0;
            int.TryParse(scImg.HSpace, out hSpace);
            int vSpace = 0;
            int.TryParse(scImg.VSpace, out vSpace);

            img.Alt = scImg.Alt;
            img.Border = scImg.Border;
            img.Class = scImg.Class;
            img.Height = height;
            img.HSpace = hSpace;
            img.MediaId = scImg.MediaID.Guid;
            if(scImg.MediaItem != null)
                img.Src = MediaManager.GetMediaUrl(scImg.MediaItem);
            img.VSpace = vSpace;
            img.Width = width;

            return img;
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            Image img = new Image();
            ImageField scImg = new ImageField(field);

            int height = 0;
            int.TryParse(scImg.Height, out height);
            int width = 0;
            int.TryParse(scImg.Width, out width);
            int hSpace = 0;
            int.TryParse(scImg.HSpace, out hSpace);
            int vSpace = 0;
            int.TryParse(scImg.VSpace, out vSpace);

            img.Alt = scImg.Alt;
            img.Border = scImg.Border;
            img.Class = scImg.Class;
            img.Height = height;
            img.HSpace = hSpace;
            img.MediaId = scImg.MediaID.Guid;
            if (scImg.MediaItem != null)
                img.Src = MediaManager.GetMediaUrl(scImg.MediaItem);
            img.VSpace = vSpace;
            img.Width = width;

            return img;
        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            Image img = new Image();
            ImageField scImg = new ImageField(field);

            MapToImage(img, scImg);

            return img;
        }
        private void Init(BaseItem settings_item, string site_settings_path)
        {
            if (settings_item == null)
             {
            Log.Warn("Calendar Module: progress bar settings item isn't exist", this);
            settings_item = new ModuleSettings(site_settings_path).ProgressBarSettings;
             }

             _image = settings_item.Fields[ImageField];
             _text = settings_item[TextField];
        }
        public override void SetValue( global::Sitecore.Data.Items.Item item, object value,  ISitecoreService service)
        {

            Image img = value as Image;

            Field itemField = base.GetField(item);

            if (itemField == null) return;

            ImageField scImg = new ImageField(itemField);

            if (img == null)
            {
                scImg.Clear();
                return;
            }

            if (scImg.MediaID.Guid != img.MediaId)
            {
                //this only handles empty guids, but do we need to remove the link before adding a new one?
                if (img.MediaId == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, scImg.MediaItem.Database.Name, scImg.MediaID, scImg.MediaPath);
                    scImg.RemoveLink(link);
                }
                else
                {
                    ID newId = new ID(img.MediaId);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        scImg.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        scImg.UpdateLink(link);
                    }
                    else throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId));
                }
            }

            scImg.Height = img.Height.ToString();
            scImg.Width = img.Width.ToString();
            scImg.HSpace = img.HSpace.ToString();
            scImg.VSpace = img.VSpace.ToString();
            scImg.Alt = img.Alt;
            scImg.Border = img.Border;
            scImg.Class = img.Class;
          
           

        }
        /// <summary>
        /// Gets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {

            if (field.Value.IsNullOrEmpty())
            {
                return null;
            }

            Image img = new Image();
            ImageField scImg = new ImageField(field);

            MapToImage(img, scImg);

            return img;
        }
Exemplo n.º 8
0
        public static void OutputRecognitionResult(se.smartid.RecognitionResult recog_result)
        {
            Console.WriteLine("Document type: {0}", recog_result.GetDocumentType());
            Console.WriteLine("Match results:");

            MatchResultVector match_results = recog_result.GetMatchResults();

            for (int i = 0; i < match_results.Count; i++)
            {
                Console.WriteLine("    Template Type = {0}", match_results[i].GetTemplateType());
                Console.WriteLine("    Zone = {{({0:0.0}, {1:0.0}), ({2:0.0}, {3:0.0}), ({4:0.0}, {5:0.0}), ({6:0.0}, {7:0.0})}}",
                                  match_results[i].GetQuadrangle().GetPoint(0).x, match_results[i].GetQuadrangle().GetPoint(0).y,
                                  match_results[i].GetQuadrangle().GetPoint(1).x, match_results[i].GetQuadrangle().GetPoint(1).y,
                                  match_results[i].GetQuadrangle().GetPoint(2).x, match_results[i].GetQuadrangle().GetPoint(2).y,
                                  match_results[i].GetQuadrangle().GetPoint(3).x, match_results[i].GetQuadrangle().GetPoint(3).y);
            }
            Console.WriteLine("String fields:");
            StringVector string_field_names = recog_result.GetStringFieldNames();

            for (int i = 0; i < string_field_names.Count; i++)
            {
                StringField     field       = recog_result.GetStringField(string_field_names[i]);
                String          is_accepted = field.IsAccepted() ? "[+]" : "[-]";
                Utf16CharVector chars       = field.GetValue().GetUtf16String();
                StringBuilder   value       = new StringBuilder();
                foreach (Char ch in chars)
                {
                    value.Append(ch);
                }
                Console.WriteLine("    {0,-15} {1} {2}",
                                  field.GetName(), is_accepted, value);
            }
            Console.WriteLine("Image fields:");
            StringVector image_field_names = recog_result.GetImageFieldNames();

            for (int i = 0; i < image_field_names.Count; i++)
            {
                ImageField field       = recog_result.GetImageField(image_field_names[i]);
                String     is_accepted = field.IsAccepted() ? "[+]" : "[-]";
                Console.WriteLine("    {0, -15} {1} W: {2} H: {3}",
                                  field.GetName(), is_accepted,
                                  field.GetValue().width, field.GetValue().height);
            }

            Console.WriteLine("Result terminal:    {0}", recog_result.IsTerminal() ? "[+]" : "[-]");
        }
Exemplo n.º 9
0
    /// <summary>
    /// Get image url form an image field of the item
    /// </summary>
    /// <param name="item"></param>
    /// <param name="imageFieldID"></param>
    /// <returns></returns>
    public static string GetImageUrlFromImageField(this Item item, ID imageFieldID)
    {
        if (item != null)
        {
            ImageField field = item.Fields[imageFieldID];

            if (field != null)
            {
                if (field.MediaItem != null)
                {
                    //Always return absolute path -> CoreSitecore.Hooks.CDN.OriginStorageMediaProvider
                    return(Sitecore.Resources.Media.MediaManager.GetMediaUrl(field.MediaItem));
                }
            }
        }
        return(string.Empty);
    }
Exemplo n.º 10
0
    /// <summary>
    /// Get the URL of the image in the named field with any combination of width, height, max width and/or max height
    /// </summary>
    /// <param name="item">Sitecore item</param>
    /// <param name="imageFieldName">Name of image field</param>
    /// <param name="width">The width of the image that need to be returned; null to not specify</param>
    /// <param name="height">The height of the image that need to be returned; null to not specify</param>
    /// <param name="maxWidth">The maxWidth of the image that need to be returned; null to not specify</param>
    /// <param name="maxHeight">The maxHeight of the image that need to be returned; null to not specify</param>
    /// <returns>The URL of the MediaItem for the image in the named field with the required dimension parameters; null if the field not found, no media found, zero-size media, etc</returns>
    public static string GetImageUrl(this Item item, string imageFieldName, int?width, int?height, int?maxWidth, int?maxHeight)
    {
        Assert.ArgumentNotNull(item, "item");
        Assert.ArgumentNotNullOrEmpty(imageFieldName, "imageFieldName");

        ImageField imageField = item.Fields[imageFieldName];

        if (imageField != null && imageField.MediaItem != null)
        {
            string mediaUrl = ((MediaItem)imageField.MediaItem).GetMediaUrl(width, height, maxWidth, maxHeight);
            if (mediaUrl != null)
            {
                return(mediaUrl.Replace(" ", "%20"));
            }
        }
        return(null);
    }
Exemplo n.º 11
0
        private List <Control> GetControls(ImageField field, Size canvasSize)
        {
            DragablePictureBox pictureBox = new DragablePictureBox();

            pictureBox.Width  = 256;
            pictureBox.Height = 128;
            SetControlProperties(pictureBox, field, canvasSize);
            pictureBox.BorderStyle           = BorderStyle.Fixed3D;
            pictureBox.BackgroundImage       = global::Epi.Windows.MakeView.Properties.Resources.imageControlIcon;
            pictureBox.BackgroundImageLayout = ImageLayout.Center;
            DragableLabel  prompt   = GetPrompt(pictureBox, field, canvasSize);
            List <Control> controls = new List <Control>();

            controls.Add(prompt);
            controls.Add(pictureBox);
            return(controls);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates an entire image tag for the specified ImageField, or returns an empty String if no image was found.  This is a substitute for
        /// sc:Image; unlike that control, this one will not plug in hard width and height values, which cause problems in responsive designs.
        /// </summary>
        /// <param name="imageField">The ImageField to use</param>
        /// <param name="cssClass">An optional cssClass.  If specified, this will override any class already attached to the ImageField</param>
        /// <returns></returns>
        public static String GetImageTagForImageField(ImageField imageField, String cssClass = "")
        {
            if (null != imageField && null != imageField.MediaItem)
            {
                var    image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
                String src   = MediaManager.GetMediaUrl(image, new MediaUrlOptions());
                String alt   = imageField.Alt;
                String css   = (String.IsNullOrEmpty(cssClass) ? imageField.Class : cssClass);

                return(String.Format("<img src=\"{0}\" alt=\"{1}\" {2}>",
                                     src,
                                     alt,
                                     String.IsNullOrEmpty(css) ? String.Empty : String.Format("class=\"{0}\"", css)));
            }

            return(String.Empty);
        }
Exemplo n.º 13
0
        public void InitAdapter(Item item, ID propId)
        {
            Url = string.Empty;
            Alt = string.Empty;

            ImageField image = item.Fields[propId];

            if (image == null || image.MediaID == ItemIDs.Null)
            {
                return;
            }

            var mediaItem = image.MediaDatabase.GetItem(image.MediaID);

            Url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
            Alt = image.Alt;
        }
Exemplo n.º 14
0
        public List <Event> PopulateEventList(MultilistField eventListField)
        {
            Item[]       eventItems = eventListField.GetItems();
            List <Event> eventList  = new List <Event>();

            if (eventItems != null && eventItems.Count() > 0)
            {
                foreach (Item ev in eventItems)
                {
                    Event e         = new Event();
                    Item  eventItem = Sitecore.Context.Database.GetItem(ev.ID);
                    e.EventName = eventItem.Fields[Templates.Event.Fields.EventName.ToString()].Value;
                    CheckboxField isFeaturedEventField = eventItem.Fields[Templates.Event.Fields.IsFeaturedEvent];
                    e.IsFeaturedEvent = isFeaturedEventField.Checked;
                    DateField eventDateField = eventItem.Fields[Templates.Event.Fields.EventDate];
                    e.EventDate       = eventDateField.DateTime.ToLocalTime();
                    e.EventDateString = eventDateField.DateTime.ToLocalTime().ToString("f");
                    e.EventTimeString = eventDateField.DateTime.ToLocalTime().ToString("t");

                    //TreelistEx
                    MultilistField eventArtistsField = eventItem.Fields[Templates.Event.Fields.EventArtists];
                    Item[]         eventArtistItems  = eventArtistsField.GetItems();
                    List <Artist>  eventArtistList   = new List <Artist>();
                    if (eventArtistItems != null && eventArtistItems.Count() > 0)
                    {
                        foreach (Item sp in eventArtistItems)
                        {
                            Artist artist     = new Artist();
                            Item   artistItem = Sitecore.Context.Database.GetItem(sp.ID);
                            artist.ArtistName = artistItem.Fields[Templates.Artist.Fields.ArtistName.ToString()].Value;
                            ImageField artistImage = artistItem.Fields[Templates.Artist.Fields.ArtistImage];
                            artist.ArtistImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(artistImage.MediaItem);
                            artist.ArtistImageAlt = artistImage.Alt;

                            eventArtistList.Add(artist);
                        }

                        e.EventArtists = eventArtistList;
                    }

                    eventList.Add(e);
                }
            }

            return(eventList);
        }
Exemplo n.º 15
0
        public static bool AttachImageToItem(BaseDataMap map, object importRow, Item newItem, string newItemField, MediaItem imageItem, ref LevelLogger logger, string height = null, string width = null)
        {
            var attachImageLogger = logger.CreateLevelLogger();

            if (imageItem != null)
            {
                if (string.IsNullOrEmpty(newItemField))
                {
                    {
                        attachImageLogger.AddError(NewItemFieldIsNotDefinedForMediaitem, String.Format("NewItemField is not defined for mediaitem: {0}.",
                                                                                                       map.GetImportRowDebugInfo(importRow)));
                        return(false);
                    }
                }
                if (!newItem.Editing.IsEditing)
                {
                    newItem.Editing.BeginEdit();
                }
                ImageField imageField = newItem.Fields[newItemField];
                if (imageField.MediaID != imageItem.ID)
                {
                    imageField.Clear();
                    imageField.MediaID = imageItem.ID;
                    if (!String.IsNullOrEmpty(height))
                    {
                        imageField.Height = height;
                    }
                    if (!String.IsNullOrEmpty(width))
                    {
                        imageField.Width = width;
                    }

                    if (!String.IsNullOrEmpty(imageItem.Alt))
                    {
                        imageField.Alt = imageItem.Alt;
                    }
                    else
                    {
                        imageField.Alt = imageItem.DisplayName;
                    }
                    return(true);
                }
            }
            return(false);
        }
        public override object GetField(Field field, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            var sitecoreImage = new ImageField(field);
            var defaultImage  = new AdvancedImageField();

            if (sitecoreImage.Value.IsEmptyOrNull())
            {
                return(defaultImage);
            }

            var xml = new XmlDocument();

            xml.LoadXml(sitecoreImage.Value);

            var resultImage = AdvancedImageHelper.ConvertMediaItemToField(xml.DocumentElement, field.Database);

            return(resultImage ?? defaultImage);
        }
        public IEnterspeedProperty Convert(Item item, Field field, EnterspeedSiteInfo siteInfo, List <IEnterspeedFieldValueConverter> fieldValueConverters)
        {
            ImageField imageField = field;

            if (imageField?.MediaItem == null)
            {
                return(null);
            }

            string mediaUrl = _urlService.GetMediaUrl(imageField.MediaItem);

            if (string.IsNullOrEmpty(mediaUrl))
            {
                return(null);
            }

            return(new StringEnterspeedProperty(_fieldService.GetFieldName(field), mediaUrl));
        }
Exemplo n.º 18
0
        /// <summary>
        /// </summary>
        /// <param name="item"></param>
        /// <param name="fieldName"></param>
        /// <param name="includeServerUrl"></param>
        /// <param name="ensureMediaUrlPrefix"></param>
        /// <returns></returns>
        public static string GetMediaItemUrl(Item item, string fieldName, bool includeServerUrl,
                                             bool ensureMediaUrlPrefix = false)
        {
            ImageField imgField = item?.Fields[fieldName];

            if (imgField?.MediaItem == null)
            {
                return(string.Empty);
            }
            var image = new MediaItem(imgField.MediaItem);
            var m     = new MediaUrlOptions
            {
                AlwaysIncludeServerUrl = includeServerUrl
            };
            var mediaUrl = MediaManager.GetMediaUrl(image, m);

            return(ensureMediaUrlPrefix ? Sitecore.StringUtil.EnsurePrefix('/', mediaUrl) : mediaUrl);
        }
Exemplo n.º 19
0
        public string BodyStyle()
        {
            Item pres = SiteConfiguration.GetPresentationSettingsItem();

            if (pres != null)
            {
                if (pres["Background Image"] != string.Empty)
                {
                    ImageField imgField = ((Sitecore.Data.Fields.ImageField)pres.Fields["Background Image"]);
                    return(String.Format("background-image: url('{0}')", MediaManager.GetMediaUrl(imgField.MediaItem)));
                }
                else if (pres["Background Color"] != string.Empty)
                {
                    return(String.Format("background-color: {0}", pres["Background Color"]));
                }
            }
            return(null);
        }
        public override void SetValue(global::Sitecore.Data.Items.Item item, object value, ISitecoreService service)
        {
            Image      img   = value as Image;
            ImageField scImg = new ImageField(item.Fields[FieldName]);

            if (img == null)
            {
                scImg.Clear();
                return;
            }

            if (scImg.MediaID.Guid != img.MediaId)
            {
                //this only handles empty guids, but do we need to remove the link before adding a new one?
                if (img.MediaId == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, scImg.MediaItem.Database.Name, scImg.MediaID, scImg.MediaPath);
                    scImg.RemoveLink(link);
                }
                else
                {
                    ID   newId  = new ID(img.MediaId);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        scImg.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        scImg.UpdateLink(link);
                    }
                    else
                    {
                        throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId));
                    }
                }
            }

            scImg.Height = img.Height.ToString();
            scImg.Width  = img.Width.ToString();
            scImg.HSpace = img.HSpace.ToString();
            scImg.VSpace = img.VSpace.ToString();
            scImg.Alt    = img.Alt;
            scImg.Border = img.Border;
            scImg.Class  = img.Class;
        }
Exemplo n.º 21
0
        public ActionResult EventSchedule()
        {
            if (Sitecore.Context.Item == null)
            {
                return(null);
            }

            var dataSourceId = Sitecore.Context.Item.ID.ToString();

            Assert.IsNotNullOrEmpty(dataSourceId, "dataSourceId is null or empty");
            var item = Sitecore.Context.Database.GetItem(dataSourceId);

            if (item == null)
            {
                return(null);
            }

            EventSchedule eventSchedule = new EventSchedule();

            //Background Image
            ImageField eventScheduleBackgroundImageField = item.Fields[Templates.EventSchedule.Fields.EventScheduleBackground];

            eventSchedule.EventScheduleBgImgUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(eventScheduleBackgroundImageField.MediaItem);

            EventHelpers helpers = new EventHelpers();

            //Multilist
            MultilistField day1EventsListField = item.Fields[Templates.EventSchedule.Fields.EventScheduleDay1Events];

            eventSchedule.EventScheduleDay1Events = helpers.PopulateEventList(day1EventsListField);

            //Date Field
            DateField day2DateField = item.Fields[Templates.EventSchedule.Fields.EventScheduleDay2Date];
            DateTime  day2DateTime  = day2DateField.DateTime;

            eventSchedule.EventScheduleDay2Date = day2DateTime.ToString("MMMM dd");

            //Multilist
            MultilistField day2EventsListField = item.Fields[Templates.EventSchedule.Fields.EventScheduleDay2Events];

            eventSchedule.EventScheduleDay2Events = helpers.PopulateEventList(day2EventsListField);

            return(View(eventSchedule));
        }
Exemplo n.º 22
0
        protected virtual void AdjustImageSize(ImageField imageField, float imageScale, int imageMaxWidth, int imageMaxHeight, ref int w, ref int h)
        {
            Assert.ArgumentNotNull(imageField, "imageField");
            var int1 = MainUtil.GetInt(imageField.Width, 0);
            var int2 = MainUtil.GetInt(imageField.Height, 0);

            if (int1 == 0 || int2 == 0)
            {
                return;
            }
            var size           = new Size(w, h);
            var imageSize      = new Size(int1, int2);
            var maxSize        = new Size(imageMaxWidth, imageMaxHeight);
            var finalImageSize = GetFinalImageSize(GetInitialImageSize(imageSize, imageScale, size), size,
                                                   maxSize);

            w = finalImageSize.Width;
            h = finalImageSize.Height;
        }
Exemplo n.º 23
0
        public static void _ImageFieldNullText(Page p)
        {
            LiteralControl lcb  = new LiteralControl(HtmlDiff.BEGIN_TAG);
            LiteralControl lce  = new LiteralControl(HtmlDiff.END_TAG);
            GridView       grid = new GridView();

            grid.DataSource = CreateDataSource(DatatableType.nullDS);
            ImageField field = new ImageField();

            field.NullDisplayText   = "NullDisplayText";
            field.DataImageUrlField = "Field";
            field.ReadOnly          = true;
            field.HeaderText        = "Data";
            grid.Columns.Add(field);
            p.Form.Controls.Add(lcb);
            p.Form.Controls.Add(grid);
            p.Form.Controls.Add(lce);
            grid.DataBind();
        }
Exemplo n.º 24
0
        public void CleanFileTest1()
        {
            using (var file = File.Open(testFileInvalid, FileMode.Open, FileAccess.Read))
            {
                var postedFile = new Mock <HttpPostedFileBase>();
                postedFile.Setup(foo => foo.FileName).Returns(Path.GetFileName(file.Name));
                postedFile.Setup(foo => foo.ContentType).Returns("text/plain");
                postedFile.Setup(foo => foo.ContentLength).Returns((int)file.Length);
                postedFile.Setup(foo => foo.InputStream).Returns(file);

                var target = new ImageField();

                // Test MaxSize property
                AssertExtras.Raises <ValidationException>(delegate()
                {
                    target.Clean(postedFile.Object);
                }).WithMessage("Upload a valid image. The file you uploaded was either not an image or a corrupted image.");
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Set value for Image field
        /// </summary>
        /// <param name="field">Sitecore Field</param>
        /// <param name="value">Path or ID of existing Sitecore Item</param>
        public static void SetImageValue(Field field, object value)
        {
            ImageField thisField = (ImageField)field;
            Item       item      = field.Database.GetItemFromValue(value);

            if (item != null)
            {
                MediaItem mediaItem = new MediaItem(item);
                thisField.MediaID = mediaItem.ID;
                if (!string.IsNullOrWhiteSpace(mediaItem.Alt))
                {
                    thisField.Alt = mediaItem.Alt;
                }
                else
                {
                    thisField.Alt = mediaItem.DisplayName;
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// get the url of the media item (e.g image)
        /// </summary>
        /// <param name="contextItem"></param>
        /// <param name="mediaItemFieldID"></param>
        /// <param name="includeServerURL"></param>
        /// <returns></returns>
        public static string GetMediaItemURL(Item contextItem, ID mediaItemFieldID, bool includeServerURL = false)
        {
            string mediaItemURL = string.Empty;

            if (contextItem != null && IsValidID(mediaItemFieldID) && ItemHasField(contextItem, mediaItemFieldID))
            {
                ImageField imageField = contextItem.Fields[mediaItemFieldID];

                if (imageField?.MediaItem != null)
                {
                    var             image = new MediaItem(imageField.MediaItem);
                    MediaUrlOptions muo   = new MediaUrlOptions();
                    muo.AlwaysIncludeServerUrl = includeServerURL;
                    mediaItemURL = MediaManager.GetMediaUrl(image, muo);
                }
            }

            return(mediaItemURL);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Computed field for image url
        /// </summary>
        /// <param name="indexable">IIndexable</param>
        /// <returns>object.</returns>
        public object ComputeFieldValue(IIndexable indexable)
        {
            Item item = null;

            try
            {
                item = indexable as SitecoreIndexableItem;
                if (item == null)
                {
                    return(null);
                }
                string formattedTemplateId = SearchHelper.FormatGuid(item.TemplateID.ToString());
                string imageUrl            = string.Empty;
                if (formattedTemplateId.Equals(SearchHelper.FormatGuid(CommonConstants.NewsTemplateID)) ||
                    formattedTemplateId.Equals(SearchHelper.FormatGuid(CommonConstants.ImageItemTemplateID)) ||
                    formattedTemplateId.Equals(SearchHelper.FormatGuid(CommonConstants.VideoItemTemplateID)) ||
                    formattedTemplateId.Equals(SearchHelper.FormatGuid(CommonConstants.DownloadItemTemplateID)))
                {
                    ImageField imageField = item.Fields["Image"];
                    if (SearchHelper.FormatGuid(item.TemplateID.ToString()).Equals(SearchHelper.FormatGuid(CommonConstants.NewsTemplateID)))
                    {
                        imageField = item.Fields["Banner"];
                    }


                    return(AdvancedImageHelper.GetImageFieldUrl(imageField, 0, 0).Replace("/sitecore/shell", ""));;
                }
            }

            catch (Exception ex)
            {
                string itemId = string.Empty;
                if (item != null)
                {
                    itemId = item.ID.ToString();
                }

                Sitecore.Diagnostics.Log.Error(GetType().Name + " - Item ID: " + itemId, ex, this);
            }

            return(null);
        }
Exemplo n.º 28
0
        public static string ImageUrl(this ImageField imageField)
        {
            if (imageField?.MediaItem == null)
            {
                throw new ArgumentNullException(nameof(imageField));
            }

            var options = MediaUrlOptions.Empty;

            if (int.TryParse(imageField.Width, out int width))
            {
                options.Width = width;
            }

            if (int.TryParse(imageField.Height, out int height))
            {
                options.Height = height;
            }
            return(imageField.ImageUrl(options));
        }
Exemplo n.º 29
0
        public NewsListModel(Item article)
        {
            this.Title   = article[Templates.NewsArticle.Fields.Title];
            this.Summary = article[Templates.NewsArticle.Fields.Summary];

            // TODO: add to constants or retrieve from settings/localization
            this.DetailsLink = new Glass.Mapper.Sc.Fields.Link()
            {
                Url = article.Url(), Text = "Read More"
            };
            ImageField imgField = string.IsNullOrEmpty(article[Templates.NewsArticle.Fields.ThumbnailImage]) ? article.Fields[Templates.NewsArticle.Fields.Image] : article.Fields[Templates.NewsArticle.Fields.ThumbnailImage];

            if (imgField != null && imgField.MediaItem != null)
            {
                this.BackgroundImage = Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(MediaManager.GetMediaUrl(imgField.MediaItem, new MediaUrlOptions()
                {
                    MaxWidth = 640
                }));
            }
        }
Exemplo n.º 30
0
        public object ComputeFieldValue(IIndexable indexable)
        {
            Item item = indexable as SitecoreIndexableItem;

            if (item != null && item.TemplateName == "Book")
            {
                ImageField thumb = item.Fields["Image"];
                if (thumb != null)
                {
                    Item mediaItem = thumb.MediaItem;
                    if (mediaItem != null)
                    {
                        MediaUrlOptions options = new MediaUrlOptions();
                        options.MaxHeight = MaxHeight;
                        return(Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem, options));
                    }
                }
            }
            return(null);
        }
Exemplo n.º 31
0
        public FieldSuiteImage(FieldSuiteImageArgs args) : base(args)
        {
            if (args.InnerItem.IsNull() || args.Node == null || args.Node.Attributes["imageField"] == null)
            {
                return;
            }

            string titleField = null;
            string imageField = args.Node.Attributes["imageField"].Value;

            if (args.Node.Attributes["titleField"] != null)
            {
                titleField = args.Node.Attributes["titleField"].Value;
            }

            //get title, fall back to display name
            Title = args.InnerItem.DisplayName;
            if (!string.IsNullOrEmpty(titleField))
            {
                Title = args.InnerItem[titleField];
            }

            //image field source
            ImageField imageFieldObject = args.InnerItem.Fields[imageField];

            if (imageFieldObject == null || imageFieldObject.MediaItem == null)
            {
                return;
            }

            MediaUrlOptions options = new MediaUrlOptions();

            options.AbsolutePath = true;
            options.UseItemPath  = true;

            ImageUrl = MediaManager.GetMediaUrl(imageFieldObject.MediaItem, options);
            if (string.IsNullOrEmpty(ImageUrl))
            {
                return;
            }
        }
Exemplo n.º 32
0
    /// <summary>
    /// Adds a column with images depicting the classes to the gridview parameter.
    /// </summary>
    /// <param name="memberDoc"></param>
    /// <param name="memberTypesDoc"></param>
    /// <param name="GridView2"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public static void getTypeColumn(XmlDocument memberDoc, XmlDocument memberTypesDoc, GridView GridView, int width, int height, int nameCell)
    {
        ImageField column = new ImageField();
        column.HeaderText = "Type";
        GridView.Columns.Add(column);

        for (int i = 0; i < GridView.Rows.Count; i++)
        {
            GridViewRow row = GridView.Rows[i];
            TableCell cell = row.Cells[row.Cells.Count - 1];
            string gangerName = row.Cells[nameCell].Text;
            string gangerType = "";
            string imageLink = "";

            foreach (XmlNode memberNode in memberDoc.LastChild.ChildNodes)
            {
                if (memberNode.Attributes["Name"].Value == gangerName)
                {
                    gangerType = memberNode.Name;
                    break;
                }
            }

            foreach (XmlNode typeNode in memberTypesDoc.LastChild.ChildNodes)
            {
                if (typeNode.Attributes["Name"].Value == gangerType)
                {
                    imageLink = typeNode.Attributes["Image"].Value;
                    break;
                }
            }

            System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
            image.Width = width;
            image.Height = height;
            image.ImageUrl = imageLink;
            image.ToolTip = gangerType;
            image.AlternateText = gangerType;
            cell.Controls.Add(image);
        }
    }
Exemplo n.º 33
0
    /// <summary>
    /// Associate an image to a certain image field of the item
    /// </summary>
    /// <param name="item"></param>
    /// <param name="imageFieldID"></param>
    /// <param name="imageItemToAssociate"></param>
    /// <param name="endEditingWhenExit">If the calling method is putting the item in editing mode already, set this to false.</param>
    public static void AssociateWithImage(this Item item, ID imageFieldID, Item imageItemToAssociate, bool endEditingWhenExit)
    {
        Assert.ArgumentNotNull(item, "item");

        if (imageItemToAssociate != null)
        {
            ImageField fld = item.Fields[imageFieldID];
            if (fld != null)
            {
                MediaItem mediaItem = (MediaItem)imageItemToAssociate;

                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    if ((fld.MediaItem != null && fld.MediaID != mediaItem.ID) ||
                        (fld.MediaItem == null || fld.MediaID.IsNull))
                    {
                        if (!item.Editing.IsEditing)
                        {
                            item.Editing.BeginEdit();
                        }

                        fld.MediaID = mediaItem.ID;
                        if (!string.IsNullOrWhiteSpace(mediaItem.Alt))
                        {
                            fld.Alt = mediaItem.Alt;
                        }
                        else
                        {
                            fld.Alt = mediaItem.Name;
                        }

                        if (endEditingWhenExit)
                        {
                            item.Editing.EndEdit();
                            item.Editing.AcceptChanges();
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 34
0
        public static void MapToField(ImageField field, Image image, Item item)
        {
            if (image == null)
            {
                field.Clear();
                return;
            }

            if (field.MediaID.Guid != image.MediaId)
            {
                //this only handles empty guids, but do we need to remove the link before adding a new one?
                if (image.MediaId == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, field.MediaItem.Database.Name, field.MediaID, field.MediaItem.Paths.Path);
                    field.RemoveLink(link);
                }
                else
                {
                    ID   newId  = new ID(image.MediaId);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        field.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        field.UpdateLink(link);
                    }
                    else
                    {
                        throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId));
                    }
                }
            }

            field.Height = image.Height.ToString();
            field.Width  = image.Width.ToString();
            field.HSpace = image.HSpace.ToString();
            field.VSpace = image.VSpace.ToString();
            field.Alt    = image.Alt;
            field.Border = image.Border;
            field.Class  = image.Class;
        }
        public static HtmlString RenderResponsivePicture(this SitecoreHelper helper, string fieldName, Item item = null, bool isEditable = false, List <Dimensions> dimensions = null)
        {
            if (item.Fields[fieldName] == null)
            {
                return(new HtmlString(string.Empty));
            }

            var mediaItem = new ImageField(item.Fields[fieldName]).MediaItem;

            if (mediaItem == null)
            {
                return(new HtmlString(string.Empty));
            }

            if (Sitecore.Context.PageMode.IsExperienceEditor)
            {
                return(helper.Field(fieldName, item));
            }

            return(GeneratePictureTag(dimensions, mediaItem));
        }
        private string GetWaterTypeImageUrl(WeatherTypes type)
        {
            var imageUrl = string.Empty;

            if (!MapperHelper.WeaterTypeToItemId.ContainsKey(type))
            {
                return(imageUrl);
            }

            var weaterTypeItem = Sitecore.Context.Database.GetItem(new ID(MapperHelper.WeaterTypeToItemId[type]));

            ImageField imageField = weaterTypeItem.Fields["image"];

            if (imageField?.MediaItem != null)
            {
                var image = new MediaItem(imageField.MediaItem);
                imageUrl = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image));
            }

            return(imageUrl);
        }
Exemplo n.º 37
0
        public void ImageField_AssignProperty()
        {
            ImageField field = new ImageField();

            field.AlternateText = "test";
            Assert.AreEqual("test", field.AlternateText, "AlternateText ");
            field.ConvertEmptyStringToNull = false;
            Assert.AreEqual(false, field.ConvertEmptyStringToNull, "ConvertEmptyStringToNull");
            field.DataAlternateTextField = "test";
            Assert.AreEqual("test", field.DataAlternateTextField, "DataAlternateTextField");
            field.DataImageUrlField = "test";
            Assert.AreEqual("test", field.DataImageUrlField, "DataImageUrlField");
            field.DataImageUrlFormatString = "test";
            Assert.AreEqual("test", field.DataImageUrlFormatString, "DataImageUrlFormatString");
            field.NullDisplayText = "test";
            Assert.AreEqual("test", field.NullDisplayText, "NullDisplayText");
            field.NullImageUrl = "test";
            Assert.AreEqual("test", field.NullImageUrl, "NullImageUrl");
            field.ReadOnly = true;
            Assert.AreEqual(true, field.ReadOnly, "ReadOnly");
        }
Exemplo n.º 38
0
        public HeaderViewModel BuildHeaderViewModel(Item mainItem)
        {
            HeaderViewModel headerViewModel = new HeaderViewModel();

            var childList  = mainItem.GetChildren();
            var headerItem = childList.FirstOrDefault(x => x.TemplateName == "Header");

            string     url        = string.Empty;
            ImageField imageField = headerItem.Fields["Logo"];

            if (imageField != null && imageField.MediaItem != null)
            {
                MediaItem media = new MediaItem(imageField.MediaItem);
                url = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(media));
            }

            headerViewModel.Name    = headerItem.Fields["Name"].Value;
            headerViewModel.URLLogo = url;

            return(headerViewModel);
        }
        public override object GetField(Field field, SitecoreFieldConfiguration config,
            SitecoreDataMappingContext context)
        {
            ImageField field1 = new ImageField(field);

            ExifImage img;

            // if there is a target media item then we use Glass to create a concrete version 
            // of that using it's standard field mappings. Otherwise we just use a blank copy.
            if (field1.MediaItem == null)
            {
                img = new ExifImage();
            }
            else
            {
                img = context.Service.CreateType<ExifImage>(field1.MediaItem);
            }

            //with the new populated class we then populate the image with specific field values.
            SitecoreFieldImageMapper.MapToImage(img, field1);
            
            return (object) img;
        }
Exemplo n.º 40
0
 public _min.Models.ColumnField Create(DataColumn column)
 {
     ImageField imf = new ImageField(column.ColumnName, column.ColumnName);
     imf.MainDirectory = mainPath;
     imf.ThumbDirectory = thumbPath;
     imf.FullWidth = fullWidth;
     imf.ThumbWidth = thumbWidth;
     imf.TargetFormat = targetFormat;
     return imf;
 }
 private static MediaItem GetMediaItem(string fieldName, Item item)
 {
     if (item == null || item.Fields[fieldName] == null)
     {
         return null;
     }
     var imageField = new ImageField(item.Fields[fieldName]);
     if (imageField.MediaItem == null)
     {
         return null;
     }
     return imageField.MediaItem;
 }
        /// <summary>
        /// Gets the media URL.
        /// </summary>
        /// <returns></returns>
        public static string GetMediaUrl(ImageField imageField)
        {
            if (imageField == null)
                return string.Empty;
            var mediaItem = imageField.MediaItem;
            if (mediaItem == null)
                return string.Empty;

            //var options = CustomMediaUrlOptions.GetMediaUrlOptions(mediaItem);
            var options = CustomMediaUrlOptions.Empty;

            int height;
            if (int.TryParse(imageField.Height, out height))
            {
                options.Height = height;
            }

            int width;
            if (int.TryParse(imageField.Width, out width))
            {
                options.Width = width;
            }

            options.Language = mediaItem.Language;
            options.UseDefaultIcon = true;

            return GetMediaUrl(imageField, options);
        }
Exemplo n.º 43
0
        public void SetItem_Test2()
        {
            //Assign 
            //clear all fields
            using (new SecurityDisabler())
            {
                _test2.BeginEdit();
                foreach (Field field in _test2.Fields)
                {
                    field.Value = "";
                }
                _test2["GroupedDropList"] = "Test2";
                _test2["DropList"] = "Test2";
                _test2.EndEdit();
            }
            
            MiscFixtureNS.BasicTemplate test = 
                _sitecore.GetItem<MiscFixtureNS.BasicTemplate>("/sitecore/content/Glass/Test2");
            
            //Simple Types

            test.Checkbox = true;
            test.Date = new DateTime(2011, 02, 28);
            test.DateTime = new DateTime(2011, 03, 04, 15, 23, 12);
            test.File = new File() { Id = new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}") };
            test.Image = new Image()
            {
                Alt="Test Alt",
                Border = "Test Border",
                Class="Test Class",
                Height=487,
                HSpace=52,
                MediaId = new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"),
                VSpace= 32,
                Width = 26
            };
            test.Integer = 659;
            test.Float = 458.7f;
            test.Double = 789.5d;
            test.Decimal = 986.4m;
            test.MultiLineText = "Test MultiLineText";
            test.Number = 986;
            test.Password = "******";
            test.RichText = "test Rich Text";
            test.SingleLineText = "test single line text";

            //List Types
            test.CheckList = new MiscFixtureNS.SubClass[]{
                new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid},
                new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid},
            };
            test.DropList = MiscFixtureNS.TestEnum.Test3;
            test.GroupedDropLink = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.GroupedDropList = MiscFixtureNS.TestEnum.Test3;
            test.MultiList = new MiscFixtureNS.SubClass[]{
                new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid},
                new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid},
            };
            test.Treelist = new MiscFixtureNS.SubClass[]{
                new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid},
                new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid},
            };
            test.TreeListEx = new MiscFixtureNS.SubClass[]{
                new MiscFixtureNS.SubClass(){Id = _test1.ID.Guid},
                new MiscFixtureNS.SubClass(){Id = _test2.ID.Guid},
            };

            //Link Types 
            test.DropLink = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.DropTree = new MiscFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.GeneralLink = new Link(){
                Type = LinkType.External,
                Anchor="test anchor",
                Class="test class",
                Target="test target",
                Text="test text",
                Title="test title",
                Url="test url"
            };

            //Developer Types
            test.Icon = "test icon";
            test.TriState = TriState.Yes;


            //Act
            using (new SecurityDisabler())
            {
                _sitecore.Save<MiscFixtureNS.BasicTemplate>(test);
            }
            
            //Assert

            //Simple Types
            Item result = _db.GetItem(_test2.ID);
            Assert.AreEqual("1", result["Checkbox"]);
            Assert.AreEqual("20110228T000000", result["Date"]);
            Assert.AreEqual("20110304T152312", result["DateTime"]);
          
            var file = new FileField(result.Fields["File"]);
            Assert.AreEqual(new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}"), file.MediaID.Guid);
            Assert.AreEqual("/~/media/Files/SimpleTextFile2.ashx", file.Src);
           
            var image = new ImageField(result.Fields["Image"]);
            Assert.AreEqual("Test Alt", image.Alt);
            Assert.AreEqual("Test Border", image.Border);
            Assert.AreEqual("Test Class", image.Class);
            Assert.AreEqual("487", image.Height);
            Assert.AreEqual("52", image.HSpace);
            Assert.AreEqual(new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), image.MediaID.Guid);
            Assert.AreEqual("/~/media/Files/Kitten2.ashx", image.Src);
            Assert.AreEqual("32", image.VSpace);
            Assert.AreEqual("26", image.Width);

            Assert.AreEqual("659", result["Integer"]);
            Assert.AreEqual("458.7", result["Float"]);
            Assert.AreEqual("789.5", result["Double"]);
            Assert.AreEqual("986.4", result["Decimal"]);
            Assert.AreEqual("Test MultiLineText", result["MultiLineText"]);
            Assert.AreEqual("986", result["Number"]);
            Assert.AreEqual("test password", result["Password"]);
            Assert.AreEqual("test Rich Text", result["RichText"]);
            Assert.AreEqual("test single line text", result["SingleLineText"]);
            
            //List Types

            Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["CheckList"].ToUpper());
            Assert.AreEqual("Test3", result["DropList"]);
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["GroupedDropLink"].ToUpper());
            Assert.AreEqual("Test3", result["GroupedDropList"]);
            Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["MultiList"].ToUpper());
            Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["Treelist"].ToUpper());
            Assert.AreEqual("{BD193B3A-D3CA-49B4-BF7A-2A61ED77F19D}|{8A317CBA-81D4-4F9E-9953-64C4084AECCA}", result["TreeListEx"].ToUpper());

            //Linked Types
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropLink"].ToUpper());
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropTree"].ToUpper());
            LinkField link = new LinkField(result.Fields["GeneralLink"]);
            Assert.AreEqual("test class", link.Class);
            Assert.AreEqual("test target", link.Target);
            Assert.AreEqual("test text", link.Text);
            Assert.AreEqual("test title", link.Title);
            Assert.AreEqual("test url", link.Url);

            //Developer Type

            Assert.AreEqual("test icon", result["Icon"]);
            Assert.AreEqual("1", result["TriState"]);

        }
 public ExtendedCustomImageField(Item item, ImageField field)
     : base(item, field)
 {
 }
Exemplo n.º 45
0
        /// <summary>
        /// Returns the dimension of a media item given as an Sitecore ImageField
        /// </summary>
        public static Dimensions GetMediaItemSize(ImageField field)
        {
            int width = 0;
            int height = 0;

            try
            {
                width = int.Parse(field.Width);
                height = int.Parse(field.Height);
            }
            catch (Exception) { }

            return new Dimensions(width, height);
        }
 public override string Import(Field field, Item item, ILanguage language, string value)
 {
     var imageField = new ImageField(field);
     return imageField.MediaItem?.Paths.Path ?? value;
 }
        public override void Initialize(Rendering rendering)
        {
            base.Initialize(rendering);

            ArticleDate = rendering.Item.Fields["ArticleDate"];
            HeaderImage = rendering.Item.Fields["HeaderImage"];
            _RelatedArticles = rendering.Item.Fields["RelatedArticles"];
            Summary = rendering.Item["Summary"];
            SummaryImage = rendering.Item.Fields["SummaryImage"];
        }
        public void SetValue_EmptyGuid()
        {
            SitecoreProperty property = new SitecoreProperty()
            {
                Attribute = new SitecoreFieldAttribute(),
                Property = new FakePropertyInfo(typeof(Image), "Image")
            };

            _handler.ConfigureDataHandler(property);


            Item item = _db.GetItem(new ID(_itemId));

            Image img = new Image()
            {
                Alt = "New alt",
                Border = "New Border",
                Class = "New Class",
                Height = 70,
                HSpace = 90,
                MediaId = Guid.Empty,
                VSpace = 200,
                Width = 567

            };

            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                //Act
                _handler.SetValue( item, img, null);


                //Assert
                ImageField field = new ImageField(item.Fields["Image"]);

                Assert.AreEqual(img.Alt, field.Alt);
                Assert.AreEqual(img.Border, field.Border);
                Assert.AreEqual(img.Class, field.Class);
                Assert.AreEqual(img.Height.ToString(), field.Height);
                Assert.AreEqual(img.HSpace.ToString(), field.HSpace);
                Assert.AreEqual(null, field.MediaItem);
                Assert.AreEqual(img.VSpace.ToString(), field.VSpace);
                Assert.AreEqual(img.Width.ToString(), field.Width);

                item.Editing.CancelEdit();
            }
        }
        public void SetValue_SaveDataCorrectly()
        {
            //Assign
            // /sitecore/media library/Files/DSC01034
            ID newMediaId = new ID(new Guid("{210FAF49-5AA4-471E-BBFE-B4D3ACB6ADC0}"));
            SitecoreProperty property = new SitecoreProperty()
            {
                Attribute = new SitecoreFieldAttribute(),
                Property = new FakePropertyInfo(typeof(Image), "Image")
            };

            _handler.ConfigureDataHandler(property);


            Item item = _db.GetItem(new ID(_itemId));

            Image img = new Image()
            {
                Alt = "New alt",
                Border = "New Border",
                Class = "New Class",
                Height = 70,
                HSpace = 90,
                MediaId = newMediaId.Guid,
                VSpace = 200,
                Width = 567

            };

            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                //Act
                _handler.SetValue( item, img, null);


                //Assert
                ImageField field = new ImageField(item.Fields["Image"]);

                Assert.AreEqual(img.Alt, field.Alt);
                Assert.AreEqual(img.Border, field.Border);
                Assert.AreEqual(img.Class, field.Class);
                Assert.AreEqual(img.Height.ToString(), field.Height);
                Assert.AreEqual(img.HSpace.ToString(), field.HSpace);
                Assert.AreEqual(img.MediaId, field.MediaItem.ID.Guid);
                Assert.AreEqual(img.VSpace.ToString(), field.VSpace);
                Assert.AreEqual(img.Width.ToString(), field.Width);

                item.Editing.CancelEdit();
            }



        }
    private void FillGridView(string p, bool reloadFile)
    {
        if (Unified == null || reloadFile)
            Unified = new ResXUnified(p);

        gridView.Columns.Clear();

        SortedList<string, string> langs = Unified.GetLanguages();

        Unit columnSize = new Unit((gridView.Width.Value - 30) / (langs.Values.Count), UnitType.Pixel);

        ImageField keyColumn = new ImageField();
        keyColumn.HeaderText = "Key";
        keyColumn.DataAlternateTextField = "Key";
        keyColumn.DataImageUrlField = "Key";
        keyColumn.DataImageUrlFormatString = "~/images/information.png"; // ignore key
        //keyColumn.DataField = "Key";
        //keyColumn.ItemStyle.BackColor = Color.Gray;
        //keyColumn.ItemStyle.ForeColor = Color.White;
        keyColumn.ReadOnly = true;
        keyColumn.ItemStyle.Width = new Unit(30);
        keyColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
        keyColumn.ControlStyle.Width = new Unit(16);
        gridView.Columns.Add(keyColumn);

        foreach (string lang in langs.Values)
        {
            BoundField field = new BoundField();
            CultureInfo culture = null;
            try { culture = new CultureInfo(lang); }
            catch { }
            if (culture != null)
                field.HeaderText = culture.DisplayName;
            else
                field.HeaderText = "Default";

            field.DataField = lang;
            field.ItemStyle.Width = columnSize;
            field.ControlStyle.Width = columnSize;

            gridView.Columns.Add(field);
        }

        gridView.DataSource = Unified.ToDataTable(!chShowEmpty.Checked);
        gridView.DataBind();
    }
        /// <summary>
        /// Gets the media URL.
        /// </summary>
        /// <param name="imageField">The image field.</param>
        /// <param name="options">The options.</param>
        /// <returns></returns>
        public static string GetMediaUrl(ImageField imageField, CustomMediaUrlOptions options)
        {
            if (imageField == null)
                return string.Empty;
            var mediaItem = imageField.MediaItem;
            if (mediaItem == null)
                return string.Empty;

            string cropRegion = HttpUtility.HtmlEncode(new XmlValue(imageField.Value, "image").GetAttribute("cropregion"));
            if (!string.IsNullOrEmpty(cropRegion))
            {
                try
                {
                    options.CropRegion = cropRegion;
                    var coordinates = ConvertToIntArray(cropRegion);
                    if (options.Width + options.Height > (coordinates[2] - coordinates[0] + coordinates[3] + coordinates[1]))
                    {
                        options.Width = coordinates[2] - coordinates[0];
                        options.Height = coordinates[3] + coordinates[1];
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message, ex, typeof(CustomMediaManager));
                }
            }
            if (!Settings.Media.RequestProtection.Enabled || imageField.InnerField.Name.StartsWith("__"))
                return GetMediaUrl(mediaItem, options); 
            return HashingUtils.ProtectAssetUrl(GetMediaUrl(mediaItem, options));
        }
 /// <summary>
 /// Add to image field
 /// </summary>
 /// <param name="field"></param>
 /// <param name="mediaItem"></param>
 public void AssignMediaItem(ImageField field, Item mediaItem)
 {
     field.MediaID = mediaItem.ID;
     field.SetAttribute("mediapath", mediaItem.Paths.MediaPath);
     field.SetAttribute("showineditor", "1");
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="ImageProperty"/> class.
		/// </summary>
		/// <param name="field">The field to wrap.</param>
		public ImageProperty(Field field)
			: base(field)
		{
			this.imageField = field;
		}
        /// <summary>
        /// Sets the field.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="Glass.Mapper.MapperException">No item with ID {0}. Can not update Media Item field.Formatted(newId)</exception>
        public override void SetField(Field field, object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            Image img = value as Image;
            var item = field.Item;

            if (field == null) return;

            ImageField scImg = new ImageField(field);

            MapToField(scImg, img, item);
        }
        public static void MapToField(ImageField field, Image image, Item item)
        {
            if (image == null)
            {
                field.Clear();
                return;
            }

            if (field.MediaID.Guid != image.MediaId)
            {
                //this only handles empty guids, but do we need to remove the link before adding a new one?
                if (image.MediaId == Guid.Empty)
                {
                    ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, field.MediaItem.Database.Name, field.MediaID, field.MediaItem.Paths.Path);
                    field.RemoveLink(link);
                }
                else
                {
                    ID newId = new ID(image.MediaId);
                    Item target = item.Database.GetItem(newId);
                    if (target != null)
                    {
                        field.MediaID = newId;
                        ItemLink link = new ItemLink(item.Database.Name, item.ID, field.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath);
                        field.UpdateLink(link);

                    }
                    else throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId));
                }
            }

            if (image.Height > 0)
                field.Height = image.Height.ToString();
            if (image.Width > 0)
                field.Width = image.Width.ToString();
            if (image.HSpace > 0)
                field.HSpace = image.HSpace.ToString();
            if (image.VSpace > 0)
                field.VSpace = image.VSpace.ToString();

            if (field.Alt.IsNotNullOrEmpty() || image.Alt.IsNotNullOrEmpty())
                field.Alt = image.Alt ?? string.Empty;
            if (field.Border.IsNotNullOrEmpty() || image.Border.IsNotNullOrEmpty())
                field.Border = image.Border ?? string.Empty;
            if (field.Class.IsNotNullOrEmpty() || image.Class.IsNotNullOrEmpty())
                field.Class = image.Class ?? string.Empty;
        }
Exemplo n.º 56
0
		protected IStorageImageField CreateEmptyImageFieldObject(ImageField field)
		{
			var storageService = service.StorageService;
			return (IStorageImageField)storageService.GetObjectFactory().CreateEmptyFieldObject(field.GetType());
		}
Exemplo n.º 57
0
        /// <summary>
        /// Creates an entire image tag for the specified ImageField, or returns an empty String if no image was found.  This is a substitute for
        /// sc:Image; unlike that control, this one will not plug in hard width and height values, which cause problems in responsive designs.
        /// </summary>
        /// <param name="imageField">The ImageField to use</param>
        /// <param name="cssClass">An optional cssClass.  If specified, this will override any class already attached to the ImageField</param>
        /// <returns></returns>
        public static String GetImageTagForImageField(ImageField imageField, String cssClass = "")
        {
            if (null != imageField && null != imageField.MediaItem)
            {
                var image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
                String src = MediaManager.GetMediaUrl(image, new MediaUrlOptions());
                String alt = imageField.Alt;
                String css = (String.IsNullOrEmpty(cssClass) ? imageField.Class : cssClass);

                return String.Format("<img src=\"{0}\" alt=\"{1}\" {2}>",
                    src,
                    alt,
                    String.IsNullOrEmpty(css) ? String.Empty : String.Format("class=\"{0}\"", css));
            }

            return String.Empty;
        }
Exemplo n.º 58
0
        /// <summary>
        /// Initialize the collection of shape fields associated with this shape type.
        /// </summary>
        protected override void InitializeShapeFields(global::System.Collections.Generic.IList<ShapeField> shapeFields)
        {
            base.InitializeShapeFields(shapeFields);

            ImageField titleIconField = new ImageField("WidgetTitleIcon");
            titleIconField.DefaultSelectable = false;
            titleIconField.DefaultFocusable = false;
            //titleIconField.DefaultImage = ImageHelper.GetImage(MVCViewDesignerDomainModel.SingletonResourceManager.GetObject("GridLayoutToolToolboxBitmap"));
            titleIconField.AnchoringBehavior.SetTopAnchor(AnchoringBehavior.Edge.Top, 0.02);
            titleIconField.AnchoringBehavior.SetLeftAnchor(AnchoringBehavior.Edge.Left, 0.02);
            shapeFields.Add(titleIconField);

            TextField titleTextField = new TextField("WidgetTitleText");
            titleTextField.DefaultText = string.Empty;
            titleTextField.DefaultFocusable = true;
            titleTextField.DefaultAutoSize = true;
            titleTextField.AnchoringBehavior.MinimumHeightInLines = 1;
            titleTextField.AnchoringBehavior.MinimumWidthInCharacters = 1;
            titleTextField.DefaultAccessibleState = global::System.Windows.Forms.AccessibleStates.Invisible;
            titleTextField.AnchoringBehavior.SetTopAnchor(AnchoringBehavior.Edge.Top, 0.02);
            titleTextField.AnchoringBehavior.SetLeftAnchor(titleIconField, AnchoringBehavior.Edge.Right, 0.02);
            titleTextField.DefaultFontId = new StyleSetResourceId(string.Empty, "ShapeTextBold9");
            shapeFields.Add(titleTextField);

            // more title icons
            ShapeField leftSibling = titleTextField;
            for (int i = 0; i < ADDITIONAL_TITLE_ICON_COUNT; i++)
            {
                VDTitleImageField moreTitleIconField = new VDTitleImageField("WidgetTitleIcon" + i, i);
                moreTitleIconField.DefaultSelectable = false;
                moreTitleIconField.DefaultFocusable = false;
                moreTitleIconField.AnchoringBehavior.SetTopAnchor(AnchoringBehavior.Edge.Top, 0.02);
                moreTitleIconField.AnchoringBehavior.SetLeftAnchor(leftSibling, AnchoringBehavior.Edge.Right, 0.02);
                shapeFields.Add(moreTitleIconField);
                leftSibling = moreTitleIconField;
            }

            PinButtonField pinField = new PinButtonField("WidgetTitlePinIcon");
            pinField.AnchoringBehavior.SetTopAnchor(AnchoringBehavior.Edge.Top, 0.02);
            pinField.AnchoringBehavior.SetRightAnchor(AnchoringBehavior.Edge.Right, 0.02);
            pinField.DefaultSelectable = false;
            pinField.DefaultFocusable = false;
            shapeFields.Add(pinField);
        }
        public void SetItem_Test2()
        {
            //Assign 
            //clear all fields
            var clearItem = _db.GetItem("/sitecore/content/Configuration/Fluent/GeneralFluent/SetItemTest2");

            using (new SecurityDisabler())
            {
                clearItem.BeginEdit();
                foreach (Field field in clearItem.Fields)
                {
                    field.Value = "";
                }
                clearItem["GroupedDropList"] = "Test2";
                clearItem["DropList"] = "Test2";
                clearItem.EndEdit();
            }

            GeneralFluentFixtureNS.BasicTemplate test;
            using (new SecurityDisabler())
            {
               test =
                    _sitecore.GetItem<GeneralFluentFixtureNS.BasicTemplate>("/sitecore/content/Configuration/Fluent/GeneralFluent/SetItemTest2");

            }
            //Simple Types

            test.Checkbox = true;
            test.Date = new DateTime(2011, 02, 28);
            test.DateTime = new DateTime(2011, 03, 04, 15, 23, 12);
            test.File = new File() { Id = new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}") };
            test.Image = new Image()
            {
                Alt="Test Alt",
                Border = "Test Border",
                Class="Test Class",
                Height=487,
                HSpace=52,
                MediaId = new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"),
                VSpace= 32,
                Width = 26
            };
            test.Integer = 659;
            test.Float = 458.7f;
            test.Double = 789.5d;
            test.Decimal = 986.4m;
            test.MultiLineText = "Test MultiLineText";
            test.Number = 986;
            test.Password = "******";
            test.RichText = "test Rich Text";
            test.SingleLineText = "test single line text";

            //List Types
            test.CheckList = new GeneralFluentFixtureNS.SubClass[]{
                new GeneralFluentFixtureNS.SubClass(){Id = _check1.ID.Guid},
                new GeneralFluentFixtureNS.SubClass(){Id = _check2.ID.Guid},
            };
            test.DropList = GeneralFluentFixtureNS.TestEnum.Test3;
            test.GroupedDropLink = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.GroupedDropList = GeneralFluentFixtureNS.TestEnum.Test3;
            test.MultiList = new GeneralFluentFixtureNS.SubClass[]{
                new GeneralFluentFixtureNS.SubClass(){Id = _multiList1.ID.Guid},
                new GeneralFluentFixtureNS.SubClass(){Id = _multiList2.ID.Guid},
            };
            test.Treelist = new GeneralFluentFixtureNS.SubClass[]{
                new GeneralFluentFixtureNS.SubClass(){Id = _treeList1.ID.Guid},
                new GeneralFluentFixtureNS.SubClass(){Id = _treeList2.ID.Guid},
            };
            test.TreeListEx = new GeneralFluentFixtureNS.SubClass[]{
                new GeneralFluentFixtureNS.SubClass(){Id = _treeList1.ID.Guid},
            };

            //Link Types 
            test.DropLink = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.DropTree = new GeneralFluentFixtureNS.SubClass() { Id = _test3.ID.Guid };
            test.GeneralLink = new Link(){
                Type = LinkType.External,
                Anchor="test anchor",
                Class="test class",
                Target="test target",
                Text="test text",
                Title="test title",
                Url="test url"
            };

            //Developer Types
            test.Icon = "test icon";
            test.TriState = TriState.Yes;


            //Act
            using (new SecurityDisabler())
            {
                _sitecore.Save<GeneralFluentFixtureNS.BasicTemplate>(test);
            }
            
            //Assert

            //Simple Types
            Item result = _db.GetItem(clearItem.ID);
            Assert.AreEqual("1", result["Checkbox"]);
            Assert.AreEqual("20110228T000000", result["Date"]);
            Assert.AreEqual("20110304T152312", result["DateTime"]);
          
            var file = new FileField(result.Fields["File"]);
            Assert.AreEqual(new Guid("{B89EA3C6-C947-44AF-9AEF-7EF89CEB0A4B}"), file.MediaID.Guid);
            Assert.AreEqual("/~/media/Files/SimpleTextFile2.ashx", file.Src);
           
            var image = new ImageField(result.Fields["Image"]);
            Assert.AreEqual("Test Alt", image.Alt);
            Assert.AreEqual("Test Border", image.Border);
            Assert.AreEqual("Test Class", image.Class);
            Assert.AreEqual("487", image.Height);
            Assert.AreEqual("52", image.HSpace);
            Assert.AreEqual(new Guid("{0CF0A6D0-8A2B-479B-AD8F-14938135174A}"), image.MediaID.Guid);
            Assert.AreEqual("/~/media/Files/Kitten2.ashx", image.Src);
            Assert.AreEqual("32", image.VSpace);
            Assert.AreEqual("26", image.Width);

            Assert.AreEqual("659", result["Integer"]);
            Assert.AreEqual("458.7", result["Float"]);
            Assert.AreEqual("789.5", result["Double"]);
            Assert.AreEqual("986.4", result["Decimal"]);
            Assert.AreEqual("Test MultiLineText", result["MultiLineText"]);
            Assert.AreEqual("986", result["Number"]);
            Assert.AreEqual("test password", result["Password"]);
            Assert.AreEqual("test Rich Text", result["RichText"]);
            Assert.AreEqual("test single line text", result["SingleLineText"]);
            
            //List Types

            Assert.AreEqual("{68B87391-CFF7-4FF2-848E-90C8FD8336A2}|{154CABCB-9B04-449A-9F6F-8FD2AD0783D9}", result["CheckList"].ToUpper());
            Assert.AreEqual("Test3", result["DropList"]);
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["GroupedDropLink"].ToUpper());
            Assert.AreEqual("Test3", result["GroupedDropList"]);
            Assert.AreEqual("{1BE4FAC5-90C2-4A5E-952C-071ECD7DA957}|{6127B3E3-B2EB-4B96-AE6D-51DF0212C0EA}", result["MultiList"].ToUpper());
            Assert.AreEqual("{35E0CE21-2651-46CD-B87D-0B34216D3137}|{F52A1B3B-356E-45A4-B06C-DFAE28B6D78A}", result["Treelist"].ToUpper());
            Assert.AreEqual("{35E0CE21-2651-46CD-B87D-0B34216D3137}", result["TreeListEx"].ToUpper());

            //Linked Types
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropLink"].ToUpper());
            Assert.AreEqual(_test3.ID.Guid.ToString("B").ToUpper(), result["DropTree"].ToUpper());
            LinkField link = new LinkField(result.Fields["GeneralLink"]);
            Assert.AreEqual("test class", link.Class);
            Assert.AreEqual("test target", link.Target);
            Assert.AreEqual("test text", link.Text);
            Assert.AreEqual("test title", link.Title);
            Assert.AreEqual("test url", link.Url);

            //Developer Type

            Assert.AreEqual("test icon", result["Icon"]);
            Assert.AreEqual("1", result["TriState"]);

        }