示例#1
0
        public bool Execute(string packageName, XmlNode xmlData)
        {
            bool flag;

            try
            {
                #region MediaType
                User      adminUser       = new User(0);
                MediaType theme           = CreateMediaType(adminUser, MediaTypeName);
                MediaType folder          = MediaType.GetByAlias("Folder");
                int[]     folderStructure = folder.AllowedChildContentTypeIDs;
                int       newsize         = folderStructure.Length + 1;
                Array.Resize(ref folderStructure, newsize);
                folderStructure[newsize - 1]      = theme.Id;
                folder.AllowedChildContentTypeIDs = folderStructure;
                MediaType image = MediaType.GetByAlias(MediaTypeName);
                #endregion
                #region Theme Images
                #endregion
                flag = true;
            }
            catch
            {
                flag = false;
            }
            return(flag);
        }
示例#2
0
        /// <summary>
        ///   Creates an image media.
        /// </summary>
        /// <param name = "parentId">The parent media id.</param>
        /// <param name = "mediaName">Name of the media.</param>
        /// <param name = "image">The image.</param>
        /// <param name = "outputFormat">The output format.</param>
        /// <returns>Media Url</returns>
        public static int CreateImageMedia(int parentId, string mediaName, Image image, OutputFormat outputFormat)
        {
            // Create media item
            mediaName = LegalizeString(mediaName.Replace(" ", "-"));
            var mediaItem = Media.MakeNew(mediaName, MediaType.GetByAlias("image"), new User(0), parentId);

            // Filename
            // i.e. 1234.jpg
            var mediaFileName  = string.Format("{0}.{1}", mediaItem.Id, outputFormat);
            var mediaThumbName = string.Format("{0}_thumb.{1}", mediaItem.Id, outputFormat);

            // Client side Paths
            //
            //      sample folder : /media/1234/
            //                    : /media/1234/1234.jpg
            //
            var clientMediaFolder = string.Format("{0}/../media/{1}", GlobalSettings.Path, mediaItem.Id);
            var clientMediaFile   = string.Format("{0}/{1}", clientMediaFolder, mediaFileName);
            var clientMediaThumb  = string.Format("{0}/{1}", clientMediaFolder, mediaThumbName);

            // Server side Paths
            var serverMediaFolder = IOHelper.MapPath(clientMediaFolder);
            var serverMediaFile   = IOHelper.MapPath(clientMediaFile);
            var serverMediaThumb  = IOHelper.MapPath(clientMediaThumb);

            var extension = Path.GetExtension(serverMediaFile).ToLower();

            // Create media folder if it doesn't exist
            if (!Directory.Exists(serverMediaFolder))
            {
                Directory.CreateDirectory(serverMediaFolder);
            }

            // Save Image and thumb for new media item
            image.Save(serverMediaFile);
            var savedImage = Image.FromFile(serverMediaFile);

            savedImage.GetThumbnailImage((int)(image.Size.Width * .3), (int)(image.Size.Height * .3), null, new IntPtr()).
            Save(serverMediaThumb);

            mediaItem.getProperty(Constants.Umbraco.Media.Width).Value     = savedImage.Size.Width.ToString();
            mediaItem.getProperty(Constants.Umbraco.Media.Height).Value    = savedImage.Size.Height.ToString();
            mediaItem.getProperty(Constants.Umbraco.Media.File).Value      = clientMediaFile;
            mediaItem.getProperty(Constants.Umbraco.Media.Extension).Value = extension;
            mediaItem.getProperty(Constants.Umbraco.Media.Bytes).Value     = File.Exists(serverMediaFile)
                                                              ? new FileInfo(serverMediaFile).Length.ToString()
                                                              : "0";

            mediaItem.Save();
            mediaItem.XmlGenerate(new XmlDocument());

            image.Dispose();
            savedImage.Dispose();

            // assign output parameters
            return(mediaItem.Id);
        }
示例#3
0
        public MediaService(string mediaFolder, string installFolder)
        {
            _mediaFolder   = mediaFolder;
            _installFolder = installFolder;

            _defaultFolderName = "avenue-clothing.com";
            _folderType        = MediaType.GetByAlias("folder");
            _imageType         = MediaType.GetByAlias("image");

            _rootMediaNode = GetRootMediaFolder();
        }
示例#4
0
 private bool CreateSubMediasForArtist(List <string> subFolderTypeNameAndArtistName, Media mediaFolder)
 {
     foreach (string folderName in subFolderTypeNameAndArtistName)
     {
         Media m = Media.MakeNew(folderName, MediaType.GetByAlias("Folder"), User.GetCurrent(), mediaFolder.Id);
         if (m == null)
         {
             return(false);
         }
     }
     return(true);
 }
        public XElement Export(Umbraco.Core.Models.IMediaType item)
        {
            var legacyItem = MediaType.GetByAlias(item.Alias);

            XmlDocument xmlDoc = uSyncXml.CreateXmlDoc();

            xmlDoc.AppendChild(legacyItem.ToXml(xmlDoc));

            XElement node = xmlDoc.ToXElement();

            return(node);
        }
示例#6
0
        public void Can_Verify_AllowedChildContentTypes_On_MediaType()
        {
            // Arrange
            var folder          = MediaType.GetByAlias(Constants.Conventions.MediaTypes.Folder);
            var folderStructure = folder.AllowedChildContentTypeIDs.ToList();

            folderStructure.Add(1045);

            // Act
            folder.AllowedChildContentTypeIDs = folderStructure.ToArray();
            folder.Save();

            // Assert
            var updated = MediaType.GetByAlias(Constants.Conventions.MediaTypes.Folder);

            Assert.That(updated.AllowedChildContentTypeIDs.Any(), Is.True);
            Assert.That(updated.AllowedChildContentTypeIDs.Any(x => x == 1045), Is.True);
        }
        // IMediaFactory Members
        // -------------------------------------------------------------------------

        #region IMediaFactory Members

        public override Media CreateMedia(IconI parent, HttpPostedFile uploadFile)
        {
            string filename = uploadFile.FileName;

            // Create new media object
            Media media = Media.MakeNew(filename, MediaType.GetByAlias("File"),
                                        new User(0), parent.Id);

            // Get umbracoFile property
            int propertyId = media.getProperty("umbracoFile").Id;

            // Set media properties
            media.getProperty("umbracoFile").Value      = VirtualPathUtility.Combine(ConstructRelativeDestPath(propertyId), filename);
            media.getProperty("umbracoBytes").Value     = uploadFile.ContentLength;
            media.getProperty("umbracoExtension").Value = VirtualPathUtility.GetExtension(filename).Substring(1);

            return(media);
        }
示例#8
0
        private Media GetOrCreateFolder(Media parent, string name)
        {
            var children = parent.Id == -1 ? Media.GetRootMedias() : parent.Children;

            if (children.Length > 0)
            {
                foreach (var node in children.Where(node => node.Text.ToLower() == name.ToLower()))
                {
                    return(node);
                }
            }

            var media = Media.MakeNew(name, MediaType.GetByAlias("Folder"), User.GetUser(0), parent.Id);

            media.sortOrder = 0;
            media.Save();

            return(media);
        }
示例#9
0
        // -------------------------------------------------------------------------
        // Public members
        // -------------------------------------------------------------------------

        // IMediaFactory Members
        // -------------------------------------------------------------------------

        #region IMediaFactory Members

        public override Media CreateMedia(IconI parent, HttpPostedFile uploadFile)
        {
            string filename = uploadFile.FileName;

            // Create new media object
            Media media = Media.MakeNew(filename, MediaType.GetByAlias("Image"),
                                        new User(0), parent.Id);

            // Get Image object, width and height
            Image image      = Image.FromStream(uploadFile.InputStream);
            int   fileWidth  = image.Width;
            int   fileHeight = image.Height;

            // Get umbracoFile property
            int propertyId = media.getProperty("umbracoFile").Id;

            // Get paths
            string relativeDestPath     = ConstructRelativeDestPath(propertyId);
            string relativeDestFilePath = VirtualPathUtility.Combine(relativeDestPath, filename);
            string ext = VirtualPathUtility.GetExtension(filename).Substring(1);

            // Set media properties
            SetImageMediaProperties(media, relativeDestFilePath, fileWidth, fileHeight, uploadFile.ContentLength, ext);

            // Create directory
            if (UmbracoSettings.UploadAllowDirectories)
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(relativeDestPath));
            }

            // Generate thumbnail
            string absoluteDestPath     = HttpContext.Current.Server.MapPath(relativeDestPath);
            string absoluteDestFilePath = Path.Combine(absoluteDestPath, Path.GetFileNameWithoutExtension(filename) + "_thumb");

            GenerateThumbnail(image, 100, fileWidth, fileHeight, absoluteDestFilePath + ".jpg");

            // Generate additional thumbnails based on PreValues set in DataTypeDefinition uploadField
            GenerateAdditionalThumbnails(image, fileWidth, fileHeight, absoluteDestFilePath);

            image.Dispose();

            return(media);
        }
示例#10
0
        protected void btnInsertProject_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtProjectName.Text))
            {
                // ensure membergroups folder in content tree
                Document contentCategory = DocumentHelper.GetOrCreateProjectgroupCategory();

                // create project
                Document newProject = Document.MakeNew(this.txtProjectName.Text, DocumentType.GetByAlias(GlobalConstants.ProjectAlias), User.GetUser(0), contentCategory.Id);
                newProject.Template = Template.GetByAlias(GlobalConstants.ProjectTemplateName).Id;
                // set default properties
                newProject.getProperty(GlobalConstants.PermissionKarmaAmount).Value     = GlobalConstants.PermissionKarmaAmountDefaultValue;
                newProject.getProperty(GlobalConstants.PermissionPostKarmaAmount).Value = GlobalConstants.PermissionPostKarmaAmountDefaultValue;
                newProject.getProperty(GlobalConstants.DescriptionField).Value          = this.txtProjectDescription.Text;
                newProject.getProperty(GlobalConstants.IsMainCategory).Value            = true;
                newProject.Publish(User.GetUser(0));

                // clear document cache
                umbraco.library.UpdateDocumentCache(newProject.Id);

                // ensure membergroups folder in media tree
                Media mediaCategory = MediaHelper.GetOrCreateProjectCategory();

                // create media folder
                Media.MakeNew(this.txtProjectName.Text, MediaType.GetByAlias("folder"), User.GetUser(0), mediaCategory.Id);

                // create agenda
                Document agenda = Document.MakeNew(GlobalConstants.AgendaFolder, DocumentType.GetByAlias(GlobalConstants.AgendaAlias), User.GetUser(0), newProject.Id);
                agenda.Template = Template.GetByAlias(GlobalConstants.AgendaTemplateAlias).Id;
                agenda.Publish(User.GetUser(0));
                umbraco.library.UpdateDocumentCache(agenda.Id);

                // create membership group
                CreateMembershipGroup(this.txtProjectName.Text);

                SetOption(enuOption.None);
                lblResultInfo.Text = "Project '" + this.txtProjectName.Text + "' aangemaakt!";
            }
            else
            {
                lblResultInfo.Text = "Projectnaam is een verplicht veld";
            }
        }
示例#11
0
        protected void btnInsertMembergroup_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtMembergroupName.Text))
            {
                // ensure membergroups folder in content tree
                Document contentCategory = DocumentHelper.GetOrCreateMembergroupCategory();

                // create membergroup
                Document newMemberGroup = Document.MakeNew(this.txtMembergroupName.Text, DocumentType.GetByAlias(GlobalConstants.MembergroupAlias), User.GetUser(0), contentCategory.Id);
                newMemberGroup.Template = Template.GetByAlias(GlobalConstants.MembergroupTemplateAlias).Id;
                // set default properties
                newMemberGroup.getProperty(GlobalConstants.PermissionKarmaAmount).Value     = GlobalConstants.PermissionKarmaAmountDefaultValue;
                newMemberGroup.getProperty(GlobalConstants.PermissionPostKarmaAmount).Value = GlobalConstants.PermissionPostKarmaAmountDefaultValue;
                newMemberGroup.getProperty(GlobalConstants.DescriptionField).Value          = this.txtMembergroupDescription.Text;
                newMemberGroup.getProperty(GlobalConstants.IsMainCategory).Value            = true;
                newMemberGroup.Publish(User.GetUser(0));

                // clear document cache
                umbraco.library.UpdateDocumentCache(newMemberGroup.Id);

                // ensure membergroups folder in media tree
                Media mediaCategory = MediaHelper.GetOrCreateMembergroupCategory();

                // create media folder
                Media.MakeNew(this.txtMembergroupName.Text, MediaType.GetByAlias("folder"), User.GetUser(0), mediaCategory.Id);

                // create noticeboard
                Document noticeBoard = Document.MakeNew(GlobalConstants.NoticeBoardFolder, DocumentType.GetByAlias(GlobalConstants.NoticeBoardAlias), User.GetUser(0), newMemberGroup.Id);
                noticeBoard.Template = Template.GetByAlias(GlobalConstants.NoticeBoardTemplateAlias).Id;
                noticeBoard.Publish(User.GetUser(0));

                // create membership group
                CreateMembershipGroup(this.txtMembergroupName.Text);

                SetOption(enuOption.None);
                lblResultInfo.Text = "Kennisgroep '" + this.txtMembergroupName.Text + "' aangemaakt!";
            }
            else
            {
                lblResultInfo.Text = "Kennisgroepnaam is een verplicht veld";
            }
        }
示例#12
0
    // -------------------------------------------------------------------------

    protected void Install(object sender, EventArgs e)
    {
        pnlInstaller.Visible = false;

        // Get MultipleFileUpload DataType
        DataTypeDefinition ddMultipleFileUpload = null;

        foreach (DataTypeDefinition dt in DataTypeDefinition.GetAll())
        {
            if (dt.DataType != null && dt.DataType.Id.Equals(DATATYPE_UID))
            {
                ddMultipleFileUpload = dt;
            }
        }

        if (ddMultipleFileUpload != null)
        {
            // Add tab to Folder Media type
            MediaType        mediaType = MediaType.GetByAlias("Folder");
            ContentType.TabI uploadTab = null;
            foreach (ContentType.TabI tab in mediaType.getVirtualTabs)
            {
                if (tab.Caption.Equals("Upload"))
                {
                    uploadTab = tab;
                }
            }

            if (uploadTab == null)
            {
                int tabId = mediaType.AddVirtualTab("Upload");
                mediaType.AddPropertyType(ddMultipleFileUpload, "MultipleFileUpload", "Upload multiple files");
                mediaType.SetTabOnPropertyType(mediaType.getPropertyType("MultipleFileUpload"), tabId);
                mediaType.Save();
            }
        }

        pnlUninstall.Visible = true;
    }
示例#13
0
        private static Media GetOrCreateCategory(string folderName)
        {
            Media rootMedia = GetRootMedia();

            if (rootMedia == null)
            {
                Media.MakeNew(GlobalConstants.SiteRootName, MediaType.GetByAlias("folder"), User.GetUser(0), 0);
            }

            // if rootMedia is null, create root Node
            foreach (Media document in rootMedia.GetDescendants())
            {
                if (document.Text == folderName)
                {
                    return(document);
                }
            }

            // folder document does not exists, create it
            Media newMembergroupFolder = Media.MakeNew(folderName, MediaType.GetByAlias("folder"), User.GetUser(0), rootMedia.Id);

            return(newMembergroupFolder);
        }
示例#14
0
        public static void Import(XmlNode n, bool ImportStructure)
        {
            if (n == null)
            {
                throw new ArgumentNullException("Node cannot be null");
            }

            //
            // using xmlHelper not XmlHelper because GetNodeValue has gone all
            // Internall on us, this function probibly does belong in the core
            // (umbraco.cms.buisnesslogic.packageInstaller) so that packages
            // can also do media types, but at the mo, it's uSync's until i read
            // about contributing to the core.
            //

            // using user 0 will come unstuck oneday
            User u = new User(0);

            // does this media type already exist ?
            string alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias"));

            if (String.IsNullOrEmpty(alias))
            {
                throw new Exception("no alias in sync file");
            }

            MediaType mt = null;

            try
            {
                mt = MediaType.GetByAlias(alias);
            }
            catch (Exception ex)
            {
                LogHelper.Debug <SyncMediaTypes>("Media type corrupt? {0}", () => ex.ToString());
            }

            if (mt == null)
            {
                // we are new
                mt       = MediaType.MakeNew(u, xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Name")));
                mt.Alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias"));
            }
            else
            {
                mt.Text = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Name"));
            }

            // core
            mt.IconUrl     = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Icon"));
            mt.Thumbnail   = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Thumbnail"));
            mt.Description = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Description"));

            // v6 you can have allow at root.
            // Allow at root (check for node due to legacy)
            bool   allowAtRoot     = false;
            string allowAtRootNode = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/AllowAtRoot"));

            if (!String.IsNullOrEmpty(allowAtRootNode))
            {
                bool.TryParse(allowAtRootNode, out allowAtRoot);
            }
            mt.AllowAtRoot = allowAtRoot;

            //Master content type
            string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Master"));


            if (!String.IsNullOrEmpty(master))
            {
                // throw new System.Exception(String.Format("Throwing in {0}, master {1}", mt.Text, master));
                try
                {
                    MediaType pmt = MediaType.GetByAlias(master);
                    if (pmt != null)
                    {
                        mt.MasterContentType = pmt.Id;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Debug <SyncMediaTypes>("Media type corrupt? {0}", () => ex.ToString());
                }
            }

            //tabs

            ContentType.TabI[] tabs = mt.getVirtualTabs;

            // load the current tabs
            string tabnames = ";";

            for (int t = 0; t < tabs.Length; t++)
            {
                tabnames += tabs[t].Caption + ";";
            }

            Hashtable ht = new Hashtable();

            foreach (XmlNode t in n.SelectNodes("Tabs/Tab"))
            {
                // is this a new tab?
                // if ( tabnames.IndexOf(";" + xmlHelper.GetNodeValue(t.SelectSingleNode("Caption")) + ";" == -1)
                if (!tabnames.Contains(";" + xmlHelper.GetNodeValue(t.SelectSingleNode("Caption")) + ";"))
                {
                    ht.Add(int.Parse(xmlHelper.GetNodeValue(t.SelectSingleNode("Id"))),
                           mt.AddVirtualTab(xmlHelper.GetNodeValue(t.SelectSingleNode("Caption"))));
                }
            }
            // clear cache
            mt.ClearVirtualTabs();

            // put tabs in a hashtable, so we can check they exist when we add properties.
            Hashtable tabList = new Hashtable();

            foreach (ContentType.TabI t in mt.getVirtualTabs.ToList())
            {
                if (!tabList.ContainsKey(t.Caption))
                {
                    tabList.Add(t.Caption, t.Id);
                }
            }

            // properties..
            global::umbraco.cms.businesslogic.datatype.controls.Factory f =
                new global::umbraco.cms.businesslogic.datatype.controls.Factory();

            foreach (XmlNode gp in n.SelectNodes("GenericProperties/GenericProperty"))
            {
                int  dfId = 0;
                Guid dtId = new Guid(xmlHelper.GetNodeValue(gp.SelectSingleNode("Type")));

                if (gp.SelectSingleNode("Definition") != null && !string.IsNullOrEmpty(xmlHelper.GetNodeValue(gp.SelectSingleNode("Definition"))))
                {
                    Guid dtdId = new Guid(xmlHelper.GetNodeValue(gp.SelectSingleNode("Definition")));
                    if (CMSNode.IsNode(dtdId))
                    {
                        dfId = new CMSNode(dtdId).Id;
                    }
                }

                if (dfId == 0)
                {
                    try
                    {
                        dfId = findDataTypeDefinitionFromType(ref dtId);
                    }
                    catch
                    {
                        throw new Exception(String.Format("Cound not find datatype with id {0}.", dtId));
                    }
                }

                //fix for ritch text editor
                if (dfId == 0 && dtId == new Guid("a3776494-0574-4d93-b7de-efdfdec6f2d1"))
                {
                    dtId = new Guid("83722133-f80c-4273-bdb6-1befaa04a612");
                    dfId = findDataTypeDefinitionFromType(ref dtId);
                }

                if (dfId != 0)
                {
                    PropertyType pt = mt.getPropertyType(xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias")));
                    if (pt == null)
                    {
                        mt.AddPropertyType(
                            global::umbraco.cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(dfId),
                            xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias")),
                            xmlHelper.GetNodeValue(gp.SelectSingleNode("Name"))
                            );
                        pt = mt.getPropertyType(xmlHelper.GetNodeValue(gp.SelectSingleNode("Alias")));
                    }
                    else
                    {
                        pt.DataTypeDefinition = global::umbraco.cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(dfId);
                        pt.Name = xmlHelper.GetNodeValue(gp.SelectSingleNode("Name"));
                    }

                    pt.Mandatory        = bool.Parse(xmlHelper.GetNodeValue(gp.SelectSingleNode("Mandatory")));
                    pt.ValidationRegExp = xmlHelper.GetNodeValue(gp.SelectSingleNode("Validation"));
                    pt.Description      = xmlHelper.GetNodeValue(gp.SelectSingleNode("Description"));

                    // tab
                    try
                    {
                        if (tabList.ContainsKey(xmlHelper.GetNodeValue(gp.SelectSingleNode("Tab"))))
                        {
                            pt.TabId = (int)tabList[xmlHelper.GetNodeValue(gp.SelectSingleNode("Tab"))];
                        }
                    }
                    catch (Exception ee)
                    {
                        LogHelper.Debug <SyncMediaTypes>("Packager: Error assigning property to tab: {0}", () => ee.ToString());
                    }
                    pt.Save();
                }
            }

            if (ImportStructure)
            {
                if (mt != null)
                {
                    ArrayList allowed = new ArrayList();
                    foreach (XmlNode structure in n.SelectNodes("Structure/MediaType"))
                    {
                        try
                        {
                            MediaType dtt = MediaType.GetByAlias(xmlHelper.GetNodeValue(structure));
                            if (dtt != null)
                            {
                                allowed.Add(dtt.Id);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Info <uSync>("Can't find structure mediatype - so skipping");
                        }
                    }

                    int[] adt = new int[allowed.Count];
                    for (int i = 0; i < allowed.Count; i++)
                    {
                        adt[i] = (int)allowed[i];
                    }
                    mt.AllowedChildContentTypeIDs = adt;
                }
            }

            mt.Save();

            /*
             * foreach (MediaType.TabI t in mt.getVirtualTabs.ToList())
             * {
             *  MediaType.FlushTabCache(t.Id, mt.Id);
             * }
             *
             * // need to do this more i think
             * MediaType.FlushFromCache(mt.Id);
             */
        }
示例#15
0
        // Helper Method to upload and store your image in the media tree
        protected Media SaveFile(FileUpload uploadControl)
        {
            bool   isImage        = false;
            string mediaPath      = "";
            Media  mediaFile      = null;
            Media  parentMedia    = null;
            bool   categoryExists = false;

            if (uploadControl.PostedFile != null)
            {
                if (uploadControl.PostedFile.FileName != "")
                {
                    // Find filename

                    string filename = uploadControl.PostedFile.FileName;;
                    string fullFilePath;

                    filename = filename.Substring(filename.LastIndexOf("\\") + 1, filename.Length - filename.LastIndexOf("\\") - 1).ToLower();

                    // create the Media Node

                    // get file extension
                    string orgExt = ((string)filename.Substring(filename.LastIndexOf(".") + 1, filename.Length - filename.LastIndexOf(".") - 1));
                    orgExt = orgExt.ToLower();
                    string ext = orgExt.ToLower();

                    MediaType type;

                    if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + ext + ",") > 0)
                    {
                        isImage = true;
                        type    = MediaType.GetByAlias("image");
                    }
                    else
                    {
                        type = MediaType.GetByAlias("file");
                    }

                    //check if category allready exists in library, create it if it does not extists
                    parentMedia    = MediaHelper.GetMediaFolderByName(currentCategory.Name, Node.GetCurrent().Parent.Name);
                    categoryExists = (parentMedia != null);

                    if (categoryExists == false)
                    {
                        parentMedia = Media.MakeNew(currentCategory.Name, MediaType.GetByAlias("folder"), User.GetUser(0), -1);
                    }

                    mediaFile = Media.MakeNew(filename, type, User.GetUser(0), parentMedia.Id);

                    // Create a new folder in the /media folder with the name /media/propertyid
                    string mediaRootPath = Server.MapPath("~/media/");

                    string storagePath = mediaRootPath + mediaFile.Id.ToString();
                    System.IO.Directory.CreateDirectory(storagePath);
                    fullFilePath = storagePath + "\\" + filename;
                    uploadControl.PostedFile.SaveAs(fullFilePath);

                    // Save extension
                    try
                    {
                        mediaFile.getProperty("umbracoExtension").Value = ext;
                    }
                    catch { }

                    // Save file size
                    try
                    {
                        System.IO.FileInfo fi = new FileInfo(fullFilePath);
                        mediaFile.getProperty("umbracoBytes").Value = fi.Length.ToString();
                    }
                    catch { }

                    // Check if image and then get sizes, make thumb and update database
                    if (isImage == true)
                    {
                        int fileWidth;
                        int fileHeight;

                        FileStream fs = new FileStream(fullFilePath,
                                                       FileMode.Open, FileAccess.Read, FileShare.Read);

                        System.Drawing.Image image = System.Drawing.Image.FromStream(fs);
                        fileWidth  = image.Width;
                        fileHeight = image.Height;
                        fs.Close();
                        try
                        {
                            mediaFile.getProperty("umbracoWidth").Value  = fileWidth.ToString();
                            mediaFile.getProperty("umbracoHeight").Value = fileHeight.ToString();
                        }
                        catch { }

                        // Generate thumbnails
                        string fileNameThumb = fullFilePath.Replace("." + orgExt, "_thumb");
                        generateThumbnail(image, 100, fileWidth, fileHeight, fullFilePath, ext, fileNameThumb + ".jpg");


                        image.Dispose();
                    }
                    mediaPath = "/media/" + mediaFile.Id.ToString() + "/" + filename;

                    mediaFile.getProperty("umbracoFile").Value = mediaPath;
                    mediaFile.XmlGenerate(new XmlDocument());
                }
            }

            // return the media...
            return(mediaFile);
        }
示例#16
0
 public IEnumerable <Media> GetAllImagesOrderedByCreationDate()
 {
     return(Media.GetMediaOfMediaType(MediaType.GetByAlias("Image").Id).OrderByDescending(m => m.CreateDateTime));
 }
示例#17
0
        protected UrlData newMediaObjectLogic(
            string blogid,
            string username,
            string password,
            FileData file)
        {
            if (ValidateUser(username, password))
            {
                User    u           = new User(username);
                Channel userChannel = new Channel(username);
                UrlData fileUrl     = new UrlData();
                if (userChannel.ImageSupport)
                {
                    Media rootNode;
                    if (userChannel.MediaFolder > 0)
                    {
                        rootNode = new Media(userChannel.MediaFolder);
                    }
                    else
                    {
                        rootNode = new Media(u.StartMediaId);
                    }

                    // Create new media
                    Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id);

                    Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty);

                    var filename         = file.name.Replace("/", "_");
                    var relativeFilePath = UmbracoMediaFactory.GetRelativePath(fileObject.Id, filename);

                    fileObject.Value = _fs.GetUrl(relativeFilePath);
                    fileUrl.url      = fileObject.Value.ToString();

                    if (!fileUrl.url.StartsWith("http"))
                    {
                        var protocol = GlobalSettings.UseSSL ? "https" : "http";
                        fileUrl.url = protocol + "://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + fileUrl.url;
                    }

                    _fs.AddFile(relativeFilePath, new MemoryStream(file.bits));

                    // Try updating standard file values
                    try
                    {
                        string orgExt = "";
                        // Size
                        if (m.getProperty(Constants.Conventions.Media.Bytes) != null)
                        {
                            m.getProperty(Constants.Conventions.Media.Bytes).Value = file.bits.Length;
                        }
                        // Extension
                        if (m.getProperty(Constants.Conventions.Media.Extension) != null)
                        {
                            orgExt =
                                ((string)
                                 file.name.Substring(file.name.LastIndexOf(".") + 1,
                                                     file.name.Length - file.name.LastIndexOf(".") - 1));
                            m.getProperty(Constants.Conventions.Media.Extension).Value = orgExt.ToLower();
                        }
                        // Width and Height
                        // Check if image and then get sizes, make thumb and update database
                        if (m.getProperty(Constants.Conventions.Media.Width) != null && m.getProperty(Constants.Conventions.Media.Height) != null &&
                            ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0)
                        {
                            int fileWidth;
                            int fileHeight;

                            using (var stream = _fs.OpenFile(relativeFilePath))
                            {
                                Image image = Image.FromStream(stream);
                                fileWidth  = image.Width;
                                fileHeight = image.Height;
                                stream.Close();
                                try
                                {
                                    m.getProperty(Constants.Conventions.Media.Width).Value  = fileWidth.ToString();
                                    m.getProperty(Constants.Conventions.Media.Height).Value = fileHeight.ToString();
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred reading the media stream", ex);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error <UmbracoMetaWeblogAPI>("An error occurred in newMediaObjectLogic", ex);
                    }

                    return(fileUrl);
                }
                else
                {
                    throw new ArgumentException(
                              "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support.");
                }
            }
            return(new UrlData());
        }
示例#18
0
        /// <summary>
        /// Save the kraked image to a specific Umbraco Media node
        /// </summary>
        /// <param name="imKrakTarget">Target media node</param>
        /// <param name="keepOriginal">Save the original image in Umbraco? Pass NULL to use global settings</param>
        /// <param name="hasChanged">Has a new image been selected for the media node just now?</param>
        /// <returns>Success status</returns>
        internal bool Save(Media mKrakTarget, bool?keepOriginal = null, bool hasChanged = false)
        {
            umbraco.cms.businesslogic.property.Property p;
            // Validate parameters
            var status = GetKrakStatus(mKrakTarget);

            if (status == EnmIsKrakable.Unkrakable || status == EnmIsKrakable.Original || String.IsNullOrEmpty(kraked_url))
            {
                // This image is unkrakable, do not proceed
                return(false);
            }

            // Determine the path and the name of the image
            var    relativeFilepath  = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasFile).Value.ToString();
            var    relativeDirectory = System.IO.Path.GetDirectoryName(relativeFilepath);
            var    absoluteDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~" + relativeDirectory);
            string filename          = Path.GetFileName(relativeFilepath);

            if (keepOriginal == null)
            {
                keepOriginal = Configuration.Settings.KeepOriginal;
            }

            // Has this media node already been Kraked before?
            int originalSize = 0;

            if (status == EnmIsKrakable.Kraked)
            {
                p = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasOriginalSize);
                if (p != null && p.Value != null)
                {
                    int.TryParse(p.Value.ToString(), out originalSize);
                }
            }
            if (originalSize == 0)
            {
                originalSize = original_size;
            }

            var compressionRate = (((decimal)(originalSize - kraked_size)) / originalSize).ToString("p2");

            // The following might seem redundant, but Umbraco's "SetValue" extension method used below actually does a lot of magic for us.
            // However, Umbraco will also create a new media folder for us to contain the new image which we do NOT want (the url to the image has to remain unchanged).
            // So some extra efforts are required to make sure the compressed image will be switched in the place of the original image.

            var originalUmbracoFilePropertyData = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasFile).Value.ToString(); // Get the original property data

            if (!mKrakTarget.AddFile(kraked_url, filename))
            {
                return(false); // Krak failed
            }
            // Extract the absolute directory path
            var newRelativeFilepath  = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasFile).Value.ToString(); // Retrieve the relative filepath to the new image location
            var newRelativeDirectory = System.IO.Path.GetDirectoryName(newRelativeFilepath);                         // Extract the relative directoryname
            var newAbsoluteDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~" + newRelativeDirectory);    // Convert to it's absolute variant

            mKrakTarget.getProperty(Constants.UmbracoPropertyAliasFile).Value = originalUmbracoFilePropertyData;     // Put the original property data back in place

            // If an "original" media node is already present under the current node, then save our original data to that node.
            // Else we will keep creating new nodes under the current node each time we save, and we never want more then 1 original node!
            var mOriginal = mKrakTarget.Children.FirstOrDefault(x => x.Text == EnmKrakStatus.Original.ToString() && x.getProperty(Constants.UmbracoPropertyAliasStatus) != null && x.getProperty(Constants.UmbracoPropertyAliasStatus).Value as String == "Original");

            // Does the original media node already exist?
            bool originalExists = mOriginal != null;

            // Do we need to keep a backup of the originally kraked image?
            if (keepOriginal.Value)
            {
                if (!originalExists)
                {
                    // No. Simply create a new "Original" media node under the current node, which will be used to store our "backup"
                    mOriginal = Media.MakeNew(EnmKrakStatus.Original.ToString(), MediaType.GetByAlias(mKrakTarget.ContentType.Alias), mKrakTarget.User, mKrakTarget.Id);
                }

                // We are only allowed to MODIFY the ORIGINAL media node if the FILE has CHANGED! If the original file has not been modified, then we are ONLY allowed to create a NEW media node (aka it didn't exist before)
                if (hasChanged || !originalExists)
                {
                    // Copy all properties of the current media node to the original (aka: BACKUP)
                    foreach (var p2 in mOriginal.GenericProperties)
                    {
                        p2.Value = mKrakTarget.getProperty(p2.PropertyType.Alias).Value;
                    }

                    // The image has been modified during the saving proces before, so correct that by specifying the correct original imag
                    p = mOriginal.getProperty(Constants.UmbracoPropertyAliasFile);
                    if (p != null)
                    {
                        // Save the original data, but replace the old relative filepath with the new one
                        p.Value = originalUmbracoFilePropertyData.Replace(relativeFilepath, newRelativeFilepath);
                    }

                    // The same for filesize
                    p = mOriginal.getProperty(Constants.UmbracoPropertyAliasSize);
                    if (p != null)
                    {
                        p.Value = originalSize;
                    }

                    // Set the "status" of the original image to "Original", so we know in the future this is the original image
                    p = mOriginal.getProperty(Constants.UmbracoPropertyAliasStatus);
                    if (p != null)
                    {
                        p.Value = EnmKrakStatus.Original.ToString();
                    }

                    // Save the original node. It will be placed directly underneath the current media node
                    mOriginal.Save();

                    // Now swap the folders so everything is correct again
                    string tmpFolder = absoluteDirectory + "_tmp";
                    System.IO.Directory.Move(absoluteDirectory, tmpFolder);
                    System.IO.Directory.Move(newAbsoluteDirectory, absoluteDirectory);
                    System.IO.Directory.Move(tmpFolder, newAbsoluteDirectory);
                }
                else
                {
                    // Leave the original alone! So just replace the target folder with the compressed version
                    if (System.IO.Directory.Exists(absoluteDirectory))
                    {
                        System.IO.Directory.Delete(absoluteDirectory, true);
                    }
                    System.IO.Directory.Move(newAbsoluteDirectory, absoluteDirectory);
                }
            }
            else
            {
                if (originalExists)
                {
                    var originalFilePath          = mOriginal.getProperty(Constants.UmbracoPropertyAliasFile).Value.ToString();
                    var originalRelativeDirectory = System.IO.Path.GetDirectoryName(originalFilePath);
                    var originalAbsoluteDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~" + originalRelativeDirectory);
                    mOriginal.delete(true);
                    if (System.IO.Directory.Exists(originalAbsoluteDirectory))
                    {
                        System.IO.Directory.Delete(originalAbsoluteDirectory, true);
                    }
                }
                if (System.IO.Directory.Exists(absoluteDirectory))
                {
                    System.IO.Directory.Delete(absoluteDirectory, true);
                }
                System.IO.Directory.Move(newAbsoluteDirectory, absoluteDirectory);
            }


            // Show the original size
            p = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasOriginalSize);
            if (p != null)
            {
                p.Value = originalSize;
            }

            // Show the kraked status
            p = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasStatus);
            if (p != null)
            {
                p.Value = EnmKrakStatus.Compressed.ToString();
            }

            // Show the kraked date
            p = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasCompressionDate);
            if (p != null)
            {
                p.Value = DateTime.Now.ToString();
            }

            // Show how many bytes we by kraking the image
            p = mKrakTarget.getProperty(Constants.UmbracoPropertyAliasSaved);
            if (p != null)
            {
                p.Value = compressionRate;
            }

            // Save the newly (kraked) media item
            mKrakTarget.Save();

            // Clean up the cache
            HttpRuntime.Cache.Remove("kraken_" + id);
            HttpRuntime.Cache.Remove("kraken_" + id + "_user");

            // W 8-1-2016: Obsolete as the media URL should never change in the first place
            // Refresh the Umbraco Media cache (else you might end up getting the old media node URL when fetching the filename)
            //Umbraco.Web.Cache.DistributedCache.Instance.Refresh(new Guid(Umbraco.Web.Cache.DistributedCache.MediaCacheRefresherId), imKrakTarget.Id);

            return(true);
        }
示例#19
0
        protected UrlData newMediaObjectLogic(
            string blogid,
            string username,
            string password,
            FileData file)
        {
            if (validateUser(username, password))
            {
                User    u           = new User(username);
                Channel userChannel = new Channel(username);
                UrlData fileUrl     = new UrlData();
                if (userChannel.ImageSupport)
                {
                    Media rootNode;
                    if (userChannel.MediaFolder > 0)
                    {
                        rootNode = new Media(userChannel.MediaFolder);
                    }
                    else
                    {
                        rootNode = new Media(u.StartMediaId);
                    }

                    // Create new media
                    Media m = Media.MakeNew(file.name, MediaType.GetByAlias(userChannel.MediaTypeAlias), u, rootNode.Id);

                    Property fileObject = m.getProperty(userChannel.MediaTypeFileProperty);
                    string   _fullFilePath;
                    string   filename = file.name.Replace("/", "_");
                    // Generate file
                    if (UmbracoSettings.UploadAllowDirectories)
                    {
                        // Create a new folder in the /media folder with the name /media/propertyid
                        Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Media + "/" + fileObject.Id));

                        _fullFilePath    = IOHelper.MapPath(SystemDirectories.Media + "/" + fileObject.Id + "/" + filename);
                        fileObject.Value = SystemDirectories.Media + "/" + fileObject.Id + "/" + filename;
                    }
                    else
                    {
                        filename         = fileObject.Id + "-" + filename;
                        _fullFilePath    = IOHelper.MapPath(SystemDirectories.Media + "/" + filename);
                        fileObject.Value = SystemDirectories.Media + "/" + filename;
                    }

                    fileUrl.url = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + IOHelper.ResolveUrl(fileObject.Value.ToString());

                    File.WriteAllBytes(_fullFilePath, file.bits);

                    // Try updating standard file values
                    try
                    {
                        string orgExt = "";
                        // Size
                        if (m.getProperty("umbracoBytes") != null)
                        {
                            m.getProperty("umbracoBytes").Value = file.bits.Length;
                        }
                        // Extension
                        if (m.getProperty("umbracoExtension") != null)
                        {
                            orgExt =
                                ((string)
                                 file.name.Substring(file.name.LastIndexOf(".") + 1,
                                                     file.name.Length - file.name.LastIndexOf(".") - 1));
                            m.getProperty("umbracoExtension").Value = orgExt.ToLower();
                        }
                        // Width and Height
                        // Check if image and then get sizes, make thumb and update database
                        if (m.getProperty("umbracoWidth") != null && m.getProperty("umbracoHeight") != null &&
                            ",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + orgExt.ToLower() + ",") > 0)
                        {
                            int fileWidth;
                            int fileHeight;

                            FileStream fs = new FileStream(_fullFilePath,
                                                           FileMode.Open, FileAccess.Read, FileShare.Read);

                            Image image = Image.FromStream(fs);
                            fileWidth  = image.Width;
                            fileHeight = image.Height;
                            fs.Close();
                            try
                            {
                                m.getProperty("umbracoWidth").Value  = fileWidth.ToString();
                                m.getProperty("umbracoHeight").Value = fileHeight.ToString();
                            }
                            catch
                            {
                            }
                        }
                    }
                    catch
                    {
                    }

                    return(fileUrl);
                }
                else
                {
                    throw new ArgumentException(
                              "Image Support is turned off in this channel. Modify channel settings in umbraco to enable image support.");
                }
            }
            return(new UrlData());
        }