Jean Paul's Blog

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

  • 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

Archive for September, 2012

CRUD and BCS

Posted by JP on September 30, 2012

In this article we can experiment with BCS by connecting to an external database. After completing this article you will be able to:

· View Database Table inside SharePoint

· Perform Add/Edit/Delete operations

Following are the activities involved.

1. Create database and table

2. Using SharePoint Designer create BCS External Content Type

3. Using SharePoint Designer create Add/Edit/Delete operations metadata

4. Using SharePoint Designer create Lists & Form

5. Using Central Administration set Permissions for external Content Type

1. Create database and table

Create a database and table named Customer with following fields:

clip_image002

Add some data into it:

clip_image004

2. Using SharePoint Designer create BCS External Content Type

Now we can create an External Content type using SharePoint Designer. Start the Designer application and open our SharePoint web site > External Content Types as shown below.

clip_image006

Click on the External Content Type button from the top side. In the appearing window change the Name and Display Name (click on the links) as shown below.

clip_image008

Now click on the External System link and you will get the following dialog.

clip_image010

Click on the Add Connection button and select SQL Server in the appearing dialog.

clip_image012

In the appearing connection details dialog, enter your server details.

clip_image014

Click the OK button and your server connection is ready.

3. Using SharePoint Designer create Add/Edit/Delete operations metadata

From the appearing tables list select the Customer table and right click to get the context menu. Use the Create All Operations menu item to get the Add/Edit/Delete operations wizard.

clip_image016

Click on the Finish button in the appearing wizard.

clip_image018

Click on the Save button from the top tool bar.

clip_image020

4. Using SharePoint Designer create Lists & Form

Now the operations are ready and we need to create the List Form and the associated Add/Edit/Delete forms inside SharePoint.

clip_image022

From the toolbar, click on the Create Lists & Form button as highlighted above. In the appearing dialog box enter the name for the List and click the OK button as shown below.

clip_image024

Wait for a while and your List page will be ready.

clip_image026

5. Using Central Administration set Permissions for external Content Type

Now you can try viewing the Customer Data list inside SharePoint.

clip_image028

On clicking the list, you will be seeing an “Access Denied by Business Data Connectivity” error message. To resolve this we need to set permission for the External Content Type.

Open the SharePoint Central Administration website. Click on Manage Service Applicatoins.

clip_image030

In the appearing page click on the Business Data Connectivity Services link as shown below:

clip_image032

In the appearing list, hover over the Customer Data item and click on the Set Permissions menu item as shown below.

clip_image034

You will get the following dialog.

clip_image036

Enter the user name, click the Add button and check all permissions. Click the OK button to close the wizard. (Make sure you are adding the username used to view SharePoint)

Now you are ready with the Permissions. Go back to the SharePoint > Customer Data list and you will be able to see the data as shown below.

 

Now you can try playing with the View/Edit/Delete features of the BCS list.

References

http://www.zimmergren.net/technical/access-denied-by-business-data-connectivity-solution

Summary

In this article we have seen how to create an External Content Type through Business Connectivity Services and view it inside SharePoint. In the real world scenario using BCS we can connect to WCF Services and other Business Applications like Microsoft CRM to view/update data inside SharePoint.

Advertisements

Posted in SharePoint | Tagged: , , , , , , | 2 Comments »

Debugging using SPDiagnosticsService

Posted by JP on September 29, 2012

In this article we can explore a debugging scenario using SPDiagnosticsService class and the SharePoint 2010 Logging Severity Levels.

Scenario

Your customer reported that in the middle of an operation the SharePoint site is not responding. You need to find out what is the underlying issue.

Solution

As the issue is happening in the production environment you can use the Diagnostics capabilities of SharePoint 2010.

Following are the activities involved in the solution:

1. Write events to the Log

2. Change the SharePoint Log Level

3. Deploy the Solution

4. Repeat the User Activity

5. Trace the problem

Here we are going to perform the first 3 activities.

SPDiagnosticsService

The class provides a Diagnostics service manager for SharePoint. The class is residing in namespace Microsoft.SharePoint.Administration.

We can use the static property named Local to get an instance of the service class.

image

We can use the method WriteTrace() to write to ULS log. The advantage of writing to ULS log will be following:

· Share the common location of SharePoint log

· Combined analysis of application trace along with other service application traces

Note: Please note that the WriteEvent() method writes to Windows Event Log and thus requires more Permissions. The windows event log entries can be viewed through Windows Event Viewer.

Example

Create a new SharePoint solution and add a Web Part into it. Add a button on the web part and add the following code inside button click event.

protected void Button1_Click(object sender, EventArgs e)

{

SPDiagnosticsCategory category = new SPDiagnosticsCategory(

"My Application Category",

TraceSeverity.Verbose,

EventSeverity.Verbose

);

SPDiagnosticsService.Local.WriteTrace(

0,

category,

TraceSeverity.Verbose,

"Log information"

);

}

In the above code we have set Trace Severity to Verbose. The Verbose level is used to specify log information which contains more details.

Following are the members of Trace Severity enumeration.

image

Diagnostic Logging Configuration

You can configure the Log Levels in Central Administration. Following are the properties of diagnostics logging which are configurable:

1. Log file location

2. Number of Days to retain Log file

3. Least critical event level

4. Least trace event level

5. Enable Service Application Logs

To configure these open Central Administration > Monitoring > Configure diagnostics logging

On clicking the link you will get the page below.

image

For testing our web part please make the levels to Verbose as shown below.

image

Click the OK button to save the changes.

Severity Levels

The Severity Levels are used to specify the log information level. The Severity Level is used to process or discard log information by SharePoint.

A Verbose level logging involves more write to the hard disk and eating a lot of processor cycles too. Thus verbose level logging is recommended only while debugging needs.

The Event Throttling settings control the severity of events captured in the Windows event log and the trace logs. As the severity decreases the number of events logged will increase.

Testing the Application

We can now test our web part. Build, Deploy and Insert the web part into a page. Click the button to create the trace log entry.

image

You can view the entry from the log file (latest log file) in 14 HIVE LOGS folder.

image

This concludes our test with Diagnostics Logging.

SPDiagnosticsServiceBase

SPDiagnosticsServiceBase is an abstract class. This class can be used to create a concrete class which can be used for writing custom diagnostics categories. Inside our implementation class the Category can be explicitly provided.

Additionally you can specify the Product Name for the log entry while implementing the concrete class.

References

http://tinyurl.com/sp2010-diag

http://tinyurl.com/sp2010-spdiag

http://tinyurl.com/sp2010-spdiagbase

Summary

In this article we have explored the debugging capabilities of SharePoint 2010 through logging. Following are the point worth to note:

· SPDiagnosticsService class is used for Logging

· WriteEvent() writes to Windows Event Log and needs Security Privileges

· WriteTrace() writes to SharePoint Trace Log

· Central Administration can be used to configure Diagnostics Logging

· SPDiagnosticsServiceBase provides an alternative way of Logging

Posted in C# | Leave a Comment »

Error: Your client does not support opening this list with Windows Explorer

Posted by JP on September 28, 2012

While working with a customer having Windows Vista and using SharePoint 2010 I encountered the following error.

Scenario: Clicked on a document library, and used the Open with Windows Explorer option.  This option is disabled whenever an incompatible browser is used.

 

Following is the error screen:

image 

 

Solution

I tried the following solution steps:

1. Ensured the Internet Explorer version is 32 bit

2. Added the site to Trusted Sites inside browser

3. Ensured WebClient Service was running

image

4. Modified the Registry

    1. Open regedit.exe
    2. Located HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WebClient\Parameters
    3. Modified BasicAuthLevel to 2
    4. Restarted the Machine

Solved: Now the error disappeared.  Thanks for the MSDN Documentation.

Screen Shot of Registry Key

image

Note For security purposes, Windows Vista and Windows XP SP2 disable Basic authentication in the Web Distributed Authoring and Versioning (WebDAV) Redirector.

BasicAuthLevel

Values for BasicAuthLevel are:

  • 0 – Basic authentication disabled
  • 1 – Basic authentication enabled for SSL shares only (default value)
  • 2 – Basic authentication enabled for SSL shares and for non-SSL shares

Reference

http://support.microsoft.com/kb/841215

Posted in C# | Leave a Comment »

Scenario – Move Multiple Folders between Libraries

Posted by JP on September 26, 2012

In this article we can explore a real world scenario of working with Folders and Files in a Document Library.

Scenario

Your customer has a collection of folders and files in a Document Library. Customer needs more convenient options to Cut / Copy / Paste Folders/Files between SharePoint Sites and Local File system. How to provide a solution?

Solution

The cost of developing custom actions for the above operations would be time consuming and collaboration with local file system would be still unresolved. Luckily we do not have to do it.

SharePoint 2010 has built in features to support Cut / Copy / Paste features. We can use the power of desktop using Windows Explorer to achieve the same.

Open with Windows Explorer

We can use the Open with Windows Explorer feature of SharePoint 2010 to perform the operations:

  1. Cut / Copy / Paste of Folders
  2. Cut / Copy / Paste of Files
  3. Operate between SharePoint Site and Local File System

We can access the feature from the Library tab of the document library as shown below:


On using the above option, the library gets opened in the Windows Explorer.


In the above Explorer window you can do multiple selections, cut / copy / paste operations, drag and drop etc.

Constraints

Following are the constraints on using this feature:

  1. Client should be Windows Operating System
  2. Client Browser should be Internet Explorer 32 bit
  3. Client machine should be having WebClient service Started

The operating system can be Windows 7 / Vista / 2008 etc. Internet Explorer 64 bit and other browsers will be having the button disabled. Web Client service should be started for Windows Client operating systems.

WebDAV

Web Distributed Authoring and Versioning (WebDAV) is an extension of the Hypertext Transfer Protocol (HTTP) that enables treating HTTP location as file system. WebDAV is enabled in the Internet Information Services (IIS) level of SharePoint server to provide Open with Windows Explorer functionality.

Error Situation 1: Disabled Button

An error situation can arise like the following where the button is disabled.


Solution

Ensure Windows & Browser: Ensure the Windows / Internet Explorer combination is valid according to SharePoint 2010 recommendations. Please ensure that you are using 32 bit version of Internet Explorer.

From the Start Menu launch the correct version of Internet Explorer.


You can also verify the Internet Explorer (IE) version using the About menu item inside IE. Press Alt within IE, then choose Help > About menu item as shown below.

    

 

Click the menu item and you can see the following dialog.

    

For IE 32bit the Version line looks like above.

For IE 64 bit (incompatible) the Version line looks like below.


I would like to repeat that IE 64-bit does not support Open in Windows Explorer feature.

 

Error Situation 2: Error Message

In this error situation, the button is enabled but will throw an exception dialog saying “Your client does not support opening this list with Windows Explorer”.


Solution

Start WebClient Service: The WebClient service has to be started in the client operating system. This service makes Windows Explorer treat the SharePoint site as a file system.

To ensure it is started please open the Run command window and type services.msc


This command will open the Windows Services management console. (You can also star this console from Start Menu > Control Panel > System & Security (group) > Administrative Tools > Computer Management > Services and Applications > Services)

 

Locate the WebClient service within this window and Start it if it is not already started.


Click the Play button from the toolbar to start the Service.

You can also change the Startup Type to Automatic for starting the service on operating system start. For changing this you need to right click the Service item and choose Properties menu.

 

Note: If you are using a Windows Server 2008 / 2012 machine as your client (server & client same machine) then you need to add the feature “Desktop Experience” to work with this functionality.

Server Side Troubleshooting

Additionally if you have the SharePoint deployment server under your control, you can troubleshoot the WebDAV settings.

  1. Open Server Manager application
  2. Click on the Add Roles Services item
  3. Check WebDAV Publishing item
  4. Proceed with Install
  5. Restart machine



References

http://tinyurl.com/sp2010-browcomp

Summary

In this article we have explored the flexibility on managing document libraries inside SharePoint 2010. Additionally we can map network drives to a SharePoint site using the WebDAV feature. Although

SharePoint 2010 supports almost all commonly used browsers we have to keep in mind that all the features are not supported. A browser compatibility matrix can be viewed in the References link. The Browser version should be specified in the Client deployment manual to avoid future chaos.

Posted in C# | Leave a Comment »

Importing and Exporting Certificates

Posted by JP on September 26, 2012

In this article we can explore how to Import and Export Certificates from a Windows machine.  This knowledge would be necessary while dealing with Certificate enabled web applications.

What is a Certificate?

A certificate is a mechanism used to verify an identity on a computer.

What are the types of Certificate in Internet Explorer?

Internet Explorer uses 2 types of certificates.

1.      Personal Certificates to certify the person who use the application.  Personal Certificates are to be produced to web applications requesting personal identities.  This adds much more security in accessing the application.  A personal certificate is issued by a Certificate Authority (CA).

 

2.      Web Site Certificates to certify the web site is secured and genuine.  This allows websites to gain trust of users.  It is the user’s responsibility to verify whether the web site is secured before submitting information over it.

Here we are dealing with Personal Certificates.

What is the Tool to Import / Export Certificate?

The tool to import / export certificate is: Certificate Manager Tool

image

You can launch this tool using Run window > CERTMGR.MSC

How to Export a Certificate?

Now we can try exporting a certificate.  Open the Tool and select the certificate you wanted to export.  You can locate a certificate by expanding the Certificate Group from the left pane.

image

Now right click on the certificate and choose All Tasks > Export as shown below:

image

A wizard should appear as shown below:

image

Click the Next button to continue.  You will be prompted with a File Format page as shown:

image

Select the default format for now and click the Next button to continue.  You will be prompted to enter the file name for the certificate.   The certificate file extension is .cer

image

Enter a file name as shown above and click the Next button to continue.

image

The above page summarizes the information and clicks the Finish button to complete the Export.  You can see the certificate exported in the file system.

image

How to Import a Certificate?

Now we can try importing a Certificate.  We can use the Certificate file exported in the previous step for import purpose.

Now you can proceed to the destination machine where the certificate has to be imported.  Copy the .cert file generated in previous step to the destination machine.

Run CERTMGR.MSC in the destination machine.

image

Select your Certificate category from the left pane and right click on it to get the context menu.

image 
Choose the option All Tasks > Import as shown above. In the appearing wizard click Next button and choose the certificate file from the folder.

image

Click the Next button to continue.

image

 

Click the Next button to continue..
image

Click the Finish button and you should see the Certificate being imported and listed.

image

How to Delete a Certificate?

You can delete a certificate by choosing the certificate and selecting Action > Delete from the menu bar.

image

So this concludes our article.  I hope you have learned how to:

·        What is a Certificate

·        Export a Certificate

·        Import a Certificate

·        Delete a Certificate

References

http://tinyurl.com/sp2010-certimpexp

http://tinyurl.com/sp2010-pbprkey

Summary

In this article we have seen how to Import and Export Certificates.  In real world scenario this information would be useful while dealing with certificate enabled applications.

Please note that Certificates use public key and private key encryption.  More information on this is provided in the References section.

Posted in C# | Leave a Comment »

Error :: XmlException was unhandled The ‘[‘ character, hexadecimal value 0x5B, cannot be included in a name. Line 1, position XXXXX

Posted by JP on September 25, 2012

In this article I would like to update with a possible Error Scenario while working with the SPWebConfigModification class.

Scenario

You are adding a new entry to the web.config file using SPWebConfigModification class.

SPWebService service = SPWebService.ContentService;

SPWebConfigModification modification = new SPWebConfigModification();

service.WebConfigModifications.Add(modification);

service.Update();

service.ApplyWebConfigModifications();

Unfortunately the following error is thrown repeatedly.

Error: XmlException was unhandled

The ‘[‘ character, hexadecimal value 0x5B, cannot be included in a name. Line 1, position XXXXX

Root Cause

Please note that the error might not be telling about the new modification. All the previous modifications are queued up and applied together to multiple farm servers. So you need to check all the modification entries for any problems with their Name, Value properties.

Additionally the character and position mentioned in the error message could be different.

You can locate the exact modification entry having problem using the following property.

service.WebConfigModifications

This property should contain all the modifications. You can remove the wrong modification entry and use the Update() method to save the changes. Once the problem is fixed you can re-run your new modification code.

For example if you have the wrong entry at position 13, use the following code to remove the entry and update.

service.WebConfigModifications.RemoveAt(13);

service.Update();

// You can also remove based on the Owner property.  Make sure you invoke the Update() method after making changes to the WebConfigModifications property.


Using Quick Watch

You can use the Quick Watch window to locate the problem entry.

clip_image002

Examine each item for the Name and Value property especially.

Additional Tip

You can always switch between different web applications using the following code.

SPWebService service = SPWebService.AdministrationService;

or

SPWebService service = SPWebService.ContentService;

Both the properties returns the SPWebService object associated with the name.


References

http://tinyurl.com/sp2010-spwbcfg

http://tinyurl.com/sp2010-wbcfgloc

Summary

In this article we have explored a possible error scenario while working with SPWebConfigModification class.

Posted in C# | Leave a Comment »

Updating Multiple Front End Servers Configuration

Posted by JP on September 24, 2012

In this article we can explore how to update multiple web configuration files in a Farm environment.  The configuration file which we are referring is the IIS (Internet Information Services) web application configuration file.  It is residing in the IIS folder.

For example: C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config

Abstract

SharePoint 2010 Farm Deployment may involve multiple Web Front End servers.  For example a typical farm environment is as following:

·         2 Web Front End Servers

·         1 Database Server

·         1 Search Index Server

In this case any update to web.config file should be done in the 2 servers.  Manually updating both the servers is tedious and not recommended once we are deploying a feature to a user. 

Solution

We can use the SPWebConfigModification server object model for this purpose. 

Following are some of the entry types possible with this:

·         Safe Control

·         Connection String

·         Application Setting

SPWebConfigModification is residing in the namespace Microsfot.SharePoint.Administration.

Note: The configuration modification through SPWebConfigModification server object model is the recommended one as it performs a safe updating.

Important Properties

Following are the important properties of SPWebConfigModification class:

1.       Name to hold name of attribute / section

2.       Value to hold value of the item

3.       Path to hold the X Path to the node

Adding a Safe Control

Following is the code for adding a Safe Control entry into the web.config.  Create a new SharePoint 2010 Console Application and execute the following code which creates an entry for ‘TestAssembly’.

SPWebService service = SPWebService.ContentService;

 

SPWebConfigModification modification = new SPWebConfigModification();

modification.Owner = "OwnerNameHere";

modification.Path = "configuration/SharePoint/SafeControls";

modification.Name = "SafeControl[@Assembly=’TestAssembly’][@Namespace=’TestNameSpace’][@TypeName=’*’][@Safe=’True’]";

modification.Sequence = 0;

modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

modification.Value = "<SafeControl Assembly=’TestAssembly’ Namespace=’TestNameSpace’ TypeName=’*’ Safe=’True’ />";

 

service.WebConfigModifications.Add(modification);

service.ApplyWebConfigModifications();

service.Update();

 

Later you can open the web.config file and see the new entry there.

image

Code Explained

The SPWebConfigModification class instance holds the modification information like:

·         Name

·         Value

·         Path

·         Owner

·         Sequence

The WebConfigModifications property contains all the modification entries. (Modifications stored in the Database).  We are adding our modification entry into this collection.

The ApplyWebConfigModifications () applies all the Modifications to the servers in farm.

The Update() method saves the WebConfigModifications into the Content database.  This will help to re-deploy all the modifications in future.

Note: Please make sure you have set the Platform Target of the project as .Net 3.5 Framework.

Adding a Connection String

Now let us try adding a connection string into the web.config files of multiple servers in the farm.  Create a new method in our Console Application and add the following code to it.

private static void CreateConnectionString()

{

    SPWebService service = SPWebService.ContentService;

 

    SPWebConfigModification modification = new SPWebConfigModification("CS1", "configuration/connectionStrings");

    modification.Owner = "OwnerZ";

    modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

    modification.Value = "<add name=\"CS1\" connectionString=\"Data Source=SERVER;User ID=USER;Password=PASSWORD;Initial Catalog=DBNAME;\" providerName=\"System.Data.SqlClient\"/>";

 

    service.WebConfigModifications.Add(modification);

    service.ApplyWebConfigModifications();

    service.Update();

}

 

Later you can open the web.config file and see the new entry there.

image

Please note that the above code is performing the following:

·         Specify the Web Service

·         Specify the Modification Name and X Path

·         Specify the add tag with Connection String

·         Add to Modifications list

·         Apply Modification

·         Save Modifications list to content database

Note:  If you face any error saying the section does not exists, you can manually create an empty connection string section in the configuration file.

Adding an Application Setting

We can also add an Application Setting to the configuration file.  Create a new method named CreateAppSetting() inside the console application we have and use the following code for adding an application setting to the web application configuration file.

private static void CreateAppSetting()

{

    SPWebService service = SPWebService.ContentService;

 

    SPWebConfigModification modification = new SPWebConfigModification("AppSetting", "configuration/appSettings");

    modification.Owner = "OwnerZ";

    modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

    modification.Value = "<add key=\"MYKEY\" value=\"MYVALUE\" />";

 

    service.WebConfigModifications.Add(modification);

    service.ApplyWebConfigModifications();

    service.Update();

}

 

Later you can open the web.config file and see the new entry there.

image

Please note that the above code is performing the following:

·         Specify the Web Service

·         Specify the Modification Name and X Path

·         Specify the add tag with KEY & VALUE

·         Add to Modifications list

·         Apply Modification

·         Save Modifications list to content database

Importance of Owner Property

We are using the Owner property (which is a string) to specify the owner name of the modification.  In future the specified property can be used to filter modifications based on the Owner.

So setting the Owner property gives the following advantages:

·         Finding Modification entries by Owner

·         Updating Modification entries by Owner

·         Removing Modification entries by Owner

Following is the example code that will remove modification entries by owner.

        private static void RemoveByOwner(string owner)

        {

            SPWebService service = SPWebService.AdministrationService;

 

            service.WebConfigModifications.Where(m => m.Owner == owner).ToList().

                ForEach(m => service.WebConfigModifications.Remove(m));

 

            service.Update();

        }

 

Under the Hood

Each of the Configuration Modification entry is stored in the SharePoint Content database.  This is to keep track of all the changes made using the SPWebConfigurationModification class.

Please note that there could be different SharePoint solutions creating configuration modification entries.

Why History of Modifications is maintained?

You might be wondering that why the history of modifications is maintained.  This is to apply all the changes to multiple front end servers.

Each of the Configuration Modification entry is stored in the Content database.  Later point of time when a new server is added to the farm, a quick updating is possible.

Without storing the entries in database it is difficult to parse a valid server configuration file and replicate the changes to another.

 

Various Locations of web.config

Please note that there are various locations for the web.config files depending on the context and element.

SharePoint Port 80 Application web.config is residing in:

            C:\inetpub\wwwroot\wss\VirtualDirectories\80

SharePoint Central Administration Application web.config is residing in:

            C:\inetpub\wwwroot\wss\VirtualDirectories\[Port of Central Administration]

SharePoint Port 80 Application Web Part web.config is residing in:

            C:\inetpub\wwwroot\wss\VirtualDirectories\80\wpresources

 

Additionally there is a CONFIG folder inside the 14 Hive

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

This folder contains the following types of files:

1.      web.config

2.      *.config

3.      webconfig.*.xml

More information on these can be found through the References section.

Note The Safe Control entries can also be deployed to the CONFIG folder as a webconfig.*.xml file.  The entries will be merged with the web.config file. 

References

http://tinyurl.com/sp2010-spwbcfg

Summary

In this article we have explored the problems with updating multiple web configuration file and the usage of SPWebConfigModification model to resolve it. 

Following are the points worth noting:

·         SPWeConfigModification can be used to create modification entries

·         Update() method will save the entry to database

·         Multiple Modification entries are tracked in the database

·         ApplyWebConfigModifications() method applies the modification entries in database to servers in farm

·         Adding / Updating / Deleting of configuration entries is little tricky

In real world scenarios this model should give an advantage edge for the developer and it is the recommended way for doing configuration modification. 

The source code contains the example we have discussed.

Posted in C# | Leave a Comment »

SharePoint 2010 – Custom Actions to calculate Document Size

Posted by JP on September 20, 2012

In this scenario we are using the Custom Actions infrastructure of SharePoint 2010.

Scenario

Our aim is to provide user interface controls to display the Document Size at:

  • Site level Calculate Document Size for all Libraries
  • Library level Calculate Document Size for all Documents
  • Document level Calculate Document Size for selected Document

Solution

We can use Custom Actions to address the above scenario.

What is Custom Action?

Custom Actions are special purposed actions integrated into the SharePoint user interface. A custom action could be:

  • A menu item in the Site Actions menu
  • A button in the ribbon tool bar
  • A menu item in the context menu of list or library item

Please find some custom action samples: (we are going to create these actions now)


Why we need Custom Action?

In the development life cycle using SharePoint, we may encounter scenarios where the user prefers a special user control for in a particular context. Some of the examples are:

  • Calculate Document Size in site level, library level, item level
  • Convert a particular document to PDF file
  • Display button to open Bing Search
  • Display the Audit History on site level, list level, item level

How to create Custom Actions?

We can create custom actions using Visual Studio 2010 and SharePoint project templates. The custom actions can be represented using XML Element files which are deployed as Features. The associated images can also be included in the project and get deployed automatically.

Custom Action Element

We use the XML tag CustomAction to specify custom action elements like menu item, button etc.

The custom action element defines an extension to the User Interface. A sample custom action element contains the following tags and values.

    

Following are the properties which we are interested in:

  • ID to provide a unique Identifier
  • Title to display the caption
  • Description to provide information on the UI element
  • ImageUrl to specify the relative image path
  • Sequence to specify the order of listing
  • Location to specify the container

 

Our Aim

Our aim is to create 3 custom actions as shown in the above image. For starting with create a new Visual Studio 2010 > Empty SharePoint project.


Now your Solution Explorer looks like below:

    

 

 

Create Site Actions menu item

Now we can try creating the first Custom Action:

  • Site Document Size

On clicking this menu item an application page will be shown. This page should display the total size of documents summing up all libraries and the items inside it.

To create the custom action, right click on the Solution Explorer and use the Add New Item and choose the Empty Element option.


Enter the name as SiteActionsMenuItem. Replace the contents of the file with the following.

<?xml
version=1.0
encoding=utf-8?>

<Elements
xmlns=http://schemas.microsoft.com/sharepoint/>

<CustomAction
Id=SiteActionsMenuItem


Description=Displays the Total Documents Size of the Site


Title=Site Document Size


GroupId=SiteActions


Location=Microsoft.SharePoint.StandardMenu


ImageUrl=/_layouts/images/CustomActionsExample/red.png


Sequence=10>

<UrlAction
Url=/_layouts/CustomActionsExample/DocSizeInfoPage.aspx?scope=web/>

</CustomAction>

</Elements>

 

The above Custom Action element specifies the following:

  1. Set the Location as Microsoft.SharePoint.StandardMenu. We need to specify the exact location for each custom action element. Here we are specifying the Standard Menu which is displayed on clicking the Site Actions link. You can see the GroupId set as SiteActions.


  2. Set the Title as Site Document Size. The title is used to specify the caption of men item.
  3. Set the ImageUrl, Sequence. These properties we can explore later.

     

 

Create Ribbon button

For creating the ribbon button you can add a new Empty Element. Set the name as LibraryRibbonButton.


Replace the XML content with following:

<?xml
version=1.0
encoding=utf-8?>

<Elements
xmlns=http://schemas.microsoft.com/sharepoint/>

<CustomAction
Id=LibraryRibbonButton
Location=CommandUI.Ribbon.ListView
RegistrationId=101
RegistrationType=List
Title=Library Document Size>

<CommandUIExtension>

<CommandUIDefinitions>

<CommandUIDefinition
Location=Ribbon.Documents.Share.Controls._children>

<Button
Id=DocSizeButton
Image32by32=/_layouts/images/CustomActionsExample/green.png
Command=DocSizeButton
Description=Displays the Total Documents Size of the Library
LabelText=Library Document Size
TemplateAlias=o2


Sequence=93

/>

</CommandUIDefinition>

</CommandUIDefinitions>

<CommandUIHandlers>

<CommandUIHandler
Command=DocSizeButton
CommandAction=/_layouts/CustomActionsExample/DocSizeInfoPage.aspx?scope=library&amp;ListId={ListId} />

</CommandUIHandlers>

</CommandUIExtension>

</CustomAction>

</Elements>

In order to make the above button visible only for Document Libraries we are using the Registration Id attribute as 101. 101 represent the template Id for Document types. The CommandAction is pointing to an application page with ListId as parameter set through runtime.

Create Document menu item

Here we are going to add a new menu item to the document context menu. This menu is called Edit Control Block.

To achieve this create a new Empty Element and set the name as DocumentMenuItem.


Replace the XML content with following:

<?xml
version=1.0
encoding=utf-8?>

<Elements
xmlns=http://schemas.microsoft.com/sharepoint/>

<CustomAction


Id=DocumentMenuItem


RegistrationType=List


RegistrationId=101


Location=EditControlBlock


Sequence=301


Title=Document Size


ImageUrl=/_layouts/images/CustomActionsExample/blue.png>

<UrlAction


Url=/_layouts/CustomActionsExample/DocSizeInfoPage.aspx?scope=item&amp;ListId={ListId}&amp;Itemid={ItemId}“/>

</CustomAction>

</Elements>

The Location specifies the container in which the custom action should occur. In this case it is EditControlBlock. The ImageUrl is set to a file which we will be adding later. The url contains the application page which process the request.

You can see that {ListId} and {ItemId} are the parameters resolved in the Runtime. It should contain the List GUID and the Item Id when invoked.

Creating Application Page

Here we are using a common application page to process all the 3 requests. The requests are differentiated using the query parameters.

Create a new Application Page and name it as DocSizeInfo.aspx


In the page load event invoke a RefreshData() method as following.

protected
void Page_Load(object sender, EventArgs e)

{


if (!IsPostBack)

RefreshData();

}

 

private
void RefreshData()

{


if (this.Request.QueryString[“scope”] != null)

{


string scope = this.Request.QueryString[“scope”];

 


if (scope == “web”)

{

CalcDocSizeForWeb();

}

 


else
if (scope == “library”)

{

CalcDocSizeForLibrary();

}

 


else
if (scope == “item”)

{

CalcDocSizeForItem();

}

}

}


Modify the Application Page HTML code to include a Label control.

<asp:Content
ID=”Main” ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>


<h1>

Document Size Information</h1>


<asp:Label
ID=”InfoLabel” runat=”server” Font-Size=”Small” ForeColor=”Blue”>

</asp:Label>

</asp:Content>

 

<asp:Content
ID=”PageTitle” ContentPlaceHolderID=”PlaceHolderPageTitle” runat=”server”>

Document Size Information

</asp:Content>

 

<asp:Content
ID=”PageTitleInTitleArea” ContentPlaceHolderID=”PlaceHolderPageTitleInTitleArea”


runat=”server”>

Document Size Information

</asp:Content>

 

Please note that I have updated the Title in various places to Document Size Information. These updating are reflected in various places as shown below.


Application Pages & Site Pages

In this example we have used Application Pages. The Application pages are residing in the File System and are not editable like the Site Pages.

 

 

Calculation Methods

Now we can try completing the calculation methods for document size.

Method 1

private
void CalcDocSizeForWeb()

{


long total = 0;


int count = 0;

 


foreach (SPList list in
SPContext.Current.Web.Lists)

{


if (list is
SPDocumentLibrary)

{

count += list.Items.Count;

 


foreach (SPListItem item in list.Items)

{

total += item.File.Length;

}

}

}

 

InfoLabel.Text = “Number of Documents in Web: “ + count.ToString() + “</br>Total Documents Size of Web: “ + total.ToMBString();

}

Method 2

private
void CalcDocSizeForLibrary()

{


long total = 0;


int count = 0;

 


// ListId assigned by SharePoint runtime


Guid listGuid = new
Guid(this.Request.QueryString[“ListId”]);


SPList list = SPContext.Current.Web.Lists[listGuid];

 


if (list != null)

{


if (list is
SPDocumentLibrary)

{

count = list.Items.Count;


foreach (SPListItem item in list.Items)

{

total += item.File.Length;

}

}

}

 

InfoLabel.Text = “Number of Documents in Library: “ + count.ToString() + “</br>Total Documents Size of Library: “ + total.ToMBString();

}

 

Method 3

private
void CalcDocSizeForItem()

{


// ListId assigned by SharePoint runtime


Guid listGuid = new
Guid(this.Request.QueryString[“ListId”]);


SPList list = SPContext.Current.Web.Lists[listGuid];

 


if (list != null)

{


int itemId = Int32.Parse(this.Request.QueryString[“ItemId”].ToString());


SPListItem item = list.GetItemById(itemId);


if (item != null)

{

InfoLabel.Text = “Documents Size: “ + item.File.Length.ToMBString();

}

}

}

 

You can see that an Extension Method is used. Create a class for the extension method and place the following code in it.

namespace CustomActionsExample

{


public
static
class
ExtensionMethods

{


public
static
string ToMBString(this
long size)

{


double result = (double)(((double)size / 1024) / 1000);

 


return
string.Format(“{0:0.00}”, result) + ” MB”;

}

}

}

 

The above extension method ToMBString converts the long value to Mega Bytes and returns a formatted string.

 

Now you are ready with the Methods and try building the project. Fix errors if there are any, and we can proceed to the next section to set Images for our custom actions.

Setting Images for Custom Actions

Setting the Images are little tricky. We need to map them to the correct folder. Copy the images from the source (or create 3 images of your own).

Right click on the solution and use the Add > SharePoint “Images” mapped folder.


This will create an Images folder with a sub folder inside it. Now add the images into it.

    

You need to place the image files inside this folder. The above folder is mapped to:


After deployment the above image files will be copied to the SharePoint Front End Server > 14 HIVE > Template > Images > CustomActionsExample folder

    

You can see the same folder inside IIS (Internet Information Services)

Open IIS > Select SharePoint site > Expand _layouts folder

The _layouts folder is a Virtual folder which is resolving into the 14 HIVE folder of SharePoint. You can try clicking the Explore button from the right side to see the Images folder.

Pointing the Images from Custom Actions

Inisde the custom action file we are pointing to the image as shown below:

Site Actions Menu Item > ImageUrl=/_layouts/images/CustomActionsExample/red.png

Library Ribbon Button > Image32by32=/_layouts/images/CustomActionsExample/green.png

Document Menu Item > ImageUrl=/_layouts/images/CustomActionsExample/blue.png

Deployment

You can try deploying the solution. Right click on the project and use the Deploy menu item.

    

Seeing in Action

Now going back to your site, you can see the custom actions there. On clicking them you can see the result. Please note that the result changes according to the context.

 

Site Actions > Custom Action


 

Library > Ribbon > Custom Action


 

Document > Custom Action


 

Creating Test Documents

To verify the tests you can create 2 libraries in the Site. Each library can have a 2 one MB file inside it.

The results should be:

  • Site Document Size as 4 MB
  • Library Document Size as 2 MB
  • Document Size as 1 MB

Security Trimming Custom Actions

We can show or hide a custom action based on the user’s permission level. The attribute Rights can be used for this purpose. It takes comma separated values and is treated as AND operation.

For example:

<CustomAction
Rights=Approve,Read>

</CustomAction>

You can see a user permission level by going to the Site Actions > Site Permissions page.


The setting of Permission Levels using Rights attribute is referred as Security Trimming for Custom Actions.

 

References

http://tinyurl.com/sp2010-sactn

http://tinyurl.com/sp2010-caecm

http://tinyurl.com/sp2010-csact

Summary

In this scenario we have explorer the Custom Actions feature of SharePoint and using it in the Site level, Library level and Item level.

I hope this will give you good grounds for a more complex scenario in future.

The source code contains the example we have discussed.

Posted in C# | 1 Comment »

SharePoint 2010 Interview Questions!

Posted by JP on September 19, 2012

I am happy to announce the second book in SharePoint 2010 series – Interview Questions.

About the Book

This book provides 250+ Interview Questions & Answers for SharePoint 2010 Development Track.  The book covers the SharePoint Development areas including:
– Server Object Model
– Web Part
– Workflow
– Timer Job
– Client Object Model
– Administration

+ Complementary Architect Track Questions too.

Prepared in such a way that the book should boost the confidence of candidate.
Additional tips on Interview Tactics are provided.

The Interview Questions book is targeted for developers.

CoverIQ

You can avail the sample book here.

You can buy the book from Amazon!

Note: Kindle book are readily readable if you have a Kindle Device or Kindle for PC.

Posted in C# | 8 Comments »

Interview Question: How much Terabytes does SharePoint support?

Posted by JP on September 17, 2012

36 Terabytes example

http://channel9.msdn.com/Events/TechEd/NorthAmerica/2012/OSP232

image

200 Terabytes example

http://blogs.developpeur.org/patricg/archive/2012/11/14/spc12-spc221-showcase-of-microsoft-s-200-tb-hybrid-records-management-solution.aspx

Posted in C# | Leave a Comment »