protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Sitecore.Resources.Media.Media media) { Assert.ArgumentNotNull(context, "context"); Assert.ArgumentNotNull(request, "request"); Assert.ArgumentNotNull(media, "media"); if (this.Modified(context, media, request.Options) == Sitecore.Tristate.False) { Event.RaiseEvent("media:request", new object[] { request }); this.SendMediaHeaders(media, context); context.Response.StatusCode = 0x130; return true; } // Gets media stream for the requested media item thumbnail MediaStream stream = ProcessThumbnail(request, media); if (stream == null) { return false; } Event.RaiseEvent("media:request", new object[] { request }); this.SendMediaHeaders(media, context); this.SendStreamHeaders(stream, context); using (stream) { context.Response.AddHeader("Content-Length", stream.Stream.Length.ToString()); WebUtil.TransmitStream(stream.Stream, context.Response, Settings.Media.StreamBufferSize); } return true; }
public MediaResponse IsFileExists(MediaRequest request) { try { Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: IsFileExists is started"); bool result; if (request.MediaId % 2 == 0) { result = IsFileExists(_uowPhotoSQL, request.MediaType, request.MediaId); } else { result = IsFileExists(_uowPhotoMongo, request.MediaType, request.MediaId); } Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: IsFileExists is successfully completed"); return(MediaResponse.NoErrorWithResult(result)); } catch (Exception ex) { Log.Instance.ExceptionInfo(ex).LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(IsFileExists)}: Error"); return(MediaResponse.ErrorWithMessage(ex.Message)); } }
public new bool DoProcessRequest(HttpContext context, MediaRequest request, Media media) { media = DetermineImageResponse(context, request, media); bool result = base.DoProcessRequest(context, request, media); return(result); }
private void button1_Click(object sender, EventArgs e) { ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(); MediaRequest request = new MediaRequest(); request.Nota1 = Convert.ToDouble(txtP1.Text); request.Nota2 = Convert.ToDouble(txtP2.Text); MediaResponse response = client.CalcularMedia(request); txtResultado.Text = response.Resultado; txtMedia.Text = response.Media.ToString(); client.Close(); }
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Sitecore.Resources.Media.Media media) { if (Context.Database.Name.ToLower() != "core") { string mediaId = media.MediaData.MediaItem.ID.ToString(); Item disclaimerFolder = Context.Database.GetItem("/sitecore/content/Global/Settings/Disclaimers"); if (disclaimerFolder != null) { foreach (Item disc in disclaimerFolder.Children) { if (disc["Media To Protect"].IndexOf(mediaId) >= 0) { string disclaimerPageId = disc["Disclaimer Page"]; Item item = Context.Database.GetItem(new ID(disclaimerPageId)); string url = LinkManager.GetItemUrl(item); ShowDisclaimer(mediaId, url); break; } } } } return(base.DoProcessRequest(context, request, media)); }
public MediaFile DownloadFile(MediaRequest request) { try { Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(DownloadFile)}: DownloadFile is started"); byte[] image; if (request.MediaId % 2 == 0) { image = DownloadFile(_uowPhotoSQL, request.MediaType, request.MediaId); } else { image = DownloadFile(_uowPhotoMongo, request.MediaType, request.MediaId); } MediaFile result = new MediaFile() { MediaId = request.MediaId, MediaType = request.MediaType, FileByteStream = new MemoryStream(image), Size = image.LongLength }; Log.Instance.LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(DownloadFile)}: DownloadFile is successfully completed"); return(result); } catch (Exception ex) { Log.Instance.ExceptionInfo(ex).LogAsInfo($"{nameof(ImageDbFileSource)}.{nameof(DownloadFile)}: Error"); return(new MediaFile() { MediaId = -1 }); } }
private void ProcessImageDimensions(MediaRequest request, Media media) { Assert.ArgumentNotNull((object)request, nameof(request)); Assert.ArgumentNotNull((object)media, nameof(media)); Item innerItem = media.MediaData.MediaItem.InnerItem; int.TryParse(innerItem[Helper.Constants.TemplateFields.Height], out int result1); int.TryParse(innerItem[Helper.Constants.TemplateFields.Width], out int result2); bool flag = false; int maxHeight = Settings.Media.Resizing.MaxHeight; if (maxHeight != 0 && request.Options.Height > Math.Max(maxHeight, result1)) { flag = true; request.Options.Height = Math.Max(maxHeight, result1); } int maxWidth = Settings.Media.Resizing.MaxWidth; if (maxWidth != 0 && request.Options.Width > Math.Max(maxWidth, result2)) { flag = true; request.Options.Width = Math.Max(maxWidth, result2); } if (!flag) { return; } Log.Warn(string.Format(Helper.Constants.Message.ProcessImageDimensionsWarning, (object)request.InnerRequest.RawUrl), (object)this); }
/// <summary> /// Processes dimensions for dynamically scaled images according to configuration. /// /// </summary> /// <param name="request">The media request.</param><param name="media">The media.</param> private void ProcessImageDimensions(MediaRequest request, Sitecore.Resources.Media.Media media) { Assert.ArgumentNotNull((object)request, "request"); Assert.ArgumentNotNull((object)media, "media"); Item innerItem = media.MediaData.MediaItem.InnerItem; int result1; int.TryParse(innerItem["Height"], out result1); int result2; int.TryParse(innerItem["Width"], out result2); bool flag = false; int maxHeight = Settings.Media.Resizing.MaxHeight; if (maxHeight != 0 && request.Options.Height > Math.Max(maxHeight, result1)) { flag = true; request.Options.Height = Math.Max(maxHeight, result1); } int maxWidth = Settings.Media.Resizing.MaxWidth; if (maxWidth != 0 && request.Options.Width > Math.Max(maxWidth, result2)) { flag = true; request.Options.Width = Math.Max(maxWidth, result2); } if (!flag) { return; } Log.Warn(string.Format("Requested image exceeds allowed size limits. Requested URL:{0}", (object)request.InnerRequest.RawUrl), (object)this); }
protected override bool DoProcessRequest(HttpContext context) { Assert.ArgumentNotNull((object)context, "context"); //Sitecore produces media search result icons with wrong querystring (2 question marks): // "?h=48&thn=1&w=48&db=master?w=80&h=60&db=master" // using the 1st part only "?h=48&thn=1&w=48&db=master" and redirect to the fixed url: FixSearchResultIconUrl(context.Request); MediaRequest request = MediaManager.ParseMediaRequest(context.Request); if (request == null) { return(false); } Sitecore.Resources.Media.Media media = MediaManager.GetMedia(request.MediaUri); // handle 404 of media items if (media == null) { using (new SecurityDisabler()) media = MediaManager.GetMedia(request.MediaUri); string str; if (media == null) { str = Settings.ItemNotFoundUrl; } else { Assert.IsNotNull(Sitecore.Context.Site, "site"); str = Sitecore.Context.Site.LoginPage != string.Empty ? Sitecore.Context.Site.LoginPage : Settings.NoAccessUrl; } if (Settings.RequestErrors.UseServerSideRedirect) { HttpContext.Current.Server.TransferRequest(str); } else { HttpContext.Current.Response.Redirect(str); } return(true); } if (!IsCdnMedia(media)) { return(base.DoProcessRequest(context)); } if (request.Options.Thumbnail) { request.Options.UseMediaCache = false; return(base.DoProcessRequest(context, request, media)); } return(this.DoProcessRequest(context, media)); }
/// <summary> /// Processes the accept webp option for dynamically scaled images /// </summary> /// <param name="context">The HttpContext.</param> private void SetWebpOptions(MediaRequest request, HttpContext context) { Assert.ArgumentNotNull(request, "request"); if (AcceptWebP(context)) { request.Options.CustomOptions["webp"] = "1"; } }
/// <summary> /// Executes the process request event. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="request"> /// The request. /// </param> /// <param name="media"> /// The Sitecore media. /// </param> /// <returns> /// The <see cref="T:System.Boolean" /> that indicates whether request has been processed. /// </returns> protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media) { Assert.ArgumentNotNull(context, "context"); Assert.ArgumentNotNull(request, "request"); Assert.ArgumentNotNull(media, "media"); SetWebpOptions(request, context); return(base.DoProcessRequest(context, request, media)); }
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media) { if (context?.Request.QueryString?["extension"] == "webp" || (!Helpers.CdnEnabled && context.BrowserSupportsWebP())) { request.Options.CustomOptions["extension"] = "webp"; } return(base.DoProcessRequest(context, request, media)); }
public override MediaRequest ParseMediaRequest(HttpRequest request) { Assert.ArgumentNotNull((object)request, nameof(request)); MediaRequest mediaRequest = MediaManager.Config.ConstructMediaRequestInstance(request); if (mediaRequest != null && mediaRequest.MediaUri != null) { return(mediaRequest); } return((MediaRequest)null); }
// GET: Media public ActionResult Index(MediaRequest request = null) { request = request ?? new MediaRequest(); IQueryable <Media> medias = db.Medias; if (!string.IsNullOrEmpty(request.MediaName)) { medias = medias.Where(u => u.MediaName.Contains(request.MediaName)); } return(View(medias.OrderBy(u => u.Id).ToPagedList(request.PageIndex, request.PageSize))); }
/// <summary> /// Extracts the sitecore media item path from a Url /// </summary> /// <param name="localPath">~/media/path/to/file.ashx?w=1</param> /// <returns>/sitecore/media library/path/to/file</returns> public virtual string GetMediaItemPath(string localPath) { MediaRequest mr = new MediaRequest(); // this is a hack to access a private method in MediaRequest MethodInfo mi = ReflectionUtil.GetMethod(mr, "GetMediaPath", true, true, new object[] { localPath }); if (mi != null) { return((string)ReflectionUtil.InvokeMethod(mi, new object[] { localPath }, mr)); } return(null); }
public void Setup() { _someDatabase = Mock.Create <IDatabase>(); _someRequest = new MediaRequest { MediaID = _someID }; Mock.Arrange(() => _someDatabase.Update(DBTable.media, Arg.IsAny <Dictionary <string, string> >(), Arg.IsAny <KeyValuePair <string, string> >())); _someRequestContext = new MediaRequestContext() { DB = _someDatabase }; }
public async Task <MediaAbs> CreateMedia(MediaRequest mediaRequest) { try { EventType eventType = Conversions.EventTypeToStringRepresentation .Where(x => x.Value == mediaRequest.EventType) .Select(x => x.Key).First(); List <Person> participants = JsonConvert.DeserializeObject <List <Person> >(mediaRequest.Participants); DateTime date = DateTime.Parse(mediaRequest.Date); switch (mediaRequest.MediaType) { case "Book": var bookMedia = new BookMedia(mediaRequest.Name, eventType, participants, date, mediaRequest.Location); await SetUsingPersonIfNeede(bookMedia, mediaRequest.UsingPerson); return(bookMedia); case "CD": var cdMedia = new CDMedia(mediaRequest.Name, eventType, participants, date, mediaRequest.Location); await SetUsingPersonIfNeede(cdMedia, mediaRequest.UsingPerson); return(cdMedia); case "Disk On Key": var DiskOnKeyMedia = new DiskOnKeyMedia(mediaRequest.Name, eventType, participants, date, mediaRequest.Location); await SetUsingPersonIfNeede(DiskOnKeyMedia, mediaRequest.UsingPerson); return(DiskOnKeyMedia); case "Photo Album": var PhotoAlbumMedia = new PhotoAlbumMedia(mediaRequest.Name, eventType, participants, date, mediaRequest.Location); await SetUsingPersonIfNeede(PhotoAlbumMedia, mediaRequest.UsingPerson); return(PhotoAlbumMedia); default: return(null); } } catch (Exception e) { throw e; } }
public WSMediaContent.GetMediaContentResponse getMediaContent(MediaRequest mediaRequest) { this.setPath("mediaContentOutput"); var request = new WSMediaContent.GetMediaContentRequest(); request.wsVersion = mediaRequest.version; request.id = ConfigurationManager.AppSettings.Get("wsUserName"); request.password = ConfigurationManager.AppSettings.Get("wsPassword"); request.mediaType = WSMediaContent.mediaTypeType.Image; request.productId = mediaRequest.productId; var request1 = new WSMediaContent.getMediaContentRequest1(request); WSMediaContent.getMediaContentResponse1 response1 = wsClient.getMediaContent(request1); return(response1.GetMediaContentResponse); }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <string> GetCDNSeries(MediaRequest request) { var timestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var uri = new Uri(CDN_SERIES_URL + timestamp); var httpClient = _clientFactory.CreateClient("rezka"); var content = GetHttpContent(request); var response = await httpClient.PostAsync(uri, content); var result = await response.Content.ReadAsStringAsync(); return(result); }
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Media media) { Assert.ArgumentNotNull((object)context, nameof(context)); Assert.ArgumentNotNull((object)request, nameof(request)); Assert.ArgumentNotNull((object)media, nameof(media)); //OverRiding the Default Stream behavior to return CDN inage ProcessCdnRedirect(context, media); if (this.Modified(context, media, request.Options) == Tristate.False) { this.RaiseEvent(Helper.Constants.Properties.MediaRequest, request); this.SendMediaHeaders(media, context); context.Response.StatusCode = 304; return(true); } this.ProcessImageDimensions(request, media); MediaStream mediaStream = this.GetMediaStream(media, request); if (mediaStream == null) { return(false); } this.RaiseEvent(Helper.Constants.Properties.MediaRequest, request); if (Settings.Media.EnableRangeRetrievalRequest && Settings.Media.CachingEnabled) { using (mediaStream) { this.SendMediaHeaders(media, context); new RangeRetrievalResponse(RangeRetrievalRequest.BuildRequest(context, media), mediaStream).ExecuteRequest(context); return(true); } } else { this.SendMediaHeaders(media, context); this.SendStreamHeaders(mediaStream, context); using (mediaStream) { context.Response.AddHeader(Helper.Constants.Properties.ContentLength, mediaStream.Stream.Length.ToString()); WebUtil.TransmitStream(mediaStream.Stream, context.Response, Settings.Media.StreamBufferSize); } return(true); } }
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Sitecore.Resources.Media.Media media) { Assert.ArgumentNotNull((object)context, "context"); Assert.ArgumentNotNull((object)request, "request"); Assert.ArgumentNotNull((object)media, "media"); if (this.Modified(context, media, request.Options) == Tristate.False) { Event.RaiseEvent("media:request", new object[1] { (object)request }); this.SendMediaHeaders(media, context); context.Response.StatusCode = 304; return(true); } this.ProcessImageDimensions(request, media); MediaStream stream = media.GetStream(request.Options); if (stream == null) { return(false); } Event.RaiseEvent("media:request", new object[1] { (object)request }); if (Settings.Media.EnableRangeRetrievalRequest && Settings.Media.CachingEnabled) { using (stream) { this.SendMediaHeaders(media, context); new RangeRetrievalResponse(RangeRetrievalRequest.BuildRequest(context, media), stream).ExecuteRequest(context); return(true); } } else { this.SendMediaHeaders(media, context); this.SendStreamHeaders(stream, context); using (stream) { context.Response.AddHeader("Content-Length", stream.Stream.Length.ToString()); WebUtil.TransmitStream(stream.Stream, context.Response, Settings.Media.StreamBufferSize); } return(true); } }
public async Task <IActionResult> UpdateMedia([FromBody] MediaRequest mediaRequest) { MediaAbs media = await m_mediaFactory.CreateMedia(mediaRequest); if (media == null) { return(BadRequest(new { Error = "Media Type Not Found" })); } var updated = await m_mediaService.UpdateMedia(media, mediaRequest.Id); if (!updated) { return(NotFound()); } return(Ok(media)); }
protected override bool DoProcessRequest(HttpContext context, MediaRequest request, Sitecore.Resources.Media.Media media) { Assert.ArgumentNotNull((object)context, "context"); Assert.ArgumentNotNull((object)request, "request"); Assert.ArgumentNotNull((object)media, "media"); if (this.Modified(context, media, request.Options) == Tristate.False) { Event.RaiseEvent("media:request", new object[1] { (object) request }); this.SendMediaHeaders(media, context); context.Response.StatusCode = 304; return true; } this.ProcessImageDimensions(request, media); MediaStream stream = media.GetStream(request.Options); if (stream == null) return false; Event.RaiseEvent("media:request", new object[1] { (object) request }); if (Settings.Media.EnableRangeRetrievalRequest && Settings.Media.CachingEnabled) { using (stream) { this.SendMediaHeaders(media, context); new RangeRetrievalResponse(RangeRetrievalRequest.BuildRequest(context, media), stream).ExecuteRequest(context); return true; } } else { this.SendMediaHeaders(media, context); this.SendStreamHeaders(stream, context); using (stream) { context.Response.AddHeader("Content-Length", stream.Stream.Length.ToString()); WebUtil.TransmitStream(stream.Stream, context.Response, Settings.Media.StreamBufferSize); } return true; } }
private static HttpContent GetHttpContent(MediaRequest request) { string actionType = SeriesActionType.GetEpisodes; var fields = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("id", request.Id.ToString()), new KeyValuePair <string, string>("translator_id", request.TranslationId.ToString()), new KeyValuePair <string, string>("favs", request.FavsId) }; if (request is CDNSeriesRequest seriesRequest) { actionType = SeriesActionType.GetStream; var extraFields = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("season", seriesRequest.Season.ToString()), new KeyValuePair <string, string>("episode", seriesRequest.Episode.ToString()) }; fields.AddRange(extraFields); } if (request is MovieRequest movieRequest) { actionType = SeriesActionType.GetMovie; var extraFields = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("is_camrip", movieRequest.IsCamRip.ToString()), new KeyValuePair <string, string>("is_ads", movieRequest.IsAds.ToString()), new KeyValuePair <string, string>("is_director", movieRequest.IsDirector.ToString()) }; fields.AddRange(extraFields); } fields.Add(new KeyValuePair <string, string>("action", actionType)); var content = new FormUrlEncodedContent(fields); return(content); }
public async Task <IActionResult> AddMedia([FromBody] MediaRequest mediaRequest) { MediaAbs media = await m_mediaFactory.CreateMedia(mediaRequest); if (media == null) { return(BadRequest(new { Error = "Media Type Not Found" })); } await m_mediaService.AddMedia(media); var baseUri = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}://media"; var locationUrl = baseUri + "/" + media.Id.ToString(); var response = new MediaResponse() { Name = media.Name, Id = media.Id }; return(Created(locationUrl, response)); }
public Media DetermineImageResponse(HttpContext context, MediaRequest request, Media media) { Diagnostics.Assert.ArgumentNotNull(context, "context"); Diagnostics.Assert.ArgumentNotNull(request, "request"); Diagnostics.Assert.ArgumentNotNull(media, "media"); if (ShouldSkipWebProcessing(context)) { return(media); } // So why use a link field here ... Sitecore has a limitation on the default attachement field called Blob // You can only have one of these // So unfortunately you can't sore the WEBP and the JPEG binary data on the one Media Item in Sitecore. // At this stage the best way to do this for thie module is have two Media Items. Data.Fields.LinkField relatedField = media.MediaData.MediaItem.InnerItem.Fields["Related Compressed File"]; if (relatedField != null && relatedField.TargetItem != null) { var myMedia = new Data.Items.MediaItem(relatedField.TargetItem); media = new Media(new MediaData(myMedia)); } return(media); }
protected override bool DoProcessRequest(HttpContext context) { Assert.ArgumentNotNull((object)context, "context"); MediaRequest request = MediaManager.ParseMediaRequest(context.Request); if (request == null) { return(false); } Sitecore.Resources.Media.Media media = MediaManager.GetMedia(request.MediaUri); if (!IsCdnMedia(media)) { return(base.DoProcessRequest(context)); } if (request.Options.Thumbnail) { request.Options.UseMediaCache = false; return(base.DoProcessRequest(context, request, media)); } return(this.DoProcessRequest(context, media)); }
/// <summary> /// Extracts the sitecore media item path from a Url /// </summary> /// <param name="localPath">~/media/path/to/file.ashx?w=1</param> /// <returns>/sitecore/media library/path/to/file</returns> public virtual string GetMediaItemPath(string localPath) { MediaRequest mr = new MediaRequest(); // this is a hack to access a private method in MediaRequest MethodInfo mi = ReflectionUtil.GetMethod(mr, "GetMediaPath", true, true, new object[] { localPath }); if (mi != null) { return (string)ReflectionUtil.InvokeMethod(mi, new object[] { localPath }, mr); } return null; }
private void button1_Click(object sender, EventArgs e) { ConnectionSetter connection = new ConnectionSetter(); String originalFolder = @"C:\Users\Caroline\Documents\json data"; String folder = ""; String dateModifiedJson = ""; if (comboBox1.Text.Equals("Debco")) { folder = FileFolderUtils.addAndCreateFolder(originalFolder, "\\debco data"); connection.readConnectionConfig("..\\..\\config\\Debco.cfg"); connection.productDataEndpoint = "ProductDataServiceDebco"; dateModifiedJson = folder + "\\debcoDateModified.json"; if (comboBox2.Text.Equals("Descriptions")) { connection.endpoint = connection.productDataEndpoint; } else if (comboBox2.Text.Equals("Prices")) { connection.endpoint = "ProductPricingServiceDebco"; } else if (comboBox2.Text.Equals("Pictures")) { connection.endpoint = "ProductMediaServiceDebco"; } } else if (comboBox1.Text.Equals("Cap America")) { folder = FileFolderUtils.addAndCreateFolder(originalFolder, "\\capam data"); connection.readConnectionConfig("..\\..\\config\\CapAmerica.cfg"); connection.productDataEndpoint = "ProductDataServiceCapAm"; dateModifiedJson = folder + "\\capamDateModified.json"; if (comboBox2.Text.Equals("Descriptions")) { connection.endpoint = connection.productDataEndpoint; } else if (comboBox2.Text.Equals("Prices")) { connection.endpoint = "ProductPricingServiceCapAm"; } } else if (comboBox1.Text.Equals("PCNA")) { folder = FileFolderUtils.addAndCreateFolder(originalFolder, "\\pcna data"); connection.readConnectionConfig("..\\..\\config\\Pcna.cfg"); connection.productDataEndpoint = "ProductDataServicePcna"; dateModifiedJson = folder + "\\pcnaDateModified.json"; if (comboBox2.Text.Equals("Descriptions")) { connection.endpoint = connection.productDataEndpoint; } else if (comboBox2.Text.Equals("Prices")) { connection.endpoint = "ProductPricingServicePcna"; } else if (comboBox2.Text.Equals("Pictures")) { connection.endpoint = "ProductMediaServicePcna"; } } else if (comboBox1.Text.Equals("Starline")) { folder = FileFolderUtils.addAndCreateFolder(originalFolder, "\\starline data"); connection.readConnectionConfig("..\\..\\config\\Starline.cfg"); connection.productDataEndpoint = "ProductDataServiceStarline"; dateModifiedJson = folder + "\\starlineDateModified.json"; if (comboBox2.Text.Equals("Descriptions")) { connection.endpoint = connection.productDataEndpoint; } else if (comboBox2.Text.Equals("Prices")) { connection.endpoint = "ProductPricingServiceStarline"; } else if (comboBox2.Text.Equals("Pictures")) { connection.endpoint = "ProductMediaServiceStarline"; } } ConfigurationManager.AppSettings.Set("wsUsername", connection.username); ConfigurationManager.AppSettings.Set("wsPassword", connection.password); var productDataTester = new ProductDataClient(connection.productDataEndpoint); var productDataResponse = productDataTester.getProductDateModified(); Program.printResponse(productDataResponse, dateModifiedJson, productDataTester.validTypes); List <String> articleIds = JsonUtils.readJson(dateModifiedJson); StreamWriter fileStream = new StreamWriter(originalFolder + "\\debug.txt"); if (comboBox2.Text.Equals("Descriptions")) { DataRequest frRequest = new DataRequest(); frRequest.version = "1.0.0"; frRequest.country = "CA"; frRequest.language = "fr"; DataRequest enRequest = new DataRequest(); enRequest.version = "1.0.0"; enRequest.country = "US"; enRequest.language = "en"; /*if (comboBox1.Text.Equals("Starline")) * { * frRequest.version = "2.0.0"; * enRequest.version = "2.0.0"; * }*/ articleIds = ArrayListUtils.RemoveDuplicates(articleIds); String frFolder = FileFolderUtils.addAndCreateFolder(folder, "\\fr\\"); String enFolder = FileFolderUtils.addAndCreateFolder(folder, "\\en\\"); foreach (String id in articleIds) { Console.WriteLine(id); var output = new StringBuilder(); var enResponse = productDataTester.getProductData(enRequest, id); var frResponse = productDataTester.getProductData(frRequest, id); try { var enResponseType = enResponse.GetType(); var frResponseType = frResponse.GetType(); output.AppendLine("Response Object: " + frResponseType.Name); Console.WriteLine(frResponseType.GetProperties()[0].GetValue(frResponse)); enResponseType.GetProperties()[0].GetValue(enResponse).GetType(); frResponseType.GetProperties()[0].GetValue(frResponse).GetType(); StreamWriter frFile = File.CreateText(frFolder + id + ".json"); JsonWriter frWriter = new JsonTextWriter(frFile); frWriter.Formatting = Formatting.Indented; fileStream.WriteLine(id); PropertyInfo frProperty = frResponseType.GetProperties()[0]; JsonUtils.printJson(frProperty, frProperty.GetValue(frResponse), ref frWriter, 1); //writer.WriteEndObject(); frWriter.Flush(); frWriter.Close(); StreamWriter enFile = File.CreateText(enFolder + id + ".json"); JsonWriter enWriter = new JsonTextWriter(enFile); enWriter.Formatting = Formatting.Indented; PropertyInfo enProperty = enResponseType.GetProperties()[0]; JsonUtils.printJson(enProperty, enProperty.GetValue(enResponse), ref enWriter, 1); //writer.WriteEndObject(); enFile.Flush(); enFile.Close(); } catch (Exception error) { //error.ToString(); } } fileStream.Close(); } else if (comboBox2.Text.Equals("Prices")) { var pricingConfigurationClient = new PricingAndConfigurationClient(connection.endpoint); PricingRequest pricingRequest = new PricingRequest(); pricingRequest.version = "1.0.0"; pricingRequest.priceType = WSPricingAndConfiguration.priceType.List; pricingRequest.currency = WSPricingAndConfiguration.CurrencyCodeType.CAD; pricingRequest.fobId = "1"; string priceFolder = FileFolderUtils.addAndCreateFolder(folder, "\\prix\\"); foreach (String id in articleIds) { Console.WriteLine(id); var output = new StringBuilder(); pricingRequest.productId = id; var pricingResponse = pricingConfigurationClient.getConfigurationAndPricing(pricingRequest); try { var pricingResponseType = pricingResponse.GetType(); output.AppendLine("Response Object: " + pricingResponseType.Name); pricingResponseType.GetProperties()[0].GetValue(pricingResponse).GetType(); StreamWriter pricingFile = File.CreateText(priceFolder + id + ".json"); JsonWriter pricingWriter = new JsonTextWriter(pricingFile); pricingWriter.Formatting = Formatting.Indented; fileStream.WriteLine(id); foreach (var property in pricingResponseType.GetProperties()) { JsonUtils.printJson(property, property.GetValue(pricingResponse), ref pricingWriter, 1); } //writer.WriteEndObject(); pricingWriter.Flush(); pricingWriter.Close(); } catch (Exception error) { //error.ToString(); } } fileStream.Close(); } else if (comboBox2.Text.Equals("Pictures")) { var productMediaClient = new ProductMediaClient(connection.endpoint); MediaRequest mediaRequest = new MediaRequest(); mediaRequest.version = "1.1.0"; articleIds = ArrayListUtils.RemoveDuplicates(articleIds); string photoFolder = FileFolderUtils.addAndCreateFolder(folder, "\\photo\\"); foreach (String id in articleIds) { var output = new StringBuilder(); mediaRequest.productId = id; var pricingResponse = productMediaClient.getMediaContent(mediaRequest); try { var pricingResponseType = pricingResponse.GetType(); output.AppendLine("Response Object: " + pricingResponseType.Name); Console.WriteLine(pricingResponseType.GetProperties()[1].GetValue(pricingResponse).GetType().GetProperties()[0].GetValue(pricingResponseType.GetProperties()[1].GetValue(pricingResponse))); pricingResponseType.GetProperties()[0].GetValue(pricingResponse).GetType(); StreamWriter pricingFile = File.CreateText(photoFolder + id + ".json"); JsonWriter pricingWriter = new JsonTextWriter(pricingFile); pricingWriter.Formatting = Formatting.Indented; fileStream.WriteLine(id); pricingWriter.WriteStartObject(); foreach (var property in pricingResponseType.GetProperties()) { Console.WriteLine(id); JsonUtils.printJson(property, property.GetValue(pricingResponse), ref pricingWriter, 1); } Console.WriteLine("test"); pricingWriter.WriteEndObject(); pricingWriter.Flush(); pricingWriter.Close(); } catch (Exception error) { //error.ToString(); } } fileStream.Close(); Console.WriteLine("End"); } }
/// <summary> /// Processes dimensions for dynamically scaled images according to configuration. /// /// </summary> /// <param name="request">The media request.</param><param name="media">The media.</param> private void ProcessImageDimensions(MediaRequest request, Sitecore.Resources.Media.Media media) { Assert.ArgumentNotNull((object)request, "request"); Assert.ArgumentNotNull((object)media, "media"); Item innerItem = media.MediaData.MediaItem.InnerItem; int result1; int.TryParse(innerItem["Height"], out result1); int result2; int.TryParse(innerItem["Width"], out result2); bool flag = false; int maxHeight = Settings.Media.Resizing.MaxHeight; if (maxHeight != 0 && request.Options.Height > Math.Max(maxHeight, result1)) { flag = true; request.Options.Height = Math.Max(maxHeight, result1); } int maxWidth = Settings.Media.Resizing.MaxWidth; if (maxWidth != 0 && request.Options.Width > Math.Max(maxWidth, result2)) { flag = true; request.Options.Width = Math.Max(maxWidth, result2); } if (!flag) return; Log.Warn(string.Format("Requested image exceeds allowed size limits. Requested URL:{0}", (object)request.InnerRequest.RawUrl), (object)this); }
/// <summary> /// Extracts the sitecore media item path from a Url /// </summary> /// <param name="localPath">~/media/path/to/file.ashx?w=1</param> /// <returns>/sitecore/media library/path/to/file</returns> public virtual string GetMediaItemPath(string localPath) { var mr = new MediaRequest(); // this is a hack to access a private method in MediaRequest MethodInfo mi = ReflectionUtil.GetMethod(mr, "GetMediaPath", true, true, new object[] { localPath }); if (mi == null) { return null; } var result = (string)ReflectionUtil.InvokeMethod(mi, new object[] { localPath }, mr); // NOTE: DOREL CHANGE: replace %20 with white-space return !string.IsNullOrEmpty(result) ? result.Replace("%20", " ") : result; }
/// <summary> /// Process the current request and return false if the media item was not found, so Sitecore /// can go ahead with processing the pipelines. Also check the <c>availableLanguages</c> /// from the current <see cref="Sitecore.Sites.SiteContext" /> to check for a valid language /// version of the media. /// </summary> /// <param name="context">Current <see cref="System.Web.HttpContext" />.</param> /// <returns><c>True</c> if everything was OK, <c>false</c> if the request is invalid or the media was not found.</returns> protected override bool DoProcessRequest(HttpContext context) { Assert.ArgumentNotNull(context, "context"); Assert.IsNotNull(Sitecore.Context.Site, "site"); MediaRequest mediaRequest = MediaManager.ParseMediaRequest(context.Request); if (mediaRequest == null) { return(false); } bool notfound = false; bool noaccess = false; string redirect = string.Empty; // get media Media media = MediaManager.GetMedia(mediaRequest.MediaUri); try { Language lang = UrlUtil.ResolveLanguage(); // check item in language Item mediaItem = Sitecore.Context.Database.GetItem(mediaRequest.MediaUri.MediaPath); if (Sitecore.Context.GetSiteName() != "shell" && (mediaItem?.Fields["Blob"] == null || (!mediaItem.Fields["Blob"].Shared && !mediaItem.HasLanguageVersion(lang, Sitecore.Context.Site.Properties["availableLanguages"])))) { notfound = true; } } catch (Exception) { notfound = true; } // check for media if (media == null) { using (new SecurityDisabler()) { media = MediaManager.GetMedia(mediaRequest.MediaUri); } // this would not take an effect // mediaItem is read above without security disabler // null mediaItem implies true notfound // and further notfound has priority over noaccess if (media == null) { notfound = true; } else { noaccess = true; } } // generate redirect url if (notfound) { redirect = Sitecore.Configuration.Settings.ItemNotFoundUrl; } else if (noaccess) { redirect = ((Sitecore.Context.Site.LoginPage != string.Empty) ? Sitecore.Context.Site.LoginPage : Sitecore.Configuration.Settings.NoAccessUrl); } // redirect if needed if (!string.IsNullOrEmpty(redirect)) { if (Sitecore.Configuration.Settings.RequestErrors.UseServerSideRedirect) { HttpContext.Current.Items[Constants.IsMediaParameterName] = true; HttpContext.Current.Server.Transfer(redirect); } else { Sitecore.Web.WebUtil.AddQueryString(redirect, Constants.IsMediaParameterName, bool.TrueString); HttpContext.Current.Response.Redirect(redirect); } return(false); } return(this.DoProcessRequest(context, mediaRequest, media)); }
protected override bool DoProcessRequest(System.Web.HttpContext context) { Assert.ArgumentNotNull(context, "context"); // If we're in a Sitecore internal site (admin, shell etc), // then use the base MediaRequestHandler if (Sitecore.Context.Domain.Name == "sitecore") { return(base.DoProcessRequest(context)); } MediaRequest request = MediaManager.ParseMediaRequest(context.Request); // By default Sitecore will get the first matching // item regardless of the file extension. var mediaPath = request.MediaUri.MediaPath; var firstGuess = Context.Database.GetItem(mediaPath); if (firstGuess == null) { return(false); } string urlExtenstion = GetFileExtension(context.Request.RawUrl).ToLower(); // if the extension of the first guess item is // incorrect, then we have some work to do. if (firstGuess["Extension"].ToLower() != urlExtenstion) { // Check if any of the matched item's siblings have // a matching path and file extension. var siblings = firstGuess.Parent.Children; var matches = siblings.Where(t => t.Paths.Path == firstGuess.Paths.Path && t.Fields["Extensioin"].Value.ToLower() == urlExtenstion).ToList(); //from sibling in siblings // where firstGuess.Paths.Path == sibling.Paths.Path && // sibling["Extension"].ToLower() == urlExtenstion // select ; if (!matches.Any()) { return(false); } var selectedItem = matches.First(); // Now we've identified the correct item, we can // reference it by ID rather than path. request.MediaUri.MediaPath = selectedItem.ID.ToString(); } Media media = MediaManager.GetMedia(request.MediaUri); if (media == null) { return(false); } return(DoProcessRequest(context, request, media)); }
public HttpResponseMessage Put(int id, [FromBody] MediaRequest request) { _mediaRequestContext.Save(request); return(Request.CreateResponse(HttpStatusCode.OK)); }
public MediaRequestWrapper(MediaRequest mediaRequest) { _databaseName = mediaRequest.MediaUri.Database.Name; _languageName = mediaRequest.MediaUri.Language.CultureInfo.Name; _mediaPath = mediaRequest.MediaUri.MediaPath; }
private MediaStream ProcessThumbnail(MediaRequest request, Sitecore.Resources.Media.Media media) { MediaStream mStream = null; if (request.Options.Height == 0 && request.Options.Width == 0) { request.Options.Thumbnail = true; } mStream = MediaManager.Cache.GetStream(media, request.Options); if (mStream == null) { string tempPath = Settings.TempFolderPath + "/PDF-Thumbnails/"; tempPath = MainUtil.MapPath(tempPath); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } // Prepare filenames string pdfFile = tempPath + media.MediaData.MediaItem.ID.ToString() + ".pdf"; string jpgFile = tempPath + media.MediaData.MediaItem.ID.ToString() + "_" + media.MediaData.MediaItem.InnerItem["revision"] + ".jpg"; string resizedJpgFile = tempPath + media.MediaData.MediaItem.ID.ToString() + "_" + request.Options.Width.ToString() + "_" + request.Options.Height.ToString(); if (!File.Exists(jpgFile)) { // Save BLOB media file to disk MediaConverter.ConvertMediaItemToFile(media.MediaData.MediaItem, pdfFile); // Convert PDF to Jpeg - First Pager MediaConverter.ConvertPDFtoJPG(pdfFile, 1, jpgFile); } // Resize Image MediaConverter.ReSizeJPG(jpgFile, resizedJpgFile, request.Options.Width, request.Options.Height, true); // Convert resized image to stream mStream = new MediaStream(File.Open(resizedJpgFile, FileMode.Open, FileAccess.Read, FileShare.Read), "jpg", media.MediaData.MediaItem); // Add the requested thumbnail to Media Cache MediaStream outStream = null; MediaManager.Cache.AddStream(media, request.Options, mStream, out outStream); if (outStream != null) { // If Media cache is enabled return outStream; } } // If Media cache is disabled return mStream; }
public MediaRequestWrapper(MediaRequest mediaRequest) { _databaseName = mediaRequest.MediaUri.Database.Name; _languageName = mediaRequest.MediaUri.Language.CultureInfo.Name; _mediaPath = mediaRequest.MediaUri.MediaPath; }