NullReferenceException error while using SPSecurity.RunWithElevatedPrivileges?

Hi expert,

Why do I get the NullReferenceException error when I try to use the function "SPSecurity.RunWithElevatedPrivileges" in my UserControl C# code? Here is my code:

----
protected void GetData()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite("http://server/sites/mySite"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Agenda"];
                        SPListItemCollection itemColl;
                        SPQuery query = new SPQuery();

                        itemColl = list.GetItems(query);

                        string agendaSubject = string.Empty;
                        string agendaStart = string.Empty;
                        string agendaEnd = string.Empty;

                        if (itemColl.Count > 0)
                        {
                            for (int icount = 0; icount < itemColl.Count; icount++)
                            {
                                SPListItem listItem = itemColl[icount];
                                if (listItem["Subject"] != null)
                                {
                                    agendaSubject = listItem["Subject"].ToString();
                                }
                                if (listItem["Start"] != null)
                                {
                                    agendaStart = listItem["Start"].ToString();
                                }
                                if (listItem["End"] != null)
                                {
                                    agendaEnd = listItem["End"].ToString();
                                }

                                AddDataToTable(agendaSubject, agendaStart, agendaEnd, (DataTable)Session[GridValues]);
                            }
                        }
                    }
                }
            });
        }
----
Is this related to a security issue?
Thanks.
pgirardierAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

raybiesCommented:
I've just run the code without the  AddDataToTable method and it worked fine.

So I'm guessing it's Session[GridValues] or that method.
0
pgirardierAuthor Commented:
raybies, thanks for your suggestion.

I've commented the last of the above code which calls AddDataToTable method and tested it again, but it didn't work.

These are more details:
- The error message is: Object reference not set to an instance of an object.
- Stack trace:
   at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
   at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
   at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
   at GridViewControl.GridViewUserControl.GetData() in C:\Webparts\GridViewControl\GridViewControl\GridViewUserControl.ascx.cs:line 87
   at GridViewControl.GridViewUserControl.Page_Load(Object Sender, EventArgs E) in C:\Webparts\GridViewControl\GridViewControl\GridViewUserControl.ascx.cs:line 22
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   at System.Web.UI.Control.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
---

The mentioned line number 87 in the stack trace refers to the line "SPSecurity.RunWithElevatedPrivileges(delegate()..." in the code above.
And the 23 line refers to the call of of the above method (GetData) in Page_Load method.

Thanks.
0
raybiesCommented:
When is GetData() being called? Can you put it in/after Page_Load?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

raybiesCommented:
Doh!
Sorry, I hit Submit before reading the last paragraph.
0
raybiesCommented:
I'm assuming you're opening a Site in the same context, cos you can't open Site A, from Site B.

Try changing your code to something similar to this:
protected void Page_Load(object sender, EventArgs e)
{
	SPSecurity.RunWithElevatedPrivileges(delegate()
	{
		oSite = new SPSite(SPContext.Current.Site.ID, SPContext.Current.Site.SystemAccount.UserToken);
	});
	oWeb = oSite.OpenWeb(SPContext.Current.Web.ID);	
	oList = oWeb.Lists[gList];
	if (!Page.IsPostBack)
	{
		FillGrid();
	}
}

Open in new window

0
pgirardierAuthor Commented:
Hi raybies,

After testing the aboce code, I got the same exception NullReferenceException with the same error message "Object reference not set to an instance of an object".

And, what do you mean by "Opening a Site in the same context"?

In my case, simply, I'm trying to execute the following web part example on the Sharepoint Server by opening the downloaded code in Visual Studio 2008: http://www.codeproject.com/KB/sharepoint/GridviewSharepoint.aspx
0
raybiesCommented:
I'm not sure what the issue is, but http://blog.ray1.net/2008/08/sharepoint-copy-list-item-to-many-sites.html

Here I use an SPGridView...

You can install the feature or just extract the wsp using winrar or change the name to cab and extract... it's basically 1 aspx page with inline code, populates a gridview with web names.
0
pgirardierAuthor Commented:
Hi raybies,

Thank you for the suggested URL, but this is not what is needed by the client.

Simply, I want to run the above code project sample in Visual Studio 2008 under Sharepoint Server. Did you try it? If yes, did it work?

Thanks
0
pgirardierAuthor Commented:
I tried including the above code in a Smart Template project in Visual Studio, and it worked.

Thanks.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SharePoint

From novice to tech pro — start learning today.