Have only one image that is the byte[] bytes and I am trying to compress to Zip for the user to download as far I can see the byte array is saved in the MemoryStream.
The probleam is when I trie to read the buffer of MemoryStream to ImagesAux this way zippedMemoryStream.Read(ImagesAux, 0, 1000000); doesn't work but ImagesAux = zippedMemoryStream.ToArray(); this way allready works ... then stream.Write(ImagesAux, 0, ImagesAux.Length); as to pass the ZipFile to SaveFileDialog doesn't work either get the size of ImagesAux but not the content from what I saw, the ZipFile is created but gives a error of Format not supported in ALZip, can someone point what I'm doing wrong??
MemoryStream zippedMemoryStream = new MemoryStream();
ZipOutputStream zipOutputStream;
zipOutputStream = new ZipOutputStream(zippedMemoryStream, 1000000);
zipOutputStream.SetLevel(0);
zipOutputStream.UseZip64 = UseZip64.On;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
ZipEntry entry = new ZipEntry(ZipEntry.CleanName(ImageNameServer));//ImageNameServer
entry.DateTime = DateTime.Now;
entry.Comment = "Teste";
entry.ZipFileIndex = 1;
entry.Size = bytes.Length;
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(bytes, 0, bytes.Length);
var something = zipOutputStream.GetType();
var lvl = zipOutputStream.GetLevel();
//zippedMemoryStream.Write(bytes, 0, bytes.Length);
zippedMemoryStream.Read(buffer, 0, bytes.Length);
MemoryStream auxxpto = new MemoryStream();
zippedMemoryStream.WriteTo(auxxpto);
buffer = auxxpto.ToArray();
private void DataSetDownload(object sender, RoutedEventArgs e)
{
var dialog = new SaveFileDialog();
dialog.Filter = "Zip Files (*.zip)|*.zip";
dialog.DefaultExt = "zip";
dialog.DefaultFileName = "DataSet.zip";
bool? fileSelected = dialog.ShowDialog();
byte[] ImagesAux = new byte[1000000];
if (fileSelected == true)
{
var value = zippedMemoryStream.CanWrite;
var read = zippedMemoryStream.CanRead;
zippedMemoryStream.Read(ImagesAux, 0, 1000000);
ImagesAux = zippedMemoryStream.ToArray();
//ZippedFile.Read(ImagesAux, 0, ImagesAux.Length);
//ImagesAux = zippedMemoryStream.ToArray();
zipOutputStream.Finish();
zipOutputStream.Close();
using (Stream stream = dialog.OpenFile())
{
stream.Write(ImagesAux, 0, ImagesAux.Length);
//stream = zippedMemoryStream.ToArray();
//stream.Flush();
//stream.Close();
}
}
}
This code was moved from the question. Answers should be in answers.
Working code.
MemoryStream zippedMemoryStream = new MemoryStream();
ZipOutputStream zipOutputStream;
zipOutputStream = new ZipOutputStream(zippedMemoryStream, 1000000);
zipOutputStream.SetLevel(0);
zipOutputStream.UseZip64 = UseZip64.On;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
ZipEntry entry = new ZipEntry(ZipEntry.CleanName(ImageNameServer));//ImageNameServer
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(bytes, 0, bytes.Length);
zipOutputStream.Finish();
zipOutputStream.CloseEntry();
private void DataSetDownload(object sender, RoutedEventArgs e)
{
var dialog = new SaveFileDialog();
dialog.Filter = "Zip Files (*.zip)|*.zip";
dialog.DefaultExt = "zip";
dialog.DefaultFileName = "DataSet.zip";
bool? fileSelected = dialog.ShowDialog();
byte[] ImagesAux = new byte[1000000];
if (fileSelected == true)
{
var value = zippedMemoryStream.CanWrite;
var read = zippedMemoryStream.CanRead;
zippedMemoryStream.Position = 0;
zippedMemoryStream.Read(ImagesAux, 0, 1000000);
//ZippedFile.Read(ImagesAux, 0, ImagesAux.Length);
//ImagesAux = zippedMemoryStream.ToArray();
zipOutputStream.Finish();
zipOutputStream.Close();
using (Stream stream = dialog.OpenFile())
{
stream.Write(ImagesAux, 0, ImagesAux.Length);
//stream = zippedMemoryStream.ToArray();
//stream.Flush();
//stream.Close();
}
}
}
Related
I try to create a PDF report from a datatable. One of the columns contents image. How can I extract the image from datatable and insert into PDF table? I'm using iTextShap version 5.4.2.0. Here is the code:
public void Report(DataTable dt, string output)
{
Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8);
doc.Open();
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase("NewCells"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, hel8));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), hel8));
table.AddCell(new Phrase(r[1].ToString(), hel8));
table.AddCell(new Phrase(r[2].ToString(), hel8));
table.AddCell(new Phrase(r[3].ToString(), hel8));
table.AddCell(new Phrase(r[4].ToString(), hel8));
table.AddCell(new Phrase(r[5].ToString(), hel8));
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi); <-- this is the problem code
table.AddCell(img);
table.AddCell(new Phrase(r[7].ToString(), hel8));
}
}
doc.Add(table);
}
doc.Close();
}
Update: #nekno, all of your suggestions are worked.
But I still need to correct the casting at line:
byte[] byt = (byte[])r[6];
It gave me a casting exception from VS2008. So I added the conversion function (pulled it from stackoverflow):
byte[] ImageToByte(System.Drawing.Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
And revised the code:
byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);
Thanks.
What exactly is the problem? What happens when you use your problem code?
Try one of the other Image.GetInstance() overloads:
You can pass the byte array directly:
byte[] byt = (byte[])r[6];
Image img = Image.GetInstance(byt);
Or you can pass the Stream:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
Image img = Image.GetInstance(ms);
Or you can give iTextSharp more info about the image format:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drawing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi, ImageFormat.Png);
If your column can be cast to a System.Drawing.Image, then you can use it directly:
Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);
I have suggested steps how shows how to add image into PDF, given below code snippet show how to add logo into your PDF using iTextsharp, follow provided below steps:
I have provided link to download "itextsharp" component from given link http://sourceforge.net/projects/itextsharp/
You have to add reference into your application.
Next you have to add required namespaces "iTextsharp.text.html", "iTextsharp.text" to consume its best properties.
Now you have to add code snippet into your application given at the end, add code snippet under "button click" in code behind.
Hope it will work for you !!!
protected void btnPDF_Click(object sender, ImageClickEventArgs e)
{
DataTable dtn = new DataTable();
dtn = GetDataTable();
dtPDF = dtn.Copy();
for (int i = 0; i <= dtn.Rows.Count - 1; i++)
{
ExportToPdf(dtPDF);
}
}
public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);
string clientLogo = Server.MapPath(".") + "/logo/tpglogo.jpg";
string imageFilePath = Server.MapPath(".") + "/logo/tpglogo.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);
Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}
This is the same question asked before and the answer is also verified but in My Project I am using WebApi 2 and want return image from Ihttpactionresult
I have searched and lot and done some code Which I don't know if I am doing right..
I also Looked at ImageReizer but it saves the resized Images in the folder. Idon't want to save the Image.
Here is My Controller Action
[HttpGet]
[Route("GetFile")]
public IHttpActionResult GetFile(string filename, int w = 0, int h = 0)
{
//string filePath = "fdsafsa";
//int width = 0;
//var fileStream = File.Open("/ProjectFiles", FileMode.Open);
//var content = new StreamContent(fileStream);
//content.Headers.ContentType = new MediaTypeHeaderValue("png");
var imageFile = HttpContext.Current.Server.MapPath(#filename);
if(File.Exists(imageFile))
{
var srcImage = Image.FromFile(imageFile);
var newImage = new Bitmap(w, h);
var graphics = Graphics.FromImage(newImage);
var stream = new MemoryStream();
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(srcImage, new Rectangle(0, 0, w, h));
newImage.Save(stream, ImageFormat.Png);
//var content = new StreamContent(stream);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(stream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return Ok(result);
}
This is the html where I want to render the Image
<img src="/api/Public/GetFile?filename=/ProjectFiles/Project_2087/art-therapy-career2_73937984-7e03-4067-91bf-2dd4fc10b328.jpg&w=100&h=100" alt="image" />
How can I show the resized Image dynamically without storing the resize image on the server. I don't want to save the resize Images.
I need help soon.
Thanks for your help.
Another approach ......
[HttpGet]
[Route("GetFileStream")]
public IHttpActionResult GetFileStream(string filename, int w = 0, int h = 0)
{
var imagePath = HttpContext.Current.Server.MapPath(#filename);
var result = getResizedImage(imagePath, w, h);
return Ok(result);
}
byte[] getResizedImage(String path, int width, int height)
{
Bitmap imgIn = new Bitmap(path);
double y = imgIn.Height;
double x = imgIn.Width;
double factor = 1;
if (width > 0)
{
factor = width / x;
}
else if (height > 0)
{
factor = height / y;
}
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
Graphics g = Graphics.FromImage(imgOut);
g.Clear(Color.White);
g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
imgOut.Save(outStream, getImageFormat(path));
return outStream.ToArray();
}
**
This is the Working Code with Mvc
**
This is the code I found working for Simple Mvc Application
An Action
public ActionResult Thumb(string filename = "Azalea.jpg", int w = 0, int h = 0)
{
string path = Path.Combine(Server.MapPath("~/images2"), filename);
//Bitmap bitmap = new Bitmap(filepath);
//if (bitmap == null)
//{
// return new EmptyResult();
//}
//MemoryStream ms = new MemoryStream();
//bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
Bitmap imgIn = new Bitmap(path);
double y = imgIn.Height;
double x = imgIn.Width;
double factor = 1;
if (w > 0)
{
factor = w / x;
}
else if (h > 0)
{
factor = h / y;
}
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
Graphics g = Graphics.FromImage(imgOut);
g.Clear(Color.White);
g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
imgOut.Save(outStream, getImageFormat(path));
outStream.Seek(0, SeekOrigin.Begin);
FileStreamResult fileStreamResult = new FileStreamResult(outStream, "image/png");
return fileStreamResult;
}
In cshtml page
<img src="~/Home/Thumb/#Model.ImageName?w=700&h=300" alt="image" />
How to use this With web Api2 ?
Answer of My Question after long search.Please Improve this
[HttpGet]
[Route("GetFileStream")]
public IHttpActionResult GetFileStream(string filename, int w = 0, int h = 0)
{
var imagePath = HttpContext.Current.Server.MapPath(#filename);
return new FileResult(imagePath, w, h, "image/jpeg");
}
public class FileResult : IHttpActionResult
{
private readonly string filePath;
private readonly string contentType;
private readonly int width;
private readonly int height;
public FileResult(string filePath, int width, int height, string contentType = null)
{
this.filePath = filePath;
this.contentType = contentType;
this.width = width;
this.height = height;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var result = getResizedImage(filePath, width, height);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(result)
//Content = new StreamContent(File.OpenRead(filePath))
};
var contentType = this.contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return response;
}, cancellationToken);
}
}
static byte[] getResizedImage(String path, int width, int height)
{
Bitmap imgIn = new Bitmap(path);
double y = imgIn.Height;
double x = imgIn.Width;
double factor = 1;
if (width > 0)
{
factor = width / x;
}
else if (height > 0)
{
factor = height / y;
}
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));
Graphics g = Graphics.FromImage(imgOut);
g.Clear(Color.White);
g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)), new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);
imgOut.Save(outStream, getImageFormat(path));
//outStream.Seek(0, SeekOrigin.Begin);
//System.Web.Mvc.FileStreamResult fileStreamResult = new System.Web.Mvc.FileStreamResult(outStream, "image/png");
//return fileStreamResult;
return outStream.ToArray();
}
string getContentType(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return "Image/bmp";
case ".gif": return "Image/gif";
case ".jpg": return "Image/jpeg";
case ".png": return "Image/png";
default: break;
}
return "";
}
static ImageFormat getImageFormat(String path)
{
switch (Path.GetExtension(path))
{
case ".bmp": return ImageFormat.Bmp;
case ".gif": return ImageFormat.Gif;
case ".jpg": return ImageFormat.Jpeg;
case ".png": return ImageFormat.Png;
default: break;
}
return ImageFormat.Jpeg;
}
Please Help in improving this answer,
Thanks,
Sanuj
You can pass your byteArray to View, then use something like this:
Create your image model:
public class ImageData
{
public string Name { get; set; }
public byte[] Content { get; set; }
. . .
}
Then in controller assign and return your model to View():
#{
string imageBase = Convert.ToBase64String(Model.ImageContent);
string imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
}
<img src="#imageSource" alt="#Model.ImageName" width="100" height="100" />
I am calling a method that has a Grid.Children.Clear() functionality. When calling it from different methods it works well. But when I call my the method from an xmpp_onmessage method. I am experiencing an error. “The calling thread cannot access this object because a different thread owns it.”
Here is the method that containts Grid.Children.Clear()the :
private void ConstructChatView(Boolean isChat)
{
System.Uri resourceUri = new System.Uri("Public/Images/chat_green-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
System.Uri resourceUri2 = new System.Uri("Public/Images/chat_green-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo2 = Application.GetResourceStream(resourceUri2);
System.Uri resourceUri3 = new System.Uri("Public/Images/chat_blue-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo3 = Application.GetResourceStream(resourceUri3);
System.Uri resourceUri4 = new System.Uri("Public/Images/chat_blue-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo4 = Application.GetResourceStream(resourceUri4);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
BitmapFrame temp2 = BitmapFrame.Create(streamInfo2.Stream);
BitmapFrame temp3 = BitmapFrame.Create(streamInfo3.Stream);
var brush2 = new ImageBrush();
brush2.ImageSource = temp3;
BitmapFrame temp4 = BitmapFrame.Create(streamInfo4.Stream);
int ctr = 0;
chatGrid.Children.Clear();
if (isChat == true)
{
for (int i = 0; i < _messageView.Count; i++)
{
if ((!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
if (_messageView.ElementAt(i).IsMe == true)
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Right;
Message.Margin = new Thickness(0, 0, 5, 0);
Message.Background = brush2;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Bluetail = new Image();
Bluetail.Source = temp4;
Bluetail.HorizontalAlignment = HorizontalAlignment.Right;
Bluetail.Height = 10;
Bluetail.Width = 20;
Bluetail.Margin = new Thickness(0, -(0.7), 10, 0);
Grid.SetRow(Bluetail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Right;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Bluetail);
chatGrid.Children.Add(Sender);
}
else
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Margin = new Thickness(5, 0, 0, 0);
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(10, -(0.7), 5, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Left;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
}
else
{
for (int i = 0; i < _messageView.Count; i++)
{
if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Margin = new Thickness(0, 10, 300, 0);
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(5, -(0.7), 0, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
//for (int i = 0; i < _messageView.Count; i++)
//{
// if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
// {
// }
//}
ctr = 0;
scrollView.ScrollToEnd();
}
Any ideas? thanks
Most UI elements may only be modified in the UI thread. As your event handler is apparently invoked in a different thread, you have to use the Dispatcher to invoke your code in the UI thread.
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => chatGrid.Children.Clear()));
}
EDIT: You may also pass more code to the Invoke call by using an anonymous method:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() =>
{
// more code here
}));
}
Of course you may also put a bunch of code in another method and pass that to the Invoke call:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => ConstructChatViewInUI(isChat)));
}
private void ConstructChatViewInUI(Boolean isChat)
{
...
}
When I am trying to save some images to my IsolatedStorage there is an Out of Memory exception occures. If the image count is more than 20 this error occurs. I am downloading all these images and save them in a temp folder in isolated storage. When I am trying to save these images from temp folder to a folder named myImages in isolated storage, this error occurs. Each photo is read from temp and write to myImages one by one. When some 20 or 25 photos are saved to myImages then this error occures. Images has an average size of 350-400 KB. How can I avoid this error?
My Code is :
private void SaveImages(int imageCount)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
BitmapImage bitmap;
string tempfoldername = "Temp";
string tempfilename = string.Empty;
string folderName = "myImages";
string imageName = string.Empty;
for (int i = 0; i < imageCount; i++)
{
tempfilename = tempfoldername + "\\" + (i + 1) + ".jpg";
bitmap = GetImage(tempfoldername, tempfilename);
imageName = folderName + "\\" + (i + 1) + ".jpg";
SaveImage(bitmap, imageName, folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
bitmap = null;
}
}
private BitmapImage GetImage(string foldername, string imageName)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs;
BitmapImage bi = new BitmapImage();
MemoryStream ms = new MemoryStream();
byte[] data;
int FileSize = 0;
if (isf.DirectoryExists(foldername))
{
isfs = isf.OpenFile(imageName, FileMode.Open, FileAccess.Read);
data = new byte[isfs.Length];
isfs.Read(data, 0, data.Length);
ms.Write(data, 0, data.Length);
FileSize = data.Length;
isfs.Close();
isfs.Dispose();
bi.SetSource(ms);
ms.Dispose();
ms.Close();
return bi;
}
return null;
}
private void SaveImage(BitmapImage bitmap, string imageName, string folderName)
{
int orientation = 0;
int quality = 100;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.DirectoryExists(folderName))
isf.CreateDirectory(folderName);
if (isf.FileExists(imageName))
isf.DeleteFile(imageName);
Stream fileStream = isf.CreateFile(imageName);
WriteableBitmap wb = new WriteableBitmap(bi);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, orientation, quality);
fileStream.Close();
}
}
how can I fix this error?
Your BitmapImage is most likely leaking the memory.
Be sure to set the UriSource to null so that the memory is freed.
Have a look at http://blogs.msdn.com/b/swick/archive/2011/04/07/image-tips-for-windows-phone-7.aspx for more.
i've searched about how to upload files to websites using console applications and i reached some ways, seems like the correct way, but i'm not having sucess with this. So i need some help!
First, the solution that i've founded follows:
class Program
{
static void Main(string[] args)
{
//Program.Test1();
Program.Test3();
Console.ReadLine();
}
public static void Test3()
{
//Set this to dont get an Invalid Request Exception
System.Net.ServicePointManager.Expect100Continue = false;
//Set a real page for this test
string url = "http://www.toledorocket.com/perftest/uploadtest/fileselect.asp";
string[] files = { "C:\\Documents and Settings\\wkurten\\Desktop\\fogao.txt" }; //Put some real file
NameValueCollection nvc = new NameValueCollection();
nvc.Add("FILE1", "fogao.txt");
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;
//Is you have an connection with proxy, uncomment and set the values bellow:
/*NetworkCredential localNetworkCredential = new NetworkCredential("user", "pass", "domain");
httpWebRequest2.Proxy = new WebProxy("server:port", false);
httpWebRequest2.Proxy.Credentials = localNetworkCredential;*/
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "file" + i, files[i]);
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
}
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
//Gets the response
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//Retrieve the html from response
string htmlResponse = reader2.ReadToEnd();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
}
}
The problem that i'm having with this solution is that when i upload a file and retrieves the WebResponse, the page that i'm getting is the page with the upload form and not the page that appears after upload, that page with the success message.
On the page that i'm trying to upload the file i have this html/form:
<FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="uploadstatus.asp">
<INPUT TYPE="FILE" SIZE="40" NAME="FILE1"> <INPUT TYPE=SUBMIT VALUE="Upload!">
</FORM>
When i run my code i just get this same form every time, seems like i'm never posting anything... anyone have an idea of what is happening?