PetrSnobelt / UmbracoStaticPublish

Publish static documents from umbraco and optionally use it as cache
MIT License
8 stars 1 forks source link

Trying to sync (copy) media together with content publish #2

Open akeilox opened 8 years ago

akeilox commented 8 years ago

I have tried to add media sync (copy) together with StaticPublish

In basic experimentation with media service event handler, i tried to attach to media saved event and copy saved media to another drive (same host, connected drive, no IO issues in read/write).

The code

protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            MediaService.Saved += MediaServiceSaved;     
        }   

        void MediaServiceSaved(IMediaService sender, SaveEventArgs<IMedia> e)
        {

            foreach (var mediaItem in e.SavedEntities)
            {
                 var umbracoFileProperty = mediaItem.Properties["umbracoFile"].Value.ToString(); 

 var newfile = .. get file path and server.mappath it
var fromPath = get target copy directory mappath

    var fi = new System.IO.FileInfo(newfile);

            if (!fi.Directory.Exists) fi.Directory.Create();    
            System.IO.File.Copy(fromPath,newfile);
        }
}

When i save a single and/or multiple files from Media Section-> Upload, the file copy (backup) takes place fine but the UI throws error like

Transaction (Process ID 54) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

The media gets saved just fine, so the event takes place(all within the same host so it occurs within a second or two), as well as copy. But the exception is shown to the end user, which ruins the test case.

Any idea why this is happening? Do I need to call some method before and/or after file copy to prevent this?

Would be interested to hear your thoughts on this.