Images


Define the following fields used in Images section:

#region Fields
 
private List<Album> _dropboxAlbums = new List<Album>() { };
private List<Image> _dropboxImages = new List<Image>() { };
private bool _deletedImages = false;
 
#endregion

Override the GetImages method of OpenAccessLibrariesProvider class:

public override IQueryable<Image> GetImages()
{
            if (Config.Get<LibrariesConfig>().Providers[Name].Parameters["cursorImages"] != null)
            {
                DropboxBlobStorageProviderName = String.Empty;
                var libConfig = ConfigMan.GetSection<LibrariesConfig>();
                if (String.Empty.Equals(Config.Get<LibrariesConfig>().Providers[Name].Parameters["cursorImages"].Trim()))
                {
                    var imagesToDelete = base.GetImages();                   
                    if (imagesToDelete.Count<Image>() > 0)
                    {
                        var albumsToDelete = base.GetAlbums();
                        foreach (Album album in albumsToDelete)
                        {
                            base.Delete(album);
                            CommitTransaction();
                        }
                    }
                    libConfig.Providers[Name].Parameters["cursorImages"] = GetFiles(String.Empty, "images");
                }
                else
                {
                    libConfig.Providers[Name].Parameters["cursorImages"] = GetFiles(Config.Get<LibrariesConfig>().Providers[Name].Parameters["cursorImages"], "images");
                }
                if (_dropboxFolders.Count() > 0 || _dropboxFiles.Count() > 0 || _deletedImages)
                {
                    SyncAlbums();
                    SyncImages();
                    CommitTransaction();
                    ConfigMan.SaveSection(libConfig);
                    ResetImagesData();
                }
                var images = base.GetImages();
                return images;
            }
            else
            {
                throw new Exception(_dropboxConfigError);
            }
        }

This method gets the images in Sitefinity data base and from Dropbox. If there are new or deleted images, the SyncAlbums and SyncImages methods make the synchronization and then commit the transaction.

SyncAlbums and SyncImages methods:

public void SyncAlbums()
        {
            _dropboxAlbums = GetAlbums().ToList<Album>();
            if (_dropboxAlbums.SingleOrDefault<Album>(a => a.Title == _dropboxDefaultLibraryName) == null)
            {
                Album defaultAlbum = CreateAlbum();
                _dropboxAlbums.Add(defaultAlbum);
                _dropboxAlbums[_dropboxAlbums.Count - 1].BlobStorageProvider = DropboxBlobStorageProviderName;
                _dropboxAlbums[_dropboxAlbums.Count - 1].Title = _dropboxDefaultLibraryName;
                _dropboxAlbums[_dropboxAlbums.Count - 1].UrlName = _dropboxDefaultLibraryName.ToLower().Replace(' ', '-');               
                LibManager.RecompileItemUrls(_dropboxAlbums[_dropboxAlbums.Count - 1]);
            }
            foreach (DeltaEntry entry in _dropboxFolders)
            {
                CreateDropboxAlbum(entry);
            }
 
}
 
public void SyncImages()
        {
            Album defAlbum = _dropboxAlbums.FirstOrDefault<Album>(a => a.Title == _dropboxDefaultLibraryName);
            Album album;
            Image sfImage = null;
            var sfImages = base.GetImages();
            var libConfig = ConfigMan.GetSection<LibrariesConfig>();
            foreach (DeltaEntry entry in _dropboxFiles)
            {
                if (entry.MetaData.Path.Split('/').Count<string>() == 2)
                {
                    if (_dropboxImages.Where<Image>(i => i.Parent.Id == defAlbum.Id && i.Title == entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty)).FirstOrDefault() != null)
                    {
                        continue;
                    }
                    else if (sfImages.Count() > 0 && (sfImage = sfImages.Where<Image>(i => i.Parent.Id == defAlbum.Id && i.Title == entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty)).FirstOrDefault()) != null)
                    {
                        var dropboxUpdateImage = Client.GetFile(entry.MetaData.Path);
                        var updateImage = System.Drawing.Image.FromStream(new MemoryStream(dropboxUpdateImage));
                        GenerateThumbnails(sfImage, updateImage, libConfig.MimeMappings[entry.MetaData.Extension].MimeType);
                        continue;
                    }
                    _dropboxImages.Add(CreateImage());
                    _dropboxImages[_dropboxImages.Count - 1].Parent = defAlbum;
                }
                else
                {
                    string albumName = entry.MetaData.Path.Split('/')[1];
                    album = _dropboxAlbums.FirstOrDefault<Album>(a => a.Title == albumName);
                    if (_dropboxImages.Where<Image>(i => i.Parent.Id == album.Id && i.Title == entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty)).FirstOrDefault() != null)
                    {
                        continue;
                    }
                    else if (sfImages.Count() > 0 && (sfImage = sfImages.Where<Image>(i => i.Parent.Id == album.Id && i.Title == entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty)).FirstOrDefault()) != null)
                    {
                        var dropboxUpdateImage = Client.GetFile(entry.MetaData.Path);
                        var updateImage = System.Drawing.Image.FromStream(new MemoryStream(dropboxUpdateImage));
                        GenerateThumbnails(sfImage, updateImage, libConfig.MimeMappings[entry.MetaData.Extension].MimeType);
                        continue;
                    }
                    _dropboxImages.Add(CreateImage());
                    _dropboxImages[_dropboxImages.Count - 1].Parent = album;
                }
                var dropboxImage = Client.GetFile(entry.MetaData.Path);
                var image = System.Drawing.Image.FromStream(new MemoryStream(dropboxImage));
                _dropboxImages[_dropboxImages.Count - 1].Title = entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty);
                _dropboxImages[_dropboxImages.Count - 1].AlternativeText = entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty);
                _dropboxImages[_dropboxImages.Count - 1].Extension = entry.MetaData.Extension;
                _dropboxImages[_dropboxImages.Count - 1].TotalSize = entry.MetaData.Bytes;
                _dropboxImages[_dropboxImages.Count - 1].UrlName = entry.MetaData.Name.Replace(entry.MetaData.Extension, String.Empty).Trim().Replace(' ', '-');
                _dropboxImages[_dropboxImages.Count - 1].Urls.Add(new MediaUrlData() { Url = _dropboxDefaultURL + entry.MetaData.Path.Replace(entry.MetaData.Extension, String.Empty).Replace(" ", "??") });
                _dropboxImages[_dropboxImages.Count - 1].Uploaded = true;
                _dropboxImages[_dropboxImages.Count - 1].Description = String.Empty;
                _dropboxImages[_dropboxImages.Count - 1].MimeType = libConfig.MimeMappings[entry.MetaData.Extension].MimeType;
                _dropboxImages[_dropboxImages.Count - 1].Height = image.Height;
                _dropboxImages[_dropboxImages.Count - 1].Width = image.Width;
                _dropboxImages[_dropboxImages.Count - 1].ChunkSize = libConfig.SizeOfChunk;
                _dropboxImages[_dropboxImages.Count - 1].BlobStorageProvider = DropboxBlobStorageProviderName;
                LibManager.RecompileItemUrls(_dropboxImages[_dropboxImages.Count - 1]);
                GenerateThumbnails(_dropboxImages[_dropboxImages.Count - 1], image, libConfig.MimeMappings[entry.MetaData.Extension].MimeType);
            }
        }

NOTE: To sync properly the folders from Dropbox and libraries from Sitefinity you should make the root folder of the Dropbox application Default library in your Sitefinity content module and all the folders in the root folder will be your other libraries. The same is the logic with the images. All images from the root folder go to the Default library (album) in Sitefinity. All other images in the sub folders should be taken recursively and assigned to the corresponding library (album) in Sitefinity backend. When you do this you should be aware that if you have for example:

\dropboxAppFolder\RootImageFolder\Image1.jpg ;
\dropboxAppFolder\RootImageFolder\SubImageFolder\Image1.jpg;
\dropboxAppFolder\RootImageFolder\SubImageFolder\Image2.jpg
The synchronization will add in Sitefinity Image content module only first of images with name Image1.jpg
and Image.jpg and will assign them to RootImageFolder library(album).

Override Delete(Image imageToDelete) method of OpenAccessLibrariesProvider class:

public override void Delete(Image imageToDelete)
        {
            if (imageToDelete.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master)
            {
                try
                {
                    Client.Delete(imageToDelete.Urls.SingleOrDefault<MediaUrlData>(u => u.Url.Contains(_dropboxDefaultURL)).Url.Replace(_dropboxDefaultURL, String.Empty).Replace(" ", "??") + imageToDelete.Extension);
                    SetLatestCursor(imageToDelete);
                }
                catch (Exception ex) { }
            }
            var context = this.GetContext();
 
            if (imageToDelete.Parent != null)
            {
                this.DeletePermissionsInheritanceAssociation(imageToDelete.Parent, imageToDelete);
            }
 
            this.providerDecorator.DeletePermissions(imageToDelete);
 
            this.ClearLifecycle(imageToDelete, base.GetImages());
 
            if (context != null)
            {
                base.DeleteMediaContent(imageToDelete, context);
            }
        }

This method will remove the image from both Dropbox and Sitefinity and also will remove any relations to this image in Sitefinity items.

GetDropboxImages is method that sets the filters that describes which items are images from whole Dropbox set of files and call the methods which fill the final collections for syncing:

private void GetDropboxImages(DeltaPage delta)
        {
            var libConfig = ConfigMan.GetSection<LibrariesConfig>();
            string imageExt = ".gif,.jpg,.jpeg,.png,.bmp";
            if (!String.IsNullOrEmpty(libConfig.Images.AllowedExensionsSettings))
            {
                imageExt = libConfig.Images.AllowedExensionsSettings;
            }
            foreach (DeltaEntry entry in delta.Entries)
            {
                if (entry.MetaData == null)
                {
                    FillItemsToDelete(entry, imageExt, true, "images");
                    _deletedImages = true;
                }
                else
                {
                    FillContentLists(entry, imageExt, true);
                }
            }
            _dropboxFolders.RemoveAll(f => !_folders.ToString().ToLower().Contains(f.MetaData.Name.ToLower()));
}

GetDropboxImagesToDelete is method that manages the items for deleting – albums or images and call the proper delete methods:

private void GetDropboxImagesToDelete(DeltaEntry entry, string extensions)
        {
            Image image = null;
            Album album;
            string[] pathElements = entry.Path.Split('/');
            {
                if (pathElements.Count<string>() == 2)
                {
                    if (pathElements[1].Contains('.') && extensions.Contains("." + pathElements[1].Split('.')[pathElements[1].Split('.').Count<string>() - 1]))
                    {
                        string fileName = pathElements[1].Split('.')[pathElements[1].Split('.').Count<string>() - 2];
                        image = base.GetImages().SingleOrDefault<Image>(i => i.Parent.Title == _dropboxDefaultLibraryName && i.Title.ToString().ToLower() == fileName);
                        if (image != null)
                        {
                            Delete(image);
                        }
                        image = null;
                    }
                    else
                    {
                        string folderName = pathElements[1];
                        album = base.GetAlbums().SingleOrDefault<Album>(a => a.Title.ToString().ToLower() == folderName);
                        if (album != null)
                        {
                            base.Delete(album);
                        }
                        album = null;
                    }
                }
                else
                {
                    if (pathElements[pathElements.Count<string>() - 1].Contains('.') && extensions.Contains("." + pathElements[pathElements.Count<string>() - 1].Split('.')[pathElements[pathElements.Count<string>() - 1].Split('.').Count<string>() - 1]))
                    {
                        string fileName = pathElements[pathElements.Count<string>() - 1].Split('.')[pathElements[pathElements.Count<string>() - 1].Split('.').Count<string>() - 2];
                        image = base.GetImages().SingleOrDefault<Image>(i => i.Parent.Title.ToString().ToLower() == pathElements[1] && i.Title.ToString().ToLower() == fileName);
                        if (image != null)
                        {
                            Delete(image);
                        }
                        image = null;
                    }
                }
            }
        }

CreateDropboxAlbum
is method that creates albums from Dropbox folders:

private void CreateDropboxAlbum(DeltaEntry entry)
{
            if (_dropboxAlbums.SingleOrDefault<Album>(a => a.Title == entry.MetaData.Path.Split('/')[1]) == null)
            {
                _dropboxAlbums.Add(CreateAlbum());
                _dropboxAlbums[_dropboxAlbums.Count - 1].Title = entry.MetaData.Path.Split('/')[1];
                _dropboxAlbums[_dropboxAlbums.Count - 1].UrlName = entry.MetaData.Path.Split('/')[1].Replace(' ', '-');
                _dropboxAlbums[_dropboxAlbums.Count - 1].BlobStorageProvider = DropboxBlobStorageProviderName;
                LibManager.RecompileItemUrls(_dropboxAlbums[_dropboxAlbums.Count - 1]);
            }
}

ResetImagesData is method that resets the values of the fields and collections that are used for the synchronization process, after syncing is done:

private void ResetImagesData()
{
            _deletedImages = false;
            _dropboxFiles = new List<DeltaEntry>() { };
            _dropboxFolders = new List<DeltaEntry>() { };
            _dropboxAlbums = new List<Album>() { };
            _dropboxImages = new List<Image>() { };
            _folders = new StringBuilder();
}

Next steps

+1-888-365-2779
sales@sitefinity.com

Related topics:

Feedback

How useful is this article?

Tell us more

Submit
Your message was successfully sent.

We appreciate your feedback.

Your message could not be sent.

OK