0

I want to check a sub site exist in site collection. I site exist a new one will be created.This is what I have tried:

                int siteLanguage = 1033;
                //Create a new webCreateInformation object to specify the properties of the new site being created.
                Web oWebsite = clientContext.Web;
                var newUrl = contextUrl + title;
                clientContext.Load(oWebsite);
                clientContext.ExecuteQuery();
                //var subWeb = (from w in oWebsite.Webs where w.Url == webUrl select w).SingleOrDefault();
                var subWeb = (from w in oWebsite.Webs where w.Url == newUrl select w).SingleOrDefault();
                if(subWeb==null)
                {                
                WebCreationInformation webCreateInfo = new WebCreationInformation();
                webCreateInfo.Description = description;
                webCreateInfo.Language = siteLanguage;
                webCreateInfo.Title = title;
                webCreateInfo.Url = title;
                webCreateInfo.UseSamePermissionsAsParentSite = true;
                webCreateInfo.WebTemplate = templateId;

                //Adding a new site under the root web

                Web oNewWebsite = oWebsite.Webs.Add(webCreateInfo);

                // Retreiving the server properties to the client context. Here we are retreiving the web server url and the time it was created.

                clientContext.Load(oNewWebsite,
                    Website => Website.ServerRelativeUrl,
                    Website => Website.Created);
                clientContext.ExecuteQuery();
                ViewBag.Message = "Site created.";
            }
                else
            {
                ViewBag.Message = "already exist";
            }

but it is not working, got an error like collection not initialized.

Can anyone please help?

2 Answers 2

0

You could consider the following modified example for enumerating all sites within site collection:

function enumWebs(propertiesToRetrieve, success,error)
{
   var ctx = SP.ClientContext.get_current();
   var rootWeb = ctx.get_site().get_rootWeb();
   var result = [];
   var level = 0;
   ctx.load(rootWeb,propertiesToRetrieve);
   result.push(rootWeb);
   var colPropertiesToRetrieve = String.format('Include({0})',propertiesToRetrieve.join(',')); 
   var enumWebsInner = function(web,result,success,error) 
   {
      level++;
      var ctx = web.get_context();
      var webs = web.get_webs(); 
      ctx.load(webs,colPropertiesToRetrieve);
      ctx.executeQueryAsync(
        function(){
            for(var i = 0; i < webs.get_count();i++){
                var web = webs.getItemAtIndex(i);
                result.push(web);
                enumWebsInner(web,result,success,error);
            }
            level--;
            if (level == 0 && success)
              success(result);  
        },
        error);
   };
   enumWebsInner(rootWeb,result,success,error);    
}

Usage

Print web sites title:

enumWebs(['Title'],
   function(webs){
       for(var i = 0; i < webs.length;i++){
          console.log(webs[i].get_title());                               
       }
   },
   function(sender,args){
      console.log(args.get_message());
   });  

IMPORTANT

After getting all subsites from sitecollection you need to pass one by one subsite to below mentioned function to check if it is already exist or not.

bool WebExists(string siteUrl, string webUrl)
{
    //connect to the root site
    using (ClientContext context = new ClientContext(siteUrl))
    {
        // load up the root web object but only 
        // specifying the sub webs property to avoid 
        // unneeded network traffic
        var web = context.Web;
        context.Load(web, w =&gt; w.Webs);
        context.ExecuteQuery();
        // use a simple linq query to get any sub webs with the URL we want to check
        var subWeb = (from w in web.Webs where w.Url == webUrl select w).SingleOrDefault();
        if (subWeb != null)
        {
          // if found true
          return true;
        }
      }
      // default to false...
      return false;
}

You would call this as follows:

var siteExists = WebExists("http://host/sites/site/", "http://host/sites/site/subsite");
3
  • sorry.. i want like, if the site already exist then it should not create a new site. if the site doesn't exist then it should create a new site. var subWeb = (from w in oWebsite.Webs where w.Url == newUrl select w).SingleOrDefault();// i nedd this checking. if(subWeb==null) {
    – Anjitha
    May 20, 2016 at 10:36
  • Please check updated answer. It might helps you. Because you are passing the site collection URL & checking in the code with same URL that if it is exist or not.
    – Hardik
    May 20, 2016 at 10:47
  • Thank you.. the following part in your code helped :) context.Load(web, w =>; w.Webs); // forgot to include this step. var subWeb = (from w in web.Webs where w.Url == webUrl select w).SingleOrDefault();
    – Anjitha
    May 20, 2016 at 11:25
0

Use the below code

 public bool SubSiteExists(string siteUrl, string subSiteTitle,ClientContext context)
        {
            var web = context.Web;
            context.Load(web, w => w.Webs);
            context.ExecuteQuery();   
            var subWeb = (from w in web.Webs where w.Title == subSiteTitle select w).SingleOrDefault();
            if (subWeb != null)
            {
                return true;
            }
            return false;
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.