Monday, February 20, 2006

System.Runtime. InteropServices. COMException on viewlsts.aspx and SPWeb form context

Some time ago I was developing a web control which had to take a list of a SPListItems from a specific SPList from a current SPWeb. Simple thing. Code was also simple. I used SPControl.GetContextWeb and got the list I wanted. I wrote the code and everything was ok until… until during tests I got into a viewlsts.aspx page. This page welcomed me with a nasty error message:

System.Runtime.InteropServices.COMException

First thing that came to my mind was that the list was not found. Strange. That means that the list disappeared or the wrong SPWeb has been opened. To check it I printed the SPWeb.Url and SPWeb.Name properties. Url was ok, but the .Name was from totally different Web! That’s why the list couldn’t be found - SPControl.GetContextWeb opened some other Web.
Ok, ok. So let’s create SPWeb object manually. Dang, another problem. Page.Request.Url returns only "_layouts/1033/viewlsts.aspx". But hey, the .Url property of our ‘wrong’ SPWeb object from context is correct, so why not use it. That was it, now everything works like a charm :)

Here’s the code:



private SPWeb GetCurrentSPWeb()

{

    SPWeb contextWeb = SPControl.GetContextWeb(Context);

    SPSite site = new SPSite(contextWeb.Url);

 

    Uri contextWebUri = new Uri(contextWeb.Url);

 

    SPWeb currentWeb = site.OpenWeb( contextWebUri.AbsolutePath ) 

 

    return currentWeb;



The recommendation I’ve been told some time ago, says that it’s better to get the SPWeb from SPSite.OpenWeb and not from the context. As you can see recommendation is good because context sometimes doesn’t work like it should :)


No comments: