SPSite constructor returns cached instance. - asp.net

The SPSite constructor (new SPSite(mySiteId)) returns a cached entry, even though the site no longer exists. How can I prevent this?

We had the same problem and haven't found a solution for it yet. We tried to check whether a SPSite exists or not by calling the static SPSite.Exists(..) method. The method returned true also for sites that didn't exist any more.
But we have found a little workaround. We try to provoke a FileNotFoundException by calling the SPSite's Usage property. When the exception arise we know that the site doesn't exist any more.
After catching the exception you can call again the SPSite.Exists() method which will now return false.

While I do not know the Sharepoint details, I can tell you calling new will NEVER return a cached object. It will ALWAYS be a newly allocated object, although the internals may point to cached objects.

A little late maybee, but since I had this same problem.
You can call the satic method InvalidateCacheEntry(Uri uri, Guid siteId) on the SPSite class. By passing an empty guid and the uri of the SPSite you are using, you should be able to clear the cache and get the current values.
Notice that this seems to be also the cause of the issue of SPSite.Exists returning "true" for just deleted sites. By using the InvalidateCacheEntry method, I was able to detect the correct state of the site (deleted or existent). I don't know what is the performance cost of this workaround, but please consider it if you have a similar problem in the future.

Related

Is there any difference between Request.Cookies(name) and Request.Cookies.Get(name)?

As both of them can be used for retrieving cookie through name string, I would like to know if there is any difference between them.
A great way to answer a question like this yourself, for the .NET Framework, is to make use of the Microsoft Reference Source. This lets you see and navigate through the source for the .NET Framework.
Looking at this, Request.Cookies returns an HttpCookieCollection and Request.Cookies.Get is therefore a method on HttpCookieCollection.
The most useful part of the code is for the indexer on HttpCookieCollection that retrieves a cookie by name:
public HttpCookie this[String name]
{
get { return Get(name);}
}
As you can see from that, this calls into the Get(string name) method, meaning that using the Request.Cookies(name) indexer is fundamentally the same as using Request.Cookies.Get(name) as one calls the other.
It is worth mentioning that anything you see here is an implementation detail that's subject to change. You should rely on documented behaviour, not on anything you discover through digging through the code, no matter how informative and interesting it is!

Optional Invalid Query String Variables

This is a somewhat philosophical issue. I have a .net (but could be any platform) based helper library that parses query string values. Take for example a variable that returns an Int32: my framework has an option that specifies whether this value is required or optional. If it is required but not provided, the framework throws an exception. If it is optional and not specified, it returns a null.
Now an edge case has come up based on users hacking (in a good way) our urls. If they specify a variable with either an invalidly formatted Int32 ("&ID=abc") or provide the variable but not specify a value ("&id="), should the framework throw an exception or should it return a null?
Part of me feels that invalid variables or formats should return a null. It might be valid to argue that even if the parameter is optional, an invalidly formatted query string or value should still throw an exception.
Thoughts?
Since this is philophical ...
On something like an ID, I would agree with Shawn that it is a 404, especially if you are thinking in terms of state. There is no object, so not found. But, ID may not tie directly to a resource in all cases.
If the item is truly optional, a null is okay. But optional should mean "if present it makes the call more specific" in this case and there should always be a fallback. I don't see this in ID, unless the ID is keyed to an optional part of the page.
In the long run, I think you should look at the business reason for the page and what each variable means.
I believe that if a variable is optionaly, providing the variable but not specifying the value is equivalent to ommitting the variable itself. In this case, returning null seems OK.
However, providing an invalidly formatted value ought to cause an Exception, since the intent was to provide a value. In this case the user ought to be notified through some sort of validation mechanism.
A HttpException of 404 (Not Found). Your web application framework should know how to catch these errors and redirect to the proper page.
This is actually a not found error because the resources that the ID is pointing to does not exist.
I suspect there's no "right" answer to your question. If I were a developer using your library, I would expect/hope that the public API would include in its code comments, a description of how the function behaves when the URL param includes bad (wrong type) data.
You might also be able to craft your public API to get the best of both worlds: .NET seems to have adopted the "Parse" / "TryParse" approach in many places. If I'm the caller and I want the function to throw if given invalid data, I call Parse(). If I don't want it to throw, I call TryParse(). In my opinion, that is a nice pattern to follow with your API as well.

Accessing State in ASP.NET

Is
System.Web.HttpContext.Current.Session
the same as
System.Web.UI.Page.Session
?
They do indeed refer to the same instance, but if you look at the methods in Reflector, you can see that they behave a bit differently (in ways that are not likely to matter in most applications):
The call to Page.Session uses a
cached HttpSessionState reference.
The Page method will throw if
session state is not enabled, while
HttpSessionState.Session just
returns whatever is in the
"AspSession" bucket of its Items
collection.
Yup; they refer to the same instance.
There is no difference between the two.

Static data in an ASP.NET page - threadsafe?

The background to this question is that I need to use some user session data in a (static) WebMethod. I have created a static property that references the data I need like so:
private static UserWebSession UserWebSession
{
get
{
return (UserWebSession)HttpContext.Current.Session["UserWebSession"];
}
}
I can then call this in my page's static WebMethod.
My question is, is this technique thread safe? Or will this property's value be updated with every new page request - in other words, it will return the UserWebSession for the user who most recently requested the page?
That's fine - HttpContext.Current is designed precisely for this sort of thing. You won't get a previous user's session.
It's dependent on the thread though (I believe) - so if you start any extra background threads, they won't be able to see the current context.
Also be aware that although this call is safe in terms of not getting the wrong context, the normal concurrency caveats apply when it comes to what you actually do with the context.
I don't know that a Page Method is able to access Session state. If it can, then you may be ok. I recall that access to Session state is serialized, so that only one request at a time can arrive for a given session.

Hiding the stacktrace for an exception returned by a asp.net WebMethod?

I am using methods with the Attribute [WebMethod] in my aspx pages. I don't use any asp.net ajax but jQuery to call these methods and return objects in JSON. This all works fine.
Next I added an authorization check inside the webMethod, if the current user doesn't have access to the feature I need to let the calling JavaScript know.
So I am throwing an AccessViolationException exception which can then be parsed by the OnError callback function in JavaScript. This works too but the exception includes the full StackTrace and I don't want to make this available to the calling client.
What other ways I could use to return an "Access Denied" to the client when the WebMethod returns a business object?
I'm using ASP.Net 3.5SP1 and jQuery 1.32
You can also add a:
customErrors mode="On"/
in your web.config, this will cut away the stack trace and leave you only the exception message
Why propagate errors through the wire? why not use an error response ?
Just wrap your object in a response object wich can contain an error code for status and an error message to present to users.
As suggested by NunFur I changed my approach and rather than throwing an error, I return a 'richer' object.
There are at least two options, the first one would be to encapsulate my business object into a response object with some status properties. I tried this but it makes the JSON more complicated.
So rather than adding a new object I added two properties to my business object, something like ServiceStatus and ServiceMessage. By default these are 200 and '', but can be set by the WebMethod code if anything goes wrong (no access, proper error). In this case they business object will be 'empty' (no data). The JavaScript code then first checks for the ServiceStatus and reacts appropriately.
I add the two fields to all my objects that are returned by WebMethods, even a simple string. They have to implement an Interface with those two properties.
Now I have complete control over that goes over the wire in case something unexpected is happening.
Thanks for the input
I save exceptions for when things go really wrong. (e.g. can't connect to the database)
Either return nothing (null/nill/whatever), or return a false bool value.
Sorry that I don't have a better answer than that...I'll have to keep looking myself.
You could look at SoapException: http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception(VS.71).aspx
I'm just not sure, if it will work when it is called from JavaScript. Espeially if it's called with a get-request.
BTW AccessViolationException is to my best knowlegde ment to be thrown when the application is accessing memory it has no access to.
/Asger

Resources