Wednesday 16 December 2009

SharePoint Explorer in SharePoint 2010

SharePoint Server Explorer is a new feature in Visual Studio 2010. You can navigate between all objects in SharePoint 2010 but you are limited to see their properties only. The way to extend this control is creating a new class which will inherit from IExplorerNodeTypeExtension.

Spec Explorer - advanced model-based specification and conformance testing tool

Spec Explorer 2010 is a tool that extends Visual Studio for modeling software behavior, analyzing that behavior by graphical visualization, model checking; and generating standalone test code from models. Behavior is modeled in two ways: by writing rule machines in C# (with dynamic data-defined state spaces) and by defining scenarios as action patterns in a regular-expression style. One of Spec Explorer’s major features is the ability to compose models written in these two styles. This technique enables users to slice out test cases from large state machines by defining relevant scenarios, thus tackling the notorious state-space explosion problem pervasive in model-based testing. Spec Explorer also supports combinatorial interaction testing with a rich set of features.

Doloto - AJAX application optimization tool

Doloto is an AJAX application optimization tool, especially useful for large and complex Web 2.0 applications that contain a lot of code, such as Bing Maps, Hotmail, etc. Doloto analyzes AJAX application workloads and automatically performs code splitting of existing large Web 2.0 applications. After being processed by Doloto, an application will initially transfer only the portion of code necessary for application initialization.

The rest of the application's code is replaced by short stubs -- their actual function code is transferred lazily in the background or, at the latest, on-demand on first execution. Since code download is interleaved with application execution, users can start interacting with the Web application much sooner, without waiting for the code that implements extra, unused features.

http://msdn.microsoft.com/en-us/devlabs/ee423534.aspx

Monday 14 December 2009

How to Increase your VMware Hard Disk's size

Following command line works like a magic :)
vmware-vdiskmanager -x 15GB "C:\VMs\Win2008VM\SharePoint2010.vmdk"

Sunday 13 December 2009

Microsoft Project Code Named “Velocity” Community Technology Preview 3 (CTP3)

"Velocity" is a distributed in-memory application cache platform for developing scalable, high-performance applications. "Velocity" can be used to cache any common language runtime (CLR) object and provides access through simple APIs. The key aspects of "Velocity" are distributed cache performance, scalability, and availability.

Saturday 12 December 2009

How to add parameters from different sources to DataFormWebPart

Although DataFormWebPart supports several ways to get such as QueryString, Control values, CAML variable etc, There are some cases we need to assign parameters from codebehind. I am not going to show all the scenarios but I will give you hint how you can extend dataform webpart to allow taking parameter variables from different sources.

The first thing we need to do is, creating a new class which will inherit from DataFormWebPart.

using System;
using System.Text;
using Microsoft.SharePoint.WebPartPages;
public class EnhancedDataFormWebPart : DataFormWebPart
{
}

The way we do is, replacing ParameterBindings string property inside of DataFormWebPart. This property is a xml string. We will load it as xml document and use following properties to make it accessible in our code.

XmlDocument _ParameterBindingsXmlDocument = null;
XmlDocument ParameterBindingsXmlDocument
{
get
{
if (_ParameterBindingsXmlDocument == null)
{
_ParameterBindingsXmlDocument = new XmlDocument();
_ParameterBindingsXmlDocument.LoadXml("" + this.ParameterBindings + "");
}
return _ParameterBindingsXmlDocument;
}
}

XmlNode _ParameterBindingsXmlNode = null;
XmlNode ParameterBindingsXmlNode
{
get
{
if (_ParameterBindingsXmlNode == null)
{
_ParameterBindingsXmlNode = ParameterBindingsXmlDocument.SelectSingleNode("/ParameterBindings");
}
return _ParameterBindingsXmlNode;
}
}

Lets also add this helper class to be able to manipulate xml document.

private void SetParameterBinding(string key, string value)
{
XmlNode node = ParameterBindingsXmlNode.SelectSingleNode("/ParameterBindings/ParameterBinding[@Name = '" + key + "']");
if (node == null)
{
XmlNode parameterBindingNode = ParameterBindingsXmlDocument.CreateElement("ParameterBinding");

XmlAttribute nameAtrribute = ParameterBindingsXmlDocument.CreateAttribute("Name");
nameAtrribute.Value = key;
XmlAttribute locationAttribute = ParameterBindingsXmlDocument.CreateAttribute("Location");
locationAttribute.Value="None";
XmlAttribute defaultValueAttribute = ParameterBindingsXmlDocument.CreateAttribute("DefaultValue");
defaultValueAttribute.Value = value;

parameterBindingNode.Attributes.Append(nameAtrribute);
parameterBindingNode.Attributes.Append(locationAttribute);
parameterBindingNode.Attributes.Append(defaultValueAttribute);

ParameterBindingsXmlNode.AppendChild(parameterBindingNode);
}
else
{
node.Attributes["DefaultValue"].Value = value;
}
}

Here is the key method we are going to use. This is where we set our custom properties. Via using this you can set your binding parameters from anywhere you like (web.config property, sql data etc)

private void SetPropertiesAsParameterBindings()
{
SetParameterBinding("WebPartTitle", this.Title);
SetParameterBinding("WebPartTitleURL", this.TitleUrl);
this.ParameterBindings = ParameterBindingsXmlNode.InnerXml;
}

Last thing we should do is calling this method on OnLoad method of the webpart.

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SetPropertiesAsParameterBindings();
}

Now it is time to replace DataFormWebPart with our EnhancedDataFormWebPart.

Add this line into your page and replace values with appropriate values from your solution.

Here the webpart comes :)

<ExWebParts:EnhancedDataFormWebPart id="TasksDisplayDataFormWebPart" runat="server"
FrameType="None" NoDefaultStyle="TRUE" ViewFlag="1" Title="Tasks"
DisplayName="Tasks" __markuptype="vsattributemarkup"
__WebPartId="{418745AA-67C6-481e-95F9-5C824AD0CE61}" WebPart="true">

<DataSources>

<SharePointWebControls:SPDataSource runat="server" DataSourceMode="List"
UseInternalName="true" selectcommand="<View/>" id="SPDataSource1"><SelectParameters><webpartpages:DataFormParameter Name="ListName" ParameterKey="ListName"
PropertyName="ParameterValues" DefaultValue="Tasks"/>

</SelectParameters>


</SharePointWebControls:SPDataSource>

</DataSources>

<ParameterBindings>
<ParameterBinding Name="ListName" Location="None" DefaultValue="Tasks" />
<ParameterBinding Name="dvt_apos" Location="Postback;Connection" />
<ParameterBinding Name="UserID" Location="CAMLVariable"
DefaultValue="CurrentUserName" />
<ParameterBinding Name="Today" Location="CAMLVariable" DefaultValue="CurrentDate" />
<ParameterBinding Name="WebPartTitle" Location="None" DefaultValue="{Title}" />
<ParameterBinding Name="WebPartTitleURL" Location="None" DefaultValue="{TitleUrl}" />
</ParameterBindings>

<datafields>@ID,ID;@ContentType,ContentType;@Title,Title;@Modified,Modified;@Created,Created;@Author,Author;@Editor,Editor;@_UIVersionString,_UIVersionString;@Attachments,Attachments;@LinkTitleNoMenu,LinkTitleNoMenu;@LinkTitle,LinkTitle;@FileRef,FileRef;@FileDirRef,FileDirRef;@FSObjType,FSObjType;@ProgId,ProgId;@ScopeId,ScopeId;@DocIcon,DocIcon;@MetaInfo,MetaInfo;@Priority,Priority;@Status,Status;@PercentComplete,PercentComplete;@AssignedTo,AssignedTo;@TaskGroup,TaskGroup;@Body,Body;@StartDate,StartDate;@DueDate,DueDate;</datafields>

<XslLink>/Style Library/XSL Style Sheets/test.xsl</XslLink>

</ExWebParts:EnhancedDataFormWebPart>



Last thing you need to do is adding following lines into Style Library/XSL Style Sheets as test.xsl file .



<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0"
exclude-result-prefixes="xsl msxsl ddwrt"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:ddwrt2="urn:frontpage:internal">

<xsl:output method="html" indent="no"/> <xsl:decimal-format NaN=""/>

<xsl:param name="dvt_apos">'</xsl:param>

<xsl:param name="WebPartTitle">

</xsl:param>

<xsl:param name="WebPartTitleURL"></xsl:param> <xsl:variable
name="dvt_1_automode">0</xsl:variable>

<xsl:template match="/">
WebPartTitleURL:<xsl:value-of select="$WebPartTitleURL"></xsl:value-of>
WebPartTitle:<xsl:value-of select="$WebPartTitle"></xsl:value-of>
<xsl:call-template name="dvt_1"/> </xsl:template>

<xsl:template name="dvt_1">

<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>

<xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">

</xsl:if>

<xsl:call-template name="dvt_1.body">

<xsl:with-param name="Rows" select="$Rows"/>

</xsl:call-template>

</xsl:template>

<xsl:template name="dvt_1.body">

<xsl:param name="Rows"/>

<xsl:for-each select="$Rows">

<xsl:call-template name="dvt_1.rowview"/>

</xsl:for-each>

</xsl:template>

<xsl:template name="dvt_1.rowview"> Title: <xsl:value-of select="@Title"/><br/>

</xsl:template>

</xsl:stylesheet>

Tuesday 24 November 2009

Reduce VPCs size

This is a common issue we are all having. Creating seperate vhd files for each different environment such as SharePoint, Biztalk, Backend servers (Exchange, SQL etc). We still need to create different vhd files for these but instead of having 30 GB per environment, we are going to create one base vhd and inherit others from them( like an OOP ;) ). So lets take windows server 2008 as main operating system. We are going to create one vhd file and install Windows 2008 Server into that one. So lets name it as BaseWin2008.vhd .For the rest we are going to create them as using BaseWin2008.vhd file as base file. So that new vhd will only save the difference. It is saving pretty GBs is not it :)

So here is the command to create a vhd from base vhd file.

diskpart
create vdisk file=C:\SharePoint2010.vhd parent=C:\BaseWin2008.vhd
exit

Howto compact a vhd file

1. First of all, install cccleaner. This tool is very usefull. It will remove all unnecessary files from your drive.
2. Defrag your drive.
3. From the CD menu, select Capture ISO Image and browse to the Virtual PC additions directory, which is %ProgramFiles%\Microsoft Virtual PC\Virtual Machine Additions by default.
Mount Virtual Disk Precompactor.iso. Click ok to allow it to prepare your drive to be able to compacted.
4. Unmount the ISO from the CD menu.
5. Finally execute the Virtual Disk Wizard from the File menu and compact your VHD file.

Do not forget to make it read only if you want to use it as a base disk.

Thursday 19 November 2009

ADO.NET Data Services v1.5 CTP2

This release (v1.5) will target the .NET Framework 3.5 SP1 & Silverlight 3 platforms and provide new client and server side features for data service developers. In addition, the features included in this release (v1.5) will be part of the .NET Framework 4 release.
http://blogs.msdn.com/astoriateam/archive/2009/08/31/ado-net-data-services-v1-5-ctp2-now-available-for-download.aspx

Thursday 13 August 2009

Creating Proxy Object with Using Generic

public class ObjectA : MarshalByRefObject
{
public void MethodA()
{
Console.WriteLine("MethodA is called.");
}
}

public class ObjectB : MarshalByRefObject
{
public void MethodB()
{
Console.WriteLine("MethoB is called");
}
}
public class GenericProxyManager : RealProxy where TObject : new()
{
private TObject _objectInstance;

public GenericProxyManager(TObject objectInstance) : base(typeof(TObject))
{
this._objectInstance = objectInstance;
}

public static TObject GetProxyObject()
{
TObject objectInstance = new TObject();
GenericProxyManager proxyObject = new GenericProxyManager(objectInstance);
TObject transparentProxyObject = (TObject)proxyObject.GetTransparentProxy();
return transparentProxyObject;
}

public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage message = (IMethodCallMessage)msg;

// Unless you are sure the implementation covers only methods, you need to write some additional code for properties ( get/set )
if (message != null)
{
Console.WriteLine(message.MethodName + " has been handled before it called");
// Write necessary code here - this is before you invoke the method
object methodRetval = message.MethodBase.Invoke(_objectInstance, message.InArgs);
// Write necessary code here - this is after you invoke the method
ReturnMessage retVal = new ReturnMessage(methodRetval, null, 0, message.LogicalCallContext, message);
return retVal;
}
return null;
}
}


Lets execute the following code now
ObjectA obj = GenericProxyManager.GetProxyObject();
obj.MethodA();

ObjectB obj2 = GenericProxyManager.GetProxyObject();
obj2.MethodB();

Result will be

MethodA has been handled before it called
MethodA is called.
MethodB has been handled before it called
MethoB is called

Wednesday 12 August 2009

Database Normalization

Normalization is a process of certain rules to be applied while a database is being designed. The goal of this process is to prevent unnecesary data repeats and ensuring data dependencies and efficent use of data.

So what are these rules? There are five known normalization forms. Lets explain these one by one;

First Normal Form (1NF):
One row can contain only one information for a specific data.

Example;
WRONG: We have a Cars table and this table has a column called FuelType as nvarchar(255) and we are storing the data as
Cars
CarIDFuelType
1"Petrol, Diesel"
2"Diesel"
3"Electric, Diesel"




CORRECT: We need to create a new table called FuelTypes which will store all the fuel types and instead of using FuelType nvarchar(255) column, FuelTypeID int should be used and needs to be related to FuelTypes table.
FuelTypes
FuelTypeIDName
1"Petrol"
2"Diesel"
3"Electric"

Cars
CarIDFuelTypeID
11
12
22
33
32

Second Normal Form (2NF)

A table that has a lookup column (which is primary key in other table) can not contain any information from that lookup table.

Example;
WRONG:
Services
ServiceIDWorkerIDWorkerName
12Serkant
23Catherine

Workers
WorkerIDWorkerName
2Serkant
3Catherine


CORRECT:
Services
ServiceIDWorkerID
12
23



Workers
WorkerIDWorkerName
2Serkant
3Catherine

Third Normal Form (3NF)

A table whose non-primary key fields are dependent only on the primary key and therefore have no dependence any other non-primary key field in the table.

Example;
WRONG:
Services
ServiceIDWorkerNameWorkerPhone
1Serkant0777 777 7777
2Daniel0777 888 8888


CORRECT:
Services
ServiceIDWorkerID
12
23

Workers
WorkerIDWorkerNameWorkerPhone
2Serkant0777 777 7777
3Daniel0777 888 8888


Fourth Normal Form (4NF)


A table can not contain two or more 1:n or n:m relationships that are not directly related.

Example;
WRONG:
Book Deliveries
BookstoreBookArea
Bookstore ABook AArea A
Bookstore ABook AArea B
Bookstore BBook BArea B
Bookstore CBook BArea C


CORRECT:
Bookstore Books
BookstoreBook
Bookstore ABook A
Bookstore BBook A
Bookstore BBook B


Bookstore Delivery Areas
BookstoreArea
Bookstore AArea A
Bookstore BArea A
Bookstore BArea B
Bookstore BArea C


Fifth Normal Form (5NF)

This form deals with cases where information can be reconstructed from smaller pieces of information that can be maintained with less redundancy.

Example;
WRONG:
SalesmanCompanyProduct
Salesman ACompany AProduct A
Salesman ACompany AProduct B
Salesman BCompany BProduct A
Salesman BCompany BProduct B


CORRECT:

Company Salesmen
CompanySalesman
Company ASalesman A
Company BSalesman B


Company Products
CompanyProduct
Company AProduct A
Company AProduct B
Company BProduct A
Company BProduct B

Salesman Products
SalesmanProduct
Salesman AProduct A
Salesman AProduct B
Salesman BProduct A
Salesman BProduct B

[SQL Server Performance] Speed up your query with covering index

Do you use the same statement often? Are you facing performance issues on that query? Covering index is what you need :) (Ofc depends on your statement/data size)

So what is covering? Covering index is a technique of designing indexes for a table, not a type of index. I will explain this technique with an example.

Lets take Orders table from Northwind sample db. Orders table has a clustered index on CustomerID. We would like to see shipping fee for daily basis. To get this data execute to following query.

select OrderDate, SUM(Freight) from Northwind.dbo.[Orders] where group by OrderDate





As you can see from execution plan, it scans all clustered index data then sorting and grouping the result from index scan.

Lets put an index for OrderDate and Freight fields and see what happens

CREATE INDEX IX_OrderDate_Freight ON dbo.ORDERS(OrderDate, Freight)

then execute the same query

select OrderDate, SUM(Freight) from Northwind.dbo.[Orders] where group by OrderDate







It is directly accessing to the index and getting all the necessary information from index. Normally if sql scans a non-clustered index and there are some fields in the statement which does not exist in the index, Sql Server engine goes to original record to get the field values for every single record. This may cause a performance issue. In this example as it gets all necessary information from index it will speed up the query. Additionally as non-clustered index is sorted, it saves the engine from making additional sorting process.

Note: When you select your index, try to pick small size ones like smallint, integer, datetime. If you have bigger size fields then the implementation may cost more then you had. Try to prevent to put index on the table which has big number of insert/update/delete operations as well. Because everytime a record is changed, indexes will be reviewed from SQL Server Engine to see if they need to be sorted again.

Friday 7 August 2009

Difference between Clustered and Non-Clustered Indexes

Most of the performance issues are being faced is about how indexes are implemented. Although indexing is very benefical, it can cause performance problems if it is not well structured. In this post i am going to explain the difference between Clustered and Non-Clustered, and also on which condition we should prevent using indexing.

Following explains the methods we are going to use ;

* Lists all of a table's data and index pages
DBCC IND
(
['database name'|database id], -- the database to use
table name, -- the table name to list results
index id, -- an index_id from sys.indexes; -1 shows all indexes and IAMs, -2 just show IAMs
)

* Setting via trace flag 3604, It allows to instruct the engine to send output to the console
DBCC TRACEON(3604)

* DBCC PAGE statement lists the page header, data rows, and row offset table for any data page in a database.
DBCC PAGE ( {dbid | dbname}, filenum, pagenum [, printopt] [, cache]


Lets have a look how they stored by SQL;


1) Non indexed Table
Tables do not have a default index.

. Create the test table

Create Table TestTable
(
Id Int,
Name Varchar(255)
)

. Insert test data

Insert Into TestTable Values (3, 'Name3')
Insert Into TestTable Values (1, 'Name1')
Insert Into TestTable Values (2, 'Name2')

. Query the table

Select * From TestTable

. See the result

Id Name
-------------- ------------------
3 Name3
1 Name1
1 Name2

As there is no index, data was returned as the same order as they were inserted.

. See the structure of the data
Declare @dbID Int, @TableID Int
Set @dbID = db_id()
Set @TableID = object_id('TestTable')
DBCC ind(@dbID, @TableID, -1)

Here is the result



The columns mean:

* PageFID - the file ID of the page
* PagePID - the page number in the file
* IAMFID - the file ID of the IAM page that maps this page (this will be NULL for IAM pages themselves as they're not self-referential)
* IAMPID - the page number in the file of the IAM page that maps this page
* ObjectID - the ID of the object this page is part of
* IndexID - the ID of the index this page is part of
* PartitionNumber - the partition number (as defined by the partitioning scheme for the index) of the partition this page is part of
* PartitionID - the internal ID of the partition this page is part of
* iam_chain_type - see IAM chains and allocation units in SQL Server 2005
* PageType - the page type. Some common ones are:
1 - data page
2 - index page
3 and 4 - text pages
8 - GAM page
9 - SGAM page
10 - IAM page
11 - PFS page
* IndexLevel - what level the page is at in the index (if at all). Remember that index levels go from 0 at the leaf to N at the root page (except in clustered indexes in SQL Server 2000 and 7.0 - where there's a 0 at the leaf level (data pages) and a 0 at the next level up (first level of index pages))
* NextPageFID and NextPagePID - the page ID of the next page in the doubly-linked list of pages at this level of the index
* PrevPageFID and PrevPagePID - the page ID of the previous page in the doubly-linked list of pages at this level of the index


But we are only interested with PagePID, IndexID and PageType

Thursday 25 June 2009

SPDataSource

There are many ways to retrieve SharePoint content such as SPDataSource, SPQuery
and looping through in SharePoint Object library.

Today we will have a look at the SPDataSource. SPDataSource is an object
datasource which supply information from SharePoint by given parameters.



Here is a sample of SPDataSource syntax.

<SharePointWebControls:SPDataSource runat="server" DataSourceMode="List"
UseInternalName="true" selectcommand="<View/>" id="SPDataSource1">

<SelectParameters>

<webpartpages:DataFormParameter Name="ListName" ParameterKey="ListName"
PropertyName="ParameterValues" DefaultValue="Tasks"/>

</SelectParameters>


</SharePointWebControls:SPDataSource>



DataSourceMode:
(

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spdatasource.datasourcemode.aspx

)

List: Retrieves
data from a list


<SharePoint:SPDataSource ID="SPDataSource1"
runat="server" DataSourceMode="List" UseInternalName="true"
SelectCommand="<Query><OrderBy><FieldRef Name='DueDate' Ascending='true'
/></OrderBy></Query>">

<SelectParameters>

<asp:Parameter
Name="ListName" DefaultValue="Tasks" />

<asp:Parameter
Name="WebID" DefaultValue="RootWeb" />

</SelectParameters>

</SharePoint:SPDataSource>




<asp:GridView ID="GridView1"
runat="server" DataSourceID="SPDataSource1" AutoGenerateColumns="false">

<Columns>

<asp:BoundField HeaderText="Due Date"
DataField="DueDate" />

<asp:BoundField HeaderText="Priority"
DataField="Priority" />

<asp:BoundField HeaderText="Title"
DataField="Title" />

<asp:BoundField HeaderText="Status"
DataField="Status" />

</Columns>

</asp:GridView>



ListItem: Retrieves
data from a single list item


<SharePoint:SPDataSource
ID="SPDataSource1" runat="server" DataSourceMode="ListItem"
UseInternalName="true" >


<SelectParameters>

<asp:Parameter
Name="WebID" DefaultValue="RootWeb" />

<asp:Parameter
Name="ListName" DefaultValue="Announcements" />

<asp:Parameter
Name="ListItemID" DefaultValue="1" />


</SelectParameters>


</SharePoint:SPDataSource>


<asp:GridView
ID="GridView1" runat="server" DataSourceID="SPDataSource1"
AutoGenerateColumns="false">

<Columns>


<asp:BoundField
HeaderText="Title" DataField="Title" />

<asp:BoundField
HeaderText="Expires" DataField="Expires" />

</Columns>

</asp:GridView>



CrossList:
Retrieves data from multiple lists in multiple websites in the same site
collection.



<SharePoint:SPDataSource ID="SPDataSource1" runat="server"
DataSourceMode="CrossList" UseInternalName="true" SelectCommand="<Webs
Scope='Recursive'></Webs> <Lists ServerTemplate='106'></Lists> <View>
<ViewFields> <FieldRef Name='EventDate'/> <FieldRef Name='Title'/> <FieldRef
Name='Location'/ </ViewFields> <Query> <Where> <And> <Eq> <FieldRef
Name='Location'/> <Value Type='Text'>Your office</Value> </Eq> <Eq> <FieldRef
Name='EventDate'/> <Value Type='DateTime'><Today/></Value> </Eq> </And> </Where>
</Query> </View>" >


</SharePoint:SPDataSource>

<asp:GridView
ID="GridView1" runat="server" DataSourceID="SPDataSource1"
AutoGenerateColumns="false" Width="75%" HeaderStyle-HorizontalAlign="Left" >

<Columns>

<asp:BoundField
HeaderText="Date" DataField="EventDate" />

<asp:BoundField
HeaderText="Title" DataField="Title" />

<asp:BoundField
HeaderText="Location" DataField="Location" />

</Columns>

</asp:GridView>



ListOfLists:
Retrieves properties of lists in a specified web site.



<SharePoint:SPDataSource ID="SPDataSource1" runat="server"
DataSourceMode="CrossList" UseInternalName="true" SelectCommand="<Webs
Scope='Recursive'></Webs> <Lists ServerTemplate='106'></Lists> <View>
<ViewFields> <FieldRef Name='EventDate'/> <FieldRef Name='Title'/> <FieldRef
Name='Location'/ </ViewFields> <Query> <Where> <And> <Eq> <FieldRef
Name='Location'/> <Value Type='Text'>Your office</Value> </Eq> <Eq> <FieldRef
Name='EventDate'/> <Value Type='DateTime'><Today/></Value> </Eq> </And> </Where>
</Query> </View>" >


</SharePoint:SPDataSource>

<asp:GridView
ID="GridView1" runat="server" DataSourceID="SPDataSource1"
AutoGenerateColumns="false" Width="75%" HeaderStyle-HorizontalAlign="Left" >

<Columns>


<asp:BoundField
HeaderText="Date" DataField="EventDate" />

<asp:BoundField
HeaderText="Title" DataField="Title" />


<asp:BoundField
HeaderText="Location" DataField="Location" />


</Columns>

</asp:GridView>



Web: Retrieves
properties of subsites of the current web site.



<SharePoint:SPDataSource ID="SPDataSource1" runat="server" DataSourceMode="Webs"
IncludeHidden="true">


<SelectParameters>

<asp:Parameter
Name="WebId" DefaultValue="RootWeb" />


</SelectParameters>


</SharePoint:SPDataSource>

<asp:GridView
ID="GridView1" runat="server" DataSourceID="SPDataSource1"
AutoGenerateColumns="false">

<Columns>

<asp:BoundField
HeaderText="Site Title" DataField="__spTitle" />

<asp:BoundField
HeaderText="URL" DataField="__spUrl" />

<asp:BoundField
HeaderText="ID" DataField="__spID" />

<asp:BoundField
HeaderText="Web Template" DataField="__spWebTemplate" />

<asp:BoundField
HeaderText="Web Template Id" DataField="__spWebTemplateId" />

</Columns>

</asp:GridView>



SelectCommand: This is where we define our
query to get data. CAML is the query syntax. Custom parameters such as
QueryString, existing variables, programmatically defined
parameterbindings can be used.

SelectParameters (

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spdatasource.selectparameters.aspx

): That is used to define to
pass parameters into data control.

Following list states
what can be assigned as default values




































WebID

”RootWeb” for the root Web site. Otherwise, a string representation of a GUID
such as the value of the SPWeb.ID property.

WebURL

An empty string for the root Web site. Otherwise, a string containing a
server-relative URL.

ListID

A string representation of a GUID such as the value of the SPList.ID property.

ListName

The value of the SPList.Title property.

ListItemGUID

A A string representation of a GUID such as the value of the SPListItem.UniqueId
property.

ListItemID

A string representation of an integer such as the value of the SPListItem.ID
property.

RootFolder

The value of the SPFolder.Name property.

FolderID

A string representation of a GUID such as the value of the SPFolder.UniqueId
property.

Additionally we can assign parameters from;

QueryString: <asp:QueryStringParameter Name="CompanyName"
QueryStringField="Company" DefaultValue="Contoso" />


Control: <asp:ControlParameter Name="CompanyName" ControlID="DropDownList1"
PropertyName="SelectedValue" />

ParameterBinding: <webpartpages:DataFormParameter Name="PostID"
ParameterKey="PostID" PropertyName="ParameterValues" DefaultValue="0"/>

Wednesday 24 June 2009

DataFormWebPart

One of the most important part in SharePoint is displaying the content without
braking any SharePoint features.

In this scenario DataFormWebPart is our guidance. There are always other ways to
display the content like custom webparts/webpartpages, but developing with these
methods may cost us lots of time.

In the following example we will learn how to develop a simple DataFormWebPart.


This is the syntax we will work on it.

<WebPartPages:DataFormWebPart id="TasksDisplayDataFormWebPart" runat="server"
FrameType="None" NoDefaultStyle="TRUE" ViewFlag="1" Title="Tasks"
DisplayName="Tasks" __markuptype="vsattributemarkup"
__WebPartId="{418745AA-67C6-481e-95F9-5C824AD0CE61}" WebPart="true">

<DataSources>

<SharePointWebControls:SPDataSource runat="server" DataSourceMode="List"
UseInternalName="true" selectcommand="<View/>" id="SPDataSource1">

<SelectParameters>

<webpartpages:DataFormParameter Name="ListName" ParameterKey="ListName"
PropertyName="ParameterValues" DefaultValue="Tasks"/>

</SelectParameters>


</SharePointWebControls:SPDataSource>

</DataSources>

<ParameterBindings>

<ParameterBinding Name="ListName" Location="None" DefaultValue="Tasks" />

<ParameterBinding Name="dvt_apos" Location="Postback;Connection" />

<ParameterBinding Name="UserID" Location="CAMLVariable"
DefaultValue="CurrentUserName" />

<ParameterBinding Name="Today" Location="CAMLVariable" DefaultValue="CurrentDate" />

<ParameterBinding Name="WebPartTitle" Location="None" DefaultValue="{Title}" />

<ParameterBinding Name="WebPartTitleURL" Location="None" DefaultValue="{TitleUrl}" />

</ParameterBindings>

<datafields>@Title,Title;@ID,ID</datafields>

<XslLink>/Style Library/XSL Style Sheets/SPTest/FullContent.xsl</XslLink>

</WebPartPages:DataFormWebPart >



Now let’s have a look at the properties;


a) DataSources: This defines where the data to get from We have some controls to
get the data, here is some of them;




i) SPDataSource: Gets the data from single or multiple (cross, we
will mention it in later blogs) SharePoint libraries content.


DataSourceMode:


• List: Retrieves
data from a list


• ListItem: Retrieves
data from a single list item


• CrossList:
Retrieves data from multiple lists in multiple websites in the same site
collection.


• ListOfLists:
Retrieves properties of lists in a specified web site.


• Web: Retrieves
properties of subsites of the current web site.


SelectCommand: This is where we define our
query to get data. CAML is the query syntax. Custom parameters such as
QueryString, existing variables, programmatically defined
parameterbindings can be used, but it will be shown on feature blogs.


SelectParameters: That is used to define to
pass parameter binding values and also other type of parameters.

ii) SPXmlDataSource:


<SharePoint:SPXmlDataSource runat="server">

<DataFileParameters>


<WebPartPages:DataFormParameter Name="FileName" ParameterKey="FileName"
PropertyName="ParameterValues" DefaultValue="items.xml"/>


<WebPartPages:DataFormParameter Name="FilePath" ParameterKey="FilePath"
PropertyName="ParameterValues" DefaultValue=""/>

</DataFileParameters>

</SharePoint:SPXmlDataSource>




b) ParameterBindings: To supply user defined or environment defined values to
the actual query.

c) DataFields: Fields those are used in xsl.

d) XSLLink: Xsl file to display content in a custom format.

Sample of the following code xsl;

<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0"
exclude-result-prefixes="xsl msxsl ddwrt"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:SharePoint="Microsoft.SharePoint.WebControls"
xmlns:ddwrt2="urn:frontpage:internal">

<xsl:output method="html" indent="no"/> <xsl:decimal-format NaN=""/>

<xsl:param name="dvt_apos">'</xsl:param>

<xsl:param name="WebPartTitle">

</xsl:param>

<xsl:param name="WebPartTitleURL"></xsl:param> <xsl:variable
name="dvt_1_automode">0</xsl:variable>

<xsl:template match="/">

<xsl:call-template name="dvt_1"/> </xsl:template>

<xsl:template name="dvt_1">

<xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row"/>

<xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">

</xsl:if>

<xsl:call-template name="dvt_1.body">

<xsl:with-param name="Rows" select="$Rows"/>

</xsl:call-template>

</xsl:template>

<xsl:template name="dvt_1.body">

<xsl:param name="Rows"/>

<xsl:for-each select="$Rows">

<xsl:call-template name="dvt_1.rowview"/>

</xsl:for-each>

</xsl:template>

<xsl:template name="dvt_1.rowview"> Title: <xsl:value-of select="@Title"/><br/>

</xsl:template>

</xsl:stylesheet>