public static void WikipediaHtmlExampleParseTest() { // <img src="data:image/png;base64,iVBORw0KGgoAAA // ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4 // //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU // 5ErkJggg==" alt="Red dot" /> var actual = DataUri.Parse( "data:image/png;base64,iVBORw0KGgoAAA" + "ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4" + "//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU" + "5ErkJggg==" ); var expected = new DataUri( mediaType: "image/png", parameters: new Dictionary <string, string>(), data: new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130 } ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
/// <summary> /// Gets the OpenXml ImagePartType associated to an image. /// </summary> public static ImagePartType?GetImagePartTypeForImageUrl(Uri uri) { ImagePartType type; String extension = System.IO.Path.GetExtension(uri.IsAbsoluteUri ? uri.Segments[uri.Segments.Length - 1] : uri.OriginalString); if (knownExtensions.TryGetValue(extension, out type)) { return(type); } // extension not recognized, try with checking the query string. Expecting to resolve something like: // ./image.axd?picture=img1.jpg extension = System.IO.Path.GetExtension(uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.ToString()); if (knownExtensions.TryGetValue(extension, out type)) { return(type); } // so, match text of the form: data:image/yyy;base64,zzzzzzzzzzzz... // where yyy is the MIME type, zzz is the base64 encoded data DataUri dataUri = DataUri.Parse(uri.ToString()); if (dataUri != null) { if (knownContentType.TryGetValue(dataUri.Mime, out type)) { return(type); } } return(null); }
public static void DataUriFunctionExample2ParseTest() { var actual = DataUri.Parse("data:;base64,SGVsbG8sIFdvcmxkIQ=="); var expected = new DataUri( mediaType: string.Empty, parameters: new Dictionary <string, string>(), data: Encoding.UTF8.GetBytes("Hello, World!") ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
public void DataUriToObjectUnknownMediaType() { string imageUri = "data:image/jpeg;base64,fooBar"; try { var dataUri = DataUri.Parse(imageUri); DataUri.ToObject <Bitmap>(dataUri); throw new Exception("DataUri Should be invalid"); } catch (ArgumentException) { } }
//____________________________________________________________________ // // Public Functionality #region DownloadData /// <summary> /// Download the remote or local image located at the specified url. /// </summary> public HtmlImageInfo DownloadData(Uri imageUrl) { // is it a local path? if (imageUrl.IsFile) { // replace string %20 in LocalPath by daviderapicavoli (patch #15938) String localPath = Uri.UnescapeDataString(imageUrl.LocalPath); try { // just read the picture from the file system imageInfo.RawData = File.ReadAllBytes(localPath); } catch (Exception exc) { if (Logging.On) { Logging.PrintError("ImageDownloader.DownloadData(\"" + localPath + "\")", exc); } if (exc is IOException || exc is UnauthorizedAccessException || exc is System.Security.SecurityException || exc is NotSupportedException) { return(null); } throw; } return(imageInfo); } // data inline, encoded in base64 if (imageUrl.Scheme == "data") { DataUri dataUri = DataUri.Parse(imageUrl.OriginalString); return(DownloadData(dataUri)); } var response = BackChannels.CreateWebRequest(imageUrl, proxy); if (response != null) { imageInfo.RawData = response.Body; // For requested url with no filename, we need to read the media mime type if provided imageInfo.Type = InspectMimeType(response.ContentType); } return(imageInfo); }
public static void WikipediaExample1ParseTest() { var actual = DataUri.Parse("data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh"); var expected = new DataUri( mediaType: "text/vnd-example+xyz", parameters: new Dictionary <string, string> { { "foo", "bar" } }, data: Encoding.ASCII.GetBytes("GIF87a") ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
public static void DataUriFunctionExample1ParseTest() { var actual = DataUri.Parse("data:text/plain;charset=utf8;base64,SGVsbG8="); var expected = new DataUri( mediaType: "text/plain", parameters: new Dictionary <string, string> { { "charset", "utf8" } }, data: Encoding.UTF8.GetBytes("Hello") ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
public static void WikipediaExample2ParseTest() { var actual = DataUri.Parse("data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678"); var expected = new DataUri( mediaType: "text/plain", parameters: new Dictionary <string, string> { { "charset", "UTF-8" }, { "page", "21" }, }, data: Encoding.ASCII.GetBytes("the data:1234,5678") ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
public void ParseMultiline() { string html = @"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8l JCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/wAALCABVAEABAREA/8QAHwAA AQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQR BRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RF RkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ip qrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/9oACAEB AAA/APXNS1Gz0jT5r+/nWC2gXdJI3QD/AD2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XNdX4i8JxeHvgnfaUvzzRxLPPJ1Ly71Zj+mPoBXE/DP4kWnhTTl 0nUoHazmuZHlmVSTFlVC8dwSGz3o+IEPhjxVqtjF4GtDc6lMx+0C0hZIyD0JBAAOe/510+i+ OfDEXhz/AIRbxtAkV1pYNrJHNC0qSbPlDKQDg8e3tVD4Q6BKPGmp67Y2lxbaJ5ckVo04IMgZ 1KjnqAByfXFezMiv95Q2PUZoCKOigY9BSkA9QDjmgqGBDAEHsaia0tnQxtbxMjdVKAg0W9pb Wilba3ihB6iNAufyoltLaZw8tvFIw6FkBNSgADA4FLRRRRRRRX//2Q== "; Assert.IsNotNull(DataUri.Parse(html)); }
public static void Rfc2397ExampleParseTest() { var actual = DataUri.Parse( "data:,A%20brief%20note" ); var expected = new DataUri( mediaType: string.Empty, parameters: new Dictionary <string, string>(), data: new byte[] { 65, 32, 98, 114, 105, 101, 102, 32, 110, 111, 116, 101 } ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
public static void WikipediaCssExampleParseTest() { // ul.checklist li.complete { // padding-left: 20px; // background: white url('data:image/png;base64,iVB\ // ORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEU\ // AAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8\ // yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAEl\ // FTkSuQmCC') no-repeat scroll left top; // } var actual = DataUri.Parse( "data:image/png;base64,iVB" + "ORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEU" + "AAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8" + "yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAEl" + "FTkSuQmCC" ); var expected = new DataUri( mediaType: "image/png", parameters: new Dictionary <string, string>(), data: new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 16, 0, 0, 0, 16, 1, 3, 0, 0, 0, 37, 61, 109, 34, 0, 0, 0, 6, 80, 76, 84, 69, 0, 0, 0, 255, 255, 255, 165, 217, 159, 221, 0, 0, 0, 51, 73, 68, 65, 84, 120, 156, 99, 248, 255, 159, 225, 255, 95, 134, 255, 159, 25, 14, 176, 51, 220, 63, 204, 112, 127, 50, 195, 205, 205, 12, 55, 141, 25, 238, 20, 131, 208, 189, 207, 12, 247, 129, 82, 204, 12, 15, 192, 232, 255, 127, 0, 81, 134, 23, 40, 206, 93, 155, 80, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130 } ); Assert.AreEqual(expected.MediaType, actual.MediaType); Assert.AreEqual(expected.Parameters, actual.Parameters); Assert.AreEqual(expected.Data, actual.Data); }
private Drawing AddImagePart(Uri imageUrl, String imageSource, String alt, Size preferredSize) { if (imageObjId == UInt32.MinValue) { // In order to add images in the document, we need to asisgn an unique id // to each Drawing object. So we'll loop through all of the existing <wp:docPr> elements // to find the largest Id, then increment it for each new image. drawingObjId = 1; // 1 is the minimum ID set by MS Office. imageObjId = 1; foreach (var d in mainPart.Document.Body.Descendants <Drawing>()) { if (d.Inline == null) { continue; // fix some rare issue where Inline is null (reported by scwebgroup) } if (d.Inline.DocProperties.Id > drawingObjId) { drawingObjId = d.Inline.DocProperties.Id; } var nvPr = d.Inline.Graphic.GraphicData.GetFirstChild <pic.NonVisualPictureProperties>(); if (nvPr != null && nvPr.NonVisualDrawingProperties.Id > imageObjId) { imageObjId = nvPr.NonVisualDrawingProperties.Id; } } if (drawingObjId > 1) { drawingObjId++; } if (imageObjId > 1) { imageObjId++; } } // Cache all the ImagePart processed to avoid downloading the same image. CachedImagePart imagePart = null; // if imageUrl is null, we may consider imageSource is a DataUri. // thus, no need to download and cache anything if (imageUrl == null || !knownImageParts.TryGetValue(imageUrl, out imagePart)) { HtmlImageInfo iinfo = null; ImageProvisioningProvider provider = new ImageProvisioningProvider(this.WebProxy, preferredSize); if (imageUrl == null) { iinfo = provider.DownloadData(DataUri.Parse(imageSource)); } else if (this.ImageProcessing == ImageProcessing.ManualProvisioning) { // as HtmlImageInfo is a class, the EventArgs will act as a proxy iinfo = new HtmlImageInfo() { Size = preferredSize }; ProvisionImageEventArgs args = new ProvisionImageEventArgs(imageUrl, iinfo); OnProvisionImage(args); // did the user want to ignore this image? if (args.Cancel) { return(null); } } // Automatic Processing or the user did not supply himself the image and did not cancel the provisioning. // We download ourself the image. if (iinfo == null || (iinfo.RawData == null && imageUrl.IsAbsoluteUri)) { iinfo = provider.DownloadData(imageUrl); } if (!ImageProvisioningProvider.Provision(iinfo, imageUrl)) { return(null); } ImagePart ipart = mainPart.AddImagePart(iinfo.Type.Value); imagePart = new CachedImagePart() { Part = ipart }; imagePart.Width = iinfo.Size.Width; imagePart.Height = iinfo.Size.Height; using (Stream outputStream = ipart.GetStream(FileMode.Create)) { outputStream.Write(iinfo.RawData, 0, iinfo.RawData.Length); outputStream.Seek(0L, SeekOrigin.Begin); } if (imageUrl != null) // don't need to cache inlined-image { knownImageParts.Add(imageUrl, imagePart); } } if (preferredSize.IsEmpty) { preferredSize.Width = imagePart.Width; preferredSize.Height = imagePart.Height; } else if (preferredSize.Width <= 0 || preferredSize.Height <= 0) { Size actualSize = new Size(imagePart.Width, imagePart.Height); preferredSize = ImageHeader.KeepAspectRatio(actualSize, preferredSize); } String imagePartId = mainPart.GetIdOfPart(imagePart.Part); long widthInEmus = new Unit(UnitMetric.Pixel, preferredSize.Width).ValueInEmus; long heightInEmus = new Unit(UnitMetric.Pixel, preferredSize.Height).ValueInEmus; ++drawingObjId; ++imageObjId; var img = new Drawing( new wp.Inline( new wp.Extent() { Cx = widthInEmus, Cy = heightInEmus }, new wp.EffectExtent() { LeftEdge = 19050L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new wp.DocProperties() { Id = drawingObjId, Name = imageSource, Description = String.Empty }, new wp.NonVisualGraphicFrameDrawingProperties { GraphicFrameLocks = new a.GraphicFrameLocks() { NoChangeAspect = true } }, new a.Graphic( new a.GraphicData( new pic.Picture( new pic.NonVisualPictureProperties { NonVisualDrawingProperties = new pic.NonVisualDrawingProperties() { Id = imageObjId, Name = imageSource, Description = alt }, NonVisualPictureDrawingProperties = new pic.NonVisualPictureDrawingProperties( new a.PictureLocks() { NoChangeAspect = true, NoChangeArrowheads = true }) }, new pic.BlipFill( new a.Blip() { Embed = imagePartId }, new a.SourceRectangle(), new a.Stretch( new a.FillRectangle())), new pic.ShapeProperties( new a.Transform2D( new a.Offset() { X = 0L, Y = 0L }, new a.Extents() { Cx = widthInEmus, Cy = heightInEmus }), new a.PresetGeometry( new a.AdjustValueList() ) { Preset = a.ShapeTypeValues.Rectangle } ) { BlackWhiteMode = a.BlackWhiteModeValues.Auto }) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U } ); return(img); }
/// <summary> /// Gets the object. /// </summary> /// <param name="model">The model.</param> /// <param name="db">The db.</param> /// <returns></returns> /// <exception cref="Glass.Mapper.MapperException">Failed to find context {0}.Formatted(ContextName)</exception> public virtual object GetObject(string model, Database db, Rendering renderingItem) { if (model.IsNullOrEmpty()) { return(null); } //must be a path to a Model item if (model.StartsWith("/sitecore")) { var target = db.GetItem(model); if (target == null) { return(null); } string newModel = target[ModelTypeField]; return(GetObject(newModel, db, renderingItem)); } //if guid must be that to Model item Guid targetId; if (Guid.TryParse(model, out targetId)) { var target = db.GetItem(new ID(targetId)); if (target == null) { return(null); } string newModel = target[ModelTypeField]; return(GetObject(newModel, db, renderingItem)); } var type = Type.GetType(model, false); if (type == null || renderingModelType.IsAssignableFrom(type)) { return(null); } IMvcContext mvcContext = new MvcContext(new SitecoreService(Sitecore.Context.Database)); //this is really aggressive if (!mvcContext.SitecoreService.GlassContext.TypeConfigurations.ContainsKey(type)) { //if the config is null then it is probably an ondemand mapping so we have to load the ondemand part IConfigurationLoader loader = new OnDemandLoader <SitecoreTypeConfiguration>(type); mvcContext.SitecoreService.GlassContext.Load(loader); } if (renderingItem.DataSource.HasValue()) { // Switch to handle AB test datasources which contain Sitecore reference // syntax //TODO: repeated code - refactor to a helper and use in IMvcContext var item = renderingItem.DataSource.StartsWith("sitecore://", StringComparison.Ordinal) ? Sitecore.Context.Database.GetItem(DataUri.Parse(renderingItem.DataSource)) : MvcSettings.ItemLocator.GetItem(renderingItem.DataSource); var getOptions = new GetItemByItemOptions() { Item = item, Type = type }; return(mvcContext.SitecoreService.GetItem(getOptions)); } if (renderingItem.RenderingItem.DataSource.HasValue()) { var getOptions = new GetItemByPathOptions() { Path = renderingItem.RenderingItem.DataSource, Type = type }; return(mvcContext.SitecoreService.GetItem(getOptions)); } /** * Issues #82: * Check Item before defaulting to the current item. */ if (renderingItem.Item != null) { var getOptions = new GetItemByItemOptions() { Item = renderingItem.Item, Type = type }; return(mvcContext.SitecoreService.GetItem(getOptions)); } else { //TODO? shoudl we use the GetCurrentitem var getOptions = new GetItemByItemOptions() { Item = mvcContext.ContextItem, Type = type }; return(mvcContext.SitecoreService.GetItem(getOptions)); } }