Wednesday, December 22, 2010

Linq to class objects

This example shows how to use the array of class object and its variables on run time using "LINQ".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class LinqClass
    public string Name;
    public string contact;
    public string city;


using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Data;

var sp = new[] {
          new LinqClass { Name="Murugesan",
                        new LinqClass { Name="Pandian",
        foreach (var n in sp)

Thursday, December 09, 2010

C# Writing XML strings on runtime

This is an example for creating the XML string from the dynamic data.

StringWriter sw = new StringWriter();
XmlTextWriter txtWriter = new XmlTextWriter(sw);
txtWriter.Formatting = Formatting.Indented;
DataSet myDataSet = new DataSet();
foreach (DataRow row in myDataSet.Tables[0].Rows)
txtWriter.WriteElementString("Name", row[0].ToString());


string s1 = sw.ToString().TrimStart('{');
string s2 = s1.TrimEnd('}');

Monday, December 06, 2010

SharePoint-Active Directory Synchronize

Please do not follow the logic that retrieving user details from the Active Directory mentioned here, please visit my TechNet article for alternate approaches

Last week,I prepared the small SharePoint utility to retrieving the Active Directory users and synchronize with SharePoint List.

public string LDAPUsers()
            string listD = "";
            string strResult = "";
            string strRes = "";
            DirectoryEntry entry = new DirectoryEntry("LDAP://domainName", "userid", "pAsSwrd");
            DirectorySearcher mySearcher = new DirectorySearcher(entry);
            mySearcher.Filter = "((objectCategory=Person))";

            foreach (SearchResult resEnt in mySearcher.FindAll())
                listD = listD + resEnt.GetDirectoryEntry().Name + ",";

            string[] test = listD.Split('=');
            for (int i = 0; i < test.Length; i++)
                strResult = strResult + test[i].ToString();

            string[] test1 = strResult.Split(',');
            for (int j = 0; j < test1.Length; j++)
                strRes = strRes + test1[j] + ",";
            return strRes.Replace("CN", ""); ;
Below code pushing the string array values in to SharePoint List.
SPSite site = new SPSite("http://moss:4100");
        SPWeb web = site.OpenWeb();
        SPList list = web.Lists["LDAP User"];
        string[] names = LDAPUsers().Split(',');
        for (int j = 0; j < names.Length; j++)
            SPListItem item = list.Items.Add();
            web.AllowUnsafeUpdates = true;
            item["Title"] = names[j].ToString();
            web.AllowUnsafeUpdates = true;
            web.AllowUnsafeUpdates = false;

Sunday, November 21, 2010

SPQuery Value retreiving

 SPSite site = new SPSite("http://localhost");
        SPWeb web = site.OpenWeb();
            SPList item = web.Lists["Friends"];

            SPQuery spQuery = new SPQuery();
            spQuery.Query = "" +
            SPListItemCollection ListItems = item.GetItems(spQuery);

            foreach (SPListItem items in ListItems)
                Response.Write((items["Name"].ToString()) +
"); } }

Monday, November 08, 2010

UserProfileManager - Webservice in Sharepoint

Listing all domain users in Sharepoint 2007 using UserProfileManager webservice class.
First create the proxy class using wsdl or  add webreference from Visual Studio.
The main difference in using webservice method is any user can access the resources within default network credentials.
But Sharepoint object model lets you use only with in production server with administrative privileges.

 localhost.UserProfileService service = new localhost.UserProfileService();
        service.Credentials = System.Net.CredentialCache.DefaultCredentials;
        int a = (int)service.GetUserProfileCount();
        for (int i = 0; i < a; i++)

Friday, October 15, 2010

Sharepoint 2007 migration to Sharepoint 2010

SharePoint 2007 upgrade to SharePoint 2010
Attach/detach the Content database
Check the SQL Server version and SQL Instance build number on the SharePoint 2007 farm.
Check the what instance has been used to storing the content database to point SharePoint 2007 site whether SharePoint 2007’s built in instance or external SQL Server instance.
If external SQL Instance have been used you must have the same SQL Server version and build number on targeting server same apply for built in SQL Instance. Otherwise version conflict will occur on migration time.
Scan thoroughly all the Solutions and Features those are installed on SharePoint 2007 and map with the sites those using the solutions.
Install these features and solutions on targeting machine before attaching the content database on SharePoint 2010 machine.

Step – I
Starting the detach operation on SharePoint 2007 machine.

Step –II

If there is active connection on the database, check the Drop check box.
Now the database will goes away from the tree view.
Go to physical location of your database. Caution on taking the copy of the detached file if there is more than one SQL Server instances are on your machine.
C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEX2K8\MSSQL\DATA
Copy the files named WSS_Content_10K.mdf and WSS_Content_10.ldf and place it on SharePoint 2010 machine to attach later to SQL Server.
Usually SQL SERVER 2008 or SQL SERVER 2008R2 on SHAREPOINT 2010.
Step- III

Attaching the detached database which we have got from SharePoint 2007 machine to SharePoint 2010

Once you attached the database go to stsadm command prompt on your SharePoint 2010 server.


Create new webapplication on SharePoint 2010 as follows:
By default SharePoint 2010 will use the SharePoint instance of the SQL Server.So let it is as it is.
After you created the site without errors,
Go to Central Administration – Application Management ->Select the Content Database.
Choose the newly created web application from the drop down menu.
It will shows the database name with some scrambled id prefix with “WSS_Content”.
Remove the content database as it shows.
Now you have only site skeleton without “Content Database”.
Add the content database using the STSADM tool or mount the database using SharePoint Power Shell

If you add the content database for the first time to your newly created website,
You will see the progress of database attaching to your new server.

I encountered the serious problem when I am migrating the site which had “U2UCAMLQUERYBUILDER” list items.

I downloaded the “C2UCA MLQUERYBUILDER” from the product site and tried to install it on SharePoint 2010 machine by clicking the “.EXE” file from the “Setup” Folder.
It gives the error says that “I must have installed Windows SharePoint Services 3.0”.
I overcome this issue by picking the “U2Ucamlquerybuilder.wsp” file and adding the solution on “Server Farm features of SharePoint 2010”.
First add the solution to SharePoint 2010 Farm
Deploy the solution with gacdeployment parameter

Thursday, September 23, 2010

subsites in sharepoint

this code snippet retrieving all sub sites from the root site in Share point Server 2007

SPSite site = new SPSite("http://win-j40e6cmrcl9/personal/administrator/");
string[] subsites = site.AllWebs.Names;
for (int i = 0; i < subsites.Length; i++)
SPWeb web = site.AllWebs[i];


Tuesday, September 21, 2010

Site deleting in sharepoint server

Deleting the site from the share point server can be done via STSADM.EXE and through the central administration.

switch command prompt

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\BIN\STSADM -o deletesite -url http://localhost/sites/Murugesan

Through Central Administration,

Click on Application Management and Delete Site collection,choose the site name under the web application.

Wednesday, September 15, 2010

Site backup in Moss 2007

Site backup in moss 2007 is not an rocket science anymore.
Download the tool Smigrate.exe from the Microsoft site.
extract under the Bin folder of the 12 hive.

pass the command
sMigrate.exe -w http://localhost/sites/Murugesan -f Murugesan1.fwp -u administrator -pw your password

Yes ! look at the command window for the status of the given command.

Friday, September 10, 2010

Listing all webpages from moss site

Listing the all the webpages from the site in MOSS 2007/sharepoint service
I used to itereate the file names using the Sharepoint Object Model's SPListItems

SPSite mySite = new SPSite("http://localhost/MurugesanSite/");
SPWeb myWeb = mySite.OpenWeb();
SPList NoOfPages= myWeb.Lists[2];
foreach(SPListItem items in NoOfPages.Items)


Monday, September 06, 2010

Calling usercontrol in sharepoint webparts

Create the usual User Control in and calling into Share point is simple process that reduces the complexity of deploying and developing the web part.
Place the 2 text boxes and label to create simple add two number calculator in your
On click of the button result will be displayed on label.

protected void Button1_Click(object sender, EventArgs e)
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
Label3.Text = (a + b).ToString();

Before using the user control check it on .aspx file by registering the user control in directives.

<%@ Register Src="~/Calculator.ascx" TagName="_userCntrl" TagPrefix="SP" %>

once you tested the user control on .aspx file,now you are ready to place the
user control design page calculator.ascx and source code file calculator.ascx.cs in to share point folder structure

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS

Now go to visual studio,select the Webpart template,

public class UserControlCalculator : System.Web.UI.WebControls.WebParts.WebPart
Control _cntrl;
string ErrorDesc;
public UserControlCalculator()
this.ExportMode = WebPartExportMode.All;

protected override void CreateChildControls()
_cntrl =Page.LoadControl("\\_layouts\\Calculator.ascx");

catch (Exception ex)
ErrorDesc = ex.Message.ToString();

protected override void Render(HtmlTextWriter writer)
catch (Exception ex)



Sunday, August 29, 2010

Sharepoint BDC

Sharepoint BDC Architecture

BDC [Business Data Catalog] is a service which part of MOSS 2007.
Its an middle man between external datasources and Sharepoint service.
It manages how the data should be passed between outside datasources are like
SQL Server and WebService using Metadata to Sharepoint service.
Example "DUET" its an collaboration software between SAP and Microsoft Office.
From SAP,Sibel or any other RDBMS data source can be used to supply the information to
SharePoint portal.
For this BDC uses the metadata to describe the APIs of business application.
This metadata model abstracts the underlying physical sources an provides a consistent and simple model of business applications to Sharepoint Service.

Runtime Object Model allows you to create,read,update and delete metadata objects in the Shared Services database.

Wednesday, August 25, 2010

Eventhandlers in MOSS 2007

Creating or adding extra customised features to the sharepoint components like
SharepointItems,List and WebEventReceivers is called "Features in Sharepoint/moss 2007".
usually developer create the customised action by deriving the event handler class of the sharepoints ie.SPItemEventReceiver,SPListEventReceiver and SPWebEventReceiver and attach to the sharepoint site.

Administrator installing the features and activate them on the site or web.

Synchronous Event:
Events that activate before the action occur
Example : FieldAdding event of SPListEventReceiver

Asynchronous Event
Events that activate before the action occur
Example : FiledAdded event of SPListEventReceiver

Wednesday, July 21, 2010

Sharepoint Object model

Sharepoint Object model

To programmatically deal with your Sharepoint services or officer server you need to
add the references Microsoft.Office.Server or Microsoft.Sharepoint to your
You can find this references under
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\ISAPI

These are my oftenly used classes.Here I categorised these classes

Document Library

Features [ EventHandling in sharepoint you can find these in Feature.XML as attributes]

Site Level

List Level

Solution Level




User Profile related [ Imports the namespace Microsoft.Office.Server.UserProfiles ]
UserProfilesManager [ In moss 2007 installed farm,Its obsolete]

Tuesday, May 11, 2010

selecting records between two dates

ALTER procedure [dbo].[uspLeaveDetails](@User varchar(15),@FromDate datetime,@ToDate datetime)

Select FromDate,ToDate,
NoOfDays,FirstName from UserDetails,LeaveDetails
where FromDate > =@FromDate AND ToDate <=@ToDate AND

Tuesday, March 30, 2010

Sharepoint Website Collection.

Listing all the websites from the share point site and its owner.

SPSite site = new SPSite("http://localhost");
SPWeb web=site.AllWebs;
foreach(SPWeb web in collection)

Listing all lists in the website
SPSite site = new SPSite("http://localhost/SiteDirectory/IT"); //IT-site name
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Posts"]; // a List in the site
foreach(SPListItem col in list.Items)
DropDownList2.Items.Add(col.Title.ToString()); // Item in the List


SPWebCollection lets you to enumerate the Websites in the Share point server.

SPSite site = new SPSite("http://win-zmmypcbnz7k/");

SPWebCollection collection = site.AllWebs;
foreach (SPWeb web in collection)

Monday, March 15, 2010

Webservice String array value in C #

When we works with Webservice,we can't use the .NET data types like DataSet or DataTable,ArrayList as return value.
So we need to convert these into unified data type such as string or string array.

public string[] RecordAll()
SqlConnection con = new SqlConnection("Server=Your server\\SQLExpress;Database=SPTest; Trusted_Connection=Yes");
DataSet ds = new DataSet();
ArrayList al = new ArrayList();
SqlCommand cmd = new SqlCommand("Select * from Registers",con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds, "Registers");
foreach (DataRow row in ds.Tables[0].Rows)
string[] stringArray = (string[])al.ToArray(typeof(string));
return stringArray;


Saturday, March 13, 2010

Querying the XML file using LINQ

In this example i tried to find the available balance by passing the account number as parameter to the function through Linq

XDocument doc = XDocument.Load("C:\\Account.xml");
var result = from ds in doc.Descendants("Account")
where ds.Element("IDNumber").Value == account.ToString()
select new
Balance = ds.Element("AvailableBalance").Value,
AccountID = ds.Element("IDNumber").Value

return result.ToArray();

My accounts XML will be



Friday, March 12, 2010

How sharepoint functioning

Its my scribble for understanding clearly what i learned from googling.

When you install the WSS 3.0 or Microsoft Office Sharepoint server 2007,WSS configures the IIS server to forward all requests regardless of file[such as HTML,ASPX or other web supported files]and content types[ such as .doc,.docx,.xls,ppt or.pdf or video streaming files] using the "Virtual Path Provider component".

In traditional web application ASP.NET framework process the file system[.aspx] alone.But in WSS or MOSS handles this in different way using Virtual Path Provider.
All site details and file name will be stored in MS-SQL Database or Windows Internal Database.WSS or MOSS fetch these details from the SQL Database.
We can deal with the database using SPContentDatabase object from the Microsoft.Sharepoint namespace to manipulate.

When you create the site in WSS 3.0,all site details,file name,contents such as webparts and context [Admin or user] will be stored in SQL Database.When accessing this site WSS serves from the SQL DB.

Tuesday, March 09, 2010

UserControl events in ASP.NET

Usercontrol's events
It occurs when user ends transaction
It occurs when user completes transaction
It occurs when usercontrol binds to DataSource
When user control(Server controls) releases the memory.This is last stage of server control's life cycle.
It occurs when usercontrol initializes.This is the first step of server control's life cycle.
this event occurs where server control load into Page Object
occurs after the controls loaded but prior to rendering.
Occurs where server controls unloaded from the memory

Tuesday, February 09, 2010

CacheManager in enterprise library 4.1

I worked around how to get familiar with Microsoft's Enterprise Library 4.1 Cache Manager.
GetCacheManager method of CacheFactory will retrieve the data from the Cached pool of data.

CacheManager cm = CacheFactory.GetCacheManager("Cache Manager");
DataSet ds = new DataSet();
cm.Add("CachedDataSet", ds.Tables[0]);
DataTable dt = (DataTable)cm.GetData("CachedDataSet");
foreach (DataRow row in dt.Rows)

Place the following line between or use the Enterprise Library 4.1 GUI to generate config setting for your web.config file.

Following code goes between tag