September 19, 2008

How to delete a specific user from all sites collections

The following piece code is a little console application which allows to delete a specific user from all sites collections on SharePoint server.

The application requires 3 parameters passed as arguments:
1) Authentication type: "w" (Windows authentication) or "f" (Forms authentication)
2) Domain name in case of Windows authentication or MembershipProvider name in case of Forms authentication
3) User name

using System;
using System.Web.Configuration;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
 
namespace DeleteUserFromAllSiteCollections
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (args == null || args.Length != 3)
                {
                    throw new ArgumentException("Invalid parameters.");
                }
 
                string authenticationType = args[0];
                string domainName = args[1];
                string userName = args[2];
 
                if (authenticationType.ToLower() != "w" && authenticationType.ToLower() != "f")
                {
                    throw new ArgumentException("Invalid authentication type parameters.");
                }
 
                string longUserName = string.Empty;
                AuthenticationMode authenticationMode;
                if (authenticationType.ToLower() == "w")
                {
                    longUserName=string.Format(@"{0}\{1}",domainName.ToUpper(),userName.ToLower());
                    authenticationMode = AuthenticationMode.Windows;
                }
                else
                {
                    longUserName = string.Format(@"{0}:{1}", domainName.ToLower(), userName.ToLower());
                    authenticationMode = AuthenticationMode.Forms;
                }
 
                SPFarm farm = SPFarm.Local;
                Console.WriteLine(string.Format("Connected with farm: {0}", farm.DisplayName));
 
                SPWebService service = farm.Services.GetValue<SPWebService>("");
                Console.WriteLine("Services has been retrieved.");
 
                foreach (SPWebApplication webApp in service.WebApplications)
                {
                    Console.WriteLine(string.Format("Connected with WebApp: {0}", webApp.DisplayName));
 
                    if (!webApp.IsAdministrationWebApplication)
                    {
                        foreach (SPUrlZone zone in webApp.IisSettings.Keys)
                        {
                            SPIisSettings setting = webApp.IisSettings[zone];
                            if (setting.AuthenticationMode == authenticationMode)
                            {
                                bool ok = true;
                                if (authenticationMode == AuthenticationMode.Forms)
                                {
                                    if (setting.MembershipProvider.ToLower() != domainName.ToLower())
                                    {
                                        ok = false;
                                    }
                                    else
                                    {
                                        Console.WriteLine(string.Format("{0} installed.", domainName.ToLower()));
                                    }
                                }
                                if(ok)
                                {
                                    foreach (SPSite siteCollection in webApp.Sites)
                                    {
                                        Guid siteCollectionId = siteCollection.ID;
 
                                        SPSecurity.RunWithElevatedPrivileges(delegate
                                        {
                                            using (SPSite elevatedSiteCollection = new SPSite(siteCollectionId))
                                            {
                                                Console.WriteLine(string.Format("Connected with SiteCollection: {0}", elevatedSiteCollection.Url));
                                                Guid siteId = elevatedSiteCollection.RootWeb.ID;
 
                                                using (SPWeb elevatedSite = elevatedSiteCollection.OpenWeb(siteId))
                                                {
                                                    Console.WriteLine(string.Format("Connected with root site: {0}", elevatedSite.Url));
 
                                                    SPUser userToRemove = null;
                                                    try
                                                    {
                                                        userToRemove = elevatedSite.SiteUsers[longUserName];
                                                    }
                                                    catch { }
 
                                                    if (userToRemove != null)
                                                    {
                                                        elevatedSite.SiteUsers.RemoveByID(userToRemove.ID);
                                                        Console.WriteLine("{0} has been deleted.", longUserName);  
                                                    }
                                                    else
                                                    {
                                                        Console.WriteLine("{0} not found.", longUserName);
                                                    }
                                                }
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Message: {0} {1} Stack:{2}", ex.Message, System.Environment.NewLine, ex.StackTrace));
            }
        }
    }
}

September 11, 2008

How to get usage information for a specific site collection by code

To get usage information for a site collection, have a look at the Usage property of the SPSite class.

This property is a structure which contains 5 fields:
- Storage: total amount of storage (bytes) consumed
- DiscussionStorage: amount of storage (bytes) used by the web discussion data
- Hits: cumalative number of visits
- Bandwidth: cumulative bandwith used
- Visits: cumulative number of visits

Note that 2 (Storage and DiscussionStorage) are updated in real time and 3 (Bandwidth, Hits and Visits) are updated daily by the usage analysis timer job.

The following console application displays the usage information for a specific site collection:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
 
namespace UsageInformation
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite siteCollection = new SPSite("http://siteCollectionUrl"))
            {
                Console.WriteLine(string.Format("SiteCollection Url: {0}", siteCollection.Url));
                Console.WriteLine(string.Format("Storage: {0}", siteCollection.Usage.Storage));
                Console.WriteLine(string.Format("Discussion Storage: {0}", siteCollection.Usage.DiscussionStorage));
                Console.WriteLine(string.Format("Bandwidth: {0}", siteCollection.Usage.Bandwidth));
                Console.WriteLine(string.Format("Hits: {0}", siteCollection.Usage.Hits));
                Console.WriteLine(string.Format("Visits: {0}", siteCollection.Usage.Visits));
 
                Console.WriteLine(string.Format("Press a touch to exit..."));
                Console.ReadLine();
            }
        }
    }
}

SharePoint List Access Layer Generator

SPList Access Layer Generator is a windows application which allows developers to generate classes to access SharePoint lists like an ORM. This project has been initiated to be compliant with the Rapid Application Development methodology.

The first version of this project is always a beta, so be careful when using it.

You can find the solution on CodePlex: http://www.codeplex.com/SPLALGenerator

September 10, 2008

Automated SharePoint Site Branding on MSDN Magazine (July 2008)

Ted Patisson has written an interesting article about how to automate SharePoint site branding. It's really helpful when you have a company brandind for a SharePoint site and you want to apply automatically this branding to all sub-sites and so on.

Link to the article: http://msdn.microsoft.com/en-us/magazine/cc700347.aspx

How to display the SharePoint waiting page when doing long operations in your code

Displaying the SharePoint waiting page with the rotating gear image is easy. The Microsoft.SharePoint namespace provides the SPLongOperation class to play the trick.

As this class implements the IDisposable interface, the best is to use a using statement like in the following example:

void buttonProcess_Click(object sender, EventArgs e)
{
    using (SPLongOperation operation = new SPLongOperation(this.Page))
    {
        // Define the url to be redirected after the long operation
        string url = "http://myserver/myotherpage.aspx";
 
        operation.LeadingHTML = "Please wait...";
        operation.TrailingHTML = "Description...";
 
        operation.Begin();
        //Place here the code that takes a long time to be executed
        operation.End(url);
    }
}

MSDN link: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splongoperation.aspx

September 05, 2008

Patrick Tisseghem passed away


It's with sadness I learned this morning that Patrick Tisseghem passed away on Wednesday 3 September 2008. He was like a mentor for the all the SharePoint developers.
All my thoughts go out to his family, friends and colleagues. You will miss the SharePoint community.