[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Object reference not set to an instance of an object.

Posted on 2011-10-10
6
Medium Priority
?
362 Views
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
            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

0
Comment
Question by:mgmhicks
  • 3
  • 2
6 Comments
 
LVL 12

Expert Comment

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

Author Comment

by:mgmhicks
ID: 36944022
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?

0
 
LVL 12

Expert Comment

by:Wouter Boevink
ID: 36944046
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

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 12

Expert Comment

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

Accepted Solution

by:
CodeCruiser earned 2000 total points
ID: 36944148
>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

myDS.Tables(0)
0
 

Author Comment

by:mgmhicks
ID: 36944263
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

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month19 days, 5 hours left to enroll

834 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