How to clear error in asp.net - asp.net

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.

Related

MS Access database able to be accessed in debug mode but not accessible when published

I've written some basic code in ASP.NET that accesses a Microsoft Access database, which works when I run in debug mode on IIS Express, but when I published the application and tried to run on the actual website, I get the error.
[IndexOutOfRangeException: There is no row at position 0.]
System.Data.RBTree`1.GetNodeByIndex(Int32 userIndex) +2430497
NIM_Tool.Default.Page_Load(Object sender, EventArgs e) +2321
System.Web.UI.Control.OnLoad(EventArgs e) +106
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3785
From modifying some of my code, I'm pretty confident that the database is unable to be found, but I can't figure out why it's able to be accessed in debug/release mode but not from the published mode. After clicking publish, all files went to the bin/Release/Publish/ folder from the root directory, which I then copied all the children of the Publish folder to the correct server path. The children files/folder also contained the correct MS Access database.
code from the DataLayer.cs file
public class DataLayer {
static OleDbConnection conn;
static OleDbCommand cmd;
static String connString;
static OleDbDataAdapter adp;
private static void CreateCommand()
{
// have also tried hardcoding this to the production server path but this failed too
connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + HttpContext.Current.Server.MapPath("MyDatabase.mdb") + ";Persist Security Info=False;"
conn = new OleDbConnection(connString);
cmd = new OleDbCommand();
cmd.Connection = conn;
adp = new OleDbDataAdapter();
}
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
}
return dt;
}
}
And The Default.aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtDeposit = DataLayer.GetDefaultDeposit();
string fixedCost = (string)dtDeposit.Rows[0]["FixedCost"];
}
}
The MyDatabase.mdb file is located in the same directory as the DataLayer.cs file. I've tried hardcoding the database path as well to where it should be accessed on the server, but got the same error message as well.
A little advice: you are being your own enemy when you catch an error and don't do anything with it. It is called "swallowing an error" and it hides root-causes.
Instead, I would recommend doing a re-throw. Put your (original) Exception as the .InnerException. You might want to have your connString in the .Description for the (outer) Exception. (Just in case MapPath didn't do what you thought it should, etc.)
Like this:
public static DataTable GetDefaultDeposit()
{
DataTable dt = new DataTable();
CreateCommand();
try {
cmd.CommandText = "SELECT * FROM Table1";
adp.SelectCommand = cmd;
adp.Fill(dt);
}
catch (Exception ex) {
throw new Exception("ConnString=" + connString, ex);
}
return dt;
}

Error in Application : The specified string is not in the form required for an e-mail address

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.

Not able to connect to database in ASP IIS

I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on
page.redirect["master.apsx",true]
so I changed it to
page.redirect["master.aspx",false]
and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{
strconn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
Label1.Text = " conn string";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{
try
{
if (txt_username.Text != null)
{
if (txt_password.Text != null)
{
DataTable dt = new DataTable();
conn = new SqlConnection(strconn);
conn.Open();
cmd = new SqlCommand("Select * From UserMaster Where Username=#username and Password=#password", conn);
cmd.Parameters.AddWithValue("#username", txt_username.Text);
cmd.Parameters.AddWithValue("#password", txt_password.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
{
if (dt.Rows.Count > 0)
{
userloginname = txt_username.Text;
userloginpassword = txt_password.Text;
Session["username"] = txt_username.Text;
MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Response.Redirect("Marketing.aspx",false);
}
else
{
Label1.Text = "else part";
MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txt_username.Focus();
}
txt_username.Text = "";
txt_password.Text = "";
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
conn.Close();
Label1.Text = "login";
}
You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.
I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
You need to provide more detail
You need to check weather you are able to connect to database or not.
You also need to check weather the page is called or not (which comes after login).

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);
}
}
}

Manual Databind in Gridview Paging

Server Error in '/' Application.
--------------------------------------------------------------------------------
The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.
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.Web.HttpException: The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.
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:
[HttpException (0x80004005): The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.]
System.Web.UI.WebControls.GridView.OnPageIndexChanging(GridViewPageEventArgs e) +1325594
System.Web.UI.WebControls.GridView.HandlePage(Int32 newPage) +86
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +464
System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument) +207
System.Web.UI.WebControls.GridView.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) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
when using this function and enable paging = true
private void BindGrid(string sqlQuery, ref GridView gv)
{
SqlConnection sqlConnection = null;
try
{
sqlConnection = new SqlConnection(strConnect);
SqlCommand scom = new SqlCommand(sqlQuery, sqlConnection);
scom.CommandTimeout = 100;
sqlConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(scom);
DataTable dt = new DataTable();
adapter.Fill(dt);
gv.DataSource = dt;
gv.DataBind();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
if (sqlConnection != null) sqlConnection.Close();
}
}
Add a handler for PageIndexChanging event.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
.....
.....
GridView1.DataSource=dt;
GridView1.DataBind();
}
Try, this code:
int newPagenumber = e.NewPageIndex;
GridView1.PageIndex = newPagenumber;
GridView1.DataSource = call the method that will fill ur dataset.
GridView1.DataBind();

Resources