Disha Shah's Blog

November 5, 2009

Some Information on Web Parts and AJAX Web Parts

Web Parts

Web Part pages are pages that host Web Parts. Technically speaking a  Web Part is a class that inherits from the WebPart class defined in System.Web.UI.WebControls. ASP.NET 2.0 introduced  a Web Part infrastructure that requires exactly one WebPartManager control and one or more WebPartZone controls. The WebPartManager manages Web Part Instances and supports serialization of web part data so that it can be stored in the ASP.NET services database.  WSS 3.0 uses a control derived from WebPartManager called SPWebPartManager.

SPWebPartManager persists this data in the content database instead of the services database.  SPWebPartManager is already defined in the default.master page, so when you create a site page that links to this master page, this control is automatically added to your page.  Therefore you only need to add WebPartZones to create a Web Part.

Web Parts are the fundamental building block of SharePoint’s user interface.  They allow the SharePoint developer to achieve the goal of creating reusable components for business users which is, in many organizations, the primary task of a SharePoint developer.   Many Web Parts already exist  which may meet the needs of business users.

Web Parts make it possible for changes to customized site pages to be seen by all users on that site.  They also allow individual users to create personalized changes that only they can see. So Web Parts support both  customization and of personalization. Web Parts support customization of site pages but not application pages.   Customizing web parts does not require customization of the pages that host them.  All customization and personalization data are hosted inside the content database and is managed by the web part infrastructure.

To create a Web Part page, you must inherit from WebPartPage which is defined in Microsoft. SharePoint.dll, and you must add one or more WebPartZone controls.   One way to add a web part instance to a web part zone is to add an AllUsersWeb Part element to a feature.xml file.  A second method is to write code against the WSS object model  which may be required for more sophisticated processing.

Web Parts render inside what is know is chrome, the common user interface elements such as formatted title bar and borders around the web part’s body.  Chrome is rendered by the application framework (in this case WSS).

In SharePoint, Web Parts exist entirely within the content database and they are processed in safe mode. They should be as autonomous  as possible and should be compiled into a DLL.  They run under security settings that are defined in the web.config file and for this reason they should be deployed in solutions since Solution packages should correctly specify trust settings for deployment.

A Web Part Verb is an action that is rendered in the Web Part menu by the Web Part framework as a part of the chrome rendered around the control.  Web Part Connections are frequently used for master/detail records in Web Parts.

One useful building block for a Web Part is the SPGridView control which can be bound to SPDataSource to retrieve data from SharePoint lists.

AJAX Web Parts

AJAX Web Parts use several technologies to achieve an increased level of responsiveness once possible only in rich-client applications.  These technologies include:  object-oriented JavaScript, asynchronous data requests utilizing the XML HttpRequest object, XML data streams, Extensible Stylesheet Language Transforms (XSLT),  and dynamic manipulation of the HTML Document Object Model (DOM).

One of the main benefits is that smaller components are rendered in response to a user’s actions rather than rendering the entire page as a unit.   The AJAX approach includes a client runtime based on the ASP.NET AJAX library.  Instead of one large data stream being processed in the main request/response, individual components are responsible for their processing and can be individually refreshed based on user actions and events.   The user can continue working while individual AJAX components are processing.

Designing and building AJAX Web Parts is quite complex and this topic is definitely beyond the scope of this document.

Step by Step Tutorial for How to create and implement custom field type in SharePoint

Hi Everyone


What is Custom field Type in SharePoint ? Why we need Custom field type?

We have sometime instances where our business data does not fit to the field types included in Windows SharePoint Services or some situations where we need to further customize those general field types. Windows SharePoint Services enables you to create custom field types. These custom fields can include custom data validation and custom field rendering. You can also customize the way that variable properties of your custom field types are processed and rendered when users set property variables and create new columns that are based on your custom field type.


Example:

We need Country and State Columns in SharePoint List and when user selects Country we need to populate states according to that, How to implement this functionality If we need to use Country and State drop down again and again in number of places in SharePoint lists then we need to use Custom Field Type and add that Custom Field in SharePoint List.

Today I’ll show you how to create and implement Custom Field Type step by step.

  1. Open Microsoft Visual Studio, Go to File–>New–>Project.
  2. In the New Project dialog box, select Class Library from the Templates box, give it a name and location, then click OK.
  3. Add Reference of Microsoft.SharePoint assembly, and then click OK.
  4. Make the project as strong name key file.
  5. Now rename class.cs with CountryStateField.cs
  6. Creating a class for Custom field Type
  7. Create a field definition Schema XML file
  8. Create a class which contains FieldTypeValue.
  9. Create a class which is used for to display that , fieldcontrol.

Let us go through every step in detail one by one.

Step No 6 :Creating a Custom Field Type

The first step in creating a custom field type and field control is to create the field type class — the hub of everything related to the field. All field types must inherit from the Microsoft.SharePoint.SPField class or one that is derived from it.

Sample of Code

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

namespace Sample.FieldType

{

class CountryRegionField:SPFieldMultiColumn
public {
public CountryStateField(SPFieldCollection fields, string fieldName): base(fields, fieldName) { }
public CountryStateField(SPFieldCollection fields, string typeName, string  displayName): base(fields, typeName, displayName) { }
public override object GetFieldValue(string value)

{

if (string.IsNullOrEmpty(value))   return null;

return new CountryStateValue(value);

}

public override BaseFieldControl FieldRenderingControl

{

get

{

BaseFieldControl control = new CountryStateControl();

control.FieldName = this.InternalName;

return control;

}

}

public override string GetValidatedString(object value)

{

if (value == null)

{

if (this.Required) throw new SPFieldValidationException(“Invalid value for this field.”);

return string.Empty;

}

else

{

CountryStateValue field = value as CountryStateValue;

// if no value obtained, error in the field

if (field == null) throw new ArgumentException(“Invalid value.”);

// if it is required…

if (this.Required)

{

// make sure that both COUNTRY & State are selected

if (field.Country != string.Empty && field.State != string.Empty)

throw new SPFieldValidationException(“Both are required.”);

}

else

{

// else, even if not required, if one field is filled in, the other must beas well

if (!string.IsNullOrEmpty(field.Country))

if(string.IsNullOrEmpty(field.State))

throw new SPFieldValidationException(“Both are required if one value is entered.”);

}

return value.ToString();

}

}

}

}

Let us move to the next step , Create a xml file for Custom field Definition.

Step No. 7 : Creating a Custom Field Type Definition

With a field type class created, the next step is to create the field type definition that will make SharePoint aware of the field. This is done by creating an XML file in the [..]\12\TEMPLATE\XML Folder. When SharePoint starts up ,it looks at the [..]\12\TEMPLATE\XML folder and loads all the field type – defined files named fldtypes[_*].xml .

All the SharePoint fields provided in the WSS 3.0 install are found in the fldtypes.xml file. Other fields are added based on the MOSS 2007 installation. For instance, all the Publishing – specific fields are defined in the fldtypes.publishing.xml file.

CountryStateField definition (fldtypes _ CountryState.xml)

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

< FieldTypes >

< FieldType >

< Field Name=”TypeName” > CountryState< /Field >

< Field Name=”ParentType” > MultiColumn < /Field >

< Field Name=”TypeDisplayName” > Country, State < /Field >

< Field Name=”TypeShortDescription” > Country and state < /Field >

< Field Name=”UserCreatable” > TRUE < /Field >

< Field Name=”FieldTypeClass” > Sample.FieldType. CountryStateField,Sample.FieldType,Version=1.0.0.0, Culture=neutral,  PublicKeyToken=e42a63991be18435 < /Field >

< RenderPattern Name=”DisplayPattern” >

< Switch >

< Expr > < Column / > < /Expr >

< Case Value=”” / >

< Default >

< Column SubColumnNumber=”0” HTMLEncode=”TRUE” / >

<HTML> <![CDATA[;]]></HTML>

< Column SubColumnNumber=”1” HTMLEncode=”TRUE” / >

< /Default >

< /Switch >

< /RenderPattern >

< /FieldType >

< /FieldTypes >

  • TypeName: This is the unique name of the field used when creating items such as site columns using a Feature. For example, if a site column were created that was based on the field type created in this chapter, the element manifest ’ s site element would look like the following (omitting the other required attributes):
  • ParentType: The parent type is the field type from which the custom field type is derived — in this case, SPFieldMultiColumn or just MultiColumn .
  • TypeDisplayName: This name is used to display the field type on pages such as the Site Column Gallery or a content type ’ s detail page.
  • TypeShortDescription: The short description is the string used to display the field type as an option when creating new site or list columns (the long radio button list under the new column ’ s title textbox).
  • UserCreatable: This Boolean property tells SharePoint whether the field type can be used in the creation of a column in a list by a user. When false , developers can still use the field type in sitecolumns within the definition of list templates created using Features.
  • FieldTypeClass: This contains the strong name of the field type class and the assembly containing the class. This is also referred to as the five – part name: namespace.type, Assembly,Version, Culture, PublicKeyToken .

The custom field type definition should be added to the Visual Studio project in the following location: \TEMPLATE\XML\fldtypes_ CountryState.xml .

Step no 8  Creating a Custom Field Value

One of the requirements of the ContryStateField custom field type was to store the data within a custom data structure. While it sounds a bit complex, it is actually very simple. The custom field value class is very handy with field types that are derived from the SPFieldMultiColumn field because data is stored in the SPFieldMultiColumn field as a special delimited string using ;# as the delimiter, and not just between two values but surrounding them ;#United States;#Florida;#

CountryStateValue.cs file containing the field value

using System;

using Microsoft.SharePoint;

namespace Sample.FieldType{

public class CountryStateValue : SPFieldMultiColumnValue {

private const int NUM_FIELDS = 2;

public CountryStateValue ()

: base(NUM_FIELDS) { }

public CountryStateValue (string value)

: base(value) { }

public string Country {

get { return this[0]; }

set { this[0] = value; }

}

public string State {

get {return this[1];}

set { this[1] = value; }

}

}

}

Step No 9 : Creating a Custom Field Control

The first piece in a custom field control is the control class. This class must inherit from the Microsoft.SharePoint.WebControls.BaseFieldControl class or one that derives from it. For the CountryStateField , the BaseFieldControl will work.

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint.WebControls;

using System.Web.UI.WebControls;

using Microsoft.SharePoint;

namespace Sample.FieldType

{

public class CountryStateControl : BaseFieldControl,IDesignTimeHtmlProvider

{

protected DropDownList _country;

protected DropDownList _StateSelector;

protected Literal _StateSelectorLiteral;

public override object Value {

get

{

EnsureChildControls();

CountryStateValue field = new CountryStateValue();

if (_country == null || _StateSelector == null )

{

field.Country = String.Empty;

field.State = String.Empty;

}

else

{

// set country value

if (_country.SelectedIndex == 0)

field.Country = String.Empty;

else

field.Country = _country.SelectedValue;

// set State value

if (_StateSelector.SelectedIndex == 0)

field.State = String.Empty;

else

field.State = _StateSelector.SelectedValue;

}

return field;

}

set

{

EnsureChildControls();

if (value != null && !string.IsNullOrEmpty(value.ToString()))

{

CountryStateValue field = new CountryStateValue(value.ToString());

_country.SelectedValue = field.Country;

if (_country.SelectedIndex > 0)

_StateSelector.SelectedValue = field.State;

SetStateControlVisibility(_country.SelectedIndex);

}

}

}

private void SetStateControlVisibility(int countrySelectedIndex)

{

switch (countrySelectedIndex)

{

case 0: // if none selected

_StateSelector.Visible = false;

_StateSelectorLiteral.Visible = false;

break;

default: sss

_StateSelector.Visible = true;

_StateSelectorLiteral.Visible = true;

break;

}

}

protected void Country_SelectedIndexChanged(object sender, EventArgs e)

{

EnsureChildControls();

//ADDstatesdependsonCountry(_country.SelectedIndex);

SetStateControlVisibility(_country.SelectedIndex);

}

protected void ADDstatesdependsonCountry(int countrySelectedIndex)

{

_StateSelector.Items.Clear();

//Code for Adding items to State dropdown depends on contry

}

void AddItesmsForContry()

{

//code for adding items to country dropdown

}

protected override void CreateChildControls()

{

if (this.Field == null || this.ControlMode == SPControlMode.Display ||this.ControlMode == SPControlMode.Invalid)

return;

base.CreateChildControls();

// get reference to Country selector

_country = new DropDownList();

_country.SelectedIndexChanged += new EventHandler(Country_SelectedIndexChanged);

_country.AutoPostBack = true;

//AddItesmsForContry()

_StateSelector = new  DropDownList();

_StateSelectorLiteral = new Literal();

//Add country ,state Selector and State Literal to control collection

this.Controls.Add(_country);

this.Controls.Add(_StateSelectorLiteral);

this.Controls.Add(_StateSelector);

}

}

}

Happy Coding :)

November 4, 2009

How to upload big size of documents to SharePoint site

When we upload documents to SharePoint Document Library from SharePoint GUI or from Customized web part if our document size is more than 50 MB, it will not allow us to upload the documents.

In this article, I will explain about how to resolve that problem!

We need to change configurations at two places.

  1. Web.Config :-
  • We need to make change for below two important thing.
  • NOTE: This change is very important when you upload document to SharePoint document library by using programmatically or from SharePoint Object Model Code by using Asp.NET File Upload control or HTML File Upload.

i. maximumRequestLengh: What is maximum size of File, a user can upload.

ii. Execution Timeout: it is very important because if it is less than upload time, upload of file operation can fail.

  • Open the Web.config file of this webapplication by going to Local Drive:\Inetpub\wwwroot\wss\VirtualDirectories\SharepointApplicationPortNumber(example 80)
  • Find < httpRuntime and replace that line with the following line.

2. Change in Central Administration site

  • Go to SharePoint 3.0 Central Administration -> Application Management
  • Under “SharePoint WebApplication Management”, we need to go into “WebApplication General Settings”.
  • Change the “SharePoint Web application” in which we need to make changes.
  • There is option called “Maximum Upload Size” – 50 MB is default value, make it 2047 value.
  • Click OK.

We are done!

Now user can upload more size of documents into SharePoint site.

August 21, 2009

How to exclude fields from SharePoint ListFieldIterator Control

Here I am going to share with you a very small things but I think it’s very helpful. SharePoint Web Controls provides set of controls which we can use for generating our custom pages very easily without writing much custom code, there is control called “ListFieldIterator”, in which we need to specify which SharePoint List we are going to bind with controls and it will generate all controls related to SharePoint List.

In ListFieldIterator control if we want to exclude some fields from generated control, then we can use ListFieldIterator.ExcludeFields property, but when we have multiple fields for exclusion then we need to separate the fields with a semicolon and pound sign;#” as separator, for single field we are using “.” as separator.

SharePoint Web Controls rocks !!!

August 15, 2009

How to apply custom master page into SharePoint Site

You can get information regarding master page and branding from below article.

http://dishashah.wordpress.com/2009/08/13/sharepoint-master-pages-and-branding/

In this article, I’ll share with you how to apply custom master page into SharePoint root site and its sub sites, here I have created one feature in which I applied custom master page code into Feature Activated Event.

Example Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
namespace ApplymasterPage
{
class ApplyMasterPage : Microsoft.SharePoint.SPFeatureReceiver
{
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site == null)
return;
SPWeb rootWeb = site.RootWeb;
DeactivateWeb(rootWeb);
rootWeb.Update();
foreach (SPWeb subWeb in rootWeb.Webs)
{
ProcessSubWebs(subWeb,
false);
}
}
private void DeactivateWeb(SPWeb web)
{
if (web.AllProperties.ContainsKey(“OldMasterUrl”))
{
string oldMasterUrl = web.AllProperties["OldMasterUrl"].ToString();
try
{
bool fileExists = web.GetFile(oldMasterUrl).Exists;
web.MasterUrl = oldMasterUrl;
}
catch (ArgumentException)
{
web.MasterUrl = defaultMasterUrl;
}
string oldCustomUrl = web.AllProperties["OldCustomMasterUrl"].ToString();
try
{
bool fileExists = web.GetFile(oldCustomUrl).Exists;
web.CustomMasterUrl = web.AllProperties[
"OldCustomMasterUrl"].ToString();
}
catch (ArgumentException)
{
web.CustomMasterUrl = defaultMasterUrl;
}
web.AllProperties.Remove(“OldMasterUrl”);
web.AllProperties.Remove(“OldCustomMasterUrl”);
}
else
{
web.MasterUrl = defaultMasterUrl;
web.CustomMasterUrl = defaultMasterUrl;
}
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
const string defaultMasterUrl = “/_catalogs/masterpage/default.master”;
const string customizedMasterUrl = “/_catalogs/masterpage/Custom.master”;

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site == null)
return;
SPWeb rootWeb = site.RootWeb;
rootWeb.AllProperties["OldMasterUrl"] = rootWeb.MasterUrl;
rootWeb.AllProperties["OldCustomMasterUrl"] = rootWeb.CustomMasterUrl;
rootWeb.MasterUrl = customizedMasterUrl;
rootWeb.CustomMasterUrl = customizedMasterUrl;
rootWeb.Update();
foreach (SPWeb subWeb in rootWeb.Webs)
{
ProcessSubWebs(subWeb,true);
}
}
private void ProcessSubWebs(SPWeb web, bool isActivation)
{
if (isActivation)
{
web.AllProperties["OldMasterUrl"] = web.MasterUrl;
web.AllProperties["OldCustomMasterUrl"] = web.CustomMasterUrl;
web.MasterUrl = web.Site.RootWeb.MasterUrl;
web.CustomMasterUrl = web.Site.RootWeb.MasterUrl;
}
else
{
DeactivateWeb(web);
}
web.Update();
foreach (SPWeb subWeb in web.Webs)
{
ProcessSubWebs(subWeb, isActivation);
}
}

}
}

Next Page »

Blog at WordPress.com.