Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Archive for September, 2012

SharePoint 2010 – Retrieve all Documents in a Site Collection

Posted by Paul on September 14, 2012

In this article we can explore how to retrieve all the documents in a Site Collection programmatically.  The scenario is useful to process all documents in a Site Collection.

 

Our Aim

 

Our final aim is to retrieve all the document file names along with the sizes as shown below:

 

clip_image002

 

Server Object Model

 

Following are the Server Object Model types and properties we have used:

 

1.      SPSite

 

2.      SPWeb

 

3.      SPSite > AllWebs

 

4.      SPWeb > Lists

 

5.      SPList

 

6.      SPList > IsApplicationList

 

Web Part

 

Open Visual Studio 2010, create a new Visual Web Part project and place a button on it.

 

On click of the button the Current Site Collection is examined for all the sub sites using AllWebs property. For each of the Web Site (SPWeb) the corresponding Lists are iterated.

 

The list is checked for Application List using the property IsApplicationList.  This is in order to discard the system lists of web site.

 

Code

 

Following is the code that performs the following activities:

 

·         Enumerate All Web Sites in Site Collection

 

·         Enumerate All Lists in each Web Site

 

·         Validate the List is Document Library

 

·         Validate the List is Application List

 

·         Ensures List contains Items

 

On the button click place the following code.

 

protected void GetInfoButton_Click(object sender, EventArgs e)

 

{

 

    ResultLabel.Text = string.Empty;

 

 

    StringBuilder builder = new StringBuilder();

 

    double total = 0;

 

 

    foreach (SPWeb web in SPContext.Current.Site.AllWebs)

 

    {

 

        foreach (SPList list in web.Lists)

 

        {

 

            if (list is SPDocumentLibrary)

 

            {

 

                if ((!list.IsApplicationList) && (list.OnQuickLaunch))

 

                {

 

                    if (list.Items.Count > 0)

 

                    {

 

                        // Display Library Name

 

                builder.Append(“<h2>” + web.Title + ” > “ + list.Title + “</h2></br>”);

 

 

                        foreach (SPListItem item in list.Items)

 

                        {

 

                            // Display File Name

 

                            builder.Append(item.File.Name + ” (“ + (item.File.Length / 1024).ToString() + ” KB) </br>”);

 

 

                            total += item.File.Length;

 

                        }

 

 

                        builder.Append(“</br>”);

 

                    }

 

                }

 

            }

 

        }

 

    }

 

 

    int itotal = (int)total / (1024 * 1000);

 

    builder.Append(“<h2> Total Size: “ + itotal.ToString() + ” MB</h2>”);

 

 

    ResultLabel.Text += builder.ToString();

 

}

 

Please note that the above code include the HTML formatting code as well.

 

Deployment

 

Deploy the project to SharePoint and add the Web Part to a site page. 

 

Add some documents to the current site libraries as well as in the sub sites libraries. 

 

clip_image004 

 

clip_image006 

 

Try clicking the button and you can see the results. 

 

clip_image001

 


 

References

 

http://tinyurl.com/sp2010-enumdocs1

 

http://tinyurl.com/sp2010-enumdocs2

 

Summary

 

In this article we have seen how to retrieve all documents in a Site.  The same code can be extended to retrieve all documents in the Site Collection.

 

The source code contains the example we discussed. 

Advertisements

Posted in C# | 2 Comments »

CAML Query Builder

Posted by Paul on September 11, 2012

In this article we can explore the SharePoint 2010 free tool CAML Query Builder.

What is CAML?

CAML represents Collaborative Markup Language which is an XML based language for querying and updating SharePoint objects. 

What are the Advantages of this Tool?

We can see following are the advantages of using this Tool:

1.      As CAML is non-typed and error prone during development the CAML Query Builder provides advantage of writing and validating the CAML queries.

2.      An Intuitive User Interface is provided by the application for more easier Query building

3.      Above all the Tool is Free

Download

You can download the tool from following location:

            http://www.u2u.be/res/tools/camlquerybuilder.aspx

Please make sure you download the 2007 version which is working well with SharePoint 2010.

image

Download the tool and extract the zip file to a temporary folder.  Execute the setup.exe inside it and follow the wizard to install the tool.

Note: The SharePoint binaries are required for working with this tool.


 

Starting with the Tool

After the installation execute the tool from Start Menu or Desktop.  The tool is available on Start Menu > U2U > CAML Builder > CAML Builder as shown below.

image

On execution you can see the following screen.

image

Enter the following details as shown above:

·         Url of the site

·         Connect through SharePoint Web Services

·         User Credentials

After entering the details click the Connect button.

Note: As the tool is for SharePoint 2007, the Connect via Object Model option cannot be used. 

Inside the Tool

On connecting successfully you will get the following screen.

image

You can see that the above screen displays your existing Lists and Libraries.  Additionally it displays the Lists & Libraries which are hidden in the Quick Launch too.

Create a Contacts List

To start with create a Contacts list of Contacts template inside your SharePoint site.  Insert the following test data into it and refresh the CAML Query Builder Tool.

image

Building your first CAML Query

Now we can try building our first query using the CAML Query Builder Tool.

Here we are trying to find the list items for which First Name contains ‘1’.

Step 1: Start the New Query pane

Right click on the Contacts list from the left side pane and choose the New Query menu.

image

You can also use the New Query button from the tool bar.

Step 2: Specify the Column Parameters

From the pane on the right side, choose the Filter Column > First Name using the second drop down list as shown below.

image

Now choose the option Contains from the third drop down list.  Enter the text 1 in the textbox. 

Note: Following are the drop down lists shown above and the purpose:

·         The first drop down list contains the options Filter, And, Or. 

·         The second drop down list contains the Column Names of the selected list. 

·         The third drop down list contains the conditions like Equal, Not Equal, Contains etc.

Step 3: View the CAML Query

On performing the above steps you can see that the CAML Query is generated for the above condition.  You can see the CAML Query in the bottom pane as shown below.

image

Step 4: Executing the CAML Query

Now you are ready with the CAML Query but it is not Tested yet.  For testing the query use the Execute query button from the top toolbar as shown below.

image

You should be getting the results as shown above.

So now you are ready with the CAML Query which is tested and can be copied to your application.


 

Step 5: Adding OR Condition

Now we can play a little bit more by adding an OR Condition to list all the Contacts items which contains ‘1’ or ‘2’ in the First Name column.

For achieving this select the Or option from the Filter drop down list.

image

You can see that a new filter row is getting added to the query pane.  Enter the new parameters in the new row as shown below.

image

Step 6: Execute the New Query

Now you can try executing the above query and this time the result should show both the records from the Contacts list.

image

 

Add Order By Element

Now we can try using the Add Order By element button.  This option allows us to add the Order By CAML tags.  You can specify a column and the order (ascending  or descending)

Create a new Query and click on the Add Order by element button from the toolbar.

Choose the ID column and order as Descending.

image

On executing the query you can see the following result.

image

Please note that the items are now shown in the Descending order of ID values.

Multiple Order By Columns

We can have multiple Order By columns.  Use the same button again to add a new Order By CAML tag as shown below.

image

This time we are having 2 Order by columns.  The Created By column with Ascending sorting.

More Options in CAML Query Builder Tool

You can explore more options in building CAML Queries using the tool like:

1.      Creating Queries for Date Columns

2.      Trying with And operator

3.      Filtering with Equal To, Lower Than, Greater Than conditions

4.      Using the Copy Query button to copy the query to clipboard

References

http://tinyurl.com/sp2010-camlqb

Summary

In this article we have explored the tool CAML Query Builder.  In real life scenarios this tool should give time, cost & efficiency advantages.

 

Posted in SharePoint | Tagged: , | 2 Comments »

ULS Log Viewer

Posted by Paul on September 11, 2012

In this article we can explore the SharePoint 2010 free tool ULS Log Viewer.  This is a tool from Microsoft and we are free to use it, but there is no customer support for any issues or queries.

What is Logging?

Eventually in the life cycle of a SharePoint deployment the Administrator and Developer need to look into the log information of SharePoint.  There are basically 3 kinds of log information to look for.

1.      SharePoint 14 hive LOGS folder where the SharePoint log information is kept.

2.      IIS web application log files inside INETPUB LOGS folder

3.      Windows Event log where Service Application log information are kept.

What is ULS?

The ULS represents Unified Logging Service and it captures the following:

·         Exceptions of SharePoint

·         Logs by Applications

The unified logging is stored in .log files in 14 HIVE > LOGS folder.  The unified view helps in understanding the problem in the order of activities.

Note: SPDiagnosticsBase class in namespace Microsoft.SharePoint.Administration enables writing Trace Log in SharePoint 2010.  This is the preferred way for SharePoint 2010 and it includes WriteTrace() and WriteEvent()  methods to be overridden.

Who is the Intended Audience?

This tool can be used by following type of audience:

1.      SharePoint Administrators

2.      Developers

3.      Architects

Download

You can download the tool from following location:

            http://archive.msdn.microsoft.com/ULSViewer

On opening the above link you should get the following page:

image

Click on the Downloads tab and download the file shown.

image

 

How to view the LOGS files?

We are actually interested in the first option of looking into the SharePoint 14 hive LOGS folder.  You can open the folder and see that there are a number of log files as shown below.

·         C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS

image

The latest log file (sorted by date) should contain the latest log information as shown below:

image

So there involves a bit of clumsy tasks to view the log information of SharePoint. 


 

What are the Advantages of this Tool?

The ULS Log Viewer tool provides the following advantage:

1.      A better user interface to view the Log Information

2.      Filtering of log levels based on Basic, High, Verbose etc.

3.      Formatting of log information

4.      Real time Log Information Viewing

5.      Exporting of Log Information to CSV files

6.      Multiple Machine Log viewing

7.      It is Free

Starting with the Tool

After downloading you can execute the tool.  The main screen looks like as shown below.

image

Viewing a Log file

You can use the File > Open from > File menu to open a log file from the 14 hive LOGS folder.
image

As you can see there are Time, Server, Process, Product, Category, Level information for each rows listed.

Filtering the Rows

You can filter the rows using the tool bar buttons:

image

 The rows will be filtered accordingly.

 

Real time Tracing

Another advantage of the tool is Real Time Tracing.  We can see the real time log messages by watching the tool.

For monitoring a folder for real time log messages, use the File > Open From > ULS menu item.

image

On enabling ULS monitoring, the Notifications List contains the source log file which contains the new log entries.  Please note that the specified folder can contain multiple log files.

Click on the Notifications List to see the source file which contains new log entries.

Command Line

The real time mode can be started using command line too:

            ULSLogViewer.exe realtime:FolderPath


Exporting to File

We can also export the selected lines to a File using the context menu.

image

Smart Highlight

The Smart Highlight button on the toolbar enables highlighting the contents of similar texts.  For example placing the mouse over Medium should highlight all the entries of type Medium.

image

You need to click the Smart Highlight button to enable this view.

References

http://tinyurl.com/sp2010-ulsdoc

Summary

In this article we have explored the ULS Log Viewer tool.  In real life scenarios this tool should give time, cost & convenience advantages.

Posted in SharePoint | Tagged: , | Leave a Comment »

Error: No User Profile Application available to service the request. Contact your farm administrator.

Posted by Paul on September 10, 2012

I was getting this error while using the code:

using (SPSite site = new SPSite("http://localhost"))
{
                UserProfileManager manager = new UserProfileManager(ServerContext.GetContext(site));

                UserProfile profile = manager.GetUserProfile("hp\\hp");
                var personalSite = profile.PersonalSite;

                profile.CreatePersonalSite();
}

Solution

Searching a while I found the solution like, I have to give the user (hp\hp) Full Control Permission.  Following are the steps to achieve this.

Open Central Administration and Select the User Profile Service Application row.

image

Select the Permissions dialog from the ribbon.

image

Enter the user (hp\hp in my case) in the dialog, click the add button, check the Full Control and click OK

Try running the code again and the error should disappear.  Good Luck Ahead!

Posted in SharePoint | Tagged: , | 2 Comments »

Error: Your personal site cannot be created because Self-Service Site Creation is not enabled. Contact your site administrator for more information.

Posted by Paul on September 10, 2012

Solution

  1. Open Central Administration as Administrator
  2. Select Manage Web Applications
  3. From the toolbar choose Self Service Site Creation

image

4.  Turn On the feature and click OK button

image

 

Information

Self Service Site Creation is a feature that enables site creation by the user without requiring Administrative privileges.  Users can create their own sites if the Self Service Site Creation is enabled in the web application level.

Posted in SharePoint | Tagged: , | Leave a Comment »

UnauthorizedAccessException :: This site does not host personal sites (try ‘http://hp:80/my’)

Posted by Paul on September 9, 2012

Scenario: While calling the method CreatePersonalSite()

using (SPSite site = new SPSite("http://hp"))
{
                UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.GetContext(site));

                UserProfile profile = userProfileManager.GetUserProfile("hp\\user");
                SPSite personalSite = profile.PersonalSite;

                profile.CreatePersonalSite();
}

Solution

The My Site site collection was missing.  Create a new site collection with My Site template from Central Administration.

Open the Central Administration > Create Site collections link.

image

After entering the details click Ok button to create the site.  The error should disappear now onwards.

Posted in SharePoint | Tagged: , | Leave a Comment »

My Site access :: HTTP 404 Error

Posted by Paul on September 9, 2012

I was facing the problem for only one user.  While accessing the My Site HTTP 404 error was displayed.  Other users seems to have the My Site working fine.

Following is the fix which worked for me:

static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://hp"))
            {
                UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.GetContext(site));

                UserProfile profile = userProfileManager.GetUserProfile("hp\\user");
                SPSite personalSite = profile.PersonalSite;

                profile.CreatePersonalSite();
            }
        }

Posted in SharePoint | Tagged: , | Leave a Comment »

Introduction to SharePoint 2013

Posted by Paul on September 6, 2012

On July 2012, Microsoft announced the preview version of SharePoint 2013.  This is the next version to be out to market after SharePoint 2010.

               

Note: Preview is the version available to community before the RC and RTM versions.  Preview version gives an idea on the features of the new product.  RC (Release Candidate) version will be having updates from the Preview version.  RTM (Release to Manufacturing) version is the build to be released commercially to the customers. 

New Features in SharePoint 2013

Now we can explore some of the new features inside SharePoint 2013.

.Net 4.5

SharePoint 2013 is built on top of .Net Framework 4.5.

More Cloud Support

A new Cloud App Model is introduced in SharePoint 2013.  More support for cloud based architecture.

Introducing Apps

Apps for SharePoint 2013 are self-contained pieces of functionality that extend the capabilities of a SharePoint website. An App can be a SharePoint component like list, workflow etc.

Windows Phone 7

Windows Phone 7 application integration with SharePoint 2013 services and applications is possible.

Social & Collaboration

New features like Interactive Feed, Follow User/Site supporting Social & Collaboration infrastructure.

 

Search

Content Enrichment web service, Search enhancements and Keyword Query Language (KQL) are in the Search Enhancements area.

Windows Azure Workflow

A redesigned workflow for the Cloud is integrated.

No Client Operating System Support

There is no Client Operating System support currently.  So you cannot install SharePoint 2013 on Windows 7 and other client operating systems.  For development purpose it is advisable to use Virtual Machines. 

Visual Studio 2012

Visual Studio 2012 will be the corresponding development environment for SharePoint 2013.  It should contain the SharePoint 2013 project templates.

Hardware Configuration Information

The hardware configuration should contain a 64 bit CPU with at least 8 GB of RAM.

SharePoint 2013 can be installed on Windows Server 2008 and Windows Server 2012 RC version.

IIS 7.5

IIS 7.5 is the Internet Information Services version on which SharePoint 2013 is deployed.

SQL Server 2012

Microsoft SQL Server 2012 is the database used by SharePoint 2013.      

Napa Support

Support for Web based tool named Napa for developing apps.

REST

REST support for Web Services.

Remote Event Receivers

New Remote Event Receivers are added.

Machine Translation Service

This is an enhancement to the Application Services infrastructure which involves translating documents for multilingual support.

BCS

Business Connectivity Services now support OData, external events etc.

Office Services

There is Office Services enhancements like PowerPoint Automation, Excel Services enhancements.

Note: Some of the Virtual Machine software available are Oracle Virtual Box, VMWare etc.  You need to download the separate VHD (Virtual Hard Drive) for the SharePoint installation.

References

                http://tinyurl.com/sp2010-sp2013intro

Summary

In this chapter we have seen some of the highlighted features of new SharePoint 2013 preview version.

Posted in SharePoint | Tagged: , | Leave a Comment »

Features in SharePoint

Posted by Paul on September 6, 2012

In this article we can explore the term ‘Features’ in SharePoint.

What is a Feature?

The term Feature represents a functional component that can be activated in SharePoint.  Feature provides the following:

1.      New Functionality

2.      Site Customizations

For example, the Document ID Feature provides new Document Management functionalities to SharePoint.  We can also create our own features and deploy the customer site.  A sample Features screen is shown below:

clip_image002

Scope of a Feature

The scope of the feature is given as:

·         Web

·         Site Collection

·         Web Application

·         Farm

Feature Events

A feature supports the following events:

·         Installing

·         Uninstalling

·         Activating

·         Deactivating


 

Feature Elements

A feature contains deployable elements like:

·         Menu Commands

·         Toolbar Buttons

·         Web Parts

·         Workflows

·         Event Handlers

·         Page Definitions

·         List Definitions

·         Templates

Activating Site Collection Features

A Site Collection Feature can be activated from the Site Actions > Site Collection Features link as shown below:

clip_image003

 


 

Activating Site Features

A Site Feature can be activated from the Site Actions > Manage Site Features link as shown below:

clip_image004

Creating Features through Visual Studio

We can create Features through Visual Studio.  Whenever a new SharePoint project is created a Features folder is automatically added.

            clip_image005

Once adding a Web Part or Workflow a new Feature entry is added in the above folder.

clip_image006

In the Web Parts and Workflows chapters we can see more usage of Features.

Note: You need to install the SharePoint Project Templates for Visual Studio 2010.

Feature Stapling

The term Feature Stapling is attachment of a Feature to all new instances of particular Site Definition.    This functionality is achieved without modifying the site definition.  Feature Stapling is also called Feature Site Template Association.

 

References

http://tinyurl.com/sp2010-feature

Summary

In this article we have explored the ‘Features’ feature in SharePoint.  Features provide a convenient way in deployment, version, and dependency management.

 

Posted in SharePoint | Tagged: , | Leave a Comment »

Leave Approval without Workflow

Posted by Paul on September 1, 2012

In this article we can explore the Leave Approval Scenario without using Workflows.

Scenario

Following are the users of the system.

1.      manager (The Manager)

2.      employee1 (An Employee)

3.      employee2  (Another Employee)

An employee can apply for a Leave using the list named Leaves.  The Manager has the right to approve or reject a Leave application.   The employees should not see the applications of other employees.  How to attain the functionality?

Solution

We can have 2 approaches of solution here:

·         Use List Content Approval

·         Use Approval Workflow

For simplicity sake we are using the List Content Approval feature.  The Workflow based solution can be used for more complicated scenarios.

image

Following are the steps involved in List Content Approval solution.

Create New Users

Create 3 new users for our purpose.  If you are using Windows 7 operating system go to Control Panel > Users Accounts item.

image

If you are using Windows Server operating system use the Active Directory section of the Server Manager application to add the new users.

image

 

Create New Site Collection

After creating the users, create a new Site Collection from Central Administration.  Set the Manager as the Primary Site Collection Administrator.

image

Note: Adding as Primary Site Collection Administrator makes the manager user into the Site Owners group in Site Permissions.  The Owners should be having permissions to change the settings for lists, view etc.


 

Assign Site Permissions

After creating the site collection open the new site using the url.  Sign in as the user manager.

image

Go to Site Actions > Site Permissions and open the Members group.

image

Add the other 2 users (employee1, employee2) into this group using the New > Add Users menu item.  After adding the 2 users the list should look like.

image

Now these users should be able to view the lists and libraries inside the site collection.

Create New List

Now perform the following:

·         Open the Site Collection using url

·         Sign in as the Manager user

·         Create a custom list named Leaves

·         Add the following columns into the List

image

You can see that the Created By, Modified By columns are automatically added and represents our employee who applied for the leave.

Following is the default View of the List.

image

 

Enable Content Approval

This is the core part of the article and we are going to enable the Content Approval feature of SharePoint 2010.  On enabling this feature the List item will be having:

·         A new column named Approval Status (Pending, Approved, Rejected)

·         A notification send to Manager when an item is created for Approval

·         A notification send to Employee when an item is Approved or Rejected

To enable this feature open the above list in manager mode and go to the List Settings.

image

From there choose the Versioning settings link as highlighted above.  Choose the first option Require content approval for submitted items and click the OK button.

image

Now you can see that a new column is added to the List view.

image

Note: Using Server Object Model list property EnableModeration the same can be achieved.

Modify Default View

We need to do a slight modification on the View of the Leaves list.  Currently the view shows leave applications of all employees.  We need to restrict it to show only:

·         The current logged in user leave applications

Or

·         The leave applications which are pending

Note: Views provides flexibilities like applying multiple views and changing an existing leave.

To achieve this open the Leaves list and go to List tab and click on the Modify View button as shown below:

image

Scroll down to the Filter section and set the following:

image

The filter shows the item only on the following true condition:

·         Created By column equals [Me] as Logged in user

Or

·         Approval Status column is equal to Pending

Sign in as Employee 1

Now you need to sign in as user Employee 1.  For this create a new browser instance with a new session. 

Note: If you are using Internet Explorer, press and release the Alt key in the keyboard to see the File menu.  From the menu click the New session menu item.

image

In the appearing new browser instance sign in as the Employee 1.

image

Now create a new leave item inside the Leaves list.  Set the leave time as Reason for Employee 1 as shown below.

image

You can see that the Approval Status is automatically set to Pending.

 

 


 

Sign in as Employee 2

Now you need to sign in as user Employee 2.  For this create a new browser instance with a new session.  Use the same Alt + File > New Session if you are using Internet Explorer.

In the appearing new browser instance sign in as the Employee 2.

image

Now create a new leave item inside the Leaves list.  Set the leave time as Reason for Employee 2 as shown below.

image

You can see that the Approval Status is automatically set to Pending.

Note: You can see that Employee 1 is only able to see his own leave item and Same for the case of Employee 2.  The filtering of View is doing this magic.


 

Back to Manager

Now you can go back to the manager browsing session.   You should be able to both the list items.

image

As a manager you can Approve or Reject the item by selecting the list item and using the tool bar button.

image

On clicking the Approve/Reject button you will get the following dialog.

image

You can repeat the same for the second item too.
Back to Employees

Back to the Employee 1 session you can see the corresponding leave item as Approved.

image

Now back in the Manager screen, reject the remaining leave item and login as Employee 2 to see the status as Rejected.

image

So this concludes our Leave Application implementation without using Workflows.  For the flexibility of the Manager you can edit the site main page to include the Leaves list as shown below.

image

References

http://tinyurl.com/sp2010-contappr

Summary

In this article we have explored the Content Approval feature using a Leave Approval scenario.  Following are the points worth remembering:

·         Content Approval allows item approval without using Workflows

·         Approval Status column is automatically added to list items

·         View provides a convenient way to filter items.

To try with the email notification, you need to configure email settings for SharePoint.

Posted in SharePoint | Tagged: , | Leave a Comment »