Saturday, May 21, 2011

Dynamic sort with LINQ

Here is a bit of information on dynamic sorting using LINQ

I will work with a simple collection of City class. City class is defined below.

public class City
{
    public string Name { get; set; }
    public string Country { get; set; }
}
The collection is initialised using this code
List<City> cities =
            new List<City>
            {
                new City{ Name = "Sydney", Country = "Australia" },
                new City{ Name = "New York", Country = "USA" },
                new City{ Name = "Paris", Country = "France" },
                new City{ Name = "Milan", Country = "Spain" },
                new City{ Name = "Melbourne", Country = "Australia" },
                new City{ Name = "Auckland", Country = "New Zealand" },
                new City{ Name = "Tokyo", Country = "Japan" },
                new City{ Name = "New Delhi", Country = "India" },
                new City{ Name = "Hobart", Country = "Australia" }
            };

A typical example of applying a sort will be to write such a query.
var collection =
    from c in cities
    orderby c.Country
    select c;
Here we are sorting the collection on country. Note that this is static in nature.Code above as you can see can only sort by country. If I wanted to sort by city name then I’d be writing another query and maybe use a conditional construct such as if or switch and write a method which takes in a parameter. While this will work, it is not the best way to do it.LINQ gives us the ability to make our code dynamic. I can provide sort functionality for my query by writing a method which takes in a Func<TElement, TKey> delegate. This delegate is used by the OrderBy extension method. This is how I can write my method.
public static void Sort<TKey>(List<City> cities, Func<City, TKey> selector)
{
    var sortedCollection =
        from c in cities
        orderby selector(c)
        select c;
    foreach (var item in sortedCollection)
    {
        Console.WriteLine(item.Name);
    }
}
This method can be called like this by passing in the cities collection which has been initialised earlier.
Sort(cities, c => c.Name);
I can also sort by country without changing my query. To sort by country I just need to call my sort method like this.
Sort(cities, c => c.Country);

LINQ rocks.......

Reading a CSV file using LINQ

This is a nice article about reading a csv file using LINQ.

Sample Data
I will use a sample file which contains a data about customers. When working with text files we must know the number of columns and the data contained in each column. Below is a list of columns in their right order for our file.
1.      First Name
2.      Last Name
3.      Job Title
4.      City
5.      Country
The file itself will contain this data. I have pulled this out of Employees table in Northwind database.

First Name  Last Name  Job Title  City  Country
Sharan       Raj              SE           Bang India

Reading Data
Before we start reading our csv file we will create a class which will hold a record we will read from our csv file. For this I will create a customer class which looks like this.
public class Customer
{
    string Firstname { get; set; }
    string Lastname { get; set; }
    string JobTitle { get; set; }
    string City { get; set; }
    string Country { get; set; }
}
Reading Entire File
Now we are ready to read data from our file using LINQ. Using this code we can read the entire file. I am also using a foreach statement to output the results.
var query =
        from line in File.ReadAllLines(filePath)
        let customerRecord = line.Split(',')
        select new Customer()
            {
                Firstname = customerRecord[0],
                Lastname = customerRecord[1],
                JobTitle = customerRecord[2],
                City = customerRecord[3],
                Country = customerRecord[4]
            };
foreach (var item in query)
{
    Console.WriteLine("{0}, {1}, {2}, {3}, {4}",
        item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
}
File.ReadAllLines() returns an array of lines and we then use the split function of array to split it by a comma. Its just that simple.
Reading selected records
We can use this code to read all customers who live in UK.
var query =
        from c in
            (from line in File.ReadAllLines(filePath)
             let customerRecord = line.Split(',')
             select new Customer()
                 {
                     Firstname = customerRecord[0],
                     Lastname = customerRecord[1],
                     JobTitle = customerRecord[2],
                     City = customerRecord[3],
                     Country = customerRecord[4]
                 })
        where c.Country == "UK"
        select c;
This code can be used to read customers who have sales in their job title.
var query =
        from c in
            (from line in File.ReadAllLines(filePath)
             let customerRecord = line.Split(',')
             select new Customer()
                 {
                     Firstname = customerRecord[0],
                     Lastname = customerRecord[1],
                     JobTitle = customerRecord[2],
                     City = customerRecord[3],
                     Country = customerRecord[4]
                 })
        where c.JobTitle.Contains("Sales")
        select c;

Increase maximum size of List Template

If you try to save a list as a list template, you may see the following error due to the list being too large: The list is too large to save as a template. The size of a template cannot exceed 10485760 bytes.
You can increase the maximum size of a list / site template by running the following command (note that 500mb is the largest you can go):

stsadm -o setproperty -propertyname max-template-document-size -propertyvalue 50000000

Code Snippet to get User Profile Picture of current user -SharePoint 2010

Below is the code to get User Profile Picture from User Profile database using object model.

SPSite siteColl = SPContext.Current.Site;

                    SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
                    UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                    UserProfile profile = null;

                    bool existingUser = userProfileManager.UserExists(SPContext.Current.Web.CurrentUser.LoginName);
                    if (existingUser)
                    {
                        profile = userProfileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);
                    }
                    imgProfile.ImageUrl = profile[PropertyConstants.PictureUrl].Value.ToString();
                    lblName.Text = SPContext.Current.Web.CurrentUser.Name;


You can add this to a visual web part and to show profile picture on any page. Don’t forget add reference to Microsoft.Office.Server

Monday, May 2, 2011

Stopping the User Profile Synchronization Service of being stuck on “Starting”

Run following commands in the SharePoint 2010 Management Shell to stop the service:

get-spserviceinstance > driveletter:\outputfilelocation.txt

After the above command review your output file and you will see a list of services that are running in SharePoint.

Find out the service ID for user profile synchronization service and then use this command to stop the service:

stop-spserviceinstance <ServiceID> 

Commands To Stop User Profile Service When the status is in "Starting" Mode

Go to Sharepoint Management Shell and follow these steps.


1.  stsadm -o enumservices > c:\services.txt - Those gave me a list of services and showed me what the name of the service I need to stop is.


2.  stsadm -o provisionservice  -action stop -servicetype "Microsoft.Office.Server.Administration.ProfileSynchronizationService, Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" -servicename FIMSynchronizationService