System.ArgumentException when the code get the stream of image file - ASPX - asp.net

i hope anyone to help me in this code that i don't know where,what and why this problem has tookplace !!
i have this code responsible to get images from directory to make a simple watermark for each one, but there is an exception when the code arrive to read the image as streams..
please look at this code :
DirectoryInfo[] dir = new DirectoryInfo[2];
dir[0] = new DirectoryInfo(Server.MapPath("Image/DB/Large/"));
dir[1] = new DirectoryInfo(Server.MapPath("Image/DB/Slide/"));
Image signature = Image.FromFile(Server.MapPath("Image/Design/signature.png"));
for (int i = 0; i < dir.Length; i++)
{
FileInfo[] fs = dir[i].GetFiles("*.jpg");
foreach (FileInfo s in fs)
{
FileStream strm = s.OpenRead();
String name = s.Name;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(signature, new Point(0, 0));
g.Dispose();
strm.Close();
if (i == 0)
{
String v = Server.MapPath("Image/DB/Large/" + name);
img.Save(v);
}
else if (i == 1)
{
String v = Server.MapPath("Image/DB/Slide/" + name);
img.Save(v);
}
}
}
Excception Details :
[ArgumentException: .] System.Drawing.Image.FromStream(Stream stream, Boolean
useEmbeddedColorManagement, Boolean validateImageData) +1065883
System.Drawing.Image.FromStream(Stream stream) +8 Developer.Page_Load(Object sender,
EventArgs e) in f:\.NET Programming\‫FaieqSahwish_V.2.0\Developer.aspx.cs:29
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t,
EventArgs e) +14 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
EventArgs e) +35 System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50 System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

According to the FromStream documentation a ArgumentException is thrown if the stream is not a valid image format or if the stream is null.
Have you verified that neither of these conditions are met for the stream passed into FromStream?

When the exception happens, Visual studio might bring up a debugger. What I'd do is check to make sure your images are what you think they are, and then I'd step through your code and make sure that all the fields are as they should be.
as Ken Henderson said, something(like your FileStream) might be null
Here's a quick sample that i put together myself. It throws no exception.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(#".");
FileInfo[] fi = dir.GetFiles("*.jpg");
FileStream fs = fi[0].OpenRead();
//FileStream fs = new FileStream("New Bitmap Image.jpg", FileMode.Open);
System.Drawing.Image.FromStream(fs);
}
}
}

Related

Object reference not set to an instance of an object

My asp.net-Mysql application is hosted on windowsserver,when i tried to insert image into mysql table from the admin.aspx page,its displaying the error
"Object reference not set to an instance of an object."
But from my VS I can insert image to local mysql server without any error.
When i inserted image from webadmin,it is inserted successfully and displaying image on website.I can update the contents through my admin.aspx,but when i tried to update or insert image,I am getting the error.
[NullReferenceException: Object reference not set to an instance of an object.]
Lavande.DBconnect.addimagehome(Byte[] image, String Content, String arabiccontent) in C:\Users\user\Desktop\Lavande_Asp\Lavande\Lavande\DBconnect.cs:33
Lavande.abklavande900.button_savehome_Click(Object sender, EventArgs e) in C:\Users\user\Desktop\Lavande_Asp\Lavande\Lavande\abklavande900.aspx.cs:84
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Following is the code to read the uploaded file:
string path = System.IO.Path.GetFullPath(FileUpload_home.PostedFile.FileName);
Byte[] image = WM.ImageSetting("watermarkname", Server.MapPath("upload/") + "logo1.png", path);
DB.addimagehome(image, contentsend, arabiccontent);
watermarkclass.
public class watermark
{
public Byte[] ImageSetting(string wmText, string wmImage, string mainImage)
{
byte[] imageBytes = null;
if (File.Exists(mainImage))
{
System.Drawing.Image image = System.Drawing.Image.FromFile(mainImage);
Graphics graphic;
if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
{
// Graphic is not a Indexed (GIF) image
graphic = Graphics.FromImage(image);
}
else
{
/* Cannot create a graphics object from an indexed (GIF) image.
* So we're going to copy the image into a new bitmap so
* we can work with it. */
Bitmap indexedImage = new Bitmap(image);
graphic = Graphics.FromImage(indexedImage);
// Draw the contents of the original bitmap onto the new bitmap.
graphic.DrawImage(image, 0, 0, image.Width, image.Height);
image = indexedImage;
}
graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;
//Text Watermark properties
Font myFont = new Font("segoe script", 17, FontStyle.Bold);
SolidBrush brush = new SolidBrush(Color.FromArgb(40, Color.White));
SizeF textSize = new SizeF();
if (wmText != "")
textSize = graphic.MeasureString(wmText, myFont);
//Image Watermark
System.Drawing.Image ig = null;
if (wmImage != "")
ig = System.Drawing.Image.FromFile(wmImage);
// Write the text watermark and image watermark across the main image.
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
PointF pointF = new PointF(x, y);
PointF pointFm = new PointF(x, y+150);
if (wmText != "")
{
graphic.DrawString(wmText, myFont, brush, pointFm);
x += Convert.ToInt32(textSize.Width);
}
if (wmImage != "")
{
graphic.DrawImage(ig, pointF);
x += Convert.ToInt32(ig.Width);
}
}
if (wmText != "")
y += Convert.ToInt32(textSize.Height);
if (wmImage != "")
y += Convert.ToInt32(ig.Height);
}
using (MemoryStream memoryStream = new MemoryStream())
{
// save image in memoryStream with it format which get it from GetImageFormat function
image.Save(memoryStream, GetImageFormat(mainImage));
imageBytes = memoryStream.ToArray();
}
graphic.Dispose();
}
return imageBytes;
}
//function to return Image Format
ImageFormat GetImageFormat(String path)
{
switch (Path.GetExtension(path).ToLower())
{
case ".bmp": return ImageFormat.Bmp;
case ".gif": return ImageFormat.Gif;
case ".jpg": return ImageFormat.Jpeg;
case ".png": return ImageFormat.Png;
default: return null;
}
}
}
}
Based on your stack trace and the code it points to, the image variable there must be null. The exception is thrown when you try to look at the Length property... there is no object there to use to check that property.
The reason it's null is that your ImageSetting() function can be summarized like this:
Byte[] ImageSetting(...)
{
Byte[] imageBytes = null;
if (File.Exists(...) )
{
//...
}
return imageBytes;
}
Obviously, the File.Exists() call fails, and thus you return no image. You likely should have a placeholder image you can load and use instead. Also, you should not use File.Exists() like that in the first place, as the file system is volatile. Instead, put your coding efforts into the exception handler.
Like I wrote in my comment: your image cannot be retrieved from the server, because your pool identity has not rights to access the directory.
Set the access rights of the directory with the images to everyone, then it might work (for test purpose only).

Exception when reading file image on server - ASP.NET

i hope anyone help me in this problem ..
i have simple aspx code to get image file from directory and make some proccesses on it as drawing somthing on it after that i save it on the same directory.
really the code has worked well on local machine, but on server side the code fails and the exception appears. ( ArgumentException: Parameter is not valid )
please look at the code :
DirectoryInfo[] dir = new DirectoryInfo[2];
dir[0] = new DirectoryInfo(Server.MapPath("Image/DB/Large/"));
dir[1] = new DirectoryInfo(Server.MapPath("Image/DB/Thumb/"));
System.Drawing.Image signature = System.Drawing.Image.FromFile(Server.MapPath("Image/Design/signature.png"));
for (int i = 0; i < dir.Length; i++)
{
FileInfo[] fs = dir[i].GetFiles("*.jpg");
foreach (FileInfo s in fs)
{
FileStream strm = s.OpenRead();
String name = s.Name;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(signature, new Point(0, 0));
strm.Close();
if (i == 0)
{
String v = Server.MapPath("Image/DB/Large/" + name);
img.Save(v);
}
else if (i == 1)
{
String v = Server.MapPath("Image/DB/Slide/" + name);
img.Save(v);
}
g.Dispose();
}
}
Exception Details :
Parameter is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Parameter is not valid.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Parameter is not valid.]
System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) +1062843
System.Drawing.Image.FromStream(Stream stream) +8
Developer.Button1_Click(Object sender, EventArgs e) +279
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
You must convert your FileStream to Stream
System.Drawing.Image.FromStream(..);// This method take Stream as argument and nor FileStream
You can try with CopyTo, in order to convert.
Link : http://msdn.microsoft.com/en-us/library/dd782932.aspx
FileStream strm = s.OpenRead();
Stream stream = new Stream();
strm.CopyTo(stream);
System.Drawing.Image.FromStream(stream);
Before .Net 4, you can use this extension method
public static class Ext
{
public static void CopyTo(this FileStream in, Stream out)
{
byte[] temp= new byte[16*1024]; //You can adjust this value
int bytesRead;
while ((bytesRead = in.Read(temp,0, temp.Length)) > 0)
{
out.Write(temp, 0, bytesRead);
}
}
}

Changing Entity connection string error

I am having a problem when changing the model entities connection string,
when a user first logs in the KurtDBEntities conection string is being chosen properly
but when logging in as an admin if (daRoles.IsUserInRole(User, 1)) or any other instance it is giving me this error:
System.InvalidOperationException was unhandled by user code
Message=No modifications to connection are permitted after the metadata has been registered either by opening a connection or constructing the connection with a MetadataWorkspace.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityClient.EntityConnection.ValidateChangesPermitted()
at System.Data.EntityClient.EntityConnection.set_ConnectionString(String value)
at DataLayer.ConnectionClass..ctor(String User) in Documents\Visual Studio 2010\Projects\DataLayer\ConnectionClass.cs:line 32
at BusinessLayer.BLBase..ctor(String user) in Documents\Visual Studio 2010\Projects\BusinessLayer\BLBase.cs:line 54
at BusinessLayer.Roles..ctor(String userLogged) in Visual Studio 2010\Projects\BusinessLayer\Roles.cs:line 12
at PresentationLayer.UserControls.Menu.Page_Load(Object sender, EventArgs e) in C:\Users\Documents\Visual Studio 2010\Projects\PresentationLayer\UserControls\Menu.ascx.cs:line 23
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
and:
public ConnectionClass(string User)
{
this.Entities = new KurtDBEntities();
DataLayer.DARoles daRoles = new DARoles(this.Entities);
if (User == "Login")
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
else
{
//can also use entity connection string builder
if (User != "")
{
if (daRoles.IsUserInRole(User, 1))
{
this.Entities.Connection.ConnectionString = #"Data Source=KURT-PC\SQLEXPRESS;Initial Catalog=KurtDB;User ID=Admin;Password=123456";
}
else if (daRoles.IsUserInRole(User, 2))
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["BasicUser"].ConnectionString.ToString();
}
}
else
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
}
//this.Entities.Connection.ConnectionString = conn;
}
}
Any Help Please?
Please see my answer to your other question:
You'll need to first determine the connection string that you want to use and only after that you'll be able to new up the Entities object:
string connectionString = GetConnectionStringBasedOnUserRole(); // do your magic here
this.Entities = new KurtDBEntities(connectionString);
After this you should be able to use Entities normally, pointing to the correct database/server.

How to use PageAsyncTask with WebRequest for multiple requests?

I'm targeting a web service that takes a single string parameter.
On a schedule I want to fire off approximately 100 calls to that web service for 100 values from my database.
To optimise the process I believe I need to do the WebRequest calls asynchronously.
I've come across the code example below on a variety of blogs etc. but can't figure out how to adapt it for my requirement.
How can I wrap up the RegisterAsyncTask inside a foreach loop, parsing through the uri for the WebRequest.Create() that's inside BeginAsyncOperation?
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public partial class AsyncPageTask : System.Web.UI.Page
{
private WebRequest _request;
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
null
);
RegisterAsyncTask(task);
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e,
AsyncCallback cb, object state)
{
_request = WebRequest.Create("http://msdn.microsoft.com");
return _request.BeginGetResponse(cb, state);
}
void EndAsyncOperation(IAsyncResult ar)
{
string text;
using (WebResponse response = _request.EndGetResponse(ar))
{
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
{
text = reader.ReadToEnd();
}
}
Output.Text = text;
}
void TimeoutAsyncOperation(IAsyncResult ar)
{
Output.Text = "Data temporarily unavailable";
}
}
My intention is to write the response string back into a database. Appreciate this is an additional question but, is there any reason not to include the insert method call within the EndAsyncOperation method ?
This Q&A hints towards my main question but which 4th argument?
First you need to add this to your Web.config file (default is just 2):
<configuration>
<system.net>
<connectionManagement>
<add address="*" maxconnection="100" />
</connectionManagement>
<system.net>
<configuration>
Then you need to add async directive to your page: <%# Page Async="true" %>
protected void Page_Load(object sender, EventArgs e)
{
//...first get UriStringArray from db, and then:
foreach(string uri in UriStringArray)
{
var task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
uri,
true; //run in parallel
);
RegisterAsyncTask(task);
}
}
IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object state)
{
var request = (HttpWebRequest)WebRequest.Create((string)state);
return request.BeginGetResponse(cb, request);
}
void EndAsyncOperation(IAsyncResult ar)
{
string text;
var request = (HttpWebRequest)ar.State;
using(WebResponse response = request.EndGetResponse(ar))
{
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
text = reader.ReadToEnd();
}
//yes, you can insert in db here, even as a new PageAsyncTask - but then must call ExecuteRegisteredAsyncTasks() manually...
}

convert text to json

i use Newtonsoft.Json.Net20.dll
Html
<div id="a" runat="server">
</div>
Code
string kb = "a";
string b= Newtonsoft.Json.JsonConvert.SerializeObject(kb).ToString();
a.InnerText = b;
in local host on iis6 show "a"
but on internet show
��G�[�!�{��u^Ӹ�SY�L?��qz�Z�Ŕ�?���U1k������)f�]A�(�ݣ�w N����Q�x�.�0�=�����X�y6�?��.�r�~;��[�t�~�/�K��z�|�-��W�ź��Q��&���4B��Q�4o�u��x|wrt�L�K�$���Ms�.��4��ٺ.��|�.����s����W�$��_���ӗe�54��ȯ��`�6mk�#�.*��by�ap٤Z��Oa�^�s�jӪ.��p� �n�Y>�������Ӽ͊�����n�|1~M����z�r�}�Qz�9��u��i��v���0�-ˑǃ�������/���s��t���:b�������l�~�H[�4��o'�g�/�E�=����o�� ��3G��ގ}Yߝ|�~�����H�Z�;�����i��vrg�z�m����]�Uh�Z6>[.�� )�er����I���.��.�K_yȞF(C�v�Ha>"s�4��gE����G�/a׮֓��r^5m��u�<ϊzZ������jVM�߷��d���x���/\N�ա�b� qo�֜��%� $���l����s?/��
This link
but
when use Newtonsoft.Json
Dictionary<string, string> companyProducts = new Dictionary<string, string>();
companyProducts.Add("product" + item.IdProduct, item.NameProduct.ToString());
string JsonCompany = JavaScriptConvert.SerializeObject(companyProducts);
this code work fine.
this link
when site upload to internet for add new reference.
Enough that copy dll to appcode
Edit
use gzip in gloabal.asax
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (!(app.Context.CurrentHandler is Page ||
app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;
if (acceptEncoding == null || acceptEncoding.Length == 0)
return;
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("gzip") )
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
{
// defalte
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
}
The file that you are getting from that page is a compressed file that contains an error page with an exception in it. Why it is doing this I don't know. Your global error handler might have a bug in it that causes it to send compressed data without the correct headers...
I assume you can get the file information out now you know what it is (I just right clicked on the link above and then used 7zip to open the file).
The key points though are:
Source File: c:\inetpub\vhosts\iranfairco.com\httpdocs\test.aspx.cs Line: 20
[VerificationException: Operation could destabilize the runtime.]
Newtonsoft.Json.JsonWriter..cctor() +6
[TypeInitializationException: The type initializer for 'Newtonsoft.Json.JsonWriter' threw an exception.]
Newtonsoft.Json.JsonWriter..ctor() +0
Newtonsoft.Json.JsonTextWriter..ctor(TextWriter textWriter) +16
Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings) +157
Newtonsoft.Json.JsonConvert.SerializeObject(Object value) +9
test.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\iranfairco.com\httpdocs\test.aspx.cs:20
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
There is most likely something that is completely unrelated to the JSON conversion that is wrong, as not even the div tag show up in the page source.
Analysing the response in a binary editor reveals a lot of the UTF-8 sequence EF BF BD which is the character FFFD which is the Unicode replacement character. This is used when Unicode decoding fails, most likely because you have tried to decode something with the wrong encoding.

Resources