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

Posts Tagged ‘sharepoint 2010’

Available Now at Amazon!

Posted by JP on November 5, 2012

Black Page - Yellow Title

Book provides Basics to Advanced Topics coverage & Real World Scenarios to bet on your confidence!

Working on the commitment to make Best Resources available for SharePoint!

The Book is available at Amazon for Purchase.

I have made sure to set the minimum rate for the maximum quality &  quantity.

Advertisements

Posted in C#, SharePoint | Tagged: , , | 37 Comments »

Site Workflow with While, IfElse, Code Activities

Posted by JP on October 17, 2012

In this article we can explore using multiple activities in a Site Workflow created using Visual Studio 2010. The core activities we use here are:

  • Code Activity to execute custom code
  • While Activity to execute inner activities upon condition is true
  • IfElse Activity to execute branching activities based on condition
  • LogToHistoryList Activity to log information to Workflow internal history list

Scenario

A typical approval scenario is being addressed here. An Expenses list is given for approval. The entries having Amount lesser than 100 are Approved.

Pre-Requisites

Create a custom list named Expenses for using this example. Add some items into the new list as shown below:


Create Workflow

Open Visual Studio 2010 and create a new Sequential Workflow Project as shown below:


In the next page choose your site collection and click the Next button to continue.

In the appearing page choose Site Workflow as shown below:


In the last page choose the option to start workflow manually.

    

Now you will be getting the Workflow designer with default activity inside it.


Add Activities

Open Visual Studio Now you can drag and drop the following activities from the Toolbox:

  • 1 Code Activity
  • 1 While Activity & IfBranch Activity
  • 2 Code Activity inside If, Else branches
  • 1 LogToHistory Activity

As shown below:


Our idea is following:

  • Create property named CurrentItem of type object, Index of type integer
  • In the first Workflow Activated, fetch all the Expenses items
  • In the Code Activity initialize the Index field
  • Set While Activity condition until CurrentItem is not null
  • Set the If branch condition as Amount less than 100
  • Set the Else branch condition as Amount greater than or equal to 100
  • Set the Code Activity inside If branch, to update status as Approved
  • Set the Code Activity inside Else branch, to update status as Rejected
  • Use the LogToHistory activity for logging the workflow completion information

Create Entity, Properties & Fields

Please create the following class to hold the Expense Item, in order to give an Object Oriented Look and Feel.

    namespace ExpenseApprovalWorkflow

  {


public class ExpenseItem

{


  public int ID;


  public double Amount;

}

}

Inside the Workflow class, add the following properties and fields.

namespace ExpenseApprovalWorkflow.Workflow1

{


public sealed partial class Workflow1 : SequentialWorkflowActivity

{


List<ExpenseItem> Expenses = new List<ExpenseItem>();


int Index;


ExpenseItem CurrentItem

{


get

{


if (Index < Expenses.Count)


return Expenses[Index];


return
null;

}

}

}

}

The Expenses list holds the ExpenseItem type items. The Index property represents the current index of the item being processed.

Initiation Code

Back to the workflow designer, double click on the onWorkflowActivated step and add the following code.

private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var items = web.Lists[“Expenses”].GetItems(“ID”, “Amount”);


foreach (SPListItem item in items)

{


ExpenseItem expenseItem = new
ExpenseItem();

expenseItem.ID = (int)item[“ID”];

expenseItem.Amount = (double)item[“Amount”];

Expenses.Add(expenseItem);

}

}

}

}

The code fetches all Expenses list items from SharePoint and adds them to the Expenses field of our workflow class.

Code Activity

Double click on the Code Activity item from workflow design view (second activity). In the appearing code window enter the following code.

private void codeActivity1_ExecuteCode(object sender, EventArgs e)

{

Index = -1;

}

The code initializes the Index field to -1. This field will be incremented in the while loop later.

While Activity

Now select the While activity from the workflow design view and choose Properties window. Choose the Condition property as Code Condition and set the Inner Condition property as WhileCodeCondition.

    

The WhileCodeCondition
represents the name of the method which evaluates the While condition and returns true / false to continue / terminate the workflow.

Paste the following code in the Workflow class view.

private void WhileCodeCondition(object sender, ConditionalEventArgs e)

{

Index++;

e.Result = (CurrentItem != null);

}

You can see the method name matches the property we have specified. The method intakes the ConditionalEventArgs for specifying the condition of while activity.

IfElse Activity

You can see that there are 2 branch activities for the IfElse activity.

    

Select the first branch item and open the Properties window. Here we can specify the following properties:

  1. Condition as Declarative Rule Condition
  2. ConditionName as IfCondition
  3. Expression as this.CurrentItem.Amount < 100

You can see them in the Properties window as shown below:

    

The ellipsis button as highlighted in red color can be used to create the Expression. There is auto-completion enabled in the appearing editor dialog.


Now select the second branch item and open the Properties window. Here we can specify the following properties:

  1. Condition as Declarative Rule Condition
  2. ConditionName as ElseCondition
  3. Expression as this.CurrentItem.Amount >= 100

Now our If and Else branches are ready to proceed with their Code activities.

Code Activity for If branch

Now double click on the Code Activity for the If branch.

    

In the appearing code view, enter the following code.

private void codeActivity2_ExecuteCode(object sender, EventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var item = web.Lists[“Expenses”].GetItemById(CurrentItem.ID);

item[“Status”] = “Approved”;

item.Update();

}

}

}

The code fetches the Expense Item by ID and updates the Status as Approved.

Code Activity for Else branch

Now double click on the Code Activity for the Else branch.

    

In the appearing code view, enter the following code.

private void codeActivity3_ExecuteCode(object sender, EventArgs e)

{


using (SPSite site = SPContext.Current.Site)

{


using (SPWeb web = site.OpenWeb())

{


var item = web.Lists[“Expenses”].GetItemById(CurrentItem.ID);

item[“Status”] = “Rejected”;

item.Update();

}

}

}

The code fetches the Expense Item by ID and updates the Status as Rejected.

LogToHistoryList Activity

This activity logs information into the History List of the site. Select the activity and set the following property:

    

This list is a hidden list and is not shown in the Quick Launch or All Site Content.

To view the list you need to type the List Name in address bar. For example:

    http://SERVER/Lists/workflow%20history/AllItems.aspx

You can see various entries in the History List as shown below:

Using the History List we can verify the workflow instances being executed and their log information for troubleshooting.

Deploy the Workflow

Now we are ready to execute our workflow. Build the project, Right click on the solution and Deploy it.

Inside SharePoint

Back in SharePoint choose the Site Workflows and start our workflow.

    

Wait for a while for the execution to be completed.


Back to the Expenses list you can see the Status column being updated for the items.


You can open the Workflow History list to view the log entry as shown below:


This concludes our playing with Workflow activities.

References

http://msdn.microsoft.com/en-us/library/ms446847.aspx

Summary

In this article we have explored creating a Site Workflow using multiple activities. To summarize with following are the activities we have explored.

  • IfElse activity
  • While activity
  • Code activity
  • LogToHistoryList activity

I hope this example should provide knowledge to address complex workflow scenarios in your programming life. The source code contains the example we have discussed.

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

Three-state Workflow with Email Notification

Posted by JP on October 14, 2012

In this article we can explore the Three-state workflow of SharePoint 2010. Please note that this is an Out-of-the-box workflow also known as Built-in workflow.

image

Pre-Requisite

For viewing the email notifications generated by the workflow, you need to configure Development Machine with SMTP receiver tool.  Please view the following article to configure email.

Email

What is the purpose of Three-state workflow?

The three-state workflow can be used to track status of list items. There are 3 States involved in the whole process.  For each state change there will be Email Notification performed by this workflow.

For example, we can use this workflow to:

  1. Track Project Tasks
  2. Track Product Issues
  3. Track Reimbursement Reports

The Issue Tracking template of SharePoint is built to work with this workflow as it contains a Choice column with 3 different states.

Exploring the Workflow

For starting with create a new list using the Issue Tracking template as shown below:

clip_image002

After creating the list we need to Associate workflow with the list using List tab > Workflow Settings> Add a Workflow.

clip_image003

A wizard page will be started as shown below.

clip_image004

Select the Three-state workflow and enter a unique name for the workflow. In the bottom of the page you can see the Start Options. Check the Start this workflow when an item is created check box.

clip_image006

Click the Next button to continue.

Now you will be prompted with the second page of the Workflow as shown below:

clip_image008

Please note that the Three-state workflow requires a column with 3 states as the ‘Choice’ field. In this list the Issue Status column is selected as the ‘Choice’ field. The rest 3 drop down lists show the 3 different value selections for the Issue Status to set the Active / Resolved / Closed states.

Coming down to the page you can set Emailing options like Task Information, Email Subject and Body etc. Email Notifications are done to the involved persons.

clip_image010

Leave the default options and click the OK button.Now your workflow is ready to send email notifications on task creation.


Email Notification

For viewing the emails generated by the workflow you need to have:

· Emails Server configured in Central Administration

· E-mail Property set in User Profile

· Smtp4dev tool running

Please view the following article to configure email.

· Configuring Email for Development Server

Testing Workflow

Now let us test the workflow by creating a task. Create a Task and make sure you select a valid user having email for the Assigned To column.

clip_image012

Save the changes and you should see the smtp4dev tool caught the email as shown below.

clip_image014

You can see that the IDvalue is being highlighted. This concludes our experiment with Three-state workflow.

Editing the Workflow

We can associate multiple workflows with a list or library. To edit an existing association use the Workflow Settings > Workflow Settings menu item.

clip_image015

In the appearing page you can view the existing workflows associated and edit the settings.

clip_image017

The Workflows in Progress column displays the number of workflow instances currently active.

There are additional links to Add / Remove workflows, View workflow reports too.

Where should I apply this Workflow?

We can use this workflow for the following requirement scenarios:

· Product or Project approval process where a new product idea can be traversed through different stages of approval before acceptance.

· Issue tracking system where a customer can create an issue item, the support team updates it to resolved, Customer can change the status to Closed or Active again.

· Bug tracking system where the QA can create a task item, developer can change it to Resolved, QA can reopen it.

The effective use of Three-state workflow should decrease the delivery time for a tracking system with email notifications. We can also use custom lists with transition properties for using the Three-state workflow.

Advantage

This workflow provides a quick solution for the state tracking scenario.

image

Otherwise, the same functionality requires multiple days of development with state, email integration, deployment & management hassles.  Thanks to SharePoint as it gives us the same functionality in minutes. 🙂

References

http://tinyurl.com/sp2010-3statwf

Summary

In this article we had explored the Three-state workflow of SharePoint 2010. Following are the point’s worth to be summarized:

· Three-state workflow tracks status changes

· A Choice column is required for the list / library to use this Workflow

· Choice column requires at least 3 fields

· Issue Tracking list template is apt for this workflow

· Association of Three-state workflow with list instance is required

· Email notification is enabled for Three-state workflow

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

Version Impact on Check In & Check Out

Posted by JP on October 4, 2012

In this article we can explore the document management features Check In & Check Out with their impact on version. This document could be targeted to an Information Worker as well.

What is Check Out?

The Check Out operation creates a lock on the document preventing changes by other users. Check Out allows saving multiple time without changing the version. Other users can still access a Read-Only copy of the document.

The Version is changed as part of the Check In operation.

What is Check In?

The Check In operation releases the lock on the document. Now other user can save their changes to the document.

Version Impact

Following is the depiction of the impact on a document for Check In / Check Out operation.

image

Practice

To start with we need to create a Document Library named Version Docs.

image

We need to enable Versioning for this document library. You can do this through the Library Settings > Versioning Settings link.

image

The types of versions available are:

1. No versioning specifies versioning is not managed for this library

2. Major versions specifies whole number versions like 1, 2 and 3

3. Major & Minor Versions specifies versions like 1.0, 2.1 etc. Here the whole number on the left is called Major version and the Real number on the right is called Minor version.

A pictorial of Major & Minor parts are shown below:

image

For the time being choose Major versions (second item) and click OK button. We can see that the version number is changed during the Check In operation.

Note Please use Internet Explorer 32-bit for working with this example. The recommended MS Office version would be 2010.

Upload

Now we can perform uploading a Word Document into the library. Use the Add document link to upload a document. Make sure you have the content of the file as Initial Content.

image

After uploading the document you can view the version number using the context menu item.

image

Click on the Version History item to view the version associated.

image

You can see that the version number says as 1.0 for the newly uploaded document.

Check Out

For checking out the document choose the Check Out option from the document context menu.

image

You should be prompted with the following dialog box:

image

The dialog box asks whether to:

1. Check Out and copy the document to local folder (enables offline working)

2. Check Out and work in the Server copy of document


Click the OK button to continue with check out. Modify the file by adding some text to it as shown below.

image

You can click the Save button of MS Word Application to save the changes to your local drafts / server drafts location. These changes won’t be visible to other users reading the same document.

Local Drafts Folder

The local drafts folder is a client side folder where the checked out file is copied. Local Drafts Folder enables the user to check out the document, disconnect from the network, work offline on the document, connect back to the network, and check in the document.

You can find the Local Drafts Folder in:

OS Drive > Current User > Documents > SharePoint Drafts

For example in my Windows 7 machine the location is shown below. (Depending on the operating system the local drafts folder location changes)

image

In short the advantages of Local Drafts folder are Speed & Portability.

Check In

Now we can proceed with Check In operation. Through the check in operation the changes made to the document are saved in the Server. Any users accessing the document should receive the updated content after the Check In.

image

For checking in, choose the Check In Operation from the context menu. A dialog box will be prompted with additional options. Click the OK button in the appearing dialog box.

image

After Check In operation the Document Icon should change as:

image

from the previous icon below

image

You can verify the Version History after the Check In operation.

image

The new Version 2.0 is shown there.

Note A new version is created only when the user checks in the document. Checking out to local drafts folder makes it convenient to work on the file when your computer is away from the network.

Discard Check Out

After a Check Out operation the user can either:

· Check In the document

· Discard Check Out

The Discard Check Out operation can be done through the context menu of document item.

Possible Errors

You may encounter the following error while working with Check Out / Check In operations.

Error: The file XXX is checked out or locked for editing by YYY

In my real world experience I have seen this error occurs with many customers.

Solution

The solution which worked here is to use the Manage files which have no checked in version option from the Library Settings.

image

In the appearing page you can select the file and click the Take ownership of Selection option.
image

References

http://tinyurl.com/sp2010-docver

Summary

In this article we have explored the Version Impact on Check In, Check Out operations and viewing the Version History associated.

To summarize with, following are the points we learned:

1. Versioning of Document

2. Check Out operation

3. Check In operation

4. Local Drafts folder

5. Possible Errors & Solutions

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

Impersonation in SharePoint 2010

Posted by JP on October 2, 2012

In this article we can explore the methods of Impersonation inside SharePoint 2010.

What is Impersonation?

Impersonation is the security feature that enables to control the Identity under which code is executed. Impersonation gives the following advantages:

· Run a high privilege code through a low privilege user

· Record changes in account of another user

image

Example

A web part has to execute code that will update a List.  There are many users using this web part but they all do not have write permission on the list.  As the web part code is getting executed in the user’s context, exception occurs for some users.

Using Impersonation we can elevate the code privilege to high so that no exception occurs.

What are the Impersonation methods in SharePoint 2010?

SharePoint 2010 provides the following methods of Impersonation:

1. RunWithElevatedPrivileges to impersonate as System Account user

2. Passing User Token inside SPSite to impersonate as particular user

3. Using Windows API

Note: System Account (SHAREPOINT\system) is the application pool user of SharePoint. If you are using Developer Installations on client operating systems (Windows 7 / Vista) the account name will be different.

Now let us see how to use the above methods.

1. RunWithElevatedPrivileges

This is the most commonly used method to impersonate.

SPSecurity.RunWithElevatedPrivileges(() =>

{

// Your code here

});

Note: In the case of RunWithElevatedPrivileges the System Account is used to perform the activity.

2. Passing User Token

SPUserToken is the server model which we use for the purpose. Each user’s token can be represented by this class. The User Token is actually a byte array.

The SPUser class contains the property named UserToken. Passing SPUserToken instance into the SPSite constructor impersonates the particular user.

Eg: new SPSite(UrlText.Text, user.UserToken);

For enumerating all the users of a site the web.Users property can be used.

Eg: web.Users


Running the Code

The attached source contains the following samples:

1. Enumerate Users

For enumerating users for given website the following code can be used:

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPContext context = SPContext.GetContext(web);

var users = context.Web.Users;

// Display to grid

usersGrid.DataSource = users.Cast<SPUser>().ToList<SPUser>();

}

}

On clicking the button we can see the following users as shown below:

– Please note that there are only 2 users for the site I use

– The current user logged in is Admin

image

2. Create Data Impersonating each User

Now we can try creating list items impersonating each user. The created item will be having the system property > Created By set to different users:

Following code performs the same:

int count = 1;

foreach (SPUser user in web.Users)

{

SPSite newSite = new SPSite(UrlText.Text, user.UserToken); // Impersonate

SPWeb newWeb = newSite.OpenWeb();

SPListItem item = newWeb.Lists[ListName].AddItem();

item[“Title”] = “Item ” + count++.ToString();

item.Update();

newSite.Dispose();

newWeb.Dispose();

}

On running the code above we can see the items created as shown below:

– Please note that the Created By property is different for each row

image

Note: An exception will be thrown if any of the user above do not have write permission.

3. Create Data using RunWithElevatedPrivileges

Now we can try creating the list items using RunWithElevatedPrivileges block. In this case the user is impersonated to System Account.

The code for the same is shown below:

SPSecurity.RunWithElevatedPrivileges(() =>

{

using (SPSite site = new SPSite(UrlText.Text))

{

using (SPWeb web = site.OpenWeb())

{

SPListItem item = web.Lists[ListName].AddItem();

item[“Title”] = “Item created with RunWithElevatedPriveleges”;

item.Update(); // Item will be created with System Account

ShowData(web);

}

}

});

We can see that the new item is created with System Account as shown below:

image

References

http://msdn.microsoft.com/en-us/library/aa543158.aspx

Summary

In this article we have explored 2 methods of Impersonation in SharePoint 2010. The associated code contains the example we have discussed.

Posted in C#, SharePoint | Tagged: , , , | 5 Comments »

Error Scenario – Workflow History list not found!

Posted by JP on October 2, 2012

In this article we can explore a common scenario associated with creating Workflows in Visual Studio 2010.

Scenario

You are creating a workflow through Visual Studio 2010. The SharePoint 2010 templates are installed and while selecting Workflow template and entering site url you receive the following error:

The SharePoint site at URL is missing a target, task, or history list. Each of these lists is required to associate a workflow template. Please create a list and then launch this wizard.

clip_image001[5]

Root Cause

Workflow requires the following lists for its working:

· Workflow History of Template 140

· Workflow Tasks of Template 107

Solution

There are many solutions to the above problem like:

1. Create a new site from a site template that includes Workflow History & Task list

2. Create the 2 lists Programmatically

3. Create the 2 lists using PowerShell

Here I would apply the second solution, using C# code to create the 2 lists.

 

Implementation

Create a new SharePoint Console Application and change the project properties as:

· Target Framework to 3.5

Add the following code to the Main() method. Please change your url accordingly.

class Program

{

private static string URL = “http://yourblanksite&#8221;;

static void Main(string[] args)

{

using (SPSite site = new SPSite(URL))

{

using (SPWeb web = site.OpenWeb())

{

web.Lists.Add(“Workflow History”, string.Empty, SPListTemplateType.WorkflowHistory);

web.Lists.Add(“Workflow Task”, string.Empty, SPListTemplateType.Tasks);

}

}

}

}

Execute the above code and if it completed without errors, your problem is solved. Try creating the workflow again and you should not see the error.

Verification

Inside SharePoint you can verify our new lists as shown below.

clip_image003[6]

Template Enumeration Reference

You can refer the Template Enumeration (SPListTemplateType) here.

Name Description
InvalidType Not used. Value = -1.
NoListTemplate unspecified list type. Value = 0
GenericList Custom list. Value = 100.
DocumentLibrary Document library. Value = 101.
Survey Survey. Value = 102.
Links Links. Value = 103.
Announcements Announcements. Value = 104.
Contacts Contacts. Value = 105.
Events Calendar. Value = 106.
Tasks Tasks. Value = 107.
DiscussionBoard Discussion board. Value = 108.
PictureLibrary Picture library. Value = 109.
DataSources Data sources for a site. Value = 110.
WebTemplateCatalog Site template gallery. Value = 111.
UserInformation User Information. Value = 112.
WebPartCatalog Web Part gallery. Value = 113.
ListTemplateCatalog List Template gallery. Value = 114.
XMLForm XML Form library. Value = 115.
MasterPageCatalog Master Page gallery. Value = 116.
NoCodeWorkflows No Code Workflows. Value = 117.
WorkflowProcess Custom Workflow Process. Value = 118.
WebPageLibrary Wiki Page Library. Value = 119.
CustomGrid Custom grid for a list. Value = 120.
SolutionCatalog Solutions. Value = 121
NoCodePublic No Code Public Workflow. Value = 122
ThemeCatalog Themes. Value = 123
DataConnectionLibrary Data connection library for sharing information about external data connections. Value = 130.
WorkflowHistory Workflow History. Value = 140.
GanttTasks Project Tasks. Value = 150.
Meetings Meeting Series (Meeting). Value = 200.
Agenda Agenda (Meeting). Value = 201.
MeetingUser Attendees (Meeting). Value = 202.
Decision Decisions (Meeting). Value = 204.
MeetingObjective Objectives (Meeting). Value = 207.
TextBox Text Box (Meeting). Value = 210.
ThingsToBring Things To Bring (Meeting). Value = 211.
HomePageLibrary Workspace Pages (Meeting). Value = 212.
Posts Posts (Blog). Value = 301.
Comments Comments (Blog). Value = 302.
Categories Categories (Blog). Value = 303.
Facility Facility. Value = 402
Whereabouts Whereabouts. Value = 403
CallTrack Call Track. Value = 404
Circulation Circulation. Value = 405
Timecard Timecard. Value = 420
Holidays Holidays. Value = 421
IMEDic IME (Input Method Editor) Dictionary. Value = 499
ExternalList External. Value = 600
IssueTracking Issue tracking. Value = 1100.
AdminTasks Administrator Tasks. Value = 1200.
HealthRules Health Rules. Value = 1220
HealthReports Health Reports. Value = 1221

The link is added in the References section too.

References

http://tinyurl.com/sp2010-lsttmpref

Summary

In this article we have explored a common error scenario associated with workflow creation and a solution for it.

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

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.

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

CAML Query Builder

Posted by JP 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 JP 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 JP 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 »