How do I test if I will be able to execute a query (does the site exist)
-
16-10-2019 - |
Question
When I run a (CAML based query) executeQuery against Sharepoint, sometimes the site does not exist (it is created by a workflow process which may not have run). When this happens, I get a ClientRequestException:
Cannot contact site at the specified URL http:/[mypath]. There is no Web named "/[mypath]/_vti_bin/sites.asmx".
Is there a check I can run? I think it's probably preferable to do a bool check than to wrap with a try catch.
This code runs client side, so I believe there is a different set of APIs available.
Solution
I think, the solution here is to use the scopes approach.
There are two scope types in SharePoint: ConditionalScope and ExceptionHandlingScope. They allow you to implement conditional behaivour server-side. Only one request is sent to the server. Logics in scopes are packed together and sent to the server which is executed as a whole in a single request.
The easest way here is to implement server-side try-catch behaivour, using ExceptionHandlingScope, for example:
ClientContext clientContext = new ClientContext("http://localhost");
ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
using (scope.StartScope())
{
using (scope.StartTry())
{
// do your actions here
}
using (scope.StartCatch())
{
// if error is occured...
}
}
clientContext.ExecuteQuery();
As far as I know, there are no analogues for SPWeb.Exists
in client object model, so using ExceptionHandlingScope is probably the best solution here.
Some articles, which can help to understand server-scopes idea:
OTHER TIPS
If you are writing code always use this boolean check: SPSite.Exists()
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite.exists.aspx