Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, June 16, 2010

DataTable To String Array in C# without using a for Loop

Many time we need need to get data from dataset\Datatable to array to pass it to some function or third API like x axis or y axis series of chart controls or to some other reporting or data binding control may be dropdown. it becomes difficult to get the data of a column(s) in array and finally we end up writing a for loop. here is a sample example by which we can simply get array of a column(s) with out a for loop
public static string DataRowToString(DataRow dr)
{
       return dr["columns"].ToString();
}
public string [] DataTableToArray(DataTable dt)
{
     DataRow[] dr = dt.Select();
     string [] strArr= Array.ConvertAll(dr, new Converter(DataRowToString));
     return strArr;
}

Array.ConvertAll() function simply converts the array of one to another so here in above example we are passing dr as an araay of datarows in first arguments. second argument is a Converter delegate type which convert one type to another so in this we will pass a link to delegate which is DataRowToString() function ,the delegate should know the input datatype and output datatype which is datatrow and string in this case respectively. function DataRowToString noe simply takes a datarow and return the string value for the column specified. which can be extended for multiple columns also.

Ref: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/46ef6ca8-7f66-489a-a0f6-b6b7c4200d16

Monday, January 4, 2010

Content migration from documents to wiki (MediaWiki)

This article will cover following topics
• Statement of problem
• Feasible solutions to achieve the goal
• Automating conversion of documents using VBA macros
       o What are VBA macros
       o Functional details
• Technical aspects
       o Technology used
       o Class details
       o IO/user interface
• Configuration
       o How to use the application
       o Extend the application to web or windows
       o Exception
       o Limitation and support
Statement of problem:
To convert documents (doc/pdf/excel) to wiki formatted text so that it can be directly hosted on a wiki server and a mass import of content or document import to wiki can be achieved.
Feasible solutions to achieve the goal: The following two approaches can be followed to achieve the solution.
• Automating conversion of the documents in wiki text, using VBA macros (preferred)
• Reading the entire content with inline formatting and applying wiki syntax to it.
Automating conversion of documents using VBA macros:
• What are VBA macros: Macros are Code written in VBA ,is compiled[ to a proprietary intermediate language called P-code (packed code), which is stored by the hosting applications (Access, Excel, Word) as a separate stream in Structured storage files (e.g. doc or xls) independent of the document streams. The intermediate code is then interpreted.
• Functional details: following steps are mentioned below:
     o Write a macro for each document type as excel, word or ppt which can convert the content in wiki format by persisting the data/formatting and save the output temporarily in the same file
     o Save the macro in .bas format (change/set the extension to .bas)
     o Automate the office documents using .net libraries which can attach the corresponding macro to the document and execute the macro on the documents.
     o Read the output (wiki formatted text) generated by macro and publish it to the hosted wiki using the Mediawiki API’s for .net

Technical aspects:


Technology used: Asp.net, VBA Macros, PHP, Media Wiki, IIS, apache web server
       o write macro for each excel and word documents to convert in wiki formatted text
       o create .net based class library to convert PDF to word document
       o create .net based class library to automate the office application which can add and execute the macro
Class details: project contains a class library (wikiconversion) to automate the document conversion, media wiki API’s (wikiaccess) and a console program to invoke the application


IO/user interface: the project includes a console application by which the application can be simulated, hence there is no visible UI design. It takes input from the folder Documents read all documents in the folder and hosts the doc and excel type in media wiki. An output file is generated in the Output folder under Documents with the current timestamp with the status of documents processed. (Same library can be extended for any web or window application as needed)


Configuration: Following configuration required to run the application

1. A Mediawiki hosted on apache server (mediawiki should support the call From API e.g. $wgEnableAPI=true in localSettings.php file)
2. All the documents that has to be converted must be in documents folder of the application
3. Macros folder which consist macros for word and excel file, should be in the application with relevant word and excel macros. For further details on macro please follow this link http://en.wikipedia.org/wiki/Visual_Basic_for_Applications
4. Wikiconversion.config must be updated with relevant config values like mediawiki server name and various files path

o How to use the application: set the configuration values in config file appropriately, place the file to be converted in documents folder and run the content import project

o Extend the application to web or windows: Create a web or window application, and call the various functions available in wikiconversion class (refer the code written in Main function for more details)

o Exception: Any corrupted file or very big file in size might take either too long to host on wiki or fail to do so. Accuracy of Conversion from documents to wiki depends on the macros placed in application Macro can be replaced for better output as further if available. Current macros convert the most of features/format appropriately still some issues can be there in word macro.

o Limitation and support: currently application support only MS-Word and MS-Excel file to convert and host in media wiki but the same can be extended to PDF,HTML,PPT by converting them to MS-word documents.URL generated in output file might mislead sometimes

References: http://www.mediawiki.org/wiki/API

Introduction to Web Parts in ASP.NET/MOSS 2007

Content:

• Introduction
• System requirement
• Web part framework
• Comparing with asp.net
• Creating a new web part solution
• Deploying and debugging



Introduction:

Microsoft ASP.NET 2.0 provides a Web Part infrastructure that helps you build custom Web Parts and deploy them to Web sites built using Microsoft Windows SharePoint Services 3.0. This article provides a walkthrough how to build custom Web Parts that work in both standard ASP.NET 2.0 Web sites and Windows SharePoint Services 3.0.



Web part framework:

A Web Part is an ASP.NET server control designed to be edited and modified by users in the browser. It works as a component of a SharePoint site that presents information pulled from multiple data sources. Web Part pages allows to personalize information relevant to the needs by updating the value of specific Web Part properties. SharePoint Web Parts are UI elements that support both customization and personalization.

The Web Part infrastructure in Microsoft Windows SharePoint Services 2.0 and Microsoft Office SharePoint Portal Server 2003 provides a framework to build custom Web Parts targeted to Microsoft SharePoint Products and Technologies by using managed code.

ASP.NET 2.0 includes a new Web Part control set that allows site customization and personalization on custom Web sites that are independent of MOSS. The Web Part infrastructure in Windows SharePoint Services 3.0 exists on a layer above the ASP.NET 2.0 Web Part infrastructure.






Comparing with asp.net:


Office SharePoint Server 2007 and Windows SharePoint Services 3.0 are built on top of the ASP.NET 2.0 Framework. Windows SharePoint Services 3.0 uses the ASP.NET 2.0 Web Part infrastructure to take advantage of features such as master pages and custom Web Part development while providing a complete set of Windows SharePoint Services features, such as document services, events, workflow, search, site columns, content types and more.

We can build Web Parts for Windows SharePoint Services 3.0 in two ways:

• Create custom ASP.NET 2.0 Web Parts.
• Create SharePoint-based Web Parts.

The following table provides a decision matrix to help you choose the best option depending on your business needs.


Creating a new web part solution:
 
To create a new Web Part solution
o Open VS 2005 > File menu> click New, and then select Project.
o In Project types, select Visual C#, and then select SharePoint.


o In Templates, select Web Part.


o Specify a new name, location, or solution name of Web Part, and then click OK. The extensions create a new Web Part solution project, which includes the following:

 References to the Microsoft.sharepoint

 AssemblyInfo.cs, a file that enables you to specify company and product information for the Web Part assembly, and version information

 Temporary.snk, a temporary signature key file for the Web Part assembly

 A Visual C# code file for the Web Part, named the same as the Web Part name

 By default, the code file for the Web Part contains the following:

 using statements for the necessary System and Windows SharePoint Services namespaces, such as Microsoft. SharePoint, Microsoft.SharePoint.WebControls, and Microsoft.SharePoint.WebPartPages

 An empty Web Part class that inherits from System.Web.UI.WebControls.WebParts.WebPart

o Add the code you want to the Web Part class.



Customizing the Web Part Solution Package


The Web Part project template automatically generates the XML files needed to package your Web Part as a MOSS 2007 feature for deployment and activation. The required GUIDs contained in the XML files are also generated automatically.

The extensions generate a .webpart file as the element.xml file for the Feature containing the Web Part. Every Web Part should have a .webpart file, which is an XML file that describes the Web Part. The .webpart file also makes your Web Part appear in the Web Part gallery in MOSS 2007.

we can customize the information in these XML files by editing solution, Feature, and element properties on the SharePoint Solution tab in project's Properties dialog box, as follows:



o Solution Information in this node is written into the manifest.xml file for the Feature. You can set the following solution property:

o Name The name of your Web Part solution.

o Feature Information in this node is written into the feature.xml file for the Feature. You can set the following feature properties:

o Folder Name The name of the folder to contain the files for this Feature.

o Title The title of the Feature. Limited to 255 characters.

o Description A longer representation of what the Feature does.

o Version Specifies a System.Version-compliant representation of the version of a Feature. This can be up to four numbers delimited by decimals that represent a version.

o Scope The Feature scope. Can contain one of the following values: Farm (farm), WebApplication (Web application), Site (site collection), or Web (Web site).

o Hidden Hides the feature. This attribute is FALSE by default.

o Default Resource File Indicates a common resource file for retrieving Feature XML resources.

o Element Information in this node is written into the element.xml file for the Feature. As mentioned earlier, this file contains the information usually contained in a .webpart file. You can set the following element properties:

o Title The title of your Web Part on web page.

o Description The description of your Web Part that you want to appear in the Windows SharePoint Services user interface.

o ImportErrorMessage The error string to display if Windows SharePoint Services is unable to import your Web Part solution.


Customizing the Web Part solution feature package


o In Solution Explorer, right-click the Web Part project, and then select Properties.

o In the Properties window, select SharePoint Solution. This tab lists the nodes that contain the properties for the solution package that the extensions will generate.

o Expand the Solution node, and then expand the Feature node and the Element node.

o To edit properties for a node, click a node, and then edit the properties. For example, click the Element node, and then edit the values for the Title, Description, and ImportErrorMessage keys.

o To commit your changes for a node, click in the Description value field.




Deploying and debugging:

We can deploy and start debugging of the Web Part simply by pressing F5.

When you press F5, the extensions automatically build, deploy, and initiate debugging of Web Part solution Feature. To accomplish this, the extensions perform the following actions automatically:

o Build the Web Part assembly.

o Package the Web Part solution as a Windows SharePoint Services Feature.

o If this Web Part solution was deployed previously, the extensions retract the previous version of the Web Part solution Feature.

o Install your Web Part assembly to the global assembly cache using gacutil utility

o Deploy and activate your Web Part solution Feature in Windows SharePoint Services.

o Add your Web Part to the Safe Controls list.

o Restart Microsoft Internet Information Services (IIS) by invoking the iisreset command.

o Attach to the w3wp processes to enable debugging.


Saturday, December 5, 2009

Singleton Design Pattern

Singleton design pattern
Design patterns are useful to implement a functionality of known problem. Singleton pattern is a object creational pattern which helps when you want only and only one instance of your class

You don’t allow the consumer of your class to create the instance but return a instance to the calling class by a static property and private\protected constructor
Here is a sample implementation
Class SingletonPattern
{
Private SingletonPattern _instance ;

Private SingletonPattern(){}

Public static SingletonPattern getInstance()
{
        If(_instance==null)
       {
            _instance =new SingletonPattern();
        }
return _instance;
}
}

Key considerations in singleton patterns:

Thread safety: when multiple threads are trying to get the only instance it may behave inconsistently so you must consider locking the object e.g.

LOCK(_instance)
{
      if(_instance==null)
      {
       _instance =new SingletonPattern();
       }
       return _instance;
}
Lazy initialization: when you initialize the instance as late as it requires called as lazy initialization. To ensure thread safety we can initialize the instance while declaring it in the class but that comes with a cost of object creation as soon as the class instantiate. Above given example is a lazy initialization where we initialized it in getInstance function. Another way to do is as follows
Class SingletonPattern
{
              Private SingletonPattern _instance= new SingletonPattern() ;
              Private SingletonPattern(){}
              Public static SingletonPattern getInstance()
              {
                            return _instance;
              }
}
Private Vs Protected constructor: singleton pattern doesn’t suggest to create a public constructor so which access modifier should we use protected or private.
Well all that depends on the functionality required but if you want to inherit your singleton class you must have to provide a protected constructor

Difference in static class implementation and Singleton pattern:
  • Static class doesn’t represent the instances but represents a global variable while singleton is only possible instance of a class
  • Static classes can’t be passed as objects in a function call
  • Singleton classes can implement interfaces while static classes can’t
  • Initialization may be lazy or during the class load in singleton but static simply initialized when class loads in the memory

 Singleton pattern mostly used in scenarios when object initialization is heavy and program can’t afford to do so every time for almost similar operation



Wednesday, September 30, 2009

Creating a Tag Cloud using C#

Introduction:
A tag cloud is a visual depiction of user-generated tags used typically to describe the content of web sites, which is basically a feature of web 2.0 sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.
A tag cloud is a set of related tags with corresponding weights. Typical tag clouds have between 30 and 150 tags. The weights are represented using font sizes or other visual clues.


Types of Tag Cloud:

There are three types of tag cloud representation in WEB 2.0 as described below:
1) In the first type, size represents the number of times that tag has been applied to a single item. This approach is being used to display metadata about an item.
2) In the second type, size represents the number of items to which a tag has been applied,
This represents the popularity of a particular tag.
3) In the third type, tags are used as categorization method for content items. Tags are represented in a cloud where larger tags represent the quantity of content items in that category.
In this document, second type tag cloud is being created, where tag size is the token for the popularity of a particular tag. Tag’s size shows that how many times that particular tag is being used for tagging.

Tag Cloud Implementation:
In this approach, Tags information is stored in Tag.xml file which will provide necessary data to create tag cloud .This information can be stored in database or file system as per requirement.
Tags.xml is used to store following information:-
Tag-Id Attribute depicts uniqueness of the tag, so that no repetitive tags should be displayed in the user control.
Tag-Count Attribute defines the size of the tag that will be displayed in the user control. This count defines the uses of that particular tag. Every time an existing tag is used for tagging, Count increases by one.
The tag size is shown using a simple logic. What the user controls does is that it displays top 100 most popular tags. The tags in the xml file are sorted in descending order as per their count and then the top 100 are picked. The size of those top 100 tags is then defined by the formula:
(Tag count/max. count) x 30 pixel
Thus the most popular tag will be having the size of 30 pixel and later tags will have size with respect to most popular tag.
The below shown xml file displays all the necessary information to create a tag cloud.
Tags.xml
<tags>
<tag id="1" count="34">india</tag>
<tag id="2" count="33">chandigarh</tag>
<tag id="3" count="33">symonds</tag>
<tag id="4" count="34">adobe</tag>
<tag id="5" count="71">infosys</tag>
<tag id="6" count="36">microsoft</tag>
<tag id="7" count="156">Amir Khan</tag>
<tag id="8" count="38">tata motors</tag>
<tag id="9" count="39">bse</tag>
<tag id="12" count="40">suzene</tag>
<tag id="13" count="39">bhatinda</tag>
<tag id="14" count="23">ABB</tag>
<tag id="15" count="50">BHEL</tag>
<tag id="16" count="11">Reliance natural</tag>
<tag id="17" count="23">Asia electronics</tag>
<tag id="18" count="56">jaypee hydro</tag>
<tag id="19" count="30">bank of india</tag>
<tag id="20" count="58">HDFC</tag>
<tag id="21" count="10">Asp.Net</tag>
<tag id="22" count="78">Atlanta</tag>
<tag id="23" count="20">tiger</tag>
<tag id="25" count="47">EMEA</tag>
<tag id="26" count="50">wedding</tag>
<tag id="27" count="11">ONGC</tag>
</tags>
Create a New Visual studio C# project name Forum3.UserControls.In this project directory ,create a New folder name xml and place tags.xml file there, now a tag cloud can be created as a User Control.
By Using C# Code:
Create a User Control name UCTagCloud in Visual studio 2005.
It consists two files:-
• UCTagCloud.ascx
• UCTagCloud.ascx.cs

Now Copy the following code in UCTagCloud.ascx
<%@ Control Language="C#" AutoEventWireup="true" Inherits="Forum3.UserControls.UCTagCloud, Forum3.UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18c318ff50f694f2" %>
<table id="TABLE1" runat="server" style="width: 100%">
<tr>
<td style="width: 100%">
</td>
</tr>
</table>

And copy the following code in UCTagCloud.ascx.cs.
public partial class UCTagCloud : System.Web.UI.UserControl
{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
int mincount;
ds = new DataSet();
//Get Tags.xml Data into Dataset
ds.ReadXml(Server.MapPath("./xml/Tags.xml"));
//Sort the tags data on Its Count
ds.Tables["Tag"].DefaultView.Sort = "count desc";
DataTable dt = ds.Tables["Tag"].DefaultView.ToTable();
//Get Row count of Table
int rowCount = dt.Rows.Count;
//Get Max value of count in existing Data
int maxcount = Convert.ToInt32(dt.Rows[0]["count"].ToString());
if (rowCount > 100)
{
//If More then 100 tags are available
//Get the Value of 100 th Tag as Minimum value of Count from sorted data
mincount = Convert.ToInt32(dt.Rows[100]["count"].ToString());
}
else
{
//If less then 100 tags are available
//Get the Value of last Tag as Minimum value of Count from sorted data
mincount = Convert.ToInt32(dt.Rows[rowCount-1]["count"].ToString());
}
//Select tags data from data table which have count value more or equal then minimum count to display in tag cloud
DataRow[] drc = dt.Select("count>=" + mincount, "tag_Text");
dt = ds.Tables["Tag"].DefaultView.ToTable();
//For each tag to diplay
foreach (DataRow dr in drc)
{
HtmlAnchor a = new HtmlAnchor();
//Assign URL as a hyperlink to each tag
//User will be traversed to this link when click on particular tag
a.HRef = "http://********:999/search.aspx?q=" + dr["tag_Text"].ToString();// xnod.InnerText;
//Assign inner text to Display as a Tag
a.InnerText = dr["tag_Text"].ToString();
//Assign Text to Display as a Tag
a.Title = dr["tag_Text"].ToString();
//Calculate size(weightage) of each tag based on its count and maximum count value
double normalWeight = (Convert.ToDouble(dr["count"].ToString()) / maxcount) * 30;
//Assign Font size to Each Tag according to its weightage
a.Style.Add(HtmlTextWriterStyle.FontSize, normalWeight.ToString());
//Add tags in a Htmltable to display
this.TABLE1.Rows[0].Cells[0].Controls.Add(a);
this.TABLE1.Rows[0].Cells[0].Controls.Add(new LiteralControl(" "));
}
}
}
}

Results will be displayed as in picture

Please note that the size of some tags is too small (the tag is not popular), there is possibility that it will be difficult to read. To rectify this we need to implement the “tooltip” on all the tags as shown in the picture above.
However it depends upon the developer choice whether he/she wants to implement this functionality or not.




Friday, December 5, 2008

Arrays in C# : Value type or Ref type

Array Class is the abstract class provides methods for manipulation of array....
int [] intArray;
intArray = new int[5]

string [] names;
names = new string[10];

now from above which one is value type and which one is refrence type (Int is value type and String is refrence type)
 
ok the topic is interesting lets's play with it
 
 
as we all know the difference in readonly and const keyword in C#
readonly can be applied with only ref type and const can be only with value type except string
 
and if you try to make the above said array to const it will show error while it will work fine with readonly
try using this line of code in your program
 
you may also try this see the error
public const int[] intArray = new int[5];

now lets do another test on these arrays
declare one readonly array and try to change it svalue

like readonly int [] intarray = {1,2,3}

intArray[1] = 4

it will execute fine

because array is ref type so ref remains same when readonly but value can be changed
 
 
so we can finally conclude that all array are refernce type whether it contains value type or reference type

Monday, January 28, 2008

Creating Sites and List folders in a SharePoint using C# programmatically

Purpose of the Content:
Objective of this document is to throw some light on object model in MOSS using C#
This article will cover following topics
1. Introduction
2. Prerequisites
3. SPWebCollection.Add Method
4. Creating sites in SharePoint
5.SPListItemCollection.Add Method:
6.Creating folders in SharePoint List:


Introduction
The Windows SharePoint Services object model consists of forty-two namespaces in ten assemblies that are used in SharePoint sites on the server that is running Windows SharePoint Services1. The Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces provide types and members that can be used with lists and sites, as well as to manage a server or collection of servers that are running Windows SharePoint Services.

Now creating sites programmatically is one of the features that SharePoint SDK provides. The following sections will focus on how we can achieve this functionality.



Prerequisites :
Creating sites may be one of the task or the only that a web part does। So one must know how to develop and configure the web parts using SharePoint. Here I m using a web part consist a button on click of which, the new site creation logic will execute.

While sites are created through SharePoint we associate a site template name with the site. So it will be helpful to know how to develop and configure custom site templates if you want to use in new site. You can also refer the existing site template provided by SharePoint

SPWebCollection.Add Method:
The method Creates a Web site object with the specified site-relative URL, title, description, locale ID, and site definition or site template object.

SPWebCollection.Add Method (String, String, String, UInt32, SPWebTemplate, Boolean, Boolean) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
public SPWeb Add (
string strWebUrl,
string strTitle,
string strDescription,
uint nLCID,
SPWebTemplate WebTemplate,
bool useUniquePermissions,
bool bConvertIfThere
)

Parameters:


strWebUrl :A string that contains the new Web site URL relative to the root Web site in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite, specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite, specify Website/MyNewWebsite.

strTitle: A string that contains the title.

strDescription: A string that contains the description.

nLCID: An unsigned 32-bit integer that specifies the locale ID.

WebTemplate: An
SPWebTemplate object that represents the site definition or site template.

6· useUniquePermissions: true to create a subsite that does not inherit permissions from another site; otherwise, false.

bConvertIfThere: true to convert an existing folder of the same name to a SharePoint site. false to throw an exception that indicates that a URL path with the specified site name already exists.


Return ValueAn SPWeb object that represents the Web site.

Creating sites in SharePoint:

1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Place the site template in the following SharePoint directory
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\

4· Now call the following function with given required parameters
private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)

Usage:

SPWeb spEventWeb = this.CreateNewSite(spcurrentweb, ”MyNewSite”,”siteDescription”,”MyCustomTemplate”,”MyNewSiteURL”))

Where spcurrentweb is spweb object of current site
o siteName and siteDesc is the name and description of the new site to create
o siteTemplateName is name of the template of the new site
o strWebUrl is the relative URL of the new site which can be different or same as the siteName
Full function body is below

private SPWeb CreateNewSite(SPWeb spCurrentWeb, string siteName, string siteDesc, string siteTemplateName, string strWebUrl)
{
try
{
if (spCurrentWeb != null)
{
if (spCurrentWeb.Webs[siteName].Exists == false)
{
//get the template collection from site based on locale Id
SPWebTemplateCollection Templates = spCurrentWeb.Site.GetWebTemplates(Convert.ToUInt32(1033));
if (Templates != null)
{
//get the template object from template collection based on locale Id
SPWebTemplate siteTemplate = Templates[siteTemplateName];
if (siteTemplate != null)
{
//create a new site and add it in web collection of the parent web
using (SPWeb spChildWeb = spCurrentWeb.Webs.Add(strWebUrl, siteName, siteDesc, (uint)1033, siteTemplate, false, false))
{
if (spChildWeb != null)
{
spChildWeb.AllowUnsafeUpdates = true;
spChildWeb.Update();
return spChildWeb;
}
else
{
throw new Exception("Site " + siteName + "can't be created");
}
}
}
}
}
else
{
throw new Exception("Site " + siteName + " already exist");
}
}
return null;
}
catch (Exception ex)
{
LogException(ex, "Site can't be created!!! some exception has occoured");
return null;
}
finally
{
if (spCurrentWeb != null)
spCurrentWeb.Dispose();
}
}

SPListItemCollection.Add Method:

The following method Create an item that uses the specified folder URL, object type, and leaf name but requires the Update method to actually add the item to the list.

SPListItemCollection.Add Method (String, SPFileSystemObjectType, String) (Microsoft.SharePoint)

Namespace: Microsoft.SharePointAssembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

public SPListItem Add
(
string folderUrl,
SPFileSystemObjectType underlyingObjectType,
string leafName
)
Parameters

o folderUrl : A string that contains the server-relative URL of the folder, beginning with a forward slash; for example, /sites/mysite/subweb/Lists/mylist/myfolder.

underlyingObjectType : A
Microsoft.SharePoint.SPFileSystemObjectType value that indicates the object type. Only File and Folder are valid types for the underlying object type.


leafName: A string that contains the leaf name, which is everything after the last forward slash in the URL, including the file extension.

Return Value: A
Microsoft.SharePoint.SPListItem object that represents the new item.
Creating folders in SharePoint List:
1· Add the following namespaces and reference the DLL Microsoft. SharePoint.dll
using Microsoft.SharePoint;

2· Get the sp web object of the current site in which site is to create as
SPWeb spCurrentWeb = new SPSite(strSiteURL).OpenWeb(); where strSiteURL is the URL of the site as http://chdsez108269d:999/

3· Now call the following function with given required parameters


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
Usage:

spFolder spNewFolder = this.GetFolder(spcurrentweb, “MySiteLink”, “MyListName”, “MyFolderName”);
Where spcurrentweb is spweb object of current site
o MyListName and MyFolderName is the list name and folder name in the given list.
o MySiteLink is the relative URL of the new site which can be different or same as the siteName
Full function body is below


private SPFolder GetFolder(SPWeb spCurrentWeb,string strSiteLink, string strListName, string strFolderName)
{
using (spCurrentWeb)
{
if (!string.IsNullOrEmpty(strFolderName))
{
//create a folder with the given name in the event list if don't exist, otherwise return the existing folder
if (spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName).Exists != true)
{
spCurrentWeb.AllowUnsafeUpdates = true;
SPList spListEvent = spCurrentWeb.Lists[strListName];
//create a new folder in the list
SPListItem spFolderEvent = spListEvent.Items.Add(strSiteLink + "/Lists/" + strListName, SPFileSystemObjectType.Folder, strFolderName);
spFolderEvent.Update();
spListEvent.Update();
spCurrentWeb.Update();
}
//return the existing folder from the list
return spCurrentWeb.GetFolder("Lists/" + strListName + "/" + strFolderName);
}
return null;
}
}




References:
http://msdn2.microsoft.com/en-us/library/ms439689.aspx
http://msdn2.microsoft.com/en-us/library/ms448720.aspx