How can I send a binary file from actionScript to .net? - c#

I have a flex program (AS3/Flash) that allows the user to create PNG images of portions of the stage and send them via email. This works swimmingly.
I want to take the same image and send it to the clipboard, but that does not work. So the next best thing is to allow them to send it to their browser, where they can save it to a file.
Here is the code that I am using to do that;
bmpPanelData.draw(uiPrintObject)
var baPanel:ByteArray = PNGEnc.encode(bmpPanelData);
// Clipboard.generalClipboard.clear();
// var bolClipboard:Boolean = Clipboard.generalClipboard.setData(ClipboardFormats.BITMAP_FORMAT, baPanel, true);
// trace('bolClipboard=' + bolClipboard);
var strFileName:String = strPrintObject;
var strFileExt:String = "png"
var variables:URLVariables = new URLVariables();
variables.mimeType = "application/octet-stream";
variables.fileExt = strFileExt;
baPanel.position = 0;
var strPanel:String = getBytes(baPanel);
// var strPanel:String = baPanel.readMultiByte(baPanel.bytesAvailable,"latin1");
variables.fileContents = escape(strPanel);
trace('strPanel.length=' + strPanel.length + ' baPanel.length=' + baPanel.length);
variables.disposition = "Attachment";
variables.fileName = strFileName;
var u:URLRequest = new URLRequest( RootDomain + "SendBinaryFile2.aspx");
u.data = variables;
u.method = "POST";
navigateToURL(u,"_blank");
}
catch (err:Error)
{
Alert.show("This Panel cannot be copied to the clipboard. \nSorry for the inconvenience \nError: " + err.errorID,"E-mail not premitted",Alert.OK)
}
(I left the clipboard stuff commented out in case someone knows how to do that. It is my understanding that you cannot send binary data to the clipboard from Flash, but it works in AIR.)
Since I could not find an AS3 method to convert a binary ByteArray to a string I wrote my own called getBytes. If you know of a method in AS3, please let me know.
private function getBytes(baArray:ByteArray):String
{
var strOut:String = "";
baArray.position = 0;
var intBASize:int = baArray.bytesAvailable;
for (var i:int = 0;i < intBASize;i++)
{
strOut += String.fromCharCode(baArray.readByte());
}
return strOut;
}
On the ASPX side I have a file called SendBinaryFile2.aspx that looks like this;
<%# Page Language="C#" validateRequest="false"%>
<script Runat="Server">
void Page_Load(Object sender, EventArgs e)
{
string fileExt = Request.Form["fileExt"];
string mimeType = Request.Form["mimeType"];
string disposition = Request.Form["disposition"];
string fileName = Request.Form["fileName"];
byte [] fileContents = Encoding.ASCII.GetBytes(HttpUtility.UrlDecode(Request.Form["fileContents"]));
Response.Buffer = true;
Response.Clear();
Response.AddHeader("Content-Length", fileContents.Length.ToString());
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", disposition + "; filename=" + fileName + "." + fileExt);
Response.BinaryWrite(fileContents);
Response.Flush();
Response.Close();
Response.End();
}
</script>
The results is a file that looks a whole lot like a .PNG file, but is corrupt when it is opened. I have visually compared the file sent via email, and the one sent via this program using VIM, and they look similar, have roughly the same number of characters, begin/end with similar characters.
Help on any of the items defined above is greatly appreciated.

Try this for your getBytes function...
private function getBytes (baArray:ByteArray) : String
{
var strOut:String = ""; var strRead:String = "";
baArray.position = 0;
var intBASize:uint = baArray.length;
for (var i:int = 0; i < intBASize; i++)
{
strRead = baArray.readUnsignedByte().toString(16);
if(strRead.length < 2) { strRead = "0" + strRead; } //# do padding
strOut += strRead ;
}
return strOut.toUpperCase();
}
This should give you padded bytes. Consider x0FF3 becomes just xFF3 without the padding, later the other side could be assuming the bytes are really xFF30 leading to corrupt images.

I'd suggest you use Base64 encoding to transport your binary data. You already must have needed to use it for encoding your email attachment, anyways.
Actionscript:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/Base64Encoder.html
c#:
byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
Also, if your SWF is running as standalone AIR (You wrote "Flex program"...), you can directly save files anywhere and give the user a "Save as..." prompt to do so.
Source to save from AIR:
var bmpd:BitmapData = new BitmapData(myWidth, myHeight, true, 0);
bmpd.draw(mySource);
var imgByteArray:ByteArray = new PNGEncoder().encode(bmpd);
var fl:File = File.desktopDirectory.resolvePath("myImage.png");
var fs:FileStream = new FileStream();
fs.open(fl, FileMode.WRITE);
fs.writeBytes(imgByteArray);
fs.close();

Related

I read pdf file then for show on the client I use tempStream.WriteByte but it reverse writing

By the way my english not perfect sory .
I use this method . I want to read file then show of pdf format on the client. So this code can do it.
But when I show pdf file . İt did reverse write on the document. What is my problem I cant understand
FileStream fileStream = File.OpenRead(fileDirectoryPath + "\\" + pROJEDOKUMANBec.FILENAME);
pROJEDOKUMANBec.SOURCE = ConvertStreamToByteBuffer(fileStream);
public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
{
int b1;
System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
while ((b1 = theStream.ReadByte()) != -1)
{
tempStream.WriteByte(((byte)b1));
}
return tempStream.ToArray();
}
And here my ts code.
#ViewChild('pdfViewir') pdfViewir: PdfViewer;
private _openPdf(bec: ProjeDokumanBec): void {
this._rptSrc = bec.SOURCE;
this.pdfViewir.Zoom = 1;
this.pdfViewir.OriginalSize = true;
}
here my html code
<PdfViewer #pdfViewir Id="pdfViewir" [Src]="_rptSrc"></PdfViewer>

Error in exporting fastreport to pdf on asp.net c#

I want to export .frx report that designed by FastReport as an pdf or excel file on a c# web form application like code below:
public static bool ShowReport(string ReportFileName, DataTable ReportData, string DBObjectName, string ExportType, out string Message, params string[] AdditionalParams)
{
FastReport.Utils.Config.WebMode = true;
string ReportFile = HttpContext.Current.Server.MapPath(WPResources.ReportsRoot) + string.Format("{0}_{1}.frx", ReportFileName, ExportType.ToUpper());
FastReport.Report objReport = new FastReport.Report();
objReport.Load(ReportFile);
objReport.Dictionary.Connections.Clear();
System.Data.DataTable resultTable = new DataTable();
objReport.RegisterData(ReportData, DBObjectName);
objReport.GetDataSource(DBObjectName).Enabled = true;
int ParamsCount = AdditionalParams.Length;
if ((ParamsCount % 2) != 0)
ParamsCount--;
for (int i = 0; i < ParamsCount; i += 2)
{
var DynamicControl = (objReport.FindObject(AdditionalParams[i]) as FastReport.TextObject);
if (DynamicControl != null)
{
DynamicControl.Text = AdditionalParams[i + 1];
DynamicControl.Visible = !string.IsNullOrEmpty(AdditionalParams[i + 1]);
}
}
(objReport.FindObject("rptData") as FastReport.DataBand).DataSource = objReport.GetDataSource(DBObjectName);
string fileName = Path.GetFileNameWithoutExtension(ReportFile);
fileName += "_" + WPFarsiDate.Today.ToString().Replace("/", ".") + "_" +
DateTime.Now.Hour.ToString() + "." +
DateTime.Now.Minute.ToString();
if (ExportType == "Excel")
{
using (MemoryStream objMemoryStream = new MemoryStream())
{
objReport.Prepare(false);
FastReport.Export.OoXML.Excel2007Export objExcel2007Export = new FastReport.Export.OoXML.Excel2007Export();
objExcel2007Export.OpenAfterExport = false;
objExcel2007Export.Export(objReport, objMemoryStream);
byte[] buffer = objMemoryStream.ToArray();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("inline;filename={0}.xlsx", fileName));
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.End();
}
}
else if (ExportType == "Pdf")
{
using (MemoryStream objMemoryStream = new MemoryStream())
{
objReport.Prepare(false);
FastReport.Export.Pdf.PDFExport objPDFExport = new FastReport.Export.Pdf.PDFExport();
objPDFExport.EmbeddingFonts = true;
objPDFExport.OpenAfterExport = false;
objPDFExport.Export(objReport, objMemoryStream);
byte[] buffer = objMemoryStream.ToArray();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", fileName));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.End();
}
}
Message = string.Empty;
return true;
}
When I export it to excel, that is no any matter and it will be done successfuly. But when I export it to pdf, I get this error:
Showing a modal dialog box or form when the application is not running
in UserInteractive mode is not a valid operation. Specify the
ServiceNotification or DefaultDesktopOnly style to display a
notification from a service application.
It should be noted that mentioned error just occurs in the main server and the job can be done successfully in localhost.
It would be very helpful if someone could explain solution for this problem.
After much effort, I find solution for the problem. Fonts used in .frx files weren't the windows/fonts folder. So I copied the metioned fonts there and it worked properly.
Did you tried debug it? Which line throws this error?
Did you see any dialog windows in desktop version? Try to avoid it.
I use fast report in one of my ASP.Net Web Forms projects and I see this exception when I try to export PDF. I have this tag in .aspx file:
<fastreport:webreport id="remainedLeave" runat="server"
Width="100%" Height="100%"></fastreport:webreport>
Adding this property to fast report tag solved my problem:
PdfEmbeddingFonts="false"

SSIS 2015 Script task convert text file to UTF8 in C# or VB

I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;

How can I read a Lync conversation file containing HTML?

I'm having trouble reading a local file, into a string, in c#.
Here's what I came up with till now:
string file = #"C:\script_test\{5461EC8C-89E6-40D1-8525-774340083829}.html";
using (StreamReader reader = new StreamReader(file))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
textBox1.Text += line.ToString();
}
}
And it's the only solution that seems to work.
I've tried some other suggested methods for reading a file, such as:
string file = #"C:\script_test\{5461EC8C-89E6-40D1-8525-774340083829}.html";
string html = File.ReadAllText(file).ToString();
textBox1.Text += html;
Yet it does not work as expected.
Here are the first few lines of the file i'm trying to read:
as you can see, it has some funky characters, honestly I don't know if that's the cause of this weird behavior.
But in the first case, the code seems to skip those lines, printing only "Document generated by Office Communicator..."
Your task would be easier if you could use an API or the SDK or even would have a description of the format you try to read. However the binary format looks not to be that complicated and with an hexviewer installed I got this far to get the html out of the example you provided.
To parse non-text files you fall-back to the BinaryReader and then use one of the Read methods to read the correct type from the bytestream. I used ReadByte and ReadInt32. Notice how in the description of the method is explained how many bytes are read. That becomes handy when you try to decipher your file.
private string ParseHist(string file)
{
using (var f = File.Open(file, FileMode.Open))
{
using (var br = new BinaryReader(f))
{
// read 4 bytes as an int
var first = br.ReadInt32();
// read integer / zero ended byte arrays as string
var lead = br.ReadInt32();
// until we have 4 zero bytes
while (lead != 0)
{
var user = ParseString(br);
Trace.Write(lead);
Trace.Write(":");
Trace.Write(user.Length);
Trace.Write(":");
Trace.WriteLine(user);
lead = br.ReadInt32();
// weird special case
if (lead == 2)
{
lead = br.ReadInt32();
}
}
// at the start of the html block
var htmllen = br.ReadInt32();
Trace.WriteLine(htmllen);
// parse the html
var html = ParseString(br);
Trace.Write(len);
Trace.Write(":");
Trace.Write(html.Length);
Trace.Write(":");
Trace.WriteLine(html);
// other structures follow, left unparsed
return html.ToString();
}
}
}
// a string seems to be ascii encoded and ends with a zero byte.
private static string ParseString(BinaryReader br)
{
var ch = br.ReadByte();
var sb = new StringBuilder();
while (ch != 0)
{
sb.Append((char)ch);
ch = br.ReadByte();
}
return sb.ToString();
}
You could use the simple parsing logic in a winform application as follows:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.DocumentText = ParseHist(#"5461EC8C-89E6-40D1-8525-774340083829-Copia.html");
}
Keep in mind that this is not bullet proof or the recommended way but it should get you started. For files that don't parse well you'll need to go back to the hexviewer and work-out what other byte structures are new or different from what you already had. That is not something I intend to help you with, that is left as an exercise for you to figure out.
I don't know if it's the right way to answer this, but here's what I've managed to do so far:
string file = #"C:\script_test\{1C0365BC-54C6-4D31-A1C1-586C4575F9EA}.hist";
string outText = "";
//Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
StreamReader reader = new StreamReader(file, utf8);
char[] text = reader.ReadToEnd().ToCharArray();
//skip first n chars
/*
for (int i = 250; i < text.Length; i++)
{
outText += text[i];
}
*/
for (int i = 0; i < text.Length; i++)
{
//skips non printable characters
if (!Char.IsControl(text[i]))
{
outText += text[i];
}
}
string source = "";
source = WebUtility.HtmlDecode(outText);
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
htmlDoc.LoadHtml(source);
string html = "<html><style>";
foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//style"))
{
html += node.InnerHtml+ Environment.NewLine;
}
html += "</style><body>";
foreach (HtmlNode node in htmlDoc.DocumentNode.SelectNodes("//body"))
{
html += node.InnerHtml + Environment.NewLine;
}
html += "</body></html>";
richTextBox1.Text += html+Environment.NewLine;
webBrowser1.DocumentText = html;
The conversation displays correctly, both style and encoding.
So it's a start for me.
Thank you all for the support!
EDIT
Char.IsControl(char)
skips non printable characters :)

Export CSV file to Excel 2007

I have some code for sending a data result to the user as CSV.
This works fine with Excel 2013 but in Excel 2007, it won't split into columns, but rather as data inserted into only one column.
Is there a way of telling Excel how to split the text (it's separated by ; ) ?
Here is my code:
public async Task ExcelResultList(int id)
{
var asString = await Resolver.Resolve<IHandoutManager>().GetResultListAsStringAsync(id);
var handout = await Resolver.Resolve<IHandoutManager>().GetHandout(id);
var filename = string.Format("{0} registrations - {1:yyyy-MM-dd}.csv", handout.Name, DateTime.Now);
var contenttype = "application/csv";
Response.Clear();
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentEncoding = Encoding.Unicode;
Response.Write(asString);
Response.End();
}
To make sure that you are using the correct ListSeparator ("," or ";") use this
System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator
But since you only have access to the server side, then you can include this javascript in any of your pages,
function getListSeparator() {
var list = ['a', 'b'], str;
if (list.toLocaleString) {
str = list.toLocaleString();
if (str.indexOf(';') > 0 && str.indexOf(',') == -1) {
return ';';
}
}
return ',';
}
The key is in the toLocaleString method that uses the system list separator of the client side
You could use JavaScript to get the list separator and set it in a cookie which you could then detect from your server to generate the file as needed
And also have you try changing the contenttype to
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
or
application/vnd.ms-excel

Categories