Avatar of mgmhicks
mgmhicks

asked on 

Object reference not set to an instance of an object.

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
            myConn.Open()
            myCMD.ExecuteNonQuery()
            myConn.Close()
        Next
        lblStatus.Text = "Changes Saved"
        lblStatus.Visible = True
        Exit Sub
Problem:
        Dim myMessage As String = Err.Description
        lblStatus.Text = "Problem Saving Changes" & Err.Description
        lblStatus.Visible = True
    End Sub

Open in new window

Visual Basic.NETASP.NET

Avatar of undefined
Last Comment
mgmhicks
Avatar of Wouter Boevink
Wouter Boevink
Flag of Netherlands image

On which line does the error occur?
Avatar of mgmhicks
mgmhicks

ASKER

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?

Avatar of Wouter Boevink
Wouter Boevink
Flag of Netherlands image

My best guess is that the user is impersonted bu not authenticated.

Please read the following article: http://support.microsoft.com/kb/306158

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; 

[DllImport("advapi32.dll")]
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.
		undoImpersonation();
	}
	else
	{
		//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(RevertToSelf())
	{
		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)
				{
					CloseHandle(token);
					CloseHandle(tokenDuplicate);
					return true;
				}
			}
		} 
	}
	if(token!= IntPtr.Zero)
		CloseHandle(token);
	if(tokenDuplicate!=IntPtr.Zero)
		CloseHandle(tokenDuplicate);
	return false;
}

private void undoImpersonation()
{
	impersonationContext.Undo();
}
</script>

Open in new window

Avatar of Wouter Boevink
Wouter Boevink
Flag of Netherlands image

Sorry, the right answer to the wrong question :-)
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of mgmhicks
mgmhicks

ASKER

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

ASP.NET
ASP.NET

The successor to Active Server Pages, ASP.NET websites utilize the .NET framework to produce dynamic, data and content-driven web applications and services. ASP.NET code can be written using any .NET supported language. As of 2009, ASP.NET can also apply the Model-View-Controller (MVC) pattern to web applications

128K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo