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);
}
}
}
Related
I am trying to send an email to the user's account when the user clicks send button. But I am getting the above error. Below is my sendClick code.
protected void btnsendCode_Click(object sender, EventArgs e)
{
try
{
if (txtemail.Text != "")
{
Random rd = new Random();
veri = rd.Next(1000, 10000);
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress(txtemail.Text.ToString()));
mm.From = new MailAddress("xxx#yyy.in", "Verification Mail");
mm.Body = "Your Verification Code is - " + veri.ToString();
mm.IsBodyHtml = true;
mm.Subject = "Verification mail";
SmtpClient smcl = new SmtpClient();
smcl.Host = "smtp.gmail.com";
smcl.Port = 587;
smcl.Credentials = new NetworkCredential("xxx#yyy.in", "xxx");
//smcl.EnableSsl = true;
smcl.Send(mm);
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Verification Code sent to your Email ID! Please Check your Email!!');", true);
txtverify.Enabled = true;
btnsendCode.Text = "Send Code Again";
lblmsg.Visible = false;
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "Please enter Email ID!!";
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
lblmsg.Focus();
}
}
catch (WebException we)
{
lblmsg.Visible = true;
lblmsg.Text = we.Message.ToString();
lblmsg.ForeColor = System.Drawing.Color.Yellow;
lblmsg.BorderColor = System.Drawing.Color.Red;
lblmsg.BorderStyle = BorderStyle.Ridge;
lblmsg.BorderWidth = new Unit("2");
}
}
Stack Trace
[FormatException: The specified string is not in the form required for
an e-mail address.]
System.Net.Mail.MailAddressParser.ReadCfwsAndThrowIfIncomplete(String
data, Int32 index) +1475945
System.Net.Mail.MailAddressParser.ParseDomain(String data, Int32&
index) +135 System.Net.Mail.MailAddressParser.ParseAddress(String
data, Boolean expectMultipleAddresses, Int32& index) +99
System.Net.Mail.MailAddressParser.ParseAddress(String data) +23
System.Net.Mail.MailAddress..ctor(String address, String displayName,
Encoding displayNameEncoding) +220
System.Net.Mail.MailMessage..ctor() +130
events.btnsendCode_Click(Object sender, EventArgs e) in
d:\inetpub\vhosts\marpallichande.in\httpdocs\Test\events.aspx.cs:101
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9552874
System.Web.UI.WebControls.Button.RaisePostBackEvent(String
eventArgument) +103
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)
+35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1724
Which part I am committing mistake and need to correct it?
The reason it fails is using the empty constructor without the mail settings to match:
MailMessage mm = new MailMessage();
The empty constructor relies on:
<system.net>
<mailSettings>
<smtp from="report#company.com" />
</mailSettings>
</system.net>
in your app or web.config file. So either use the constructor that expects a from and to address, or add that node to your app/web.config file.
I firmly believe this is a bug in the .Net framework, because we were able to create new MailMessage() objects and then assign the "from" later on, but in .Net 4.0 and under certain conditions—which I still don't fully understand—this fails. I welcome being corrected of course, but for now, this seems like an oversight.
So some of our customers never encountered this issue, but to fix it we had to add that dummy setting to the web.config files.
I had a similar problem with getting [FormatException: The specified string is not in the form required for an e-mail address.] too. My problem was with this code:
void SendMail(string destinationEmail)
MailMessage message=new MailMessage("mytestmail#test.com",destinationEmail);
SmtpClient mailClient = new SmtpClient("mail.test.com", 587);
mailClient.Credentials = new System.Net.NetworkCredential("mytestmail", "pswd");
try{
mailClient.Send(mail);
}
catch (Exception ex){...}
As you can see I just tried and caught only sending part. But this problem was thrown from MailMessage constructor. I would have never guessed that a constructor would throw an exception. So I just tried this code independently:
MailMessage mail = new MailMessage("test", "test");
The result of this code is [FormatException: The specified string is not in the form required for an e-mail address.]. If you try this:
MailMessage mail = new MailMessage("", "");
you'll get ArgumentException: The parameter 'from'(or 'to') cannot be an empty string.
So what you need to do in these kind of cases is you include the MailMessage construction part in the try catch block too and make sure that the exception you catch covers exception types that MailMessage constructor might throw, in this particular case, FormatException. Although I hate cathcing the Exception class, in this case it seems to be a perfect fit.
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);
}
}
}
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.
i have been designing a web page in asp.net and my project is successful. and i published my web application.However, below error occurs.How can I clear it?
Server Error in '/sarav' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
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:
[NullReferenceException: Object reference not set to an instance of an object.]
Login.btnLogin_Click(Object sender, EventArgs e) +155
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
How to clear error
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection Cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != null)
{
constr = ConfigurationManager.ConnectionStrings["PhotostudioConnectionString"].ConnectionString;
Cnn.ConnectionString = constr;
try
{
if (Cnn.State != ConnectionState.Open)
Cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = Cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UspGetDataUsrmast";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#usrname", txtUsername.Text);
cmd.Parameters.AddWithValue("#passwrd", txtPassword.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
// cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new ApplicationException("!!! An Error Occurred While Inserting Record. " + ex.Message);
}
finally
{
da.Dispose();
cmd.Dispose();
Cnn.Close();
Cnn.Dispose();
}
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Login Successfully";
// da.Dispose();
// cmd.Dispose();
// Cnn.Close();
// Server.Transfer("Home.aspx");
Response.Redirect("PhotosettingsReport.aspx");
}
else
{
Msg.Text = "Login Failed";
}
}
}
}
Without seeing the code, it's impossible to even guess as to what object is throwing this error.
Run the website in Visual Studio in debug mode (F5), and put a breakpoint at btnLogin_Click. When you click the button, it will break and allow you to step into the code. Step through the code until you find the line that is throwing the exception - that is the object that is null.
You're either trying to access something declared in the method that has not been initialized, or an object outside the method that has not been initialized.
Stepping through the code will quickly show you what's wrong.
UPDATE
I'd check txtUserName and txtPassword to be sure they have values. Also, are you sure you're getting results into the ds.Tables[0]? Calling Rows.Count on ds.Tables[0] could also result in that error if there are no tables.
Also, check your Web.config file - make sure that "PhotostudioConnectionString" is spelled correctly, including the case of the letters.
Why are you checking for IsValid != null? I think if (!IsValid) would be more proper. IsValid will either be true or false, it will never be null, so your code will always pass that check.
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.