Monday 19 December 2011

SharePoint CAML Tutorial

The CAML language has been associated with SharePoint since the first version, SharePoint 2001, and SharePoint Team Services. It is based on a defined Extensible Markup Language (XML) document that will help you perform a data manipulation task in SharePoint. It is easy to relate a list to CAML if you compare it to a database table and query. When querying a database, you could get all of the records back from the table and then find the one that you want, or you can use a Structured Query Language (SQL) query to narrow the results to just the records in which you are interested. CAML helps you to do just this.

A CAML query must be a well-formed XML document that is composed of the following elements:

<Query>

<Where><!--Comparison Operators here-->

<Eq>

<FieldRef Name=”insertFieldNameHere” />

<Value Type=”insertDataTypeHere”>insertValueHere</Value>

</Eq>

</Where>

<OrderBy>

<FieldRef Name=”insertFieldNameHere” />

<FieldRef Name=”insertFieldNameHere” />

</OrderBy>

</Query>


 

This simple CAML query definition defines a filter where a field equals a specified value using the Eq element. In addition, one or many FieldRef elements can be specified inside
the OrderBy element to sort by one or many columns.

You must supply all of these elements with a FieldRef child element. The FieldRef element specifies the SharePoint-specific name of the column that is being evaluated. In addition, almost all of the query elements (with the exception of IsNotNull and IsNull) require that you also specify a Value child element. This is where you will specify what value to evaluate the specified FieldRef element against.

Unfortunately, SharePoint doesn’t always intuitively name each of the FieldRefs that you need to reference. The following code is an example that you can use to extract the FieldRef name from a list by using a console application and the Microsoft Office SharePoint Server 2007 application programming interface (API):

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

namespace SharePointUtils

{

class Program

{

static void Main(string[] args)

{

string siteUrl = args[0];

string listName = args[1];

string viewName = args[2];

SPSite site = new SPSite(siteUrl);

SPWeb web = site.OpenWeb();

SPList employeesList = web.Lists[listName];

SPQuery query = new SPQuery(employeesList.Views[viewName]);

System.Diagnostics.Debug.WriteLine(query.ViewXml);

Console.WriteLine(query.ViewXml);

Console.ReadLine();

}

}

}


 

The code is very simple and the output is very usable when you start writing CAML queries. Three arguments are required for the site uniform resource locator (URL), list name, and view name, respectively. Objects are created for the site, the web, and the list. Notice that an instance of SPQuery is also created. The SPQuery object is used to get the SharePoint-specific field names (or FieldRefs) from the view.

This code will help you to identify FieldRefs of the specified list. After you have identified the FieldRefs that you want to filter your query by, actually querying a list is quite simple. Taking into account the Employees list, you might want to create a query that displays all employees with a start date before January 1, 2003. The following is an example of a CAML query that will filter records by those with a start date beginning before January 1, 2003:

<Query>

<OrderBy>

<FieldRef Name=”Title” />

</OrderBy><Where>

<Lt>

<FieldRef Name=”Start_x0020_Date” />

<Value Type=”DateTime”>2003-01-01T00:00:00Z</Value>

</Lt></Where>

</Query>


This query does two things. First, it specifies how the data is sorted when values are returned by using the OrderBy element. Notice that the results will be ordered by Title, which is actually the Employee Name field. Next, a Where element is defined that will specify the filter, which is similar in functionality to a SQL WHERE clause. The Where element defines an Lt (less than element), which contains a FieldRef element and a Value element. The FieldRef element is the column in the list and the Value element represents the data type and value that is being compared.

The following is a code excerpt that will execute the CAML query defined previously:

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

namespace SharePointUtils

{

class CAMLQuery

{

static void Main(string[] args)

{

string siteName = args[0];

string listName = args[1];

string viewName = args[1];

SPSite site = new SPSite(siteName);

SPWeb web = site.OpenWeb();

SPList employeesList = web.Lists[listName];

SPQuery query = new SPQuery(employeesList.Views[viewName]);

query.Query = “<Query><OrderBy><FieldRef Name=\”Title\”/></OrderBy><Where><Lt><FieldRef name=\”Start_x0020_Date\” /><Value Type=\”DateTime\”>2003-01-01T00:00:00Z</Value></Lt></Where></Query>”;

SPListItemCollection filteredEmployees = employeesList.GetItems(query);

foreach (SPListItem i in filteredEmployees)

{

System.Diagnostics.Debug.WriteLine(i[“Title”].ToString() + “ “ + i[“Salary”].ToString() + “ “ + i[“Start_x0020_Date”].ToString());

}

Console.ReadLine();

}

}

}


The code to perform the query is identical to the first code example in the chapter with the exception of setting the Query property of the SPQuery object named query. This is
where you set the value of the CAML query that will be used to filter the data. The results are returned by using the GetItems method of the SPList object and an instance of the
SPListItemCollection class. This collection is then iterated and the values are output to the debug window. The following is an example of the results that are returned by the CAML query:
Brandon Bobb 62000 12/1/2001 12:00:00 AMRob

Foster 110000 1/1/1999 12:00:00 AM

Stephen Baron 79000 1/25/2002 12:00:00 AM

 

Though the number of records in the list is limited, the results are filtered to three records. Now what if you want to filter the list further? CAML has And and Or elements that can be used in conjunction with the Where element. The following is an example of a CAML query that filters by start dates before January 1, 2003 AND salaries lower than $80,000:

<Query>

<OrderBy>

<FieldRef Name=”Title” />

</OrderBy><Where><And><Lt>

<FieldRef Name=”Start_x0020_Date” />

<Value Type=”DateTime”>2003-01-01T00:00:00Z</Value>

</Lt><Lt><FieldRef Name=”Salary” />

<Value Type=”Currency”>80000</Value></Lt>

</And></Where></Query>


 

Naturally, this filters the sample list data to the following two records:
Brandon Bobb 62000 12/1/2001 12:00:00 AM

Stephen Baron 79000 1/25/2002 12:00:00 AM

 

As you can see in this tutorial, CAML queries are very easy to construct and execute.

Use Form Templates of InfoPath Forms Services in SharePoint 2010 Web Application

how to develop and deploy Form Templates for InfoPath Forms Services inside PS 2010 and applying some code behind using PSI to get Projects List as example. let's start :)
1- follow this article to develop and deploy your InfoPath Form (with code behind or not)
2- After you deploy your InfoPath form, you should see this screen form Central Administration -> General Application Settings -> Manage Form Templates
(then install it and you can enable it from your Site Collection Features as well)

3- So, you need to create new Form Library that will use InfoPath Form Template:

4- From Library Settings, Advanced Settings, Set Allow management of content types equal True

5- then add your Forms Services to form content and make it the default - Add Content Type and select your InfoPath Form Template:

6- Finally, you have a form library of content InfoPath Forms Services:

 

Sharepoint 2010, Claims Authentication, Developing Custom Login Form

For our login form, we’re going to develop a custom web part that we can then include on whatever page is appropriate. In Part 2, we set up a url for the custom login form. You will need to create a page at the url that you specified that has this custom login form web part on it.

To create the web part, open Visual Studio and add a new web part to your project. We’ll call the web part LoginForm. In the LoginFormUserControl, you’ll want to have something like the following to accept the username and password:

<table class="tbldetails">

    <tr>

        <td class="tddetails">

            <span class="mandatory">*</span><span class="spfields">Username:</span>

        </td>

        <td>

            <asp:TextBox runat="server" ID="Username" CssClass="required textbox" />

        </td>

    </tr>

    <tr>

        <td>

            <span class="mandatory">*</span><span class="spfields">Password:</span>

        </td>

        <td>

            <asp:TextBox runat="server" ID="Password" TextMode="Password" CssClass="required textbox" />

        </td>

    </tr>

    <tr>

        <td colspan="2">

            <asp:Button ID="Login" CssClass="btnLogin" Text="Login Now"

                runat="server" onclick="Login_Click" />

        </td>

    </tr>

</table>


In the code behind of the user control, you’ll want to have something like this:

protected void Login_Click(object sender, EventArgs e)

{

    if (Membership.ValidateUser(Username.Text, Password.Text))

    {

        SecurityToken tk = SPSecurityContext.SecurityTokenForFormsAuthentication(

            new Uri(SPContext.Current.Web.Url), "ADProvider", null,

            Username.Text, Password.Text);

        if (tk != null)

        {

            SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;

            fam.SetPrincipalAndWriteSessionToken(tk);


            //look for the Source query string parameter and use that as the redirection

            string src = page.Request.QueryString["Source"];

            if (!string.IsNullOrEmpty(src))

            {

                Response.Redirect(src, false);

            }

            else

            {

                Response.Redirect("/", false);

            }

        }

    }

}


The code is easy – getting it to compile is slightly more difficult. Finding the namespaces (and the dll’s that contain them) for some of these classes proved to be difficult.

  • SecurityToken is in the System.Security.IdentityModel.Tokens namespace.

  • SPSecurityContext is in the Microsoft.Sharepoint namespace.

  • SPFederationAuthenticationModule is in the Microsoft.Sharepoint.IdentityModel namespace.


The Microsoft.IdentityModel and Microsoft.Sharepoint.IdentityModel dll’s can be found here:

  • C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll

  • C:\Windows\assembly\GAC_MSIL\Microsoft.IdentityModel\3.5.0.0__31bf3856ad364e35\Microsoft.IdentityModel.dll


Once you have you web part in place (and compiling), add it to a login page, deploy it to Sharepoint, and you’re done.

One or more field types are not installed properly, SharePoint 2010 Upgrade

Whilst working on a recently upgraded SharePoint 2010 site (database attach upgrade) I attempted to modify an existing web part. As soon as the page went into edit mode I was presented with the following SharePoint error: “One or more field types are not installed properly. Go to the list settings page to delete these fields.”

This appears to be a random bug which seems to occur with some sites after they have been upgraded and is related to a list called ‘Relationships List’.

To fix this de-activate the SharePoint Server Publishing Infrastructure Feature in the sites settings, delete the Relationships List and re-activate the feature.

Forms Based Authentication (FBA) Tips in SharePoint 2010

Recently with a client that had enabled FBA for SharePoint 2010 and was having issues getting the User’s information due to the format and problems with connecting SharePoint user to Membership Provider user. After a bit of checking, turns out they had a) not understood the format of the user name being returned and b) didn’t know about naming in FBA.

First off is the format of the name – when pulled from either the Membership Provider or SharePoint, the format is something like: i:0#.f|MyFBA|MyLogin – for the translation:

i:0#.f = A placeholder (seems to be always 0)
MyFBA = the name of the provider
MyLogin = the actual login name of the user

Second was the naming of the provider itself – as it turns out, they had used two different names when they created the Membership Provider and the name they gave it in SharePoint and SharePoint’s web.config.

When accessing SharePoint (the SPUser object), the name SharePoint will return is in the provider format of : i0#.f|membership provider name from the web.config|user login – the provider name in this case is the name supplied when the site is created.

However my client had used a different name when creating the provider using the ASP tool – thus when returning the User from the Membership provider, the format is the same but the name is different: i0#.f|membership provider name ASP configuration|user login. This of course, makes comparison a bit difficult as you may imagine.

The problem is that once this is set up, the only way to change it is via Central Administration – Web Applications – Manage Web Applications. Click to select the site,  select it, then click Authentication Providers in the ribbon. From the pop-up, select the Default link, and then from there you can change the names.

HOWEVER BE FOREWARNED – if you change the name of the provider, it will mess up the users in SharePoint internally (those already created have the original provider name); this means you have to delete ALL USERS from SharePoint and add them back – not for the faint of heart.

For code, the following routines should help you.

To get the SharePoint User:

public SPUser ReturnCurrentSPUser()
{
SPWeb site = SPContext.Current.Web;
SPUser currUser = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite ElevatedsiteColl = new SPSite(site.Site.ID))
{
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
{
currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
}
}
});
return currUser;
}


To get the “real” login name from the Membership Provider:

public string ReturnCurrentUserLogin()
{
string LoginName = "";
SPClaimProviderManager ClaimManager = SPClaimProviderManager.Local;
if (ClaimManager != null)
{
try
{
LoginName = ClaimManager.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value;
}
catch (Exception NotMembershipUser)
{
string WhyErr = NotMembershipUser.Message.ToString();
LoginName = "";
}
}
return LoginName;
}


To get the “Formated” User Name:

public string ReturnCurrentUserClaimLogin(string UserLoginName, string ProviderName)
{
string userName = null;
SPClaimProviderManager ClaimManager = SPClaimProviderManager.Local;
if (ClaimManager != null)
{
try
{
SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, UserLoginName, "http://www.w3.org/2001/XMLSchema#string", SPOriginalIssuers.Format(SPOriginalIssuerType.Forms, ProviderName));
userName = ClaimManager.EncodeClaim(claim);
}
catch (Exception NotMembershipUser)
{
string WhyErr = NotMembershipUser.Message.ToString();
userName = "";
}
}
return userName;
}



Customizing the global navigation with Css and jQuery in SharePoint 2010

The global navigation in SharePoint is an important factor for the SharePoint site, this navigation are there to help orient users so they easily can move around the site. So when it comes to branding and customizing a SharePoint site it´s one of the key factors. When you branding the global navigation don´t forget to think simple but attractive, users may use the site navigation more than they use the search to find information.

In SharePoint 2010 the global navigation renders with unordered lists and list items (UL and LI), which gives us a simpler and more standard way for customization, especially compared to previous versions of SharePoint when the navigation rendered in a nestled table markup. There are a couple of ways and tools when it comes to build a custom navigation in SharePoint. The central point for the navigation is the functionality and the look and feel that means that we have to deal with CSS 2.1 or 3.0 and the SharePoint ASP menu control and its data source.


Global navigation

Global navigation




An example of a customized SharePoint OTB menu with use of CSS and jQuery. Check the nextcomming post (Part II) of how to extend the navigation with jQuery.

The options we have depend of the needs, but also the approach you choose depends if we talking about a public faced web site or an Intranet.

  • Use the OTB control with changed settings

  • Extend the OTB menu control with custom Css 2.1 or 3.0

  • Extend the OTB menu control and hook it up with custom jQuery

  • Extend the OTB menu control with a custom site map provider

  • Code a new navigation control, and use a technique like Silverlight

  • Use a complete stand-alone navigation with jQuery that isn’t connected to SharePoint


There is a lot to think about when it comes to customization of the SharePoint global navigation so therefore I´ll split this article in the minimum of three articles. So here´s the plan:

  1. Introduction and How to customize the global navigation with CSS 2.1 and 3.0 (this post)

  2. How to customize the global navigation with custom CSS and how to use jQuery to work with feeling of the navigation, like animating a menu. Go there

  3. Tips and tricks about navigation settings, how to use different site map providers & multiple navigation providers, branding dropdown menus and more.



Below is a bunch of examples for customized navigation menus I have created specific for the article series. Of course, no guaranties for real cross browser CSS; these examples are mostly verified in IE 8 and Firefox 3.6.12, GC and Safari.







Open up your SharePoint top site with your favorite tool SharePoint Designer 2010 and create a CSS file and put in a reference to this in a your (custom) master page. Put in the following line just below SharePoint:CSSlink tag in the master page.










<SharePoint:CssRegistration name="/Style Library/Blog/Blue.css" runat="server" After="corev4.css"/>




First off, a clean blue navigation with a smooth gradient background color. It has four properties for the background selectors and that´s because this is for various browsers. There are also a couple of extra classes below ‘Other stuff’ that you don´t need specific for the navigation. You can take those away if you prefer.



/*---| By @Cstahl 2010 |---*/
.s4-lp, body #s4-topheader2{
background-color:#2d9cc7; /*Fallback*/
background: -webkit-gradient(linear, left top, left bottom, from(#2d9cc7), to(#157db2));
background: -moz-linear-gradient(top, #2d9cc7, #157db2);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#2d9cc7, endColorstr=#157db2);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#2d9cc7, endColorstr=#157db2)";
margin-left:0px;
border-top:0px;
border-bottom:0px;
margin-left:0px;
}
.menu-horizontal{
margin-left:10px;
border-right: 1px #167FB3 solid;
background-image:none;
}
.menu-horizontal ul li{
color:#fff!important;
min-height:31px;
line-height:30px;
border:0px;
padding:0px;
margin:0px;
border-left:1px #167FB3 solid;
}
.menu-horizontal ul li a{
color:#fff!important;
font-weight:bold;
border:0px!important;
padding:0px!important;
margin:0px;
height:31px!important;
background-color:#2d9cc7; /*Fallback*/
background: -webkit-gradient(linear, left top, left bottom, from(#2d9cc7), to(#157db2));
background: -moz-linear-gradient(top, #2d9cc7, #157db2);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#2d9cc7, endColorstr=#157db2);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#2d9cc7, endColorstr=#157db2)";
padding-right:20px!important;
padding-left:20px!important;
}
.s4-toplinks .s4-tn > .menu-horizontal ul li a:hover {
text-decoration:none!important;
/*if use 333 the DD color will not work*/
color:#333!important;
background-color:#036ba8; /*Fallback*/
background: -webkit-gradient(linear, left top, left bottom, from(#036ba8), to(#4fb3d3));
background: -moz-linear-gradient(top, #036ba8, #4fb3d3);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#036ba8, endColorstr=#4fb3d3);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#036ba8, endColorstr=#4fb3d3)";
height:31px!important;
border:0px;
padding:0px;
margin:0px;
}
.s4-toplinks .s4-tn > .menu-horizontal a.selected {
color: #fff!important;
background-color:#4fb3d3; /*Fallback*/
background: -webkit-gradient(linear, left top, left bottom, from(#4fb3d3), to(#036ba8));
background: -moz-linear-gradient(top, #4fb3d3, #036ba8);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#4fb3d3, endColorstr=#036ba8);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4fb3d3, endColorstr=#036caa)";
line-height:30px;
height:31px;
border:0px;
padding:0px;
margin:0px;
}
.menu-horizontal A.dynamic-children SPAN.additional-background {
background-image:none!important;
}
.s4-tn ul.dynamic {
background-image:none!important;
border:1px solid #f7f7f7;
border-top:0px;
border-bottom:1px solid #ccc;
margin:0px;
padding:0px;
}
.s4-tn li.dynamic {
background-image:none!important;
border-top:1px solid #ccc;
border-right:1px solid #ccc;
border-bottom:0px solid #ccc;
border-left:1px solid #ccc;
}
.s4-tn li.dynamic > .menu-item {
display:block;
padding-left:19px!important;
white-space:nowrap;
font-weight:normal;
background-color:#ffffff!important;
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f7f7f7))!important;
background: -moz-linear-gradient(top, #ffffff, #f7f7f7)!important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff, endColorstr=#f7f7f7)!important;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff, endColorstr=#f7f7f7)"!important;
color:#333!important;
}
.s4-tn li.dynamic > a:hover {
background-color:#ffffff;
background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#ffffff))!important;
background: -moz-linear-gradient(top, #ffffff, #ffffff)!important;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff, endColorstr=#ffffff)!important;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffff, endColorstr=#ffffff)"!important;
color: green!important;
}
/*----- Some other stuff -------*/
.col-fluid-1, .right-wp-zone-col {
margin-top:20px
}
#s4-leftpanel-content {
padding-top:20px!important;
border-right:0px!important;
border-bottom:0px!important;
margin-right:0px;
margin-left:0px;
background-color:#f7f7f7!important
}
.s4-title{
min-height:70px;
padding:0px;
}
.s4-titlelogo{
padding-left:10px
}
TD.ms-sbscopes {
padding-right:0px
}
.s4-search, .s4-rp{
padding-top:3px!important;
margin-right:0px;
}
.s4-search TABLE {
margin-right:0px
}
.s4-title-inner{
background-color:#a0d9e6; /*Fallback*/
background: -webkit-gradient(linear, left top, left bottom, from(#a0d9e6), to(#f7f7f7));
background: -moz-linear-gradient(top, #a0d9e6, #f7f7f7);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#a0d9e6, endColorstr=#f7f7f7);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#a0d9e6, endColorstr=#f7f7f7)";
padding:0px 0px 0px 0px;
margin:0px;
min-height:70px;
}

Next: A tabbed navigation with use of three images. In the next post I will show you have to interact with the tabs to make them jump on hover.
Want to try the tabbed navigation?



/*---| By @Cstahl 2010 |---*/
.menu-horizontal{
margin-left:5px;
}
.menu-horizontal A.dynamic-children SPAN.additional-background {
background-image:none;
}
.menu-horizontal ul li{
text-align:center;
font-size:11px;
line-height:18px;
padding:0;
margin:0;
}
.menu-horizontal ul li a{
width:105px;
background-image:url('/Style Library/Blog/Images/tab.png');
background-position: 0 0;
background-repeat:no-repeat;
padding:0;
cursor:pointer;
color:#0a7285;
text-decoration:none;
}
.menu-horizontal ul li.active{
width:105px;
height:18px;
margin:0;
}
.menu-horizontal ul li.active a{
background-image:url('/Style%20Library/Blog/Images/TabActive.gif');
background-position: 0 0;
background-repeat:no-repeat;
color:#0a7285;
width:105px;
height:18px;
padding-top:8px;
}
.menu-horizontal ul li a:hover{
background-image:url('/Style%20Library/Blog/Images/TabActiveHover.gif');
background-position: 0 0;
background-repeat:no-repeat;
width:105px;
}
.s4-toplinks .s4-tn a.selected{
border-style: none;
border-color: inherit;
border-width: 0px;
background-image:url('/Style%20Library/Blog/Images/TabActive.gif');
background-position: 0 0;
background-repeat:no-repeat;
background-color: transparent;
width:118px;
height:16px;
color:#333;
margin-top:1px;
margin-right:1px;
margin-bottom:0px;
margin-left:1px;
}
.s4-tn ul.dynamic{
background-color:#f7f7f7!important;
border:1px solid #ccc;
border-top:0px;
margin-left:2px;
}
.s4-tn li.dynamic > .menu-item{
display:block;
padding:5px 10px;
white-space:nowrap;
font-weight:normal;
background-image:none;
text-align:left
}
.s4-tn li.dynamic > a:hover{
font-weight:normal;
background-color:#9FD8E6;
background-image:none;
}
/*----- Other stuff -------*/
.col-fluid-1, .right-wp-zone-col {
margin-top:20px
}
#s4-leftpanel-content {
padding-top:20px!important;
border-right:0px!important;
border-bottom:0px!important;
margin-right:0px;
margin-left:6px;
background-color:#f7f7f7!important
}
.s4-titlelogo{
padding-left:10px
}
.s4-title{
padding-left:0px;
}
TD.ms-sbscopes {
padding-right:0px
}
.s4-search, .s4-rp{
padding-top:2px!important;
margin-right:0px;
}
.s4-search TABLE {
margin-right:0px
}
.s4-title-inner{
background: -webkit-gradient(linear, left top, left bottom, from(#a0d9e6), to(#7ec1d0));
background: -moz-linear-gradient(top, #f7f7f7, #7ec1d0);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#a0d9e6, endColorstr=#7ec1d0);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#a0d9e6, endColorstr=#7ec1d0)";
padding:0px 0px 0px 0px;
margin:0px;
min-height:100px;
}
.s4-lp, body #s4-topheader2{
background-color:#7ec1d0;
margin-left:0px;
border-top:0px;
border-bottom:0px;
}

Scroll any sharepoint list in web part

All you need is a SharePoint web site, a list and a SharePoint designer!the process is really quick and simple - believe me, it will take much less time to do it, then it took me to prep it :)

Step One: take a list, any list (in fact any web part or other content)

links list

Step Two: prepare a site page on which you'll have the list displayed

press "Edit Page" > "Insert" > "Existing List" and select your list

site page?

Step Three: Adjust list web part appearence

select wanted view, disable list toolbar, remove web part frame..

prepare the list visual appearence

list properties

 

Step Four: Open SharePoint Designer

open the site, which contains your page and edit it

edit page

 

Step Five: Find list's web part in code view

code view

Step Six: Add marquee object

in a brief: html marquee object let's you scroll it's content on a web page.

Main attributes:

now you need to "wrap" the list's web part with the marquee element, so:

 

marquee

save the page and you're all done, let it scroll !!!

 

scrolling

it's hard to show scrolling content with an image - so you'll just have to take my word on it

Enjoy

Select XML Nodes by Name in C#

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

Suppose we have this XML file.

[XML]
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>

To get all <Name> nodes use XPath expression /Names/Name. The first slash means that the <Names> node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the <Name> nodes. To get value of sub node <FirstName> you can simply index XmlNode with the node name: xmlNode["FirstName"].InnerText. See the example below.

[C#]
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

The output is:
Name: John Smith
Name: James White

Using Document Templates with Lists and Content Types in SharePoint

While the concept of document templates has been in SharePoint for a very long time, and content types since SharePoint 2007, I often find that many organizations don’t take complete advantage of their power, or don’t use them at all. In many cases, this is because they are unaware of how to properly do so.

This post is an attempt at demonstrating how templates can work with both libraries and document templates, taking full advantage of the metadata contained within SharePoint in the document. It will also describe an approach that we use to help with their maintenance.

I have described 3 walkthrough scenarios, each complete in its own right, but when taken together form a comprehensive template management strategy. These 3 scenarios are:


  1. Using a Library Template

  2. Using a Content Type Template

  3. Use A Library to Manage Your Document Templates



All of the examples here are shown using the 2010 suite of tools (Office 2010, SharePoint 2010). However, almost all of this capability is available in the 2007 family of products. Some of the menu locations are different with 2007 (Particularly with Word) , but the capabilities are there.

A – Using a Library Template


The simplest way of working with templates is to modify the default template for a document library. In the example below, we’ll create a new library, create metadata, display and use the metadata, and finally, create a new document based on this template. Several of the steps used in this example will be used in the other examples.

1. Create a new Document library


From your destination site, click either “Libraries” or “All site content” from the Quick Action pane on the left (note – the menu options that appear will vary according to the site template used, and the options that have been chosen by the site administrator). If neither option is available, select “Site Actions” then View All Site Content”.

Finally, from the resultant dialog, select “Document Library”, give the new library a name, and click the “Create” button. In this case, we’ll use “Letters”.

image

2. Add metadata to the library


Now we need to add some metadata to this library. When the Library is first created, the Library ribbon tab will be open. From there click the “Library Settings” button.

image

On the following screen, in the columns section, select “Create Column” (or add from existing site columns, and add the metadata fields that you want to use with this library. In this case, we’ll add a few (pretty boring) fields that you might want to use when tracking letters.

Side note – as a best practice, I try to never use spaces in the names when creating fields, lists, sites, etc. When spaces are used, SharePoint converts these spaces to _x0020_ in the internal field names. Once the field is created, the name can be changed, and that will only affect the display name, not the internal field name.

image

3. Edit the default template


Once we have our metadata fields in place, it is time to edit the default template. This example is using a word template, but the same approach works for other Office content (Excel, Powerpoint, etc).

Without leaving the list settings screen, select Advanced Settings (in the General Settings section).

image

On the next screen, there is a section for the library’s document template.  in that section, select the “(Edit Template)” link. Word should open (you may be prompted for credentials) and then you will be editing the library template.

4. Show the Document Information Panel


Since we want to incorporate the document metadata into the body of the document, we will want to use the document information panel. The document information panel will show the user editable metadata for a document. When the document is stored in a SharePoint library, or is a template for one, you can also expose the metadata from the library itself (or from a content type….more on that later). The nice part is that it can be displayed right at the top of the document, so if the properties are used throughout the document, you only need to edit them in one place. Unfortunately, it is turned off by default, and it really has to be one of the best hidden features in Word 2010. It was hard enough to find in 2007 – you had to add the developer tab to your ribbon, and then select “show information panel” there. In 2010, it’s hidden in the backstage.

Click File, and then click on the info tab. To the right of the screen you’ll see the section for properties. You might think that “Show All Properties” at the bottom would do it, but no. You need to hover your mouse over the “Properties” title, and select the dropdown arrow. You will be rewarded with two options, and  we want the first one, “Show Document Panel.

image

The good part is, you only need to set it once, and it sticks. If you’re setting it for a template, it’ll stick there too. Once selected, you will be returned to the document and the document information panel will be displayed.

SNAGHTML1bbdb5c8

You should see all of the metadata fields that you created for the list, in their proper column order, using the appropriate controls for their data type. Any metadata changes made in SharePoint will be reflected here, and conversely, SharePoint will be updated with any of the changes entered here. This is helpful, but it’s really powerful when you use the metadata to help form the document.

5. Quick Parts – Put the Metadata to work


To use a metadata field in the document, position your cursor where you would like the field to be displayed (or edited), click the “Insert” ribbon tab, select the “Quick Parts” button, select “Document Property” from the dropdown, and finally select the field that you want to use.

image

Repeat the procedure for each field that you want to use. When finished, your document will look something like the following:

SNAGHTML1bcd54d5

Finally, Save your template, and exit Word. You’re pretty much done.

6. Test the Template


After you close Word, you should be returned to your library. To test your template, you’ll want to try creating a new document. Go ahead and do so – click on the Documents tab in the toolbar, and the click on the new document button.

image

Go ahead and enter in the metadata values. Notice how the document updates as you do so. When complete, your document should look something like the image below:

SNAGHTML1cd0018d

Finally, save the document, and exit Word (or just exit). You’ll likely be prompted for a name – give it one. After Word closes refresh the library view, and you should see your document, with all of the relevant metadata in the library view.

image

B – Using A Content Type Template


Modifying a library template is relatively straightforward, but it does entail several limitations. Firstly, by using library defined metadata (and template) you are limiting yourself to only that library. Neither these fields nor this template can be used elsewhere in the site or site collection. In addition, all of the documents in the library must use this metadata definition.

In order to move beyond this limitation, SharePoint 2007 introduced the concept of Content Types. A detailed discussion of content types is beyond the scope of this article, but simply put, a content type is a collection of metadata fields that can be applied to a document. A content type is loosely analogous to a class in object oriented programming.

Luckily, content types contain not only metadata, but also documents. That means that we can define a content type in a similar fashion to the way we modified a list in the example above, but we can then take that content type and apply it to any library in the site collection. With the content type syndication features available in SharePoint 2010, we can apply it to any library in our organization (it’s no longer limited to even the farm). In addition, by using content types, any given library is no longer limited to a single set of metadata fields.

The process for creating a content type template is similar to creating a library template, but there are a few important differences. Where identical, I will reference the library template procedure.

1. Create The Content Type


Content types can be created at the site level or the site collection level. They will be available to their containing site and all sites below. If the content type is created at the root of the site collection, it will be available to the entire site collection.

To do this, navigate to the root site and select “Site Actions”  and then Site Settings

image

You will then be presented with the Site Settings page. The Content types are stored in the Content Type Gallery, so next we will select “Site Content Types”.

image

We are going to create the “Letter” Content Type, so go ahead and click the “Create” button. You will then be taken to the Content type creation screen. This is similar to creating the new list as we did in the example above, but this time, there are additional options that control how the content type works.

image

We’ll be calling this content Type Letter, and it will inherit all of the properties (things like Name, and title) from the “Document” content type, which is in the “Document Content Types” category. Finally, we’ll want to group all of our content types in the same group, and since we don’t already have one, we’ll create the “My Custom Types” group.

Once created, we can add all of our custom fields to the content type. We’ll use the same fields that we did in the example above.

2. Add Metadata to the Content Type


Upon creation of the content type, you should be taken to the Content Type Information page for it. From here, go ahead and add the same columns that added to the list above.If you bump into a reserved or in use column name (i.e. First Name) either use a different name (ie  Recipient First) or use the existing site column. Also, don’t forget to put all of the new columns into a group for later maintenance). When complete, the information page should look similar to the screen shown below.

image

Content types have some additional controls that allow you to control how the Document Information Panel appears within Word. In the settings section, Click on the “Document information Panel settings” link. On the next screen, ensure that the “Show Always” option is selected.

image

You should also note that this is where you can control precisely what appears in the Document Information Panel. Should you choose to do so, you can replace the default panel with an InfoPath form, but I won’t be covering that in this post.

Once you are ready, click OK.

3. Create an Word File and Upload it


When a document library is created, a document template is normally created along with it, unless specified otherwise. This is not true for content types. Therefore, We need to create a document to use as the template for this content type. Initially the process is very straightforward. Start Word, create a new document. If you want to add content to the document at this point, that will work, but it’s not necessary. When ready, save the document to your file system and remember its name/location.

Once done, go back to the content type definition window, and click the “Advanced Settings” link. in the resulting window, click the browse button, and navigate to the file that you just created.

image

Click OK, and then navigate back to the site. The content type is complete – for the moment.

4. Add a Library for Template Customization


Although we can edit the template once it’s been added to the content type, we can’t do anything with the metadata fields. That’s because Word can only reach back into the library that contains a document to see the metadata fields (the columns), and the content type gallery does not contain the columns that the content type itself does. We therefore need to create a document library that will use our content type. We will then create a new document that uses this content type, configure it the way we wish, and then replace the content type template with this document.

Firstly, add a new document library to a site (ideally the root site). We will be using it again below, and ultimately to house other document templates, so give it a logical name, something like “Document Templates”. Once created, we need to enable content types, and choose the our content type.

To enable content types, first navigate to the new library, and from the Ribbon, click the Library Tab, and then click the Library Settings button. From the Library Settings page, click the “Advanced Options” link. Once on the Advanced settings page, set “Allow management of content types?” to “Yes”.

image

Notice that the document template setting is greyed out. That’s because the content type will control the template. Click OK to close the advanced options screen.

You will now notice that we have a content types section, and the Document content type is being used. We want to add our content type, and then remove the generic Document content type. Since a library must have at least one content type, we must first add ours, and then remove the Document type.

First, click the “Add from existing site content types” link.

image

The “Add Content Types” dialog is loaded. Select your group from the dropdown, and add your content type to the Add list.

image

Click OK when ready. You will be returned to Library Settings, and you should now see your content type as number 2 in the list. We now want to remove the Document type, but there’s a slight catch. It is the first item in the content type list. The first item is the default content type, and the default content type cannot be deleted. We must first therefore make our content type the default, and then we can delete the Document content type. To do this, we click the “Change new button order and default content type” link.

image

From the next page, set the order of the Document content type to anything other than 1.

image

Click OK, and then click on the “Document” link in the Content Types list.  You are then taken to the List Content Type settings screen. From here, click the “Delete this content type” link, and confirm. Note that you are NOT deleting the Document content type itself, but only its association with this document library.

image

You should be returned to the Library Settings page, and see only one content type. Return to the library to perform the next step.

5. Create a New Document in the Library


From the library, click the Documents tab on the ribbon, and the the New Document button.

image

Accept the confirmation, and Word will open.  You will not need to turn on the Information Panel, as that is controlled by the content type itself. Recreate the letter following the procedure laid out in step 5 above.

Once you finish using Quick Parts, save the letter back into the library (this isn’t absolutely necessary for what we’re doing right now, but will help us in the last example). Once saved to the library, save it once again, but this time to your file system, and take note of the location/name.

6. Replace the Existing Content Type Template


The content type template that you had originally created was blank, but was necessary for the content type to work at all. We now need to replace it with our formatted letter template. To do so, we need to navigate back to our site content gallery (Site Actions – Site Settings – Site Content Types). Locate and click on the site content type created above (Letter in this case), and the content type information screen appears. Click on advanced settings, and replace the existing template with the new one by uploading the new one.

image

Close this window and return to your site. We’re ready to test this out.

7. Consume the New Content Type


Create a new library to test this. Configure it to use content types, add the new content type and remove the default Document content type. I’ve already outlined the procedure for doing this above with the template library, so I won’t repeat it here. Create a new document, change some of the metadata values and save it.

If you will not be using the procedure outlined below for template maintenance, you can delete the template library at this point.

In order to make changes to the template at this point, you will need to repeat the procedures in steps 5 and 6, immediately above, but you will be able to do this from any library configured to use this content type. There are a few down sides to maintaining the template in this way. For one, it is cumbersome, and for another, the ability to modify site content types, particularly at the root level is very high (or at least it should be….). This is a problem because you don’t necessarily want to charge farm administrators with the task of keeping document templates current.

Below, I will outline the last example which allows you to edit the template simply by editing a document in a library.

C – Using A Library to Manage Your Document Templates


So far, we have set up our template using our library metadata and stored it within our content type definition. We can use that content type throughout our site collection, but what happens when the requirements change for the site collection? In that case, someone with authority to do so must locate the content type definition, and repeat some of the steps above to update it.

If we centralize our document templates into a single, or even multiple document libraries, it makes for easier maintenance. It will be necessary for the template library to use all of the content types that it also contains, in order to do metadata maintenance.

The good news it that if you have been following along, you have already completed steps 1 and 2 below when you created the template library. Given that we’ve already been through many of the key concepts, I’ll keep the below examples brief.

1. Create a Template Library


If you have not already done so, create a new library for containing document templates. Go into advanced settings and enable content type. Add the content type of the template that you wish to manage. If necessary, delete the default “Document” content type.

The detailed procedure for doing this can be found above.

2. Add the Template to the Library


Either upload or create the document to be used as a template. Edit the document to suit your purposes.

3. Use the Document Directly as the Content Type Template


Here is where we deviate from where we have been before. First, you’ll want to take note of the URL of the file that you used in step 2. I make it a practice to always use relative URLS, which is everything to the right of the web application in the URL of the document. If your site collection is not at the root of the application, you will need to include the site collection path (i.e. /sites/mysitecoll).

The easiest way to get the document URL is by opening it in Word and getting it from the document information panel (File-Info).

image

Navigate to the site content type gallery (Site Actions, Site Settings, Site Content Types), and open your custom content type. When the information screen opens, click the Advanced Options link. The document Template URL will be set to the file name of the current template (if one has been created). Replace that with the URL of your document in the library.

image

Click OK, and return to your site.

4. Test it Out


If you don’t already have one, go ahead and create a new document library and have it use this content type. Create a few documents. As an added bonus, go back to the content type and add a mew metadata field. Edit the template in the template library to use this new field somewhere in the body of the document. Finally, edit one of the documents that use this template, and you should see the new metadata field appear in the Document Information Panel. If you create a new document, you should see the changes that were made to the template itself.

If you’ve made it this far, congratulations! Hopefully this demonstrates the power of content types combined with document templates, and helps provide some guidance on their use.

Using quick-parts to automatically update fields in Word document, from the metadata in a SharePoint document library

Using quick-parts to automatically update fields in a Microsoft Office document, from the metadata in a SharePoint document library

Sometimes you find yourself in the scenario where you need to capture metadata as part of a document (for instance a Quote or a legal documnet, which then populates throughout the document where ever the field is placed. Sure, this doesn’t happen a lot, but when it happens, making use of quick parts is an easy way to do it.

Step 1: Create a SharePoint document library as you usually would

Step 2: If the document template is reusable, create a Site Content type as you usually would and add the site columns to it you would like to associate with it

image

Otherwise you could simply create list level custom columns and upload the document we’ll be creating in a minute under advanced settings

image

image

Step 3 (I will assume you are using a custom content type):

Create a new document of the content type you just created (for this demo I based it on a Medical Report required by one of our local banks for Insurance purposes)

image

Step 4: After creating a new document, save it first, or it won’t allow you to insert the metadata values from the document library. Call it anything, this is a temporary document.

Step 5: With the document open, click the Insert tab –> Quick-Parts –> Document Property –>
and select the property you would like to insert

image

Step 6: Repeat step 5 for all the properties you want to see on your document. You will immediately see the property fields fill them selves as you fill in the metadata at the top

image

Step 7: Once you’ve finished updating the document template with all the required fields, save it offline – i.e. to your desktop.

Step 8: Upload the document you saved offline as the template to be used for your content type

image

And that’s it! You will notice that if you change the metadata in the column on SharePoint, the values will be changed as soon as you open the document again.