XpsDocument xpsDoc = new XpsDocument(fileName, FileAccess.Read);
documentViewer.Document = xpsDoc.GetFixedDocumentSequence();
Second line gives next error: Compressed part has inconsistent data length
Why?
Ok, I've found an answer.
I have created Xps document in this way:
Package package = Package.Open(fileName, FileMode.Create);
XpsDocument xpsDocument = new XpsDocument(package);
Thus, after saving it and trying to view I got Compressed part has inconsistent data length error.
Then I changed
Package package = Package.Open(fileName, FileMode.Create);
XpsDocument xpsDocument = new XpsDocument(package);
to
XpsDocument xpsDocument = new XpsDocument(fileName, FileAccess.ReadWrite);
And it started working.
Hope this will help somebody who may face with it.
Related
SSRS report in VS2015 using a custom function to convert a value to barcode image using zxing.dll. I found this article Generate barcode using Visual Studio local report or SSRS which is essentially identical to what I'm trying to do and have followed it. When I preview the report, it produces the warnings below and the image shows the red-x. I can deploy the report but no images appear in the related columns. The image is set with the correct mime type (image/bmp) but I've tried others with the same results.
NOTE: I've searched for and read several articles that helped me make progress but can't seem to resolve this issue.
The complete errors are:
[rsRuntimeErrorInExpression] The Value expression for the image ‘ImageFromFunction’ contains an error: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
[rsInvalidDatabaseImageProperty] The value of the ImageData property for the image ‘ImageFromFunction’ is “=Code.TextToBarcode128Bmp(Fields!barcode_value.Value)”, which is not a valid ImageData.
I have a WPF where this same code (in C#) works fine. There is just something about using it in SSRS that it doesn't like. The first message seems to indicate that it is a permissions/version kind of thing. I know that SSRS is .NET 2.0. I've set my reference to System.Drawing to 2.0 versions and copied over the 2.0 version of zxing.dll to the server.
It looks like it is attempting to get security permissions (probably for the zxing.dll?) but is unable to reach System.Security.Permissions.SecurityPermission?
References
zxing, Version=0.15.0.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60
System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
I tried added a reference to the 2.0 version of System.Security but it still produced the same error.
This is the custom function:
Public Function TextToBarcode(ByVal text As String) As Byte()
Dim writer As New ZXing.BarcodeWriter()
writer.Format = ZXing.BarcodeFormat.CODE_128
writer.Options = New ZXing.Common.EncodingOptions
writer.Options.Width = 125
writer.Options.Height = 100
Dim bmp As System.Drawing.Bitmap = writer.Write(text)
Dim ms AS System.IO.MemoryStream = new System.IO.MemoryStream()
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
Dim imagedata as byte()
imagedata = ms.GetBuffer()
Return imagedata
End Function
UPDATE
I followed the steps in the article SSRS: System.Security.Permissions.SecurityPermission (Thanks, Michael and Superman) which is based upon this article How to use custom assemblies or embedded code in Reporting Services
On the server, I added zxing.dll to the GAC from its location in D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\bin
On the server, I added a CodeGroup to D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\rssrvpolicy.config:
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="ZXingCodeGroup"
Description="Code group for ZXing">
<IMembershipCondition
class="UrlMembershipCondition"
version="1"
Url="D:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\bin\zxing.dll"
/>
</CodeGroup>
And I restarted Reporting Services. No change in behavior: Running deployed report produces no errors but does not display the barcode.
On the VS dev system, I then added the CodeGroup to C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\PrivateAssemblies\RSPreviewPolicy.config and closed and re-opened Visual Studio. No change in behavior: Preview of report shows same warnings and fails to display the barcode.
UPDATE
I've confirmed this is some kind of permissions issue. By commenting the line that does the ZXing.BarcoderWriter.Write() call it no longer produces this error. In fact, by replacing the function body with code that populates a byte array from image data (below), it successfully displays the image:
Public Function getBarCodeHorizontal(ByVal text1 As String) As Byte()
Dim text as String = "89504E470D0A1A0A0000000D494844520000009600000028080200000093A394B0000000017352474200AECE1CE90000000467414D410000B18F0BFC6105000000097048597300000EC300000EC301C76FA8640000026549444154785EED9AB16EDB400C864F7D112BC892C10F5103196474CD1B548F20C32FE1B1A3FC065D8B6A28203F84072F46EC2751792475C79364C0E822B1E0372824EF3FDAB93FC7C041B2AEEBDC145996C1135621204D0888C934EC0A155CE46E04C9C293AB424F6229A3546A085A22821EE24701E9A942C84AD00C0461952AC0584FABB2EE758894510ACF81009EA1422910768DB748BEF057432D66A17ACC42F59885EA310BD56316AAC72C548F59A81EB3503D66A17ACC42F59885EA310BD56316AAC72C548F59A81EB3503D66A17ACC42F59885EA310BD56316AAC72C544FF21F8F8646EC16AAC72C54CFFF61E169976D8F774EFE9DFB719BED4E9CA8C16EA17ACC42F52CCA4298878C188B7EBA31E9B00CEAEDF1CA254FD0F3484C87ACC8E2AB0D1AA7133599AEC3E64B603916C2E96CCEF50D3EE4745DBB2E733C2428E6E5BAC5E2AD765C05E0FC378EEADDFE521EA8EAEBACBFD5E70D8ABF7EAB9A9F7FD8A2D3AF43F1F1BEF2D16E73A8A8415B35E58F672C19375F04F84D2C805B5D383ED2C8A018D3B67205DB0DF83AA5A21EC5107131DDD61394E32089279BCFCF626EE1E7A529DE5E3879C0EA75EDCE57B850F7EB994B88AF079A32C75197970D89DDEAFDC3E13D8C7710E9A7A2573EC9B8F9FC2CC6C297B7A2B97C72F200EFDCFA152C483C1B20AFD9EFEFE8177B080E567BAAA07DF9658F2A7FA59E64A2F9FCF0FB991F7F90724E618CA7DB4F2C186449DCAB7DDC275123D5BE0F20669F588DDBFDAB0D37CB77F0A0F9CC2CC742000F9388E7836748F49E11415DD4B5F81D27CA429DFC2C7862DBAAED17FD57D684656C1E364E379F17FB33B77AECA3BD7ACC42E538F7178726B2F89D7D5EF80000000049454E44AE426082"
Dim bytes As Byte() = New Byte(text.Length \ 2 - 1) {}
Dim b as Byte
For i As Integer = 0 To text.Length - 1 Step 2
bytes(i \ 2) = Byte.Parse(text(i).ToString() & text(i + 1).ToString(), System.Globalization.NumberStyles.HexNumber)
Next
Return bytes
End Function
UPDATE
I tried changing the CodeGroup on the server to Strong using the zxing.dll public key token, but no improvement:
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="ZXingCodeGroup"
Description="Code group for ZXing">
<IMembershipCondition
class="StrongNameMembershipCondition"
version="1"
PublicKeyBlob="4e88037ac681fe60"
/>
</CodeGroup>
Ohh that's a good one..
Did a lot of digging and debugging (if you can call that debugging - I put return statements into the ZXing code, and watched when it would bring up that error)
One thing that is different in my setup than yours: I am using a custom DLL to interact with zxing.dll.
It boils down to the way they put pixel-data into a bitmap:
https://github.com/micjahn/ZXing.Net/blob/eef88ee53ced1035eade39f44544aa955d2db6b6/Source/lib/renderer/BitmapRenderer.cs#L169
The Workaround is to convert it manually:
public static string Test()
// Don't let ZXing handle the conversion to a bitmap -> give me raw pixel data
var writer = new BarcodeWriterPixelData { Format = BarcodeFormat.DATA_MATRIX };
var result = writer.Write("Test123");
Bitmap bmp = new Bitmap(result.Width, result.Height);
int bpp = 32;
for (int y = 0; y < result.Height; y++)
{
for (int x = 0; x < result.Width; x++)
{
int i = ((y * result.Width) + x) * (bpp / 8);
if (bpp == 32) // in this case you have 4 color values (red, green, blue,alpha)
{
// first byte will be red, because you are writing it as first value
byte r = result.Pixels[i];
byte g = result.Pixels[i + 1];
byte b = result.Pixels[i + 2];
byte a = result.Pixels[i + 3]; // Alpha?
Color color = Color.FromArgb(r, g, b);
bmp.SetPixel(x, y, color);
}
}
}
return GetBase64(bmp);
}
public static string GetBase64(Image image)
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Png);
byte[] imageBytes = m.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
Source (slightly modified):
https://stackoverflow.com/a/16130425/11829240
Also be aware, that you maybe need to build it yourself to insert [assembly:AllowPartiallyTrustedCallers] into AssemblyInfo.cs
The perfect solution would be to generate a SVG, but SSRS doesn't like that.
More to read on that Bitmap.LockBits Topic:
https://www.codeproject.com/Articles/625868/LockBits-Alternative-SecurityException-Workaround
Also found the following:
Hi,
I'm trying to create a Barcode in CRM 2011 (On Premises) Reports. Unfortunately this isn't possible due to Sandbox and various other issues. I've tried a few methods but nothing works.
So my approach now, is to create a c# plugin that generates the barcode image when a record is created, and store the image byte as a string, and then use Convert.FromBase64String in the report to display the barcode image. This method should then hopefully work...
However, after days of trying, I'm stuck with an issue with Permission Security
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
, and have debugged to a section in the Render that doesn't work / compatible (for CRM 2011..!)
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
So my question is: Is there a way to do this without Lockbits ?
Any help here would be greatly received.
Unfortunately the Links is dead:
http://zxingnet.codeplex.com/discussions/584679
EDIT: Actually dug it up, Archive of an Archive..
https://web.archive.org/web/20210303162237/https://archive.codeplex.com/?p=zxingnet
Click on discussions and Search for Alternative to LockBits due to Security issues
Codeplex-Archive-Download (zip):
https://web.archive.org/web/20210701004220/https://codeplexarchive.blob.core.windows.net/archive/projects/ZXingNet/ZXingNet.zip
I've got code along the lines of the following which generates a new image out of some existing images.
from PIL import Image as pyImage
def create_compound_image(back_image_path, fore_image_path, fore_x_position):
back_image_size = get_image_size(back_image_path)
fore_image_size = get_image_size(fore_image_path)
new_image_width = (fore_image_size[0] / 2) + back_image_size[0]
new_image_height = fore_image_size[1] + back_image_size[1]
new_image = create_new_image_canvas(new_image_width, new_image_height)
back_image = pyImage.open(back_image_path)
fore_image = pyImage.open(fore_image_path)
new_image.paste(back_image, (0, 0), mask = None)
new_image.paste(fore_image, (fore_x_position, back_image_size[1]), mask = None)
return new_image
Later in the code, I've got something like this:
from kivy.uix.image import Image
img = Image(source = create_compound_image(...))
If I do the above, I get the message that Image.source only accepts string/unicode.
If I create a StringIO.StringIO() object from the new image, and try to use that as the source, the error message is the same as above. If I use the output of the StringIO object's getvalue() method as the source, the message is that the source must be encoded string without NULL bytes, not str.
What is the proper way to use the output of the create_compound_image() function as the source when creating a kivy Image object?
It seems you want to just combine two images into one, you can actually just create a texture using Texture.create and blit the data to a particular pos using Texture.blit_buffer .
from kivy.core.image import Image
from kivy.graphics import Texture
bkimg = Image(bk_img_path)
frimg = Image(fr_img_path)
new_size = ((frimg.texture.size[0]/2) + bkimg.texture.size[0],
frimg.texture.size[1] + bkimg.texture.size[1])
tex = Texture.create(size=new_size)
tex.blit_buffer(pbuffer=bkimg.texture.pixels, pos=(0, 0), size=bkimg.texture.size)
tex.blit_buffer(pbuffer=frimg.texture.pixels, pos=(fore_x_position, bkimg.texture.size[1]), size=frimg.texture.size)
Now you can use this texture anywhere directly like::
from kivy.uix.image import Image
image = Image()
image.texture = tex
source is a StringProperty and is expecting a path to file. That's why you got errors when you tried to pass PIL.Image object, StringIO object or string representation of image. It's not what framework wants. As for getting image from StringIO, it was discussed before here:
https://groups.google.com/forum/#!topic/kivy-users/l-3FJ2mA3qI
https://github.com/kivy/kivy/issues/684
You can also try much simpler, quick and dirty method - just save your image as a tmp file and read it normal way.
In my javascript, in Windows 7, Photoshop CS2 & Photoshop CS5, it throws an error:
Error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
- Could not save a copy as "C:...\wcb-010B-11Y.jpg" because the file could not be found.
Line: 458
-> docRef.saveAs( saveFile, jpgSaveOptions, true, Extension.LOWERCASE );
here is a summary of the code to save the image:
var selectedSaveDir = "~/Desktop/";
var sFileNamePreFix = "wcb-";
var docRef = app.activeDocument;
var docName = app.activeDocument.name;
var docNewName = docName.substr( 0, docName.length - 4 ); // strip file extension
var sNewDocName = sFileNamePreFix + docNewName + ".jpg"
var sNewFileName = selectedSaveDir + sNewDocName;
//alert( "sNewFileName = " + sNewFileName ); // test to verify correct location
var saveFile = new File(sNewFileName);
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.quality = 12;
docRef.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);
In Windows XP, this script works very well in CS2 with no problems.... just in Windows 7 is where this issue occurs using CS2 or CS5.
The problem seems to be similar to : Photoshop Javascript scripting saving and closing document
But I don't know his OS.
I've added the "alert(" and confirmed the save folder & name is correct and can be saved to, but same issue.
Could it be a UAC issue in Windows 7 ? and how do you Fix it ? I've turned off all UAC settings (I think I did it correctly), but it still occurs.
Any Help ?
You missed out " var docRef = app.activeDocument;" (which i've added); but apart from that, in CS2 the script saves out a jpeg to the desktop (wcb-text test.jpg). It's obvious, but have you made sure the image is flattened or doesn't contain any information that cannot be stored in a jpeg - like paths for example.
Try forcing a flatten before saving
//flatten the image
docRef.flatten();
Another thing to try is to save out the file to another directory. I know that long file names (especially with spaces in) can cause problems - I think there's a limit to 300 characters in the file path.
I just found that, in new versions of PS this particular path variable gives the error 8800:
var selectedSaveDir = "~/Desktop/";
Use full path instead and use apostrophes instead of quotes:
var selectedSaveDir = 'C:/Users/yourname/Desktop/';
When I use:
loader = new MovieClipLoader();
_root.createEmptyMovieClip("level1",getNextHighestDepth());
_root.level1.createEmptyMovieClip("image",getNextHighestDepth());
loader.loadClip("http://someimage.jpg",_root.level1.image);
...it works and the image shows up.
But when I use:
loader = new MovieClipLoader();
_root.createEmptyMovieClip("level1",getNextHighestDepth());
_root.level1.createEmptyMovieClip("level2",getNextHighestDepth());
_root.level1.level2.createEmptyMovieClip("image",getNextHighestDepth());
loader.loadClip("http://someimage.jpg",_root.level1.level2.image);
...the image doesn't show up. Can anyone tell me why? How can I make this work?
the depth you are supplying is going to be '1'. is that what you are expecting?
each movie clip has it's own set of depths, so the nextHighestDepth() of the newly create 'image' mc, will be 1. it should not prevent loading the image though.
As gthmb says, you should call getNextHighestDepth() on the same MovieClip as you do the createEmptyMovieClip() on. So your code example should be more like:
loader = new MovieClipLoader();
_root.createEmptyMovieClip("level1",_root.getNextHighestDepth());
_root.level1.createEmptyMovieClip("level2",_root.level1.getNextHighestDepth());
_root.level1.level2.createEmptyMovieClip("image",_root.level1.level2.getNextHighestDepth());
loader.loadClip("http://someimage.jpg",_root.level1.level2.image);
Also, I would recommend storing references to the created MovieClips, so you won't have to use the full path in each occurrence in the code, something in the lines of this:
loader = new MovieClipLoader();
var level1:MovieClip = _root.createEmptyMovieClip("level1",_root.getNextHighestDepth());
var level2:MovieClip = level1.createEmptyMovieClip("level2",level1.getNextHighestDepth());
var image:MovieClip = level2.createEmptyMovieClip("image",level2.getNextHighestDepth());
loader.loadClip("http://someimage.jpg",image);
I'm building an IronRuby Console in silverlight 4 and WinForms (net4). I can redirect the output without problems:
MyRuntime = Ruby.CreateRuntime();
msOutput = new MemoryStream();
MyRuntime.IO.SetOutput(msOutput, Encoding.UTF8);
MyEngine = MyRuntime.GetEngine("rb");
MySource = MyEngine.CreateScriptSourceFromString("a='123'\nputs a", SourceCodeKind.Statements);
MySource.Execute();
textBox2.Text = ReadFromStream(msOutput);
Now, I want to redirect the input also, but always getting a 'nil' from the script:
MyRuntime = Ruby.CreateRuntime();
msOutput = new MemoryStream();
msInput = new MemoryStream();
MyRuntime.IO.SetOutput(msOutput, Encoding.UTF8);
MyRuntime.IO.SetInput(msInput, Encoding.UTF8);
MyEngine = MyRuntime.GetEngine("rb");
MySource = MyEngine.CreateScriptSourceFromString("a=gets\nputs a", SourceCodeKind.Statements);
byte[] byteArray = Encoding.UTF8.GetBytes("123");
msInput.Write(byteArray, 0, byteArray.Length);
MySource.Execute();
textBox2.Text = ReadFromStream(msOutput);
I cannot find any samples of redirecting the input, can you please send an example? Thank you.
I don't have any sample code immediately available but instead of using a MemoryStream you need to implement the stream. When reads on the stream occur you need to send the "contents" of the text box to the stream. You'll need some mechanism for determining when you send the contents - e.g. when the user hits return. You'll also probably need to setup a thread for blocking for the reads and probably use an AutoResetEvent to block until the text box signals that the input is complete.