Enumerate SiteCollections

SharePoint is the platform where we can store the set of values as items, files as documents in folder or Library. But how we manage all the data’s, there comes Web sites. The above collection of web sites are managed by Site Collection, which is a placeholder or container for all the web sites.

Here I am enroll the snippet for enumerating the all the site collections from the web application. This Web Application is nothing but a IIS Site and has some specific properties helps to manage the Collection of Site Collections.

//Retrieving the webapplication based on Url
SPWebApplication webapps = SPWebApplication.Lookup(new Uri(“http://localhost”));
//Gets all the sites under the WebApplication
SPSiteCollection sites = webapps.Sites;
//Iterating the site collection and printing
foreach (SPSite s in sites)
{
    Console.WriteLine(s.Url);

//Disposing the SiteCollection object, use to clears the memory obtained for SPSite object 
     s.Dispose();
}

Delete old Item with new Item using SharePoint Designer Workflow

I have a scenario from SharePoint MSDN Forum, which states,

If I have an item Title named ‘Kumar’ and I am going to create a new item with Title named ‘Kumar. I need to delete the old item.

Note: In following example I have renamed the Title Display Name to ‘Names’

Here I am using SharePoint Designer workflow to achieve this by following way,

  • I have to get the old List Item,
  • Then compare the current (new item) with the old item
  • And the Old Does not have the Current Item Id
  • If above two steps are true, then delete the old item.

I have elaborated the above steps with the following activities,

  1. Create a List Workflow and associate to a List and Set the Start Option as “Start Workflow automatically when an item is created”

  2. In workflow step, First we have to create a workflow variable to get the item id which matches value entered in Current Item.

  3. Using “Set Workflow Variable” activity we are getting that Item id. Add the parameters as shown below. And name the workflow variable as ‘OldItemId’



  4. In the above figure I am getting the Item ID from the last item which matches the same vale for the Names field.

  5. For the following 2 steps, we have to If Current Item field equals value condition activity.

  6. Now we have to compare the Current Item value against the item returned by ‘OldItemId’



  7. Then we have to compare the ‘OldItemId’ not same as Current Item Id.



  8. The Use the Delete Item activity to delete the item based on ‘OlditemId’



Now the duplicate was item added with a same value will delete the old item.

Catch the Unique Items from SharePoint List

I have lot of items from SharePoint List, but most of the items are duplicated. Here, I am going to give you a tips on getting unique rows from the List. For that, I googled for some time and then I found out there is no way to get the items based on CAML.

So I tried to use LINQ to query the SharePoint Items. It works perfectly well for me. Here I provided my code to get the SharePoint Unique ListItems based on latest Items.

In the following example, I am first sorting the Items based on Modified field and then getting the unique item based on Title field by grouping.


using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("MyList");
string Modi = "Modified";
List lstitems =
(from l in list.Items.OfType<SPListItem>() orderby l[Modi] descending select l).ToList<SPListItem>();

var listitemDistinct = lstitems.GroupBy(item1 => item1.Title, (key, group) => group.First()).ToList();

foreach (SPListItem i in listitemDistinct)
{
Console.WriteLine("Title: " +i.Title +"Modified: " + i[Modi].ToString());
}
}
}

If the ListItems has the following items,

ID Title Modified
1 Sample 1 11/16/2011
2 Sample 2 11/17/2011
3 Sample 1 11/18/2011
4 Sample 2 11/19/2011

Result:
Title: Sample 2 Modified: 11/19/2011
Title: Sample 1 Modified: 11/18/2011

MySite Url via UserProfile

UserProfile has the two property members for retrieving the Url for the User. Those propertis returns the MySite Url and Personal Site url for the User.

Here, i am adding some code snippets, which gets these Url values from MySite.

Using(SPSite _site = new SPSite("http://localhost"))
{
SPServiceContext context = SPServiceContext.GetContext(_site);
UserProfileManager profileManager = new UserProfileManager(context);
string UAccount = "DomainName\\spuser";

//Getting the UserProfile based on the User's Login Name
UserProfile u = profileManager.GetUserProfile(UAccount);
//Getting the User's Personal Site(Site Collection created for User's MySite) Url
Console.WriteLine("My Content Url: " + u.PersonalUrl.ToString());
//Getting the User's MySite Url
Console.WriteLine("My Site Url: " +u.PublicUrl.ToString());
}

RESULT:
My Content Url: http://localhost/my/personal/spuser/
My Site Url: http://localhost/my/Person.aspx?accountname=DomainName\spuser

SiteCollection Storage Information

SharePoint has the Usage Analysis Time job, which updates the following information for the sites,

  • Storage,
  • Discussion Storage,
  • Bandwidth,
  • Hits,
  • Visits

The SPSite.Usage property gives us the information of site usage, bandwidth, visits.
Here I am adding the snippet for getting the Free Space available against Storage Quota and Space used by Site Collection,

using (SPSite site = new SPSite("http://localhost"))
{
SPSite.UsageInfo susg = site.Usage;
long spaceused = (((susg.Storage + 0x80000L) / 0x100000L));
if (site.Quota.StorageMaximumLevel == 0L)
{
Console.WriteLine("Storage Quota: Not applicable");
Console.WriteLine("Free Space Available: Unlimited");
}
else
{
long sitequota = (site.Quota.StorageMaximumLevel / 0x100000L);
long freespace = sitequota - spaceused;
Console.WriteLine("Storage Quota: " + sitequota.ToString());
Console.WriteLine("Free Space Available: " + freespace.ToString() + " MB");
}
Console.WriteLine("Storage Used: " + spaceused + " MB");
}

Clear SharePoint Lists

My colleague asked me about, is there any tool available for removing the entire list items from multiple list with single Click. I have taken that idea and created a tool for removing the entire items.

URL: http://clearspitems.codeplex.com/

The project is in alpha stage, i have planned for adding more functionality to this tool. And I will also publish this in the format of stsadm, powershell and in Ribbon mode.

I am expecting those things to be happen within next week..

So stay tuned … :)

Why Workflow not started on Item Creation?

There are some cases, why the workflow was not started during item creation,

1. If you create an item using System Account, the workflow will not funtion properly or that couldn’t start.
2. The workflow start option was not enabled to “Start workflow automatically when an item was created”. Ensure this option was checked.
3. If you create and publish a workflow without enabling the Start option(Start workflow automatically when an item was created). And after some time you came and enable that start option & saves without Publishing also cause a problem.
4. Or remove the “Allow this workflow to be manually started” start option and Initiation workflow. Enable “Start workflow automatically when an item was created” option and Publish the workflow.

check the following link has the soltuoions for SharePoint Designer workflows, http://office.microsoft.com/en-us/sharepoint-designer-help/troubleshoot-workflow-errors-HA010237912.aspx#BM2
If the above solutions couldn’t solve the problem, the you have to create new workflow.

Hide Fields in List Forms

We have three types of List Forms in SharePoint.,

New Form, Edit Form and Display Form.

For some times or in some requirements, we need to hide some of the fields in List Forms. By OOB there is no page or option for hiding fields on separate form, but we can hide the fields in all forms in List.

I am just giving snippet to hide the Fields in each separate form, separately,

using (SPSite site = new SPSite(“http://localhost”))
            {
                using (SPWeb web = site.OpenWeb())
                {                   
                    SPList list = web.Lists.TryGetList(“Custom”);
                    SPField field = list.Fields.GetFieldByInternalName(“field1″);
                    //To hide the field from New Form
                    field.ShowInNewForm = false; 
                    //To hide the field from Edit Form
                    field.ShowInEditForm = false; 
                    //To hide the field from Display Form
                    field.ShowInDisplayForm = false; 
                    field.Update();
                }
            }

We can also show / hide the fields based on content Types. For Content Types, we can retrieve the field from Content Type.

SPField field = list.ContentTypes["ctype1"]. Fields.GetFieldByInternalName("field1");

and the add the further lines to hide the field in SharePoint Lists.

For revert back, we can set the ShowInNewForm  property as true.

Inherit / Stop Web Site Top-Level Navigation

We have two option on Top Link bar navigation, either we can inherit the Top-Link bar from the parent site or use the own Top-Level navigation.

Sharing the Top-link bar can be achieved through browser interface by navigating,

1) Site Actions –> Site Settings

2) On Site Settings page, under Look and Feel section, click Top link bar

3) On Top Link bar page, Click Use Links from Parent and then Click OK in pop-up box to share the Top-Links between Sites.

or

3) On Top Link bar page, Click Stop Inheriting Links to stop the Shared links between sites and used to have the own Top-Links for the site.

The following section contains the code to achieve the Share and Stop the inheriting links

Code allows to Share the Top-Level links between all the sub-sites under Top Level Site

using (SPSite site = new SPSite(“http://localhost”))
{
    SPWeb web = site.RootWeb;
    //We can’t able to Set true to top level site or root site
    foreach (SPWeb subweb in web.Webs)
    {
        //Check if the subsite  not Sharing the Top-Links
        if (!subweb.Navigation.UseShared)
        {
            subweb.Navigation.UseShared = true;
        }
        subweb.Dispose();
    }
    web.Dispose();
}

Code allows to Stop the Top-Level links between all the sub-sites under Top Level Site

using (SPSite site = new SPSite(“http://localhost”))
{
    SPWeb web = site.RootWeb;
    foreach (SPWeb subweb in web.Webs)
    {
        //Check if the subsite already Shared the Top-Links
        if (subweb.Navigation.UseShared)
        {
            subweb.Navigation.UseShared = false;
        }
        subweb.Dispose();
    }
    web.Dispose();
}

 

We don’t need to call SPWeb.Update() to update the Link Sharing.