Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jay Dobson 75 posts 121 karma points
    Jan 13, 2011 @ 16:12
    Jay Dobson
    0

    Extending Media Before or AfterSave - All Sender Properties are null

    Hi All,

    I have a bit of code within the App_Code folder that extends the Media.AfterSave event:

        public class PdfDocumentSaveEvent : ApplicationBase
        {
       
            public PdfDocumentSaveEvent()
            {
                Media.AfterSave += Media_AfterSave;
            }

            /*private void Media_New(Media sender, NewEventArgs e)*/
            private void Media_AfterSave(Media sender, SaveEventArgs e)       
            {
           
                if (sender.ContentType.Alias == "Form")
                {
               
                    Property title = sender.getProperty("Title");
                   
                    if (title != null) {
                        title.Value = "Jay was here";
                    }
                   
                    else {
                        HttpContext.Current.Response.Write("Title is null");
                    }                               
                   
                }
               
            }
           
        }

    This code does fire after I save a media item (custom: Form in my case) but Title is always null.  As with other properties such as umbracoFile, etc.  I can't seem to access any of them.  I've also tried this code on the New and BeforeSave events and still everything is null.  It is running within the Umbraco context, so I'm at a loss.

    I've also tried:

    sender.getProperty("Title").Value = "Jay was here";

    Instead of creating the property object and assigning it to that.

    Any thoughts?

  • Ismail Mayat 4511 posts 10092 karma points MVP 2x admin c-trib
    Jan 13, 2011 @ 17:55
    Ismail Mayat
    0

    Jay,

    What version of umbraco are you using I have seen this before with 4.0.3 basically i was doing pdf indexing with the old umbSearch and was tapping into the after save event but was also getting nothing in the properties so i did the following

    i was in the event passing into index media item then calling getMediaData which makes raw sql call to get the media data then i was adding that to the node xml the indexing.  I did raise this as issue but no one could replicate the error.

            internal struct mediaItem {
                public string url;
                public string ext;
            }
    
    /// <summary>
            /// we are still not getting umbracoFile at this point
            /// </summary>
            /// <param name="sender"></param>
            private void index(Media sender)
            {
    
                XmlDocument x = new XmlDocument();
    
                int id = sender.Id;       
                writer = new IndexWriter(Settings.IndexDirectory, new StandardAnalyzer(), true);
                //media.toxml seems to be returning nothing so had to do it this way
                XmlNode node = ((IHasXmlNode)umbraco.library.GetMedia(sender.Id, true).Current).GetNode();
    
                mediaItem m = getMediaData(id);
    
                //update the doc xml
                node = addMediaInfoToXmlDoc(m, node);
    
                x.LoadXml(node.OuterXml);
    
                Indexer.AddNodeToIndex(x.SelectSingleNode("/node"), writer, null, true);
    
                writer.Optimize();
                writer.Close();
            }
    
            /// <summary>
            /// add the missing info to xml doc so that we can index the media item
            /// </summary>
            /// <param name="m"></param>
            /// <param name="n"></param>
            /// <returns></returns>
            private XmlNode addMediaInfoToXmlDoc(mediaItem m, XmlNode n){
                XmlNode node = n;
                n.SelectSingleNode("/node/data[@alias='umbracoFile']").InnerText = m.url;
                n.SelectSingleNode("/node/data[@alias='umbracoExtension']").InnerText = m.ext;
                return node;
            }
    
            /// <summary>
            /// have to do this becuase we dont have it in the xml
            /// something todo with order of events, ie item is saved but file path and extension is not picked up at this point
            /// </summary>
            /// <param name="mediaId"></param>
            /// <returns></returns>
            private mediaItem getMediaData(int mediaId) {
    
    
                string sql = "select dataNvarchar from cmsPropertyData where contentnodeid=@id and (propertytypeid=24 or propertytypeid=25)";
                mediaItem md = new mediaItem();
                StringBuilder sb=new StringBuilder();
    
                IRecordsReader dr = SqlHelper.ExecuteReader(sql, SqlHelper.CreateParameter("@id", mediaId));
    
                using (dr)
                {
    
                    while (dr.Read())
                    {
                        sb.Append(dr.GetString("dataNvarchar"));
                        sb.Append(",");
    
                    }
    
                }
    
                string result = sb.ToString().TrimEnd(new char[] { ',' });
                string[] res = result.Split(new char[] { ',' });
                md.url = res[0];
                md.ext = res[1];
    
                return md;
            }
    
    
            #endregion    
    
            public static ISqlHelper SqlHelper
            {
                get
                {
    
                    return Application.SqlHelper;
    
                }
            }

     

    Regards

    Ismail

  • Jay Dobson 75 posts 121 karma points
    Jan 13, 2011 @ 18:32
    Jay Dobson
    0

    Thanks for the reply Ismail.  Turns out I needed to use lower-case T on the title attribute.  Also, umbracoFile wasn't the attribute I needed for the file path.  Just plain-ol' file worked. 

    So, once I got things working, I wrote a bit of code that provides the ability for custom media paths by first checking if a PDF is a Form media type and if so, grabs the parent, checks if it's a Folder media type and looks for its mappedPath property (which is a custom string property I added to store paths like /media/pdf/somedir/).  It then moves the PDF from its current folder to the specified mappedPath from its parent and saves the new path under it's record.  Content pickers seem to work well and point to the proper/new paths.

    This code needs a lot of cleaning, checking, exception-handling, etc.  It's just a basic working prototype:

        public class PdfDocumentSaveEvent : ApplicationBase
        {
       
            public PdfDocumentSaveEvent()
            {
           
                Media.AfterSave+= Media_AfterSave;
               
            }
           
            private void Media_AfterSave(Media sender, SaveEventArgs e) {
           
                if (sender.ContentType.Alias == "Form") {
               
                    Property file = sender.getProperty("file");
                    Media parent = new Media(sender.Parent.Id);
                   
                    string newPath = "/media/";
                    string oldPath = string.Empty;
                   
                    string fullNewPath = string.Empty;
                    string fullOldPath = string.Empty;
                   
                    if ( parent != null && parent.ContentType.Alias == "Folder")
                    {
                        newPath = parent.getProperty("mappedPath").Value.ToString();
                    }
                               
                   
                    if (file != null) {                   
                                   
                        string fileName = System.IO.Path.GetFileName(file.Value.ToString());
                        oldPath = file.Value.ToString().Replace(fileName, string.Empty);
                       
                        fullNewPath = HttpContext.Current.Server.MapPath(newPath + fileName);
                        fullOldPath = HttpContext.Current.Server.MapPath(oldPath + fileName);
                       
                        // Moving file
                        if ( fullOldPath != fullNewPath ) {
                       
                            if ( File.Exists(fullNewPath) )
                                File.Delete(fullNewPath);
                               
                            File.Move(fullOldPath, fullNewPath);
                       
                        }
                       
                        file.Value = newPath + fileName;
                       
                    }           
               
                }
           
            }
           
        }

     

Please Sign in or register to post replies

Write your reply to:

Draft