Click here to Skip to main content
15,900,461 members
Please Sign up or sign in to vote.
2.78/5 (3 votes)
See more:
I am doing one simple mail Application in which I want to set one static profile pic or any logo of the company I wrote the following code but I its not working and NullReferenceException is coming while I am debugging my code. Please try to solve this and Thanks in Advance.

Below is my code which I wrote in button click.



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Net.Mime;

public partial class _Default : System.Web.UI.Page
{
    MailMessage msgobj;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        string strMailContent = "Welcome new user";
        string ContentId = "image1";
        SmtpClient serverobj = new SmtpClient();

        serverobj.Credentials = new NetworkCredential(txtFrom.Text, txtPassword.Text);
        serverobj.Port = 587;//25
        serverobj.Host = "smtp.gmail.com";
        serverobj.EnableSsl = true;
        String FileName = fileUploadControl.PostedFile.FileName;
        string path = Server.MapPath("~/download.jpg");
        LinkedResource logo = new LinkedResource(path);
        logo.ContentId = "download.jpg";
        //AlternateView av1 = new AlternateView();
        AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:http://localhost:58146/WebMail/download.jpg /><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
        av1.LinkedResources.Add(logo);

        msgobj.AlternateViews.Add(av1);
        msgobj = new MailMessage();
        msgobj.From = new MailAddress(txtFrom.Text, "Mukesh", System.Text.Encoding.UTF8);
        string s = @"<br /> <img src=""http://localhost:58146/WebMail/download.jpg"" alt=""Logo"" /><br />";

        msgobj.Body = s + txtMessageBox.Text;
        msgobj.To.Add(txtTO.Text);
        msgobj.Subject = txtSubjcet.Text;
       
        msgobj.IsBodyHtml = true;
        msgobj.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        serverobj.Send(msgobj);
        lblMessageStatus.Text = "Mail Sent Successfully";
    }
}
Posted
Updated 25-Apr-14 3:31am
v2
Comments
On which line?
Mukesh Pr@sad 25-Apr-14 10:09am    
in the following line error occurred.

msgobj.AlternateViews.Add(av1);

You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Good luck,
—SA
 
Share this answer
 
NullReference means that something that should have been initialized or set with a value wasn't. All you have to do is find the line of code where the error is and then fix it.

Since you didn't tell us where the error occurred I am going to guess it was on this line, fileUploadControl.PostedFile.FileName;

The upload control does not retain the posted file, I do not believe. When it uploads it does a postback so you'll need to store the image somewhere and then after the button to send email is clicked then you'll have to retrieve that image again.
 
Share this answer
 
Comments
Mukesh Pr@sad 25-Apr-14 10:07am    
In the following line Exception is occurred.

msgobj.AlternateViews.Add(av1);
ZurdoDev 25-Apr-14 10:20am    
If you debug it you'll see that msgobj is null. You haven't instantiated it anywhere.
There isn't a one size fits all solution for this I'm afraid. The reason you get this is because the code tries to access a member of a variable that is null:
e.g.
foo.Bar
or
foo.Bar()
or even
foo.Bar.SomethingElse

If foo is null you'll get the exception. Also if you try an pass foo into a method and manipulate it there - you'll get it.

In practise this means the exception could come anywhere in your code - or even in framework code where you've passed a null in.


In general:

  • The exception should give you where the problem occurred in code - use this to find the problem. Take a look at the stack trace to narrow your problem down.
  • Run the code in debug mode from IE. The IDE should move you to where the error happens
  • If all else fails put a breakpoint at the top of the method called, run under debug and step though until you get the problem. This might take a couple of goes.


Once you've found the line, you can put a breakpoint on it and examine the variables before the exception is raised (note for foo.Bar.SomethingElse you need to check "foo" and "bar"). You can then hover over the propery in Visual studio or right click it in code and select "quickwatch". If you've found a null you've found your culprit.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900