Object reference not set to an instance of an object.

Posted on 2011-10-10
Last Modified: 2012-05-12
I am receiving the "Object reference not set to an instance of an object. " on my production web site, but am not receiving it on my developement web site.   I have attached the code it is error out on.  Any ideas why this is happening.

thank you
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click

        Dim i As Integer = 0
        'Dim myConn As New SqlConnection(myConnStr)
        Dim myRow As DataRow
        Dim mUser As MembershipUser = (Session("myUser"))
        On Error GoTo Problem

        For i = 0 To myDS.Tables(1).Rows.Count - 1
            myRow = myDS.Tables(1).Rows(i)
            Dim myCMD As New SqlCommand
            With myCMD
                .Connection = myConn
                .CommandType = CommandType.StoredProcedure
                .CommandText = "TAG_UpdateMOInspectionDetail_Web"
                .Parameters.Add(New SqlParameter("@ItemQty", myRow.Item(5).ToString))
                .Parameters.Add(New SqlParameter("@ItemCost", myRow.Item(6)))
                .Parameters.Add(New SqlParameter("@ItemPrice", myRow.Item(7)))
                .Parameters.Add(New SqlParameter("@Charge", myRow.Item(8)))
                .Parameters.Add(New SqlParameter("@LastEditDate", FormatDateTime(Now, DateFormat.GeneralDate)))
                .Parameters.Add(New SqlParameter("LastEditBy", mUser.UserName))
                .Parameters.Add(New SqlParameter("@ID", myRow.Item(0)))
            End With
        lblStatus.Text = "Changes Saved"
        lblStatus.Visible = True
        Exit Sub
        Dim myMessage As String = Err.Description
        lblStatus.Text = "Problem Saving Changes" & Err.Description
        lblStatus.Visible = True
    End Sub

Open in new window

Question by:mgmhicks
    LVL 12

    Expert Comment

    by:Wouter Boevink
    On which line does the error occur?

    Author Comment

    Since it only does it on Production not really sure.  Put the code looks good no?   Any ideas on how to find the exact line that it is erroring?

    LVL 12

    Expert Comment

    by:Wouter Boevink
    My best guess is that the user is impersonted bu not authenticated.

    Please read the following article:

    Especially the part about 'Impersonate a Specific User in Code'.

    <%@ Page Language="C#"%>
    <%@ Import Namespace = "System.Web" %>
    <%@ Import Namespace = "System.Web.Security" %>
    <%@ Import Namespace = "System.Security.Principal" %>
    <%@ Import Namespace = "System.Runtime.InteropServices" %>
    <script runat=server>
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;
    WindowsImpersonationContext impersonationContext; 
    public static extern int LogonUserA(String lpszUserName, 
    	String lpszDomain,
    	String lpszPassword,
    	int dwLogonType, 
    	int dwLogonProvider,
    	ref IntPtr phToken);
    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public static extern int DuplicateToken(IntPtr hToken, 
    	int impersonationLevel,  
    	ref IntPtr hNewToken);
    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
    public static extern bool RevertToSelf();
    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern  bool CloseHandle(IntPtr handle);
    public void Page_Load(Object s, EventArgs e)
    	if(impersonateValidUser("username", "domain", "password"))
    		//Insert your code that runs under the security context of a specific user here.
    		//Your impersonation failed. Therefore, include a fail-safe mechanism here.
    private bool impersonateValidUser(String userName, String domain, String password)
    	WindowsIdentity tempWindowsIdentity;
    	IntPtr token = IntPtr.Zero;
    	IntPtr tokenDuplicate = IntPtr.Zero;
    		if(LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, 
    			LOGON32_PROVIDER_DEFAULT, ref token) != 0)
    			if(DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
    				tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
    				impersonationContext = tempWindowsIdentity.Impersonate();
    				if (impersonationContext != null)
    					return true;
    	if(token!= IntPtr.Zero)
    	return false;
    private void undoImpersonation()

    Open in new window

    LVL 12

    Expert Comment

    by:Wouter Boevink
    Sorry, the right answer to the wrong question :-)
    LVL 83

    Accepted Solution

    >On Error Goto Problem

    That is not used in .NET. Use Try catch blocks instead

    I suspect the error is in
    >For i = 0 To myDS.Tables(1).Rows.Count - 1

    What is MyDS? Dataset? Did you save it to session and restore it?

    Also, do you have two tables in dataset? Index starts at 0 in .NET so if you have only one table then use


    Author Comment

    The error ended up being on line
      .Parameters.Add(New SqlParameter("LastEditBy", mUser.UserName))
    muser.username was nothing.  Probably because of authenication.  Changed code to

     Dim mCurrUser As String = Page.User.Identity.Name

    and then

     .Parameters.Add(New SqlParameter("LastEditBy", mcurrUser))
    and it works fine.

    Not sure why it would error on production but not developement machine but thats what fixed it


    Featured Post

    Courses: Start Training Online With Pros, Today

    Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

    Join & Write a Comment

    Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
    Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now