/// <summary>
        /// Sets the value to field.
        /// </summary>
        /// <param name="args">ClientPipelineArgs</param>
        /// <param name="selectedImage">Selected image</param>
        private void ImportImageFinished(ClientPipelineArgs args, SelectedImageModel selectedImage)
        {
            var itemIdString = args.Parameters[Templates.ImportImageClientPipeline.Parameters.MediaItemId];

            if (!string.IsNullOrEmpty(itemIdString))
            {
                var itemId = new ID(itemIdString);

                var mediaItem = _imageService.GetImageById(itemId);

                if (mediaItem != null)
                {
                    this.SetValue(mediaItem);
                    this.Update();
                    this.SetModified();
                }
                else
                {
                    SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                    FotoWareFieldsLog.WriteToLog("--- FotoWareImageField: Could not set field-value ---");
                }
            }
            else
            {
                SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                FotoWareFieldsLog.WriteToLog("--- FotoWareImageField: Could not set field-value ---");
            }
        }
        /// <inheritdoc />
        public MetaDataResponse GetMetaData(string imageInfoUrl, string accessToken)
        {
            try
            {
                var client = new RestClient(imageInfoUrl);
                client.Timeout = -1;
                var request = new RestRequest(Method.GET);
                request.AddHeader("Accept", "application/vnd.fotoware.asset+json");
                request.AddHeader("Authorization", "Bearer " + accessToken);
                IRestResponse response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    var metaData = JsonConvert.DeserializeObject <FotoWareImageMetaDataModel>(response.Content);
                    return(new MetaDataResponse()
                    {
                        StatusCode = HttpStatusCode.OK,
                        MetaData = metaData
                    });
                }
                else
                {
                    FotoWareFieldsLog.WriteToLog($"--- FotoWare Repository: Could not get MetaData : { response.StatusDescription } ---");
                    return(new MetaDataResponse()
                    {
                        StatusCode = response.StatusCode
                    });
                }
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog("--- FotoWare Repository: Could not get MetaData: ---", e);
                return(null);
            }
        }
Example #3
0
        /// <summary>
        /// Sets the value to field.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="selectedImage"></param>
        private void ImportImageFinished(ClientPipelineArgs args, SelectedImageModel selectedImage)
        {
            var itemIdString = args.Parameters[Templates.ImportImageClientPipeline.Parameters.MediaItemId];

            if (!string.IsNullOrEmpty(itemIdString))
            {
                var itemId   = new ID(itemIdString);
                var mediaUrl = _imageService.GetImageUrlById(itemId);

                if (!string.IsNullOrEmpty(mediaUrl))
                {
                    var imageResponse = new RichTextImageResponse
                    {
                        Url = mediaUrl,
                        Alt = selectedImage.Alt
                    };

                    var imageResponeJson = JsonConvert.SerializeObject(imageResponse);

                    SheerResponse.Eval("scClose(" + StringUtil.EscapeJavascriptString(imageResponeJson) + ")");
                }
                else
                {
                    SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                    FotoWareFieldsLog.WriteToLog("--- SelectImageFromFotoWare Dialog: Could not set field-value ---");
                }
            }
            else
            {
                SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                FotoWareFieldsLog.WriteToLog("--- SelectImageFromFotoWare Dialog: Could not set field-value ---");
            }
        }
Example #4
0
        /// <inheritdoc />
        protected override void OnOK(object sender, EventArgs args)
        {
            Assert.ArgumentNotNull(sender, "sender");
            Assert.ArgumentNotNull(args, "args");

            var value = RawValue.Value;

            if (IsRichTextEditorMode())
            {
                var mediaResponse = _selectedImageModelMapper.MapJsonStringToSelectedImageModel(value);

                if (mediaResponse != null)
                {
                    ClientPipelineArgs pipeline = new ClientPipelineArgs();
                    pipeline.Parameters.Add(Templates.ImportImageClientPipeline.Parameters.SelectedImageJson, JsonConvert.SerializeObject(mediaResponse, Formatting.Indented));
                    Context.ClientPage.Start(this, "StartImageImport", pipeline);
                }
                else
                {
                    FotoWareFieldsLog.WriteToLog("--- SelectImageFromFotoWare Dialog: Selected image must be exported before upload to media-library ---");
                    SheerResponse.Alert(_statusMessageService.GetImageMustBeExportedMessage());
                }
            }
            else
            {
                SheerResponse.SetDialogValue(value);
                base.OnOK(sender, args);
            }
        }
        /// <inheritdoc />
        public bool IsImageExists(string imageUrl)
        {
            try
            {
                var client = new RestClient(imageUrl);
                client.Timeout = -1;
                var           request  = new RestRequest(Method.GET);
                IRestResponse response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    return(true);
                }
                else
                {
                    FotoWareFieldsLog.WriteToLog($"--- FotoWare Repository: Could not get Image with Url { imageUrl } : { response.StatusDescription } ---");
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        return(false);
                    }

                    //unknown error
                    return(true);
                }
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog($"--- FotoWare Repository: Could not get Image with Url { imageUrl } ---", e);
                return(true);
            }
        }
 /// <inheritdoc />
 public void UpdateMetaData(Item image, SitecoreMetaDataModel metaData, Language language)
 {
     using (new SecurityDisabler())
     {
         using (new LanguageSwitcher(language))
         {
             try
             {
                 image.Editing.BeginEdit();
                 image.Fields[Templates.ImageMediaItem.Fields.LastModification].Value = metaData.LastModification.ToString();
                 image.Appearance.DisplayName = metaData.Title;
                 image.Fields[Templates.ImageMediaItem.Fields.Alt].Value         = metaData.Title;
                 image.Fields[Templates.ImageMediaItem.Fields.Title].Value       = metaData.Title;
                 image.Fields[Templates.ImageMediaItem.Fields.Keywords].Value    = string.Join(" ", metaData.Keywords.ToArray());
                 image.Fields[Templates.ImageMediaItem.Fields.Description].Value = metaData.Description;
                 image.Editing.EndEdit();
             }
             catch (Exception e)
             {
                 FotoWareFieldsLog.WriteToLog("--- Media Repository: could not updates the meta data. : ---", e);
                 throw;
             }
         }
     }
 }
        /// <inheritdoc />
        public string GetAccessToken(string tenantUrl, string clientId, string clientSecret)
        {
            //try to get access-token
            try
            {
                var client = new RestClient(tenantUrl + "/fotoweb/oauth2/token");
                client.Timeout = -1;
                var request = new RestRequest(Method.POST);
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                request.AddParameter("grant_type", "client_credentials");
                request.AddParameter("client_id", clientId);
                request.AddParameter("client_secret", clientSecret);
                IRestResponse response = client.Execute(request);

                if (!response.IsSuccessful)
                {
                    FotoWareFieldsLog.WriteToLog("--- FotoWare Repository: Authentication exception while calling FotoWare-API to get Access-Token: ---", response.ErrorException);
                    return(string.Empty);
                }
                else
                {
                    var auth = JsonConvert.DeserializeObject <AuthResponseModel>(response.Content);
                    return(auth.AccessToken);
                }
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog("--- FotoWare Repository: Authentication exception while calling FotoWare-API to get Access-Token: ---", e);
                return(string.Empty);
            }
        }
        /// <summary>
        /// Sets the value to field.
        /// </summary>
        /// <param name="args"></param>
        /// <param name="selectedImage"></param>
        private void ImportImageFinished(ClientPipelineArgs args, SelectedImageModel selectedImage)
        {
            Assert.ArgumentNotNull((object)args, nameof(args));
            Item itemNotNull = Client.GetItemNotNull(args.Parameters["itemid"], Language.Parse(args.Parameters["language"]));

            itemNotNull.Fields.ReadAll();
            Field field = itemNotNull.Fields[args.Parameters["fieldid"]];

            Assert.IsNotNull((object)field, "field");
            ImageField imageField = new ImageField(field, field.Value);
            string     parameter  = args.Parameters["controlid"];
            string     xml        = args.Parameters[Templates.ImportImageClientPipeline.Parameters.FieldValue];

            var itemIdString = args.Parameters[Templates.ImportImageClientPipeline.Parameters.MediaItemId];

            if (!string.IsNullOrEmpty(itemIdString))
            {
                var itemId = new ID(itemIdString);

                var mediaItem = _imageService.GetImageById(itemId);

                if (mediaItem != null)
                {
                    imageField.SetAttribute("mediaid", mediaItem.ID.ToString());
                    if (xml.Length > 0)
                    {
                        XmlValue xmlValue   = new XmlValue(xml, "image");
                        string   attribute1 = xmlValue.GetAttribute("height");
                        if (!string.IsNullOrEmpty(attribute1))
                        {
                            imageField.Height = attribute1;
                        }
                        string attribute2 = xmlValue.GetAttribute("width");
                        if (!string.IsNullOrEmpty(attribute2))
                        {
                            imageField.Width = attribute2;
                        }
                    }

                    SheerResponse.SetAttribute("scHtmlValue", "value", WebEditImageCommand.RenderImage(args, imageField.Value));
                    SheerResponse.SetAttribute("scPlainValue", "value", imageField.Value);
                    SheerResponse.Eval("scSetHtmlValue('" + parameter + "')");
                }
                else
                {
                    SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                    FotoWareFieldsLog.WriteToLog("--- SelectImageImageFieldCommand: Could not set field-value ---");
                }
            }
            else
            {
                SheerResponse.Alert(_statusMessageService.GetJobStatusValueCouldNotSet());
                FotoWareFieldsLog.WriteToLog("--- SelectImageImageFieldCommand: Could not set field-value ---");
            }
        }
 /// <inheritdoc />
 public SelectedImageModel MapJsonStringToSelectedImageModel(string jsonString)
 {
     try
     {
         return(JsonConvert.DeserializeObject <SelectedImageModel>(jsonString));
     }
     catch (Exception e)
     {
         FotoWareFieldsLog.WriteToLog("--- SelectedImageModel Mapper: JSON-String could not be mapped to Model: ---", e);
         return(null);
     }
 }
        /// <summary>
        /// Starts the synchronization routine
        /// </summary>
        public void Execute()
        {
            var accessToken = _authenticationService.GetAccessToken();

            if (!string.IsNullOrEmpty(accessToken))
            {
                _synchronizationService.SynchronizeData(accessToken);
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- SynchronizationStarter: could not get access token. ---");
            }
        }
Example #11
0
        /// <inheritdoc />
        public void StartJob(SelectedImageModel selectedImage, ClientPipelineArgs args, Action <ClientPipelineArgs, SelectedImageModel> postAction)
        {
            ClientPipelineArgs currentPipelineArgs = Sitecore.Context.ClientPage.CurrentPipelineArgs as ClientPipelineArgs;

            if (currentPipelineArgs != null)
            {
                ExecuteSync("ImportFotoWareImageJob", "", ImportImage, postAction, selectedImage);
            }
            else
            {
                FotoWareFieldsLog.WriteToLog(
                    "--- ImportFotoWareImageTest Job: ClientPipelineArgs is null ---");
            }
        }
Example #12
0
 /// <summary>
 /// Generates a specific sitecore item name for selected image.
 /// </summary>
 /// <param name="selectedImage">Selected image</param>
 /// <returns>Item-name</returns>
 private string GetItemName(SelectedImageModel selectedImage)
 {
     try
     {
         var fullImageName  = Path.GetFileName(selectedImage.ImageUrl.LocalPath);
         var imageNameArray = fullImageName.Split('.');
         return(imageNameArray[0]);
     }
     catch (Exception e)
     {
         FotoWareFieldsLog.WriteToLog("--- Image Service: Could not generate item name for selected image: ---", e);
         return(string.Empty);
     }
 }
Example #13
0
        /// <inheritdoc />
        public MediaItem UploadImage(SelectedImageModel selectedImage)
        {
            var contentLanguage = _languageRepository.GetContentLanguage();

            try
            {
                return(_mediaRepository.UploadToMediaLibrary(selectedImage, GetItemName(selectedImage), contentLanguage));
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog("--- Image Service: FotoWare-Image could not be uploaded to sitecore media-library: ---", e);
                return(null);
            }
        }
 /// <inheritdoc />
 public void DeleteImage(Item image)
 {
     using (new SecurityDisabler())
     {
         try
         {
             image.Delete();
         }
         catch (Exception e)
         {
             FotoWareFieldsLog.WriteToLog(
                 $"--- Media Repository: could not delete image with id  {image.ID} from Sitecore. : ---", e);
         }
     }
 }
Example #15
0
        /// <inheritdoc />
        public string GetImageUrlById(ID id)
        {
            var mediaItem = GetImageById(id);

            if (mediaItem != null)
            {
                var itemId = mediaItem.ID.Guid.ToString("N");
                return(string.Format("/-/media/{0}.ashx", itemId));
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- Image Service: Url to image is empty, because item not found ---");
                return(string.Empty);
            }
        }
Example #16
0
        /// <inheritdoc />
        public MediaItem GetImageById(ID id)
        {
            var contentLanguage = _languageRepository.GetContentLanguage();
            var mediaItem       = _mediaRepository.GetMediaItemById(id, contentLanguage);

            if (mediaItem != null)
            {
                return(mediaItem);
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- Image Service: item not found. : ---");
                return(null);
            }
        }
        /// <inheritdoc />
        public string GetAccessToken()
        {
            var tenantUrl    = Settings.GetSetting("Foundation.FotoWareExtensions.FotoWare.TenantUrl", string.Empty);
            var clientId     = Settings.GetSetting("Foundation.FotoWareExtensions.FotoWare.ClientId", string.Empty);
            var clientSecret = Settings.GetSetting("Foundation.FotoWareExtensions.FotoWare.ClientSecret", string.Empty);

            if (string.IsNullOrEmpty(tenantUrl) ||
                string.IsNullOrEmpty(clientId) ||
                string.IsNullOrEmpty(clientSecret))
            {
                FotoWareFieldsLog.WriteToLog("--- Authentication Service: FotoWare-Setings are incomplete or not exists ---");
                return(string.Empty);
            }

            return(_fotoWareRepository.GetAccessToken(tenantUrl, clientId, clientSecret));
        }
 /// <inheritdoc />
 public MediaItem GetMediaItemById(ID id, Language language)
 {
     try
     {
         using (new LanguageSwitcher(language))
         {
             var item = _database.GetItem(id);
             return(new MediaItem(item));
         }
     }
     catch (Exception e)
     {
         FotoWareFieldsLog.WriteToLog("--- Media Repository: Could not get media-item by id: ---", e);
         return(null);
     }
 }
 /// <inheritdoc />
 public void ResetImageStatus(Item image)
 {
     using (new SecurityDisabler())
     {
         try
         {
             image.Editing.BeginEdit();
             image.Fields[Templates.ImageMediaItem.Fields.DeletedFromFotoWare].Value = string.Empty;
             image.Editing.EndEdit();
         }
         catch (Exception e)
         {
             FotoWareFieldsLog.WriteToLog(
                 $"--- Media Repository: could not reset image status for image with id  {image.ID} : ---", e);
         }
     }
 }
        /// <summary>
        /// Uploads the selected image to media-library and set value to image-field.
        /// </summary>
        /// <param name="args">ClientPipeline</param>
        protected void SelectFromFotoWare(ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (!args.HasResult || this.Value.Equals(args.Result))
                {
                    return;
                }

                SelectedImageModel selectedImage = null;
                if (args.Result == "Finished")
                {
                    var selectedImageJson = args.Parameters[Templates.ImportImageClientPipeline.Parameters.SelectedImageJson];
                    selectedImage = _selectedImageModelMapper.MapJsonStringToSelectedImageModel(selectedImageJson);
                }
                else
                {
                    selectedImage = _selectedImageModelMapper.MapJsonStringToSelectedImageModel(args.Result);
                    args.Parameters.Add(Templates.ImportImageClientPipeline.Parameters.SelectedImageJson, args.Result);
                }

                if (selectedImage != null)
                {
                    _fotoWareImageJob.StartJob(selectedImage, args, this.ImportImageFinished);
                }
                else
                {
                    //image has to be exported to upload
                    FotoWareFieldsLog.WriteToLog("--- FotoWareImageField: Selected image has to be exported before ---");
                    SheerResponse.Alert(_statusMessageService.GetImageMustBeExportedMessage());
                }
            }
            else
            {
                _fotoWareImageJob.ResetStatus();
                string url = UIUtil.GetUri("control:SelectImageFromFotoWareDialog");
                string str = this.GetValue();
                if (!string.IsNullOrEmpty(str))
                {
                    url = string.Format("{0}&value={1}", (object)url, (object)str);
                }
                SheerResponse.ShowModalDialog(url, "1200", "750", "", true, "1200", "750", false);
                args.WaitForPostBack();
            }
        }
        /// <inheritdoc />
        public bool HasLinks(Item image)
        {
            try
            {
                var links = Sitecore.Globals.LinkDatabase.GetItemReferrers(image, true);
                if (links.Length > 0)
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog(
                    $"--- Media Repository: could not delete image with id  {image.ID} from Sitecore. : ---", e);
                return(true);
            }
        }
        /// <inheritdoc />
        public List <Item> GetAllImages(Language language)
        {
            var targetSitecorePath = Settings.GetSetting("Foundation.FotoWareExtensions.TargetPath", "/sitecore/media library/FotoWare");

            if (!string.IsNullOrEmpty(targetSitecorePath))
            {
                var item = GetItemByPath(targetSitecorePath, language);
                if (item != null)
                {
                    return(item.GetChildren().ToList());
                }
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- Media Repository: target-path-setting is not set in config-file. : ---");
                return(null);
            }

            return(null);
        }
        /// <summary>
        /// Sets the metadata from FotoWare for image-item.
        /// </summary>
        /// <param name="itemId">ID of Image</param>
        /// <param name="imageData">Metadata of Image</param>
        /// <param name="tenantUrl">Tenant-Url</param>
        /// <param name="language">Content-Language</param>
        /// <returns></returns>
        private MediaItem UpdateMetaData(ID itemId, SelectedImageModel imageData, string tenantUrl, Language language)
        {
            try
            {
                using (new SecurityDisabler())
                {
                    using (new LanguageSwitcher(language))
                    {
                        var mediaItem = _database.GetItem(itemId);
                        if (mediaItem != null)
                        {
                            mediaItem.Editing.BeginEdit();
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Software].Value         = "FotoWare";
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.LastModification].Value = imageData.LastModification.ToString();
                            mediaItem.Appearance.DisplayName = imageData.Title;
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Alt].Value             = imageData.Alt;
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Title].Value           = imageData.Title;
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Keywords].Value        = string.Join(" ", imageData.Keywords.ToArray());
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Description].Value     = imageData.Description;
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Height].Value          = imageData.Height.ToString();
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.Width].Value           = imageData.Width.ToString();
                            mediaItem.Fields[Sitecore.Buckets.Util.Constants.BucketableField].Value = "1"; //make Item bucketable
                            mediaItem.Fields[Templates.ImageMediaItem.Fields.FotoWareUrl].Value     = string.Format("{0}|{1}", tenantUrl + imageData.MetaDataUrl, imageData.ImageUrl);
                            mediaItem.Editing.EndEdit();

                            return(new MediaItem(mediaItem));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog("--- Media Repository: Metadata could not be updated: ---", e);
                return(null);
            }

            return(null);
        }
Example #24
0
        public SitecoreMetaDataModel MapFotoWareMetaDataToSitecoreMetaData(FotoWareImageMetaDataModel metaData)
        {
            try
            {
                var lastModification = metaData.Modified;
                var title            = metaData.BuiltinFields[0].Value.String;
                var description      = metaData.BuiltinFields[1].Value.String;
                var keywords         = metaData.BuiltinFields[2].Value.StringArray;

                return(new SitecoreMetaDataModel
                {
                    LastModification = lastModification,
                    Title = title,
                    Description = description,
                    Keywords = keywords
                });
            }
            catch (Exception e)
            {
                FotoWareFieldsLog.WriteToLog("--- FotoWareMetaDataToSitecoreMetaData Mapper: Could not map FotoWare-MetaData to Sitecore MetaData: ---", e);
                return(null);
            }
        }
        /// <inheritdoc />
        public Language GetContentLanguage()
        {
            Language contentLanguage = null;
            var      code            = Settings.GetSetting("Foundation.FotoWareExtensions.Language", "de-DE");

            if (string.IsNullOrEmpty(code))
            {
                contentLanguage = Sitecore.Context.Language;
            }
            else
            {
                try
                {
                    contentLanguage = Language.Parse(code);
                }
                catch (Exception e)
                {
                    FotoWareFieldsLog.WriteToLog("--- Language Repository: Language-Code could no be parsed: ---", e);
                    contentLanguage = Sitecore.Context.Language;
                }
            }

            return(contentLanguage);
        }
Example #26
0
        /// <summary>
        /// Imports the selected Image to media-library.
        /// </summary>
        /// <param name="args">ClientPipelineArgs</param>
        /// <param name="selectedImage">Selected image</param>
        private void ImportImage(ClientPipelineArgs args, SelectedImageModel selectedImage)
        {
            Job job = Sitecore.Context.Job;

            job.Status.State = JobState.Running;
            job.Status.AddMessage(_statusMessageService.GetJobStatusImporting());

            var uploadedImage = _imageService.UploadImage(selectedImage);

            if (uploadedImage != null)
            {
                args.Parameters.Add(Templates.ImportImageClientPipeline.Parameters.MediaItemId, uploadedImage.ID.ToString());
                job.Status.AddMessage(_statusMessageService.GetImageUploadSuccessfullyMessage());
                job.Status.State = JobState.Finished;
            }
            else
            {
                job.Status.AddMessage(_statusMessageService.GetImageCouldNotUploadedMessage());
                job.Status.LogError(_statusMessageService.GetImageCouldNotUploadedMessage());
                FotoWareFieldsLog.WriteToLog(
                    "--- ImportFotoWareImageProgressBar Job: Selected image could not be added to media library ---");
                job.Status.Failed = true;
            }
        }
 /// <summary>
 /// Get image by path.
 /// </summary>
 /// <param name="path">Path</param>
 /// <param name="language">Content-Language</param>
 /// <returns></returns>
 private Item GetItemByPath(string path, Language language)
 {
     using (new LanguageSwitcher(language))
     {
         try
         {
             var item = _database.GetItem(path);
             if (item != null)
             {
                 return(item);
             }
             else
             {
                 FotoWareFieldsLog.WriteToLog($"--- Media Repository: image with path { path } not found : ---");
                 return(null);
             }
         }
         catch (Exception e)
         {
             FotoWareFieldsLog.WriteToLog("--- Media Repository: could not get image by path. : ---", e);
             return(null);
         }
     }
 }
        /// <inheritdoc />
        public void SynchronizeData(string accessToken)
        {
            var targetMediaPath = Settings.GetSetting("Foundation.FotoWareExtensions.TargetPath", "/sitecore/media library/FotoWare");

            if (!string.IsNullOrEmpty(targetMediaPath))
            {
                var deletedImages  = new List <Tuple <Item, bool> >();
                var modifiedImages = new List <Tuple <Item, FotoWareImageMetaDataModel> >();

                var allImages = _mediaRepository.GetAllImages(_languageRepository.GetContentLanguage());
                if (allImages != null)
                {
                    foreach (var image in allImages)
                    {
                        try
                        {
                            if (_mediaRepository.HasLinks(image))
                            {
                                var imageUrls = image.Fields[Templates.ImageMediaItem.Fields.FotoWareUrl].Value;
                                var urlArray  = imageUrls.Split('|');
                                var infoUrl   = urlArray[0];
                                if (!string.IsNullOrEmpty(infoUrl))
                                {
                                    var metaData = _fotoWareRepository.GetMetaData(infoUrl, accessToken);
                                    if (metaData?.MetaData != null)
                                    {
                                        if (urlArray.Length > 1)
                                        {
                                            if (_fotoWareRepository.IsImageExists(urlArray[1]))
                                            {
                                                //reset status
                                                _mediaRepository.ResetImageStatus(image);

                                                //check modification
                                                if (IsModified(image, metaData.MetaData))
                                                {
                                                    //image was modified in FotoWare
                                                    modifiedImages.Add(new Tuple <Item, FotoWareImageMetaDataModel>(image, metaData.MetaData));
                                                }
                                            }
                                            else
                                            {
                                                //exported image not exists on FotoWare
                                                deletedImages.Add(new Tuple <Item, bool>(image, true));
                                            }
                                        }
                                        else
                                        {
                                            FotoWareFieldsLog.WriteToLog($"--- Synchronization Service: Image with ID {image.ID} has no FotoWare-Embed-Url: ---");
                                        }
                                    }
                                    else if (metaData?.StatusCode == HttpStatusCode.NotFound)
                                    {
                                        //image was deleted from FotoWare
                                        deletedImages.Add(new Tuple <Item, bool>(image, true));
                                    }
                                    else
                                    {
                                        FotoWareFieldsLog.WriteToLog($"--- Synchronization Service: Could not get FotoWare-MetaData for Image with ID {image.ID}: ---");
                                    }
                                }
                                else
                                {
                                    FotoWareFieldsLog.WriteToLog($"--- Synchronization Service: Image with ID {image.ID} has no FotoWare-Info-Url: ---");
                                }
                            }
                            else
                            {
                                //image not used in sitecore
                                deletedImages.Add(new Tuple <Item, bool>(image, false));
                            }
                        }
                        catch (Exception e)
                        {
                            FotoWareFieldsLog.WriteToLog($"--- Synchronization Service: Error while synchronize metadata for Image with ID {image.ID}: ---", e);
                        }
                    }
                }
                else
                {
                    FotoWareFieldsLog.WriteToLog("--- Synchronization Service: There was an error while getting all images ---");
                }

                DeleteRemovedImages(deletedImages);
                ModifyOutdatedImages(modifiedImages);
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- Synchronization Service: target-path-setting is not set in config-file. : ---");
            }
        }
        /// <inheritdoc />
        public MediaItem UploadToMediaLibrary(SelectedImageModel selectedImage, string itemName, Language language)
        {
            var targetSitecorePath = Settings.GetSetting("Foundation.FotoWareExtensions.TargetPath", "/sitecore/media library/FotoWare");
            var tenantUrl          = Settings.GetSetting("Foundation.FotoWareExtensions.FotoWare.TenantUrl", string.Empty);

            if (!string.IsNullOrEmpty(tenantUrl))
            {
                if (!string.IsNullOrEmpty(targetSitecorePath))
                {
                    try
                    {
                        var webRequest = WebRequest.Create(selectedImage.ImageUrl);
                        using (var webResponse = webRequest.GetResponse())
                        {
                            using (var stream = webResponse.GetResponseStream())
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    if (stream != null)
                                    {
                                        stream.CopyTo(memoryStream);
                                    }
                                    else
                                    {
                                        return(null);
                                    }

                                    var mediaCreator = new MediaCreator();
                                    var options      = new MediaCreatorOptions
                                    {
                                        Versioned = false,
                                        IncludeExtensionInItemName = false,
                                        Database      = _database,
                                        Destination   = string.Format("{0}/{1}", targetSitecorePath, itemName),
                                        AlternateText = selectedImage.Alt
                                    };

                                    using (new SecurityDisabler())
                                    {
                                        Item item = null;

                                        using (new EventDisabler())
                                        {
                                            item = mediaCreator.CreateFromStream(memoryStream,
                                                                                 Path.GetFileName(selectedImage.ImageUrl.LocalPath), options);
                                        }

                                        if (item != null)
                                        {
                                            return(UpdateMetaData(item.ID, selectedImage, tenantUrl, language));
                                        }

                                        return(null);
                                    }
                                }
                            }
                        }
                    }

                    catch (Exception e)
                    {
                        FotoWareFieldsLog.WriteToLog(
                            "--- Media Repository: FotoWare-Image could not be uploaded to sitecore media-library: ---", e);
                        return(null);
                    }
                }
                else
                {
                    FotoWareFieldsLog.WriteToLog("--- Media Repository: target-path-setting is not set in config-file. : ---");
                    return(null);
                }
            }
            else
            {
                FotoWareFieldsLog.WriteToLog("--- Media Repository: tenant-url-setting is not set in config-file. : ---");
                return(null);
            }
        }