Search This Blog

2009-04-30

SPSite and SPContext

SPSite:
Represents a collection of sites in a Web application, including a top-level Web site and all its subsites. Each SPSite object, or site collection, is represented within an SPSiteCollection object that consists of the collection of all site collections in the Web application.

To instantiate an SPSite object for a specific site collection on an ASP.NET page, or for a specific site collection within a console application, use the SPSite constructor as follows:
SPSite oSiteCollection = new SPSite("Absolute_URL");
Within an ASP.NET application, you can use the Site property of the SPContext class to return an SPSite object that represents the current site collection, as follows:
SPSite oSiteCollection = SPContext.Current.Site;
If you create your own SPSite object, you can use the Dispose method to close the object. You can also instead implement a using statement so that the .NET Framework common language runtime (CLR) automatically releases the memory that is used to store the site collection as follows:

using (SPSite oSiteCollection = new SPSite("Absolute_URL")
{
...
}

However, if you have a reference to a shared resource, such as when the object is provided by the GetContextSite method in a Web Part, do not use either method to close the object. Using either method on a shared resource causes an Access Violation error to occur. In scenarios where you have a reference to a shared resource, instead let Windows SharePoint Services or your portal application manage the object.

Note:-
Some Important properties are AllWebs ,WebApplication ,Owner etc


SPContext :-
Represents the context of an HTTP request in Windows SharePoint Services

Use the SPContext class to return context information about such objects as the current Web application, site collection, site, list, or list item.
The following examples illustrate how to use properties of the SPContext class to return the current list, site, and site collection.

SPList oListCur = SPContext.Current.List;
SPWeb oWeb = SPContext.Current.Web;
SPSite oSite = SPContext.Current.Site;
SPWebApplication oWebApplicationCur = SPContext.Current.Site.WebApplication;
Cast the value of the Item property as an SPListItem object to return the current list item, as follows:
SPListItem item = (SPListItem)SPContext.Current.Item;

Properties:-

Name
Description
Current
Gets the context of the current HTTP request in Windows SharePoint Services.
Fields
Gets the fields metadata associated with the item or content type of the Windows SharePoint Services context.
File
Gets the file that is associated with the list item object of the given Windows SharePoint Services context.
Item
Gets either the SPListItem object that is determined by the given list and item ID, or the SPItem object that is set when the SPContext object is created.
ItemId
Gets the ID of the item that is associated with the Windows SharePoint Services context.
List
Gets the list that is associated with the Windows SharePoint Services context.
ListId
Gets the GUID of the list that is associated with the Windows SharePoint Services context.
ListItem
Gets the list item associated with the Windows SharePoint Services context.
ListItemServerRelativeUrl
Gets or sets the server-relative URL for the list item in the current HTTP context of Windows SharePoint Services.
Site
Gets the site collection that is associated with the Windows SharePoint Services context.
SiteFeatures
Gets the activated site collection features of the Windows SharePoint Services context.
Web
Gets the Web site that is associated with the Windows SharePoint Services context.
WebFeatures
Gets the activated site features of the Windows SharePoint Services context.

SPSiteDataQuery

GHow we can use SPSiteDataQuery

SPSiteDataQuery object is used to perform the crosslist queries.As we have seen before that SPQuery is used to perform the query on a single list at a time, what if We want to run the same Query on multiple list on the websites in the site collection ? SPSiteDataQuery solves this purpose .It runs the query on multiple list and give all the results merged in a datatable.We Use

SPWeb.GetSiteData(SPSiteDataQueryObj) to get the final Datatable.

Properties :-
Lists
Gets or sets the inner XML that specifies which lists to include in the query.
Query
Gets or sets the inner XML that defines the query.
RowLimit
Gets or sets a limit for the number of items in the query that are returned per page.
ViewFields
Gets or sets the inner XML that describes the view fields used in the query.
Webs
Gets or sets the inner XML that specifies which Web sites to include in the query as specified by the Scope attribute on the Webs tag in the query. By default, the query considers the current Web site, that is, the Web site from which the GetSiteData method was invoked.

Note:-

Webs

Possible values of the Scope attribute include Recursive and SiteCollection. When the Scope attribute is set to Recursive, the query considers all Web sites that are descended from the current SPWeb object. For example: When the Scope attribute is set to SiteCollection, the query considers all Web sites that are in the same site collection as the current Web site.


Lists Attributes
Supported optional attributes for the Lists tag include the following:
· ServerTemplate -- Limits the query to lists of the specified server template. Example: <Lists ServerTemplate="104" />
· BaseType -- Limits the query to lists of the specified base type. Example: <Lists BaseType="1" />
The following table lists possible values for the default base types.


Value Description
0 Generic list
1 Document library
3 Discussion forum
4 Vote or Survey
5 Issues list

· Hidden -- Determines whether the query will include hidden lists. Example: <Lists Hidden = "TRUE />By default, the query will consider all non-hidden lists of base type 0.· MaxListLimit -- Limits the query to the total number of lists specified. If the query would exceed the limit, the query will instead fail and raise an SPException. By default, the limit is 1000. When set to 0, there is no limit to the number of lists that will be considered. Example: <Lists MaxListLimit="500" />

Lists Subelements
Possible subelements of the Lists tag include List and WithIndex.
· The List tag allows the query to include specific lists, instead of returning all lists of a particular type. The ID attribute identifies each list. Example:

<Lists> <List ID="7A9FDBE6-0841-430a-8D9A-53355801B5D5" /> <List ID="3D18F506-FCA1-451e-B645-2D720DC84FD8" /></Lists>

Code Snipet Example :-
SPWeb oWebsite = SPContext.Current.Web;
SPSiteDataQuery oQuery = new SPSiteDataQuery();
string strWhere = "<Where><Gt>" + "<FieldRef Name=\"ID\" />" + "<Value Type=\"Number\">1</Value>" + "</Gt></Where>";
string strOrderBy = "<OrderBy><FieldRef Name=\"FileRef\" /></OrderBy>";
oQuery.Query = strWhere + strOrderBy;
oQuery.Lists = "<Lists ServerTemplate=\"101\" />";
oQuery.ViewFields = "<FieldRef Name=\"Title\" />";
DataTable dtResults = oWebsite.GetSiteData(oQuery);

SPQuery

What is SPQuery
SPQuery class is used to instantiate objects which can are used to query the list and document libraries.The Query is prepared using a xml language called CAML.The Query returns all the records from the list which meets athe criteria.

Public Properties :-

Folder
Microsoft.SharePoint.SPFolder
Gets or sets the folder within a document library from which to return items in the query.
ListItemCollectionPosition
Microsoft.SharePoint.SPListItemCollectionPosition
Gets or sets an object that is used to obtain the next set of rows in a paged view of a list.
Query
String
Gets or sets the inner XML used in the query.
RowLimit
UInt32
Gets or sets a limit for the number of items returned in the query per page.
ViewAttributes
String
Gets or sets the attributes of the view used in the query.
ViewFields
String
Gets or sets the fields that are displayed in the query.

Code Snippet example:-

//****** SPQuery Example and Adding Atachments to List Item********//
SPSite site = new SPSite("http://gpchbs-s6137:92");
SPWeb web = site.OpenWeb();
SPQuery query = new SPQuery();
SPList dlist=web.Lists["Dlist"];
SPListItemCollection collection = null;
SPListItem item = null;
query.Query = "" +
"" +
"" +
"0"+
"
"+
""+
"" +
"
"+
"
" +
"
"+
"";
query.RowLimit = 10;
//query.ViewFields = "" +
// "";
query.ViewAttributes = "Scope=\"Recursive\"";

collection = dlist.GetItems(query);
if (collection != null)
{
if (collection.Count > 0)
{
dlist.EnableAttachments = true;
dlist.Update();
for (int i = 0; i < collection.Count - 1; i++)
{
item = collection[i];
byte[] barr1 = File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\backupkmlist.txt");
byte[] barr2=File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\Copybackupkmlist.txt");
item.Attachments.AddNow("backupkmlist.txt", barr1);
item.Attachments.AddNow("Copybackupkmlist.txt", barr2);
}
for (int j = 0; j < item.Attachments.Count; j++)
{
Console.WriteLine("Leaf Name: " + item.Attachments[j]);
}

Console.ReadLine();}}








//****** SPQuery Example With Forward only Pagination********//
SPSite site = new SPSite("http://gpchbs-s6137:92");
bool nextPage = true;
SPWeb web = site.OpenWeb();
SPQuery query = new SPQuery();
SPList dlist=web.Lists["Dlist"];
SPListItemCollection collection = null;
SPListItem item = null;
query.Query = "" +
"" +
"" +
"0"+
"
"+
""+
"" +
"
"+
"
" +
"
"+
"";
query.RowLimit = 2;
//query.ViewFields = "" +
// "";
query.ViewAttributes = "Scope=\"Recursive\"";

while (nextPage)
{
collection = dlist.GetItems(query);
if (collection != null)
{
if (collection.Count > 0)
{
Console.WriteLine("**********************");
Console.WriteLine("Title " + "\t" + "ID ");
//dlist.EnableAttachments = true;
//dlist.Update();
//for (int i = 0; i < collection.Count - 1; i++)
//{
// item = collection[i];
// byte[] barr1 = File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\backupkmlist.txt");
// byte[] barr2=File.ReadAllBytes("C:\\Arijit\\PracticeDemos\\Copybackupkmlist.txt");
// item.Attachments.AddNow("backupkmlist.txt", barr1);
// item.Attachments.AddNow("Copybackupkmlist.txt", barr2);
//}
//for (int j = 0; j < item.Attachments.Count; j++)
//{
// Console.WriteLine("Leaf Name: " + item.Attachments[j]);
//}
for (int i = 0; i < collection.Count; i++)
{
Console.WriteLine(collection[i].Title + "\t" + collection[i].ID);
}

}


}
if (collection.ListItemCollectionPosition != null)
{
if (!string.IsNullOrEmpty(collection.ListItemCollectionPosition.PagingInfo))
{
query.ListItemCollectionPosition = collection.ListItemCollectionPosition;
Console.WriteLine("Press Enter for Next Page...");
Console.ReadLine();

}
else
{
Console.WriteLine("Last Page Reached");
Console.ReadLine();
}
}
else
{
nextPage = false;
Console.WriteLine("Last Page Reached");
Console.ReadLine();
}
}

SPDocumentLibrary

What is SPDocumentLibrary /What are the methods and properties of SPDocumentLibrary /How can we use SPDocumentLibrary

SPDocumentLibrary represents the sharepoint document library lists.

Properties:-

CheckedOutFiles
Gets the collection of files that are checked out of the document library.

Methods:-

GetItemsInFolder
Returns a collection of items from the document library based on the specified view and folder.

Note:- All other properties are inherited from SPList.


Some Code Snippets:-

//*******code snippet which shows the uploading of document
SPSite site = new SPSite("http://gpchbs-s6137:92");
SPWeb web = site.OpenWeb();
SPDocumentLibrary docLib1=null;
SPDocumentLibrary docLib2=null;
if ((web.Lists["Audio"].BaseType == SPBaseType.DocumentLibrary) && (web.Lists["Awards"].BaseType == SPBaseType.DocumentLibrary))
{
docLib1 = (SPDocumentLibrary)web.Lists["Audio"];

docLib2 = (SPDocumentLibrary)web.Lists["Awards"];
}
if (docLib1 != null && docLib2 != null)
{
docLib1.ContentTypesEnabled = true;
SPFolder folder1 = docLib1.RootFolder.SubFolders.Add("FirstChild");
folder1.Item["Title"]= "FirstFolder1";
folder1.Item.Update();
folder1.SubFolders.Add("FirstSF");
folder1.Update();
docLib1.Update();

//Create the stream object to add a file
FileStream fstream = new FileStream("C:\\KMLists.txt", FileMode.Open, FileAccess.Read);
SPFile file1= folder1.Files.Add("KMLists.txt", fstream);
folder1.Update();
fstream.Close();

file1.Item["Title"] = "KMDetails";
file1.Item.Update();
file1.Update();

folder1.CopyTo(docLib2.RootFolder.Url + "/" + folder1.Name+"_Copy");
docLib2.Update();

foreach (SPFolder folder in docLib2.RootFolder.SubFolders)
{
Console.WriteLine("Folder Names at root level :" + folder.Name);
Console.WriteLine(folder.ServerRelativeUrl);
Console.WriteLine(folder.Url);
Console.WriteLine(folder.SubFolders.Count);

foreach (SPFile file in folder.Files)
{
Console.WriteLine("File length is :" + file.Length.ToString());
Console.WriteLine(file.ServerRelativeUrl);
Console.WriteLine(file.Url);
Console.WriteLine(file.Name);

}

Console.ReadLine();
}




}





//********which shows downloading a document and displaying the versions
SPSite site = new SPSite("http://gpchbs-s6137:92");
SPWeb web = site.OpenWeb();
SPFile file1 = web.GetFile("/Audio/FirstChild/KMLists.txt");
if (file1 != null)
{
byte[] barr = file1.OpenBinary();
FileStream fstream = new FileStream("C:\\Arijit\\PracticeDemos\\backupkmlist.txt", FileMode.CreateNew, FileAccess.Write);
fstream.Write(barr, 0, Convert.ToInt32(file1.Length));
fstream.Close();

FileStream fstream2 = new FileStream("C:\\screenshot.doc", FileMode.Open, FileAccess.Read);
file1.SaveBinary(fstream2);
file1.Update();
fstream2.Close();



foreach (SPFileVersion ver in file1.Versions)
{
Console.WriteLine(ver.CheckInComment);
Console.WriteLine(ver.CreatedBy.LoginName);
Console.WriteLine(ver.ID.ToString());
Console.WriteLine(ver.VersionLabel);
Console.WriteLine(ver.Url);
Console.WriteLine(ver.Level.ToString());
}

Console.ReadLine();

}

SPFolder And SPFile

SPFolder
SPFolder class represents a folder in Sharepoint site.

Public Methods :-
The following table shows the public methods of the SPFolder class and a brief description of each.
CopyTo
Copies the folder and its contents into a new folder at the specified URL.
MoveTo
Moves the folder to the specified URL.
ToString
Returns the relative URL of the folder based on the parent Web site.

Public Properties :-
The following table shows the public properties of the SPFolder class, the data type of each property, and a brief description of each.
ContainingDocumentLibrary
System.Guid
Gets the document library that contains the folder.
Exists
Boolean
Gets a Boolean value that indicates whether the folder exists.
Files
Microsoft.SharePoint.SPFileCollection
Gets the collection of all files contained in the folder.
Name
String
Gets the name of the folder.
ParentFolder
Microsoft.SharePoint.SPFolder
Gets the parent folder of the folder.
ParentWeb
Microsoft.SharePoint.SPWeb
Gets the parent Web site of the folder.
ServerRelativeUrl
String
Gets the server-relative URL of the folder.
SubFolders
Microsoft.SharePoint.SPFolderCollection
Gets the collection of subfolders contained within the folder.
Url
String
Gets the site-relative URL of the folder.

SPFile :-
The SPFile class represents a file in a SharePoint Web site that can be a Web Part Page, an item in a document library, or a file in a folder.
Public Methods
The following table shows the public methods of the SPFile class and a brief description of each.

CheckIn
Checks in the file to a document library.
CheckOut
Checks out the file from a document library.
CopyTo(String)
Copies the file to the destination URL but does not overwrite an existing file of the same name.
CopyTo(String, Boolean)
Copies the file to the destination URL but overwrites an existing file of the same name only if bOverwrite is true.
MoveTo(String)
Moves the file to the destination URL but does not overwrite an existing file of the same name.
MoveTo(String, Boolean)
Moves the file to the destination URL but overwrites an existing file of the same name only if bOverwrite is true.
OpenBinary
Opens the file in binary format.
SaveBinary
Saves the file in binary format.
UndoCheckOut
Undoes the file check-out.
Public Properties
The following table shows the public properties of the SPFile class, the data type of each

property, and a brief description of each.
CheckedOutBy
Microsoft.SharePoint.SPUser
Gets the user who has checked out the file.

CheckedOutDate
System.DateTime
Gets the date and time that the file was checked out.

CheckInComment
String
Gets the comment used when a document is checked into a document library.

Exists
Boolean
Gets a Boolean value that indicates whether the file exists.

InDocumentLibrary
Boolean
Gets a Boolean value that indicates whether the file belongs to a document library.

Item
Microsoft.SharePoint.SPListItem
Gets the list item object that corresponds to the file if the file belongs to a document library.

Length
Int64
Gets the size of the file in bytes, including the size of any supporting files, but excluding Web Parts.

Name
String
Gets the internal name of the file.

ParentFolder
Microsoft.SharePoint.SPFolder
Gets the parent folder of the file.

ServerRelativeUrl
String
Gets the relative URL of the file based on the URL for the server.

TimeCreated
System.DateTime
Gets a date and time value indicating when the file was created.

TimeLastModified
System.DateTime
Gets a date and time value indicating when the file was last modified.

Title
String
Gets the display name of the file.

Url
String
Gets the site-relative URL of the file.

Versions
Microsoft.SharePoint.SPFileVersionCollection
Gets a collection of file version objects representing the versions of the file.

SPContentType

What is SPContentType/What are the method and properties of SPContentType/How can we use SPContentType
You create a content type at the site level. This site content type acts as a template that is independent of any specific list or library. That site content type is then available on any child site. For example, if you create a site content type at the root site of a site collection, that site content type becomes available on any site in that site collection, so that you can add it to any list in the site collection.
When you add a site content type to a list, Windows SharePoint Services 3.0 copies a local copy of the site content type onto the list itself. This local instance is called a list content type and applies only to the list onto which it was copied.
Because Windows SharePoint Services stores a copy of the site content type as a list content type on each list to which that site content type is added, you can make changes to a list content type without affecting the site content type itself. The changes to a list content type are limited to that list and do not affect the site content type, or any other content types that inherit from that same site content type.
The following figure shows this relationship. Two site content types, Memo and Spec, are defined for a site. When the Spec content type is added to the list of a child site list, Windows SharePoint Services copies an instance of the site content type locally onto the list.
The Memo site content type is also available to be added to lists on the child site. However, this content type has not been added to the list, so no copy of it resides on the list.

Base Content Hirarchy:-

Properties :-

FieldLinks
Gets an SPFieldLinkCollection that represents the collection of column, or field, references in the content type.
Fields
Gets an SPFieldCollection that represents collection of column references included in the content type.
Group
Gets and sets the content type group to which the content type is assigned.
Hidden
Gets an SPContentTypeId that represents the content type ID of the content type.
Id
Gets an SPContentTypeId that represents the content type ID of the content type.
Name
Gets or sets the content type name.

Note:-

There is a 1-to-1 correlation between the items in the SPFieldLinkCollection and SPFieldCollection objects. For each SPFieldLink you add to a content type, Windows SharePoint Services adds a corresponding SPField object that represents the merged view of that column as it's defined in the content type.
You cannot directly add or delete items from an SPFieldCollection object in an SPContentType object; trying to do so throws an error.

Methods:-
The Two most important methods are Delete and Update.

Small Code Snippet Example:-

//* Create a text field dynamically.
//* Create a contenttype dynamically.
//* Add field to a content type
//* Add content type to a list
//*Enable the content type on the list and make it vailable on New Menu Items.
namespace FieldAddDemo
{
class Program
{
static void Main(string[] args)
{
SPSite site = new SPSite("site Url");
SPWeb web = site.OpenWeb();

string fieldName = web.Fields.Add("CustomF1",
SPFieldType.Text, false);

web.Update();
SPField fieldCustom1 = web.Fields["CustomF1"];

fieldCustom1.Group = "Extended Columns";
fieldCustom1.ShowInNewForm = true;
fieldCustom1.Update();

SPContentType contentNew = new
SPContentType(web.ContentTypes["Item"], web.ContentTypes,
"NewDemoContent");

web.ContentTypes.Add(contentNew);
web.Update();
contentNew.FieldLinks.Add(new SPFieldLink(fieldCustom1));
contentNew.Update();




SPList dlist = web.Lists["list-Name"];
dlist.ContentTypesEnabled = true;
dlist.ContentTypes.Add(web.ContentTypes["NewDemoContent"]);
dlist.Update();
SPContentType[] contentCol = new SPContentType[1];
contentCol[0] = dlist.ContentTypes["NewDemoContent"];
SPFolder fld = dlist.RootFolder;
fld.UniqueContentTypeOrder = contentCol;
fld.Update();

}
}
}

Resource obtain from MSDN

SPField

What is SPField/How can we use SPField/What are the method and properties of SPField

SPField object represent a field in a list in Sharepoint web site.

Properties:-
Group
Gets or sets the column group to which the field belongs.
Hidden
Gets or sets a Boolean value that specifies whether the field is displayed in the list.
Id
Gets the GUID of the field.
InterName
Gets the internal name that is used for the field.
StaticName
Gets or sets the internal name of the field.
ShowInNewForm
Gets or sets a Boolean value that specifies whether the field is displayed in the form that is used to create list items
ShowInEditForm
Gets or sets a Boolean value that specifies whether the field is displayed in the form that is used to edit list items.
ShowInDisplayForm
Gets or sets a Boolean value that specifies whether the field is displayed in the form for displaying list items.

Method:-

Delete

Update

OnAdded
Occurs after a field is added.


OnUpdated
Occurs after changes are made to a field.
OnDeleting
Occurs when a field is being deleted.

SPListItem

What is SPListItem/What are the mrthod and properties of SPListItem/How can we use SPListItem
SPListItem object represents a list item or row in a sharepoint list.

Properties:-

Attachments
Gets the collection of attachments that are associated with the item.
ContentType
Gets the content type that is associated with the item.
Fields
Overridden. Gets or sets the collection of all fields in the parent of the item.
File
Gets the file that is represented by the item from a document library.
Folder
Gets a folder object that is associated with a folder item.
ID
Overridden. Gets the integer that identifies the item.
ListItems
Gets the parent collection of list item objects to which the item belongs.
MissingRequiredFields
Gets a Boolean value that specifies whether required fields are missing from the item's properties.
Name
Gets the name of the item.
ParentList
Gets the parent list of the list item.
Tasks
Gets the collection of workflow tasks for the item.
Title
Gets the title of the item.
UniqueId
Gets the GUID that uniquely identifies the item for the internal database.
Url
Gets the site-relative URL of the item.

Methods:-


Copy
Overloaded. Copies an item.
CopyFrom
Overloaded. Overwrites the current item.
CopyTo
Copies the item to the specified destination.
Delete
Overridden. Deletes the item.
Update
Overridden. Updates the database with changes that are made to the list item.

SPList

What is SPList/What are the properties and method of SPList/How can we use SPList
SPList :-

SPList object represent a Sharepoint list in a Sharepoint site.



Properties:-

ContentTypes
Gets the content types that are associated with the list.
ContentTypesEnabled
Gets or sets a Boolean value specifying whether content types are enabled for the list.
DefaultView
Gets the default view for the list.
Description
Gets or sets the description for the list.
EmailAlias
If e-mail notification is enabled, gets or sets the e-mail address to use to notify to the owner of an item when an assignment has changed or the item has been updated.
EnableAssignToEmail
Gets or sets a Boolean value specifying whether e-mail notification is enabled for the list.
EnableAttachments
Gets or sets a Boolean value that specifies whether attachments can be added to items in the list.
EventReceivers
Gets the collection of event receivers that have been registered for the list.
Fields
Gets the collection of field objects that represents all the fields in the list.
Folders
Gets the collection of folder items for the list.
Forms
Gets a collection of form objects that represent the forms that are used in creating, editing, or displaying items in the list.
Hidden
Gets or sets a Boolean value that specifies whether the list is hidden.
ID
Gets the GUID that identifies the list in the database.
ItemCount
Gets the number of items in the list.
Items
Gets the collection of all items in the list.
Lists
Gets the parent collection of lists to which the list belongs.
RoleAssignments
Gets the collection of role assignments for the list.
RootFolder
Gets the folder that contains all the files that are used in working with the list.
Views
Gets the collection of view objects that represents all the views of the list.

Methods :-

BreakRoleInheritance
Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments.
Delete
Deletes the list.
GetItemById
Returns the list item with the specified integer ID.
GetItemByUniqueId
Returns the list item that is associated with the specified global unique identifier (GUID).
GetItems
Overloaded. Returns a collection of items from the list.
GetView
Returns a view of the list based on the specified GUID.
Update
Overloaded. Updates the database with changes that are made to the list.

SPWeb

What is SPWeb/What are the method and properties of SPWEB:-
SPWeb object represent a Sharepoint WebSite. SPWeb object can be obtained using SPSite and SPContext.

Ex:-
· SPWeb website = SPContext.Current.Web;
· SPWeb webSite1 = site.OpenWeb(“URl”); Here site is an SPSite Object.

Properties:-


Alerts
Gets the collection of alerts for the site or subsite.
AllowUnsafeUpdates
Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation.
AllUsers
Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.
AvailableContentTypes
Gets the collection of all content type templates for the current scope, including those of the current Web site, as well as of any parent sites.
AvailableFields
Gets the collection of the available fields of the Web site.
ContentTypes
Gets the collection of content types for the Web site.
CurrentUser
Gets the current user of the site.
EventReceivers
Gets the collection of event receiver definitions that are currently available on the Web site.
Exists
Gets a Boolean value that indicates whether the Web site exists.
Features
Gets the collection of Features that are currently activated in the Web site.
Fields
Gets the collection of field objects that represents all the fields in the Web site.
Files
Gets the collection of all files in the root directory of the Web site.
Folders
Gets the collection of all first-level folders in the Web site.
Groups
Gets the collection of cross-site groups for the site.
ID
Gets the GUID for the site.
IsRootWeb
Gets a Boolean value that indicates whether the site is the top-level Web site of the site collection.
Site
Gets the parent site collection for the Web site.
SiteGroups
Gets the collection of cross-site groups for the site collection.
SiteUsers
Gets the collection of all users that belong to the site collection.
Url
Gets the absolute URL for the Web site.
Users
Gets the collection of user objects that are explicitly assigned permissions on the Web site.
Lists
Gets the collection of all lists that are contained in the Web site

Methods:-


Close
Closes the Web site at the end of a request and releases resources.
Delete
Deletes the Web site.
EnsureUser
Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.
GetFile
Overloaded. Returns the file object with the specified GUID or the file object that is located at the specified URL.
GetFolder
Overloaded. Returns the folder object with the specified GUID or the folder object that is located at the specified URL.
GetList
Returns the list that is associated with the specified site-relative URL.
GetListItem
Returns the list item that is associated with the specified server-relative URL.
GetSiteData
Performs a query for list items across multiple lists, which can be located in multiple Web sites in the same Web site collection.
Update
Updates the database with changes that are made to the Web site.

Sharepoint Object Model Overview

Windows SharePoint Services offers a highly structured server-side object model that makes it easy to access objects that represent the various aspects of a SharePoint Web site. From higher-level objects, you can drill down through the object hierarchy to obtain the object that contains the members you need to use in your code.
What can be done with OM :-
· Add, edit, delete, and retrieve data from SharePoint Lists
· Create new lists and set list metadata (e.g. the fields in a list)
· Set web properties
· Work with documents in document libraries.
· Perform administrative tasks such as creating webs, adding users, creating roles, etc.
· Pretty much any functionality in the UI can be automated through the OM!

Important Classes of Object Model:-

SPSite
SPContext
SPWeb
SPList
SPListItem
SPListItemCollection
SPField
SPDocumentLibrary
SPFile
SPFolder
SPContentType
SPQuerySPSiteDataQuery

Example:-
· If you are creating a Web Part, custom Web service, or Web application to work with site collections, individual sites, or lists, you can use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list.
· Outside of an HTTP context, such as in a console application or a Windows application, use a constructor of the SPSite class to obtain a specific site collection and to reach various objects within the collection

Difference between Windows SharePoint Services (WSS) and Microsoft Office SharePoint Server 2007 (MOSS)

What is the difference between Windows SharePoint Services (WSS) and Microsoft Office SharePoint Server 2007 (MOSS)
It is important that you know the difference between Windows SharePoint Services (WSS) and Microsoft Office SharePoint Server 2007 (MOSS). While WSS and MOSS are both pieces of software built by the Microsoft Office team, WSS is included as a part of the Windows Server 2003 operating system while MOSS is a separate product with its own SKU. You should think of WSS as the underlying platform and think of MOSS as a value-added set of components and services that has been built on top of this platform.
WSS does not have its own licensing model. Instead, the use of WSS is controlled through Windows Server 2003 licenses. This makes it very cost effective for companies to roll out applications that have been designed and built on top of the WSS platform. MOSS, on the other hand, has its own licensing model that includes server-side licenses and client access licenses (CALs). The MOSS licensing model is further broken out into a Standard Edition and an Enterprise Edition

2009-04-29

Progressbar in Ajax

Progressbar in ASP.NET using AJAX
Progressbar control is not in ASP.NET control,But we can create the progressbar using Ajax UpdateProgress control.
Following is the code of of how we can create the progressbar in ASP.NET.
Just create a new ASPX page ,then delete all code from the HTML page and paste the following code.Be sure that the website already has the ajaxcontroltoolkit

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script runat="server">
protected void UploadFile(object src, EventArgs e)
{
if (myFile.HasFile)
{
string strFileName;
int intFileNameLength;
string strFileExtension;

strFileName = myFile.FileName;
intFileNameLength = strFileName.Length;
strFileExtension = strFileName.Substring(intFileNameLength - 4, 4);

if (strFileExtension == ".txt")
{
try
{
myFile.PostedFile.SaveAs(Server.MapPath(".") + "//Upload//AJAXUpload.txt");
lblMsg.Text = strFileName + " Uploaded successfully!";
}
catch (Exception exc)
{
lblMsg.Text = exc.Message;
}
}
else
{
lblMsg.Text = "Only Text File (.txt) can be uploaded.";
}
}
else
{
lblMsg.Text = "Please select a file!";
}
}
</script>


<script language="javascript" type="text/javascript">
function showWait()
{
if ($get('myFile').value.length > 0)
{
$get('UpdateProgress1').style.display = 'block';
}
}
</script>
<title>File Upload</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
<ContentTemplate>
<asp:FileUpload ID="myFile" runat="server" />
<asp:Label ID="lblMsg" runat="server"></asp:Label>
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="UploadFile" OnClientClick="javascript:showWait();"/>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<asp:Label ID="lblWait" runat="server" BackColor="#507CD1" Font-Bold="True" ForeColor="White" Text="Please wait ... Uploading file"></asp:Label>
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

Good Morning


2009-04-28

Upload any file into a database

Upload and download any file to a database:
Any type of file can be saved in the database as a binary stream.Sql server 2005 has a datatype varbinary(max).We can store the file in the database using this varbinary(max) datatype.Here I will explain how to save and retrieve files from database.

Database Design :Here I have created a Database called dbFiles and it has a table called tblFiles.
It has 4 Fields as follows



id contains Identification Number (Autogenerate ID),Name contains File Name ,Content Type contains Content Type for the file and Data contains File stored as Binary Data.

Depending on the type of the file below are the content types

Content Type of "Word Document" is "application/vnd.ms-word"

Content Type of "Excel Document" is "application/vnd.ms-excel"

Content Type of "JPEG Image" is "image/jpeg"

Content Type of "Portable Document Format " is "application/pdf "

Code:Insert the file to the database

// Read the file and convert it to Byte Array
string filePath = Server.MapPath("APP_DATA/TestDoc.docx");
string filename = Path.GetFileName(filePath);

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();


//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);


private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}

Retrieving the File from Database


string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}


private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}


private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}

2009-04-27

Multi select Dropdown control

Multi select dropdown is not available in the HTML Control or ASPX control.We can create the multi select dropdown using combo box ,textbox and an image.The multiselect dropdwn control will be look like as follows.






Code:

Step 1.Create an HTML file and copy the following HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>MultiSelect Dropdown List</TITLE>
<SCRIPT Language="javaScript">
function ShowList(textID,fieldid){

if(document.getElementById(fieldid).style.display == 'none') //if the dropdown is not displayed, display the dropdown below the textbox.
{
document.getElementById(fieldid).style.display = 'inline';
var lsobj=document.getElementById(textID);
var lscurleft = 0;
var lscurtop = 0;
if (lsobj.offsetParent) {
do {
lscurleft += lsobj.offsetLeft;
lscurtop += lsobj.offsetTop;
} while (lsobj = lsobj.offsetParent);
}
document.getElementById(fieldid).style.left=lscurleft;
document.getElementById(fieldid).style.top=lscurtop + 22;
}
else
{
document.getElementById(fieldid).style.display = 'none';
}
}

function HideDropdown(fieldname,textfield,hiddenfield)
{
var lsnewStr="";
var lsnewVal="";
var lsCurrentSelectedvalue=document.frmMultiSelect[fieldname].value;
var lsCurrentSelected= document.frmMultiSelect[fieldname].options[document.frmMultiSelect[fieldname].selectedIndex].text;
lsCurrentSelected = lsCurrentSelected.replace(/^\s+\s+$/, ''); // used to trim the selected text in the dropdown

var lsSelectedDisplayValues= document.frmMultiSelect[textfield].value;
var lsSelectedValue= document.frmMultiSelect[hiddenfield].value;

if(lsSelectedDisplayValues.indexOf(lsCurrentSelected) == -1) // if the selected item is not selected earlier
{
document.frmMultiSelect[textfield].value+=lsCurrentSelected + ";";
document.frmMultiSelect[hiddenfield].value+=lsCurrentSelectedvalue + ";";
}
else // if the current selected item is already selected, it removes the current selected item in the list displayed in the text box
{
document.frmMultiSelect[textfield].value=lsSelectedDisplayValues.replace(lsCurrentSelected + ";","");
document.frmMultiSelect[hiddenfield].value=lsSelectedValue.replace(lsCurrentSelectedvalue + ";","");
}

var larr_col=document.frmMultiSelect[textfield].value.split(";"); // splits the value in the hidden field in to an aray list
var larr_col_text = document.frmMultiSelect[hiddenfield].value.split(";"); // splits the value in the textbox field in to an aray list

document.frmMultiSelect[fieldname].selectedIndex = -1;
var i;
<!--- the following loop is helps to select the selected items in the dropdown programatically --->
for(i=0;i<=document.frmMultiSelect[fieldname].length-1;i++) // loop through the entire list in the select dropdown
{
var lspart_num=0;
while (lspart_num < larr_col.length-1)
{
if(document.frmMultiSelect[fieldname].options[i].value==larr_col_text[lspart_num])
{
var lstemp = document.frmMultiSelect[fieldname].options[i].text;
lstemp = lstemp.replace(/^\s+\s+$/, ''); // trims the leading spaces for the selected item
lsnewStr+= lstemp+";"; // this variable stores the dispalyed text of the selected items in the dropdown
document.frmMultiSelect[fieldname].options[i].selected = true;
lsnewVal+= document.frmMultiSelect[fieldname].options[i].value+";"; //this variable stores the value of the selected items in the dropdown
}
lspart_num++;
}
}
document.frmMultiSelect[textfield].value = lsnewStr;
document.frmMultiSelect[hiddenfield].value = lsnewVal;
}
</SCRIPT>
</Head>
<BODY LINK="#3300FF" ALINK="#3300FF" VLINK="#3300FF">
<FORM NAME="frmMultiSelect" ACTION="" METHOD="Post">
<TABLE WIDTH="100%" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR>
<TD ALIGN="CENTER">
<SPAN STYLE="">SELECT MULTIPLE VALUES IN A DROPDOWN LIST WITHOUT USING CTRL KEY</SPAN>
</TD>
</TR>
<TR><TD> </TD></TR>
<TR>
<TD ALIGN="CENTER">
<SPAN><B>Select Country:</B></SPAN>
<INPUT TYPE="hidden" NAME="hdnCountryValue" VALUE="">
<!--- hidden field is used to hold the values of the selected items in the dropdown. Useful when the value of the items in the dropdown is different than the displayed text for each item in the dropdown. --->
<INPUT TYPE="text" NAME="txtCountryText" READONLY STYLE="Width:280px;" VALUE="" ONCLICK="Javascript:ShowList('txtCountryText','CountryId')"><IMG SRC="./DropDown.bmp" ALIGN="Top" ONCLICK="Javascript:ShowList('txtCountryText','CountryId')">
<!--- ShowList function is used to display and hide the select dropdown list when the textbox or the image is clicked. HideDropDown function selects or deselects the items in the dropdown list --->
<DIV STYLE="Z-INDEX:1;POSITION:absolute;DISPLAY:none;" ID="CountryId">
<SELECT MULTIPLE="Yes" NAME="cboCountry" STYLE="Width: 300px;" SIZE="6" onChange="Javascript:HideDropdown('cboCountry', 'txtCountryText','hdnCountryValue')" onBlur = "Javascript:ShowList('txtCountryText','CountryId')">
<OPTION selected value=""></OPTION>
<OPTION VALUE="Afghanistan">Afghanistan</OPTION>
<OPTION VALUE="Albania">Albania</OPTION>
<OPTION VALUE="Algeria">Algeria</OPTION>
<OPTION VALUE="Antarctica">Antarctica</OPTION>
<OPTION VALUE="Argentina">Argentina</OPTION>
<OPTION VALUE="Australia">Australia</OPTION>
</SELECT>
</DIV>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>


Step 2.Put the following image file in the folder where you keep your HTML File.Be sure that the image name is "DropDown.bmp"

Step 3.Now Open your HTML file in browser .And select dropdown list values without using control key

Accessing Server side values from client Side

There are several possible ways to access server side values from client side javascript or client side values from server side.I try to describe few of them.

Method 1:-Acessing Client side values by HiddenField

In the HTML page ,write the following javascrpit function in the head section

<script type="text/javascript">
function getSharedData()
{
//Display value of hidden field.
alert("Shared data is " + document.getElementById("sharedData").value + ".");
//Change value of hidden field.
document.getElementById("sharedData").value="A new value";
}
</script>

Take a HiddenField and a button in the Body ,call the function getSharedData() from the OnCLientClick Event of the button
<asp:HiddenField ID="sharedData" runat="server" Value="Shared Data" />
<div>
<asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />

From the server side code write the following code to get the values of hidden feild which are assigned from the javascript.

protected void Page_Load(object sender, EventArgs e)
{
//Access value of hidden field from client.
String test = sharedData.Value;
}

Method 2.Dynamically create a hidden field on the client

Keep the HTML code as it is in Method 1.

Modify the server side code as follows

protected void Page_Load(object sender, EventArgs e)
{
ClientScriptManager csm = Page.ClientScript;

//Use ClientScriptManager to dynamically create a hidden field on the client.
String hiddenName = "sharedData";
String hiddenValue = "Client data value";

//This hidden field is not a server side control, just a hidden <input> element on the client.
csm.RegisterHiddenField(hiddenName, hiddenValue);

}

Method 3:Create a HiddenField server control programmatically

Keep the HTML code as it is in Method 1.

Modify the server side code as follows

protected void Page_Load(object sender, EventArgs e)
{

//Create a HiddenField server control programmatically.
System.Web.UI.WebControls.HiddenField hiddenField = new System.Web.UI.WebControls.HiddenField();
hiddenField.ID = "sharedData";
hiddenField.Value = "New client initial value on Page 3";

//Important to add the control to the Form not the Page.
Page.Form.Controls.Add(hiddenField);
}

Method 4:Create and dynamically register an array on the server
Keep the HTML code as it is in Method 1. and modify the getSharedData() function from in the Client Side javascrpit.

function getSharedData()
{
//Display the 5th element of the array, "5".
alert("Shared data is " + sharedData[4] + ".");
}

In the server side code make the following modifications.

protected void Page_Load(object sender, EventArgs e)
{

ClientScriptManager csm = Page.ClientScript;

//Create and dynamically register an array on the server that is rendered in the JavaScript on the client.
String arrayName = "sharedData";
String arrayValues = "1,2,3,4,5";

csm.RegisterArrayDeclaration(arrayName, arrayValues);

}

Creating and customizing site pages using sharepoint designer

video

Some Beautiful Painting



























2009-04-26

Tutorial 2:Receiving Data into the Workflow using Parameters

Receiving Data into the Workflow using Parameters:
In this exercise, you will modify the workflow we created in Tutorial 1 to receive data into our workflow when it is started. You will also modify the code in our Code activity’s handler to display the input values. Finally, you will change our startup project to use a Windows Forms (WinForms) host that will allow us to enter the input values and create an instance of our workflow.
Note: There are two general approaches for receiving data into a workflow when it is started. They are Parameters and Events. With parameters, a list of parameter names and types are defined with the workflow. These parameter values are passed in by a host when it starts a new instance of the workflow type. With events, workflow authors add an activity that receives an event and data associated with the event. Events are generally specific to the host and custom activities that have been designed to handle the event.
Task 1 – Define parameters for the workflow
1. In Visual Studio 2005 with the HelloWorldWorkflow project open, double click on the Workflow1.xoml file in Solution Explorer to open the Visual Studio workflow designer. 2. Right-click the workflow background in the Visual Studio workflow designer and click View Code, or select the View Code menu item. 3. Inside the Workflow1 class, type “prop” and select prop from the intelli-sense menu, to insert the snippet hit tab.

4. Fill in each of the highlighted areas in the snippet to create a string property called FirstName with a private member called firstName as shown below.


5. Use the same technique to include another string property called LastName with the private member lastName.
Task 2 – Modify the Code Activity
1. In this exercise we will use a Windows Forms application as the workflow host. Since we want to display a message box from the workflow application, we need to add a reference to the assembly for Windows Forms. Select the Project Add Reference menu item.
2. On the .NET tab in the Add Reference dialog, select System.Windows.Forms from the list of assemblies and click the OK button.

3.Right click on the Workflow1.xoml.cs file in Solution Explorer and select the View Code menu item from the context menu. Navigate to the method codeActivity1_CodeHandler in the 1. Workflow1.xoml.cs source file. This method is the code handler for the code activity in the workflow.
4. Modify the code in the codeActivity1_CodeHandler method to get the parameter values and display a Message Box with the FirstName and LastName values:
private void codeActivity1_CodeHandler(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show(
"Hello world: " + firstName + " " + lastName);
}
Task 3 – Execute the modified workflow
Now we’re ready to test the modified workflow. Instead of using a console host application as we did in Exercise 1, in this exercise we’re going to add a new Windows Forms application and some pre-written code as a host for our workflow.

1. In Visual Studio 2005, with the HelloWorldWorkflow solution open, add a new project, WinFormTestHost to the solution by selecting the File Add New Project menu item as shown below:


3.Design the Windows forms as follows

Step 5. Write the following code in the windows application
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace WinFormTestHost
{
public partial class Form1 : Form
{
private WorkflowRuntime wr;
private string workflowAssembly = "";
private string workflowTypeName = "";
public Form1()
{
InitializeComponent();
workflowAssembly = "HelloWorldWorkflow";
workflowTypeName = "HelloWorldWorkflow.Workflow1";
}
private void btnStartWorkflow_Click(object sender, EventArgs e)
{
if (wr == null)
{
wr = new WorkflowRuntime();
wr.StartRuntime();
}
Dictionary parameters = new Dictionary(); parameters.Add("FirstName", txtFirstName.Text);
parameters.Add("LastName", txtLastName.Text);
WorkflowInstance instance = wr.CreateWorkflow(typeof(HelloWorldWorkflow.Workflow1), parameters);
instance.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (wr != null)
{ if (wr.IsStarted)
{ wr.StopRuntime();
}
}
}
}
}
4. Using the Solution Explorer tool window, right click on the WinFormTestHost project and select Set as Startup Project from the context menu.


5. Now we need to make sure that the WinFormTestHost application can use the new workflow. Add a reference to the HelloWorldWorkflow project by right clicking on the References folder for the WinFormTestHost in Solution Explorer and selecting Add Reference from the context menu.
6. In the Add Reference dialog window, select the Projects tab.
7. Select the HelloWorldWorkflow project from the list and press the OK button to close the Add Reference dialog window and add the new reference.

8. We also need to ensure that the WinFormTestHost has references to the Windows Workflow Foundation system assemblies. Add these references by right clicking on the References folder for the WinFormTestHost in Solution Explorer and selecting Add Reference from the context menu
9. In the Add Reference dialog window, select the .NET tab, scroll down and select the entries shown below and click OK.

10. Right click on the Workflow1.xoml.cs file in Solution Explorer and select the View Code menu item from the context menu to open the code-beside class for the workflow.
11. Set a breakpoint in the codeActivity1_CodeHandler method.
12. Compile and run the solution under the Visual Studio debugger by pressing F5 or selecting the Debug Start Debugging menu command.
13. The WinFormTestHost will start and display a window containing fields for entering a First and Last Name.
14. Enter values in the First name and Last name fields
15. Click the Start Workflow button to instantiate a new instance of the HelloWorldWorkflow.Workflow1 and pass in the First name and Last name values as parameters.(Images are same as Task3-Step 3)
16. Visual Studio 2005 will then break into debug mode for the codeActivity1_CodeHandler method. Continue execution of the workflow by selecting the Debug Continue menu item.

17. When the code activity finishes executing you will see a message box with the first name and last name were passed as parameters to the workflow.
18. Close the WinFormTestHost application to stop the host and stop the debugger.

Reference:http://msdn.microsoft.com/workflow

Tutorial 1:Create a Simple Workflow

A tutorials on Windows workflow Foundation(WWF),Step by step tutorials on Windows workflow Foundation(WWF),A biginner tutorials on WWF
Create a Hello World Workflow
In this exercise, you will create a very simple “Hello World” workflow using the Visual Studio 2005 designer for Windows Workflow Foundation, referred to as the Visual Studio workflow designer in the remainder of this document. The Hello World workflow will be a sequential workflow that includes a single code activity. The code activity will be used to write the phrase “Hello, World!” to the console at runtime. You will explore the workflow definition and the code-beside for the workflow. Finally, you will see how to execute your workflow using a simple host and debug your workflow using Visual Studio 2005.
Task 1 – Create a new Workflow Project

1. Open Visual Studio 2005 by going to the Start Menu Programs Microsoft Visual Studio 2005 Microsoft Visual Studio 2005
2. In Visual Studio 2005, select the File New Project menu command.
3. Visual Studio 2005 will display the New Project dialog window.
4. In the New Project dialog window, expand Visual C# Workflow in the Project Types tree on the left side.
5. Select the template named “Sequential Workflow Console Application” and enter the following values:
Name: HelloWorldWorkflow
Location: C:\Windows Workflow Foundation\Labs\Lab01

6. You should now have a new solution and workflow project.
7. The project template has a Workflow1.cs which we will remove as we will be using a simpler kind of workflow for this lab. Click on Workflow1.cs and press the DEL key. Click the okay button to confirm.
8. Right click on the HelloWorldWorkflow project in Solution Explorer and select Add New Item from the context menu.
9. In the Add New Item dialog window, select the item template named Sequential Workflow (with code separation) and click the Add button to add the new workflow to the HelloWorldWorkflow project.

Note: It may be easier to read the template names if you change the view of the Add New Item dialog to large Icons by clicking on the toolbar icon in the upper right corner.

10. The new Sequential Workflow project will now contain two files: Workflow1.xoml and Workflow1.xoml.cs. Workflow1.xoml contains the XML markup that represents the workflow type. Workflow1.xoml.cs contains the code-beside class for the workflow.


Task 2 – Add a code activity

1. Double click on the Workflow1.xoml file in Solution Explorer to open the Visual Studio workflow designer.
2. In the workflow designer, select the View Toolbox menu command to display the toolbox with available activities.
3. You may need to expand the Windows Workflow category in the toolbox to view the Windows Workflow Foundation activities.

4. Select the Code activity from the toolbox.
5. Drag and drop the Code activity to the design surface for the Sequential Workflow.
6. Notice the red exclamation mark on the new Code activity. Click the exclamation mark to view the smart tag and the reason for why it’s being displayed.


7. Selecting the smart tag will cause the Properties tool window to be displayed with the ExecuteCode property highlighted.
8. Enter the value codeActivity1_CodeHandler for the ExecuteCode property and press Enter.
9. This will cause a new method or handler to be added to the code-beside class for the workflow. Visual Studio will automatically open the Workflow1.xoml.cs code file and display the new codeActivity1_CodeHandler method. Alternatively, you can switch from the design view to the code-beside for the workflow by double-clicking on the activity or by selecting the View Code menu item.
10. The code-beside class is a partial class that inherits from the SequentialWorkflowActivity base class. This code-beside class will have the same name as the workflow. You should have the following code in your code-beside class:
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;

namespace HelloWorldWorkflow
{
public partial class Workflow1 : SequentialWorkflowActivity
{
private void codeActivity1_CodeHandler(object sender, EventArgs e)
{
}
}
}

11. Insert the following code in the codeActivity1_CodeHandler method to output the string “Hello, World!” to the console:

private void codeActivity1_CodeHandler(object sender, EventArgs e)
{
Console.WriteLine("Hello, World!");
}

12. Select the Build Build Solution menu command to compile and build your project. Verify that there are no compiler errors or warnings.

Task 3 – Run the new workflow with Debugging

For this exercise we are going to use the simple host in program.cs that comes with the project template that was selected. Alternatively, you could build your own workflow host application by using the workflow runtime APIs defined in the System.Workflow.Runtime namespace.

1. Open the Visual Studio workflow designer by double clicking on workflow1.xoml in the solution explorer.
2. Click on the codeActivity1 activity to select it and set a breakpoint on it.
3. To set the breakpoint right-click on the code1 activity and choose Breakpoint Insert Breakpoint.
4. You should now see a red circle to the left of the code1 activity.






5. Compile and run the solution under the Visual Studio debugger by pressing F5 (or selecting the Debug Start Debugging menu command).
6. The ConsoleTestHost will start a workflow instance and that instance will break in the debugger when it gets to the code activity. The yellow box indicates the activity that the debugger is stopped at
7. Choose Debug Step Into from the menu and the debugger will step into the start of the code1_CodeHandler method.
8. Choose Debug Step Into a couple of more times and you should see “Hello, World!” written out into the test host’s console window.
9. The workflow will now complete and the program finishes.

2009-04-23

Generate Excel from Gridview when using Masterpage

Generate Excel from Gridview when using Master page:
You can find many example of generating excel from Gridview.Those all are fines when we are not using master page.But when we use Masterpage & in the child page we have a gridview and we want to generate the excel from that grid view ,then we need to make some modification of these codes.Following are the example of that kind of code.

Step 1.Take a Gridview "GrdCommon" in your page & bind it from the server side code.
Step 2.Make a HTML table "tblExcelFirst" in any of the section of your HTML body.Dont Worry,that will not be displayed when you run your web page ,so it will not affect your output.

<table id="tblExcelFirst" runat="server">
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>

Step 3.Write the following method in your server side code.

public void generateExcel()
{
string fileName = string.Empty;
HtmlForm frm = new HtmlForm();
this.Controls.Add(frm);
{
frm.Controls.Add(GrdCommon);
frm.Controls.Add(tblExcelFirst);
fileName = "MyReport";
}

Page.Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
frm.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
Response.End();
}

Step 4.Call this method "generateExce" from your button click Event which will generate Excel from your gridview

Step5.If you get some error
RegisterForEventValidation can only be called during Render();

Then put the follwoing property in your page directive of your HTML page

EnableEventValidation="false"
ValidateRequest="false"

and your page directive will be looked like

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailReport.aspx.cs" Inherits="_DetailReport" MasterPageFile="~/Master/MasterPage2.master" Theme="Theme1" EnableEventValidation="false" ValidateRequest="false" % >