<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Microsoft Sharepoint Server &#187; Custom Webparts</title>
	<atom:link href="http://www.fivenumber.com/tag/custom-webparts/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fivenumber.com</link>
	<description>It&#039;s all about SharePoint</description>
	<lastBuildDate>Fri, 28 May 2010 09:21:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<image>
<link>http://www.fivenumber.com</link>
<url>http://www.fivenumber.com/wp-content/mbp-favicon/5.jpg</url>
<title>Microsoft Sharepoint Server</title>
</image>
		<item>
		<title>A quick look on Sharepoint object model programs &#8211; Part 2</title>
		<link>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs-part-2/</link>
		<comments>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs-part-2/#comments</comments>
		<pubDate>Mon, 29 Mar 2010 12:04:03 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[MOSS - Quick Look]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[Webparts]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=684</guid>
		<description><![CDATA[In my previous post you can have a quick look on Sharepoint object model programs &#8211; Part 1
Here, once again am going to post Sharepoint object model programs (part 2) with minimum lines of code and are really handy, which are actually most useful even.
Show only BLOG sites:
        [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post you can have <a title="A quick look on Sharepoint object model programs" href="http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs/" target="_blank">a quick look on Sharepoint object model programs &#8211; Part 1</a></p>
<p>Here, once again am going to post Sharepoint object model programs (part 2) with minimum lines of code and are really handy, which are actually most useful even.</p>
<p><strong>Show only BLOG sites:</strong></p>
<p>        //STS#0   &#8211;   Team Site<br />
        //STS#1   &#8211;   Blank Site<br />
        //STS#2   &#8211;   Document Workspace<br />
        //MPS#0   &#8211;   Basic Meeting Workspace<br />
        //MPS#1   &#8211;   Blank Meeting Workspace<br />
        //MPS#2   &#8211;   Decision Meeting Workspace<br />
        //MPS#3   &#8211;   Social Meeting Workspace<br />
        //MPS#4   &#8211;   Multipage Meeting Workspace<br />
        //WIKI#0  &#8211;   Wiki<br />
        //BLOG#0  &#8211;   Blog</p>
<p>static void Main(string[] args)<br />
        {<br />
            SPSite site = new SPSite(&#8220;http://servername:port&#8221;);<br />
            foreach (SPWeb web in site.AllWebs)<br />
            {<br />
                string template = web.WebTemplate + &#8220;#&#8221; + web.Configuration;<br />
                if (template.ToUpper() == &#8220;BLOG#0&#8243;)<br />
                {<br />
                    Console.WriteLine(web.Title);<br />
                }<br />
            }<br />
            Console.WriteLine(&#8220;Press any key to continue&#8230;..&#8221;);<br />
            Console.ReadLine();<br />
        }</p>
<p><strong>Show services and status in Sharepoint server farm:</strong><br />
static void Main(string[] args)<br />
        {<br />
            SPServiceCollection services = SPFarm.Local.Services;<br />
            foreach (SPService service in services)<br />
            {<br />
                Console.WriteLine(&#8220;Service Name: {0}&#8221;, service.Name);<br />
                Console.WriteLine(&#8220;Service Status: {0}&#8221;, service.Status);<br />
                Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&#8221;);<br />
            }<br />
            Console.WriteLine(&#8220;Press any key to continue&#8230;..&#8221;);<br />
            Console.ReadLine();<br />
        }</p>
<p><strong>Adding/Retrieving values to property bag:</strong><br />
static void Main(string[] args)<br />
        {<br />
            using (SPSite siteCollection = new SPSite(&#8220;http://servername:port&#8221;))<br />
            {<br />
                using (SPWeb site = siteCollection.RootWeb)<br />
                {<br />
                    site.Properties.Add(&#8220;TempKey&#8221;, &#8220;TempValue&#8221;);//Adding value<br />
                    site.Properties.Update();</p>
<p>                    Console.WriteLine(site.Properties["TempKey"]);//Reading value<br />
                }<br />
            }<br />
            Console.WriteLine(&#8220;Press any key to continue&#8230;..&#8221;);<br />
            Console.ReadLine();<br />
        }</p>
<p><strong>Read files in a folder:</strong><br />
static void Main(string[] args)<br />
        {<br />
            SPSite site = new SPSite(&#8220;http://servername:port&#8221;);<br />
            SPWeb web = site.OpenWeb();<br />
            SPFolder folder = web.GetFolder(&#8220;Shared Documents&#8221;);<br />
            SPFileCollection files = folder.Files;<br />
            foreach (SPFile file in files)<br />
            {<br />
                Console.WriteLine(file.Name.ToString());<br />
            }<br />
            Console.WriteLine(&#8220;Press any key to continue&#8230;..&#8221;);<br />
            Console.ReadLine();<br />
        }</p>
<p><strong>Get content database for all site collections:</strong></p>
<p> static void Main(string[] args)<br />
        {<br />
                SPSite site = new SPSite(&#8220;http://CentralAdminSiteURL&#8221;);<br />
                SPFarm farm = site.WebApplication.Farm;<br />
                SPWebService service = farm.Services.GetValue<SPWebService>(&#8220;&#8221;);<br />
                foreach (SPWebApplication webapp in service.WebApplications)<br />
                {<br />
                    foreach (SPSite mysite in webapp.Sites)<br />
                    {<br />
                        Console.WriteLine(mysite.Url+&#8221; &#8212;&#8211; &#8220;+ mysite.ContentDatabase.Name);<br />
                    }<br />
                }<br />
            Console.WriteLine(&#8220;Press any key to continue&#8230;..&#8221;);<br />
            Console.ReadLine();<br />
        }</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sharepoint list form generator</title>
		<link>http://www.fivenumber.com/sharepoint-list-form-generator/</link>
		<comments>http://www.fivenumber.com/sharepoint-list-form-generator/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 15:49:38 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[Tool Parts]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=598</guid>
		<description><![CDATA[Today I am going to show you how to generate a list form dynamically as soon as you select the list name you can see the form generated for you with file upload field (attachment). I also know that there is  an excellent solution Sharepoint Form Generator developed by Alon Havivi, but still I want [...]]]></description>
			<content:encoded><![CDATA[<p>Today I am going to show you how to generate a list form dynamically as soon as you select the list name you can see the form generated for you with file upload field (attachment). I also know that there is  an excellent solution <a title="Sharepoint Form Generator" href="http://sfg.codeplex.com/" target="_blank">Sharepoint Form Generator</a> developed by <a title="Alon Havivi's SharePoint 2007 Blog" href="http://havivi.blogspot.com/2009/06/sharepoint-form-generator.html" target="_blank">Alon Havivi</a>, but still I want to share with you, so that for some one the code may be helpful as a whole or part of it</p>
<p>No problem whether your list contains 1 field or 100 fields, code will  generate all the &#8216;n&#8217; no.of fields with file upload field (attachment) contained in the list. It loops through all the input fields and creates at runtime.</p>
<p>All  you have to do is, open visual studio 2005/2008 create a new project using webpart template use the code from <a title="FormGeneratorWebPart1.cs" href="http://www.fivenumber.com/wp-content/uploads/2009/10/SharepointFormGenerator-WebPart1.txt" target="_blank">WebPart1.cs</a> and <a title="FormGeneratorToolPart.cs" href="http://www.fivenumber.com/wp-content/uploads/2009/10/SharepointFormGenerator-ToolPart.txt" target="_blank">FormGeneratorToolPart.cs</a> build the project, place the .dll file in GAC or site bin directory, add the necessary safe control tag in Web.config file, import the webpart in to gallery, and add the same on to your site, after adding the webpart in your site you have to select the list name from the webpart properties, so that you can see the generated form similar to the form as in NewForm.aspx</p>
<div id="attachment_599" class="wp-caption aligncenter" style="width: 153px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/10/2.gif" rel="lightbox[598]"><img class="size-medium wp-image-599" title="Select the list name from the list of lists" src="http://www.fivenumber.com/wp-content/uploads/2009/10/2-143x300.gif" alt="Select the list name from the list of lists" width="143" height="300" /></a><p class="wp-caption-text">Select the list name from the list of lists</p></div>
<div id="attachment_600" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/10/1.gif" rel="lightbox[598]"><img class="size-medium wp-image-600" title="List form generated" src="http://www.fivenumber.com/wp-content/uploads/2009/10/1-300x109.gif" alt="List form generated" width="300" height="109" /></a><p class="wp-caption-text">List form generated</p></div>
<p>Download the complete source code (<strong>Please Note</strong>: Code cannot be viewed properly on the web page, so please use the below links to view the code or for downloading)</p>
<p><a title="FormGeneratorWebPart1.cs" href="http://www.fivenumber.com/wp-content/uploads/2009/10/SharepointFormGenerator-WebPart1.txt" target="_blank">WebPart1.cs<br />
</a><a title="FormGeneratorToolPart.cs" href="http://www.fivenumber.com/wp-content/uploads/2009/10/SharepointFormGenerator-ToolPart.txt" target="_blank">FormGeneratorToolPart.cs</a></p>
<p><strong>WebPart1.cs</strong></p>
<pre name="code" class="c-sharp">
using System;
using System.Web;
using System.IO;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace FormGenerator
{
    [Guid("93612d52-737c-4e83-83c3-a228910e87a3")]
    public class FormGenerator : Microsoft.SharePoint.WebPartPages.WebPart
    {
        Table oFormTable;
        FileUpload oFormFileUpload;
        FieldLabel oFormLabelField;
        FormField oFormField;
        Button oFormButtonSubmit;
        Label oFormLabelMessage;

        SPList oFormList;

        private string _FormList = string.Empty;

        string qstitle = string.Empty;
        string qsmission = string.Empty;

        public string FormList
        {
            get { return _FormList; }
            set { _FormList = value; }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            oFormTable = new Table();
            oFormTable.CellPadding = 0;
            oFormTable.CellSpacing = 0;            

            oFormLabelMessage = new Label();
            oFormLabelMessage.ID = "lbl_message";
            oFormLabelMessage.CssClass = "ms-formvalidation";
            this.Controls.Add(oFormLabelMessage);

            //Generate Form
            GenerateFormList();
        }

        private void GenerateFormList()
        {
            SPWeb oWeb = Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(Context);
            if (FormList != "")
            {
                try
                {
                    oFormList = oWeb.Lists[FormList];
                    foreach (SPField oField in oFormList.Fields)
                    {
                        if (oField.Type == SPFieldType.Attachments)
                        {
                            FieldLabel oLabelAttachmentField = new FieldLabel();
                            oLabelAttachmentField.ControlMode = SPControlMode.New;
                            oLabelAttachmentField.ListId = oFormList.ID;
                            oLabelAttachmentField.FieldName = oField.InternalName;

                            oFormFileUpload = new FileUpload();
                            oFormFileUpload.ID = "FileUpload";

                            AttachmentsField oAttachmentField = new AttachmentsField();
                            oAttachmentField.ControlMode = SPControlMode.New;
                            oAttachmentField.ListId = oFormList.ID;
                            oAttachmentField.FieldName = oField.InternalName;
                            oAttachmentField.Controls.Add(oFormFileUpload);
                            oAttachmentField.ID = "Control_" + oField.InternalName;

                            TableRow oRowAttachment = new TableRow();
                            oFormTable.Rows.Add(oRowAttachment);
                            TableCell oCellAttachmentLabel = new TableCell();
                            oRowAttachment.Cells.Add(oCellAttachmentLabel);

                            oCellAttachmentLabel.Controls.Add(oLabelAttachmentField);
                            oCellAttachmentLabel.CssClass = "ms-formlabel";
                            TableCell oCellAttachment = new TableCell();
                            oRowAttachment.Cells.Add(oCellAttachment);
                            oCellAttachment.Controls.Add(oAttachmentField);
                            oCellAttachment.CssClass = "ms-formbody";
                        }
                    }

                    // Loop through all the fields in the list
                    foreach (SPField oField in oFormList.Fields)
                    {
                        // Avoid Hidden, Read Only, Attachments field
                        if (!oField.Hidden &#038;&#038; !oField.ReadOnlyField &#038;&#038; oField.Type != SPFieldType.Attachments)
                        {
                            oFormLabelField = new FieldLabel();
                            oFormLabelField.ControlMode = SPControlMode.New;
                            oFormLabelField.ListId = oFormList.ID;
                            oFormLabelField.FieldName = oField.InternalName;

                            oFormField = new FormField();
                            oFormField.ControlMode = SPControlMode.New;
                            oFormField.ListId = oFormList.ID;
                            oFormField.FieldName = oField.InternalName;
                            oFormField.ID = "Control_" + oField.InternalName;

                            TableRow oRow = new TableRow();
                            oFormTable.Rows.Add(oRow);

                            TableCell oCellLabel = new TableCell();
                            oRow.Cells.Add(oCellLabel);
                            TableCell oCellControl = new TableCell();
                            oRow.Cells.Add(oCellControl);

                            oCellLabel.Controls.Add(oFormLabelField);
                            oCellControl.Controls.Add(oFormField);

                            oCellLabel.CssClass = "ms-formlabel";
                            oCellControl.CssClass = "ms-formbody";
                        }
                    }

                    //Create ASP.Net button
                    oFormButtonSubmit = new Button();
                    oFormButtonSubmit.ID = "btn_submit";
                    oFormButtonSubmit.Text = "OK";
                    oFormButtonSubmit.CssClass = "ms-ButtonHeightWidth";
                    oFormButtonSubmit.Click += new EventHandler(oFormButtonSubmit_Click);
                    this.Controls.Add(oFormButtonSubmit);

                    // Create the row for the Submit button
                    TableRow oRowButton = new TableRow();
                    oFormTable.Rows.Add(oRowButton);

                    // Create the cell for the Submit button
                    TableCell oCellButton = new TableCell();
                    oCellButton.ColumnSpan = 2;
                    oRowButton.Cells.Add(oCellButton);

                    Controls.Add(oFormTable);
                }
                catch (Exception ex)
                {
                    Page.Response.Write(ex.ToString());
                }
            }
            else
            {
                Page.Response.Write("Select valid <b>List</b> from webpart properties");
            }
        }

        void oFormButtonSubmit_Click(object sender, EventArgs e)
        {
            SPSite mySite = SPControl.GetContextSite(Context);
            SPWeb myWeb = SPControl.GetContextWeb(Context);
            SPList myList = myWeb.Lists[FormList];
            SPListItem myItem = myList.Items.Add();

            //Validating the controls
            foreach (SPField sField in myList.Fields)
            {
                if (sField.Required == true)
                {
                    string oControl = "Control_" + sField.InternalName.ToString();
                    Control oFieldControl = this.FindControl(oControl);
                    FormField sFormField = (FormField)oFieldControl;
                    if ((sFormField.Value) == null || (sFormField.Value.ToString()) == "")
                    {
                        oFormLabelMessage.Visible = true;
                        oFormLabelMessage.Text = "* indicates required fields";
                        return;
                    }
                }
            }
            foreach (SPField oField in myList.Fields)
            {
                string oFieldID = "Control_" + oField.InternalName;
                Control sFieldControl = this.FindControl(oFieldID);
                if (sFieldControl != null)
                {
                    if (oField.Type != SPFieldType.Attachments)
                    {
                        FormField sFormField = (FormField)sFieldControl;
                        myItem[oField.InternalName] = sFormField.Value;
                    }
                    else
                    {
                        AttachmentsField sAttachmentField = (AttachmentsField)sFieldControl;
                        FileUpload oFileControl = (FileUpload)sAttachmentField.FindControl("FileUpload");
                        if (oFileControl != null)
                        {
                            try
                            {
                                HttpPostedFile oPostedFile = oFileControl.PostedFile;
                                string oFileName = Path.GetFileName(oPostedFile.FileName);
                                if (oPostedFile.ContentLength > 0)
                                {
                                    Stream oInputStream = oPostedFile.InputStream;
                                    byte[] oBT = new byte[oPostedFile.InputStream.Length];
                                    oPostedFile.InputStream.Seek(0, SeekOrigin.Begin);
                                    oPostedFile.InputStream.Read(oBT, 0, oBT.Length);
                                    myItem.Attachments.Add(oFileName, oBT);
                                }
                            }
                            catch (Exception ex)
                            {
                                oFormLabelMessage.Visible = true;
                                oFormLabelMessage.Text = ex.ToString();
                            }
                        }
                    }
                }
                myWeb.AllowUnsafeUpdates = true;
                myItem.Update();
                myWeb.AllowUnsafeUpdates = false;
                oFormLabelMessage.Visible = true;
                oFormLabelMessage.Text = "Record updated";
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (FormList != "")
            {
                writer.Write("<Table align='right'><Tr><Td>");
                oFormLabelMessage.RenderControl(writer);
                writer.Write("</Td></Tr></Table>");
                writer.Write("<br/>");
                writer.Write("<Table><Tr><Td>");
                oFormTable.RenderControl(writer);
                writer.Write("</Td></Tr>");
                writer.Write("<Tr><Td align='right'>");
                oFormButtonSubmit.RenderControl(writer);
                writer.Write("</Td></Tr></Table>");
            }
            else
            {
                oFormLabelMessage.RenderControl(writer);
            }
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] allToolParts = new ToolPart[3];
            WebPartToolPart standardToolParts = new WebPartToolPart();
            CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();
            allToolParts[0] = standardToolParts;
            allToolParts[1] = customToolParts;
            allToolParts[2] = new FormGeneratorToolPart();
            return allToolParts;
        }
    }
}
</pre>
<p><strong>FormGeneratorToolPart.cs</strong></p>
<pre name="code" class="c-sharp">
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace FormGenerator
{
    class FormGeneratorToolPart: Microsoft.SharePoint.WebPartPages.ToolPart
    {
        FormGenerator oFG;
        Panel oToolPartPanel;
        DropDownList oDDLListProvider;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            oToolPartPanel = new Panel();
            Controls.Add(oToolPartPanel);

            oDDLListProvider = new DropDownList();
            oToolPartPanel.Controls.Add(oDDLListProvider);

            PopulateProviderList();
        }

        private void PopulateProviderList()
        {
            SPListCollection myListCol = SPContext.Current.Web.Lists;
            oDDLListProvider.AppendDataBoundItems = true;
            foreach (SPList myList in myListCol)
            {
                ListItem myListItem = new ListItem(myList.Title, myList.Title);
                oFG = (FormGenerator)this.ParentToolPane.SelectedWebPart;
                if (oFG.FormList == myList.Title)
                    myListItem.Selected = true;
                oDDLListProvider.Items.Add(myListItem);
            }
        }

        public override void ApplyChanges()
        {
            base.ApplyChanges();
            oFG.FormList = oDDLListProvider.SelectedValue;
        }

        public override void SyncChanges()
        {
            base.SyncChanges();
            oDDLListProvider.SelectedValue = oFG.FormList.ToString();
        }

        protected override void RenderToolPart(System.Web.UI.HtmlTextWriter output)
        {
            output.Write("<b>List Name Lookup:</b>");
            output.Write("<br/><br/>");
            oDDLListProvider.RenderControl(output);
            output.Write("<br/>
<div class='UserSectionTitle'>&nbsp;</div>

<br/>");
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/sharepoint-list-form-generator/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>A quick look on Sharepoint object model programs</title>
		<link>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs/</link>
		<comments>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 13:11:16 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[MOSS - Quick Look]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[Webparts]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=578</guid>
		<description><![CDATA[Here I am going to show you that the actions which we perform normally with UI, those also can be done programmatically, the same thing I am going to show in this post, this post is mainly targeted for beginners those who are new to Sharepoint object model, a quick watch on programs to create [...]]]></description>
			<content:encoded><![CDATA[<p>Here I am going to show you that the actions which we perform normally with UI, those also can be done programmatically, the same thing I am going to show in this post, this post is mainly targeted for beginners those who are new to Sharepoint object model, a quick watch on programs to create sub sites, lists, showing web apps etc.<br />
<strong>Creating Sub Site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
SPWebCollection myWebCol = myWeb.Webs;
SPWeb mynewweb = myWebCol.Add("Web url", "Web Title", "Web Description", 1033, "STS#0", false, false);
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Creating List:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
myWeb.Lists.Add("My New List", "My new list description", myWeb.ListTemplates["Custom List"]);
SPList newList = myWeb.Lists["My New List"];
newList.OnQuickLaunch = true;
newList.Update();
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all top-level sites in a farm</strong></p>
<pre name="code" class="c-sharp">
static void Main()        
 {
 foreach (SPWebApplication myWebApp in SPWebService.ContentService.WebApplications)
 {
 foreach (SPSite mySiteCol in myWebApp.Sites)
 {
 try
 {
 Console.WriteLine(mySiteCol.Url);
 }
 catch (Exception e)
 {
 Console.WriteLine(e);
 }                   
 }
 }
 Console.WriteLine("Press any key to continue.....");
 Console.ReadLine();
 }
</pre>
<p><strong>Show all site collection in web application:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWebApplication myWebApp = mySite.WebApplication;
SPSiteCollection mySiteCol = myWebApp.Sites;
foreach (SPSite SingleSite in mySiteCol)
{
Console.WriteLine(SingleSite.Url.ToString());
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all subsites in site collection:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
foreach (SPWeb myWeb in mySite.AllWebs)
{
Console.WriteLine(myWeb.Url.ToString());
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Roles in a site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
foreach (SPRoleDefinition myRoleDef in myWeb.RoleDefinitions)
{
Console.WriteLine(myRoleDef.Name);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Alerts in a site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
foreach (SPAlert myAlerts in myWeb.Alerts)
{
Console.WriteLine(myAlerts.Title);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Lists in a site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
foreach (SPList myList in myWeb.Lists)
{
Console.WriteLine(myList.Title.ToString());
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all List Templates in a site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
foreach (SPListTemplate myListTemplate in myWeb.ListTemplates)
{
Console.WriteLine(myListTemplate.Name);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Fields in a List:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
SPList myList = myWeb.Lists["List Name"];
foreach (SPField myField in myList.Fields)
{
Console.WriteLine(myField.InternalName);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Items in a List column:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
SPList myList = myWeb.Lists["List Name"];
SPQuery myQuery = new SPQuery();
myQuery.Query = "";//Your Query
SPListItemCollection myItemCol = myList.GetItems(myQuery);
foreach (SPListItem myListItem in myItemCol)
{
Console.WriteLine(myListItem["Column Name"].ToString());
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Delete all Items from a list:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
SPList myList=myWeb.Lists["List Name"];
myWeb.AllowUnsafeUpdates = true;
int count = 1;
for (int i = 0; i < myList.ItemCount; i++)
{
SPListItem myListitem = myList.Items[0];
myListitem.Delete();
Console.WriteLine(count + " item(s) deleted");
count++;
}
myWeb.AllowUnsafeUpdates = false;
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Groups in a site:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
foreach (SPGroup myGroup in myWeb.Groups)
{
Console.WriteLine(myGroup.Name);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
<p><strong>Show all Users in a group:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
{
SPSite mySite = new SPSite("http://servername:port");
SPWeb myWeb = mySite.OpenWeb();
SPGroup myGroup = myWeb.Groups["Group Name"];
foreach (SPUser myUser in myGroup.Users)
{
Console.WriteLine(myUser.Name);
}
Console.WriteLine("Press any key to continue.....");
Console.ReadLine();
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Sharepoint hit counter web part</title>
		<link>http://www.fivenumber.com/sharepoint-hit-counter-web-part/</link>
		<comments>http://www.fivenumber.com/sharepoint-hit-counter-web-part/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 11:26:43 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=567</guid>
		<description><![CDATA[On 11th November, 2009 I have published the HitCounter webpart solution on to Codeplex
I have made the Hit Counter webpart very compact with minimum lines of code which generates user hits, before adding  the webpart to the master page you need to create a Custom List name it as Statistics then create three columns [...]]]></description>
			<content:encoded><![CDATA[<p>On 11th November, 2009 I have published the HitCounter webpart solution on to <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">Codeplex</a></p>
<div id="attachment_715" class="wp-caption aligncenter" style="width: 287px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/09/Hit-Counter1.gif" rel="lightbox[567]"><img class="size-full wp-image-715" title="Hit Counter" src="http://www.fivenumber.com/wp-content/uploads/2009/09/Hit-Counter1.gif" alt="Hit Counter" width="277" height="64" /></a><p class="wp-caption-text">Hit Counter</p></div>
<p>I have made the Hit Counter webpart very compact with minimum lines of code which generates user hits, before adding  the webpart to the master page you need to create a Custom List name it as <strong>Statistics</strong> then create three columns in <strong>Statistics</strong> list as below:</p>
<ol>
<li><strong>url</strong> <em>Multiple lines of text</em></li>
<li><strong>date</strong> <em>Single line of text</em></li>
<li><strong>uname</strong> <em>Single line of text</em></li>
</ol>
<p>Also, you have to give the <strong>Contribute – Can view, add, update,  and delete</strong> permissions for the <strong>Visitor</strong> and <strong>Viewers</strong> for  the <strong>Statistics</strong> list, so that visitor/viewers visits also  recorded in the list.</p>
<p><strong>To give permissions</strong></p>
<ol>
<li>Go to <strong>Statistics</strong> list, <strong>Settings</strong> &gt; <strong>List  Settings</strong></li>
<li>Under <strong>Permissions and Management</strong> click on <strong>Permissions for  this list</strong></li>
<li>Select <strong>Visitors</strong> checkbox then click on <strong>Actions</strong> &gt; <strong>Edit  User Permissions</strong> then select <strong>Contribute – Can view, add, update,  and delete</strong></li>
<li>Finally click <strong>Ok</strong> button</li>
</ol>
<p><strong>Please Note</strong>: For applying <strong>Contribute – Can view, add, update,  and delete</strong> permissions for <strong>Viewers</strong> repeat the above <strong>1</strong>,  <strong>2</strong>, <strong>3</strong> and <strong>4</strong> steps</p>
<p>If a user is new to  current page on the day, the code adds a record to <strong>Statistics</strong> list, if the same user visits the same page the code just returns out  from condition and do nothing, because the user already visited the page  on the same day, this is all because of to maintain the unique hits</p>
<p>To  know the hit count for all pages in site, you have to place the webpart  in master page, so that the webpart code runs on every page where the  visitor go and makes the unique entry in <strong>Statistics</strong> list</p>
<div id="attachment_716" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/09/Statistics-List2.gif" rel="lightbox[567]"><img class="size-medium wp-image-716" title="Statistics List" src="http://www.fivenumber.com/wp-content/uploads/2009/09/Statistics-List2-300x174.gif" alt="Statistics List" width="300" height="174" /></a><p class="wp-caption-text">Statistics List</p></div>
<p>You can download the Hit Counter webpart from <a title="Sharepoint Hit Counter Webpart" href="http://hitcounter.codeplex.com/" target="_blank">http://hitcounter.codeplex.com/</a></p>
<p>Comments on this solution are very much appreciated <img src='http://www.fivenumber.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Thanks for looking into this</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/sharepoint-hit-counter-web-part/feed/</wfw:commentRss>
		<slash:comments>55</slash:comments>
		</item>
		<item>
		<title>Copy Sharepoint list items from one site to another programmatically</title>
		<link>http://www.fivenumber.com/copy-sharepoint-list-items-from-one-site-to-another-programmatically/</link>
		<comments>http://www.fivenumber.com/copy-sharepoint-list-items-from-one-site-to-another-programmatically/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 06:13:47 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=541</guid>
		<description><![CDATA[In my earlier post, I have show you how to Copy items from one list to another, using Sharepoint designer workflow now we learn how to copy list items from one Sharepoint site to another site programmatically
Before executing the code I have created two Sharepoint sites, first is http://fivenumber:5/ and the second http://fivenumber:50/
I have also [...]]]></description>
			<content:encoded><![CDATA[<p>In my earlier post, I have show you how to <a title="Copy item from one list to another, using Sharepoint designer workflow" href="http://www.fivenumber.com/copy-item-from-one-list-to-another-using-sharepoint-designer-workflow/" target="_blank">Copy items from one list to another, using Sharepoint designer workflow</a> now we learn how to copy list items from one Sharepoint site to another site programmatically</p>
<p>Before executing the code I have created two Sharepoint sites, first is <strong>http://fivenumber:5/</strong> and the second <strong>http://fivenumber:50/</strong></p>
<p>I have also created custom list in each site, <strong>Source List</strong> in site <strong>http://fivenumber:5/</strong> and <strong>Desitination List</strong> in <strong>http://fivenumber:50/</strong></p>
<p>Here in this scenario I have chosen Console Application template because it doens&#8217;t contains any input fields to show as webpart and also to avoid GAC registration, safe controls etc., I felt it will be easy to execute the code in Console.</p>
<p><a title="Copy list items from one Sharepoint site to another site programmatically" href="http://www.fivenumber.com/wp-content/uploads/2009/08/Copy%20list%20items%20from%20one%20to%20another%20programmatically.txt" target="_blank">Download complete source code</a></p>
<div id="attachment_542" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/08/Source-List.gif" rel="lightbox[541]"><img class="size-medium wp-image-542" title="Source List" src="http://www.fivenumber.com/wp-content/uploads/2009/08/Source-List-300x161.gif" alt="Source List" width="300" height="161" /></a><p class="wp-caption-text">Source List</p></div>
<div id="attachment_544" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/08/Copied-List-Items.gif" rel="lightbox[541]"><img class="size-medium wp-image-544" title="Copied List Items" src="http://www.fivenumber.com/wp-content/uploads/2009/08/Copied-List-Items-300x147.gif" alt="Copied List Items" width="300" height="147" /></a><p class="wp-caption-text">Copied List Items</p></div>
<div id="attachment_543" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/08/Destination-List.gif.gif" rel="lightbox[541]"><img class="size-medium wp-image-543" title="Destination List" src="http://www.fivenumber.com/wp-content/uploads/2009/08/Destination-List.gif-300x160.gif" alt="Destination List" width="300" height="160" /></a><p class="wp-caption-text">Destination List</p></div>
<pre name="code" class="c-sharp">
using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;

namespace CopyListItems
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SPSite mySourceSite = new SPSite("http://fivenumber:5/");
                SPWeb mySourceWeb = mySourceSite.OpenWeb();
                SPList mySourceList = mySourceWeb.Lists["Source List"];
                SPQuery mySourceListQuery = new SPQuery();
                mySourceListQuery.Query = "<OrderBy><FieldRef Name='Title' />" +
                                "<FieldRef Name='Employee_x0020_Name' />" +
                                "<FieldRef Name='Designation' />" +
                                "<FieldRef Name='Age' />" +
                                "</OrderBy>";
                SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);
                int count = 0;
                foreach (SPListItem mySourceListItem in mySourceItemColl)
                {
                    string SourceEmpId = mySourceListItem["Employee Id"].ToString();
                    string SourceEmpName = mySourceListItem["Employee Name"].ToString();
                    string SourceDesig = mySourceListItem["Designation"].ToString();
                    string SourceAge = mySourceListItem["Age"].ToString();

                    SPSite myDestinationSite = new SPSite("http://fivenumber:50");
                    SPWeb myDestinationWeb = myDestinationSite.OpenWeb();
                    SPList myDestinationList = myDestinationWeb.Lists["Destination List"];
                    SPListItem myDestinationListItem = myDestinationList.Items.Add();

                    myDestinationListItem["Employee Id"] = SourceEmpId;
                    myDestinationListItem["Employee Name"] = SourceEmpName;
                    myDestinationListItem["Designation"] = SourceDesig;
                    myDestinationListItem["Age"] = SourceAge;
                    myDestinationWeb.AllowUnsafeUpdates = true;
                    myDestinationListItem.Update();
                    myDestinationWeb.AllowUnsafeUpdates = false;
                    count++;
                    Console.WriteLine(count+" item(s) copied");
                }
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
        }
    }
}
</pre>
<p>If you have Lookup column in your Source List and want to copy the same data in to Destination List, you have to create an instance for SPFieldLookupValue class like below&#8230;..</p>
<p>Let&#8217;s suppose &#8216;Employee Name&#8217; column is lookup field, comment or remove the line # 29 in the above code and replace with below code snippet</p>
<pre name="code" class="c-sharp">
SPFieldLookupValue mySourceLookupEmpName = new SPFieldLookupValue(mySourceListItem["Employee Name"].ToString());
string SourceEmpName = mySourceLookupEmpName.LookupId.ToString();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/copy-sharepoint-list-items-from-one-site-to-another-programmatically/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Export SPGridView to Excel spreadsheet in Sharepoint 2007</title>
		<link>http://www.fivenumber.com/export-spgridview-to-excel-spreadsheet-in-sharepoint-2007/</link>
		<comments>http://www.fivenumber.com/export-spgridview-to-excel-spreadsheet-in-sharepoint-2007/#comments</comments>
		<pubDate>Tue, 28 Jul 2009 08:38:09 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=528</guid>
		<description><![CDATA[In my last post I have show you how to retrieve current user profile in Sharepoint 2007, before that I have also posted on how to display custom list items in SPGridView
Today I am going to work on how to export SPGridView items into Excel spreadsheet in Sharepoint 2007
Most of the code I have used [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I have show you how to <a title="Retrieve current user profile" href="http://www.fivenumber.com/retrieve-current-user-profile-in-sharepoint-2007/" target="_blank">retrieve current user profile in Sharepoint 2007</a>, before that I have also posted on how to <a title="Display custom list items in SPGridView" href="http://www.fivenumber.com/displaying-sharepoint-custom-list-items-in-spgridview/" target="_blank">display custom list items in SPGridView</a></p>
<p>Today I am going to work on how to export SPGridView items into Excel spreadsheet in Sharepoint 2007</p>
<p>Most of the code I have used form Matt Berseth blog article <a title="Export GridView to Excel" href="http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html" target="_blank">Export GridView to Excel</a> so thanks to Matt and also thanks to my colleague Ram Gowri who helped me on this</p>
<p><a title="Export SPGridView to Excel spreadsheet" href="http://www.fivenumber.com/wp-content/uploads/2009/07/Export%20SPGridView%20items%20to%20Excel%20spreadsheet.txt" target="_blank">Download complete source code</a></p>
<p>To run the code first you need to create a custom list, name it as Countries, then create two columns int he same list Country and State</p>
<div id="attachment_530" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/15.gif" rel="lightbox[528]"><img class="size-medium wp-image-530" title="Sharepoint OOB custom list" src="http://www.fivenumber.com/wp-content/uploads/2009/07/15-300x241.gif" alt="Sharepoint OOB custom list" width="300" height="241" /></a><p class="wp-caption-text">Sharepoint OOB custom list</p></div>
<div id="attachment_538" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/25.gif" rel="lightbox[528]"><img class="size-medium wp-image-538" title="Displaying Sharepoint custom list items into SPGridView" src="http://www.fivenumber.com/wp-content/uploads/2009/07/25-300x228.gif" alt="Displaying Sharepoint custom list items into SPGridView" width="300" height="228" /></a><p class="wp-caption-text">Displaying Sharepoint custom list items into SPGridView</p></div>
<div id="attachment_532" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/31.gif" rel="lightbox[528]"><img class="size-medium wp-image-532" title="Exporting SPGridView to Excel Spreadsheet" src="http://www.fivenumber.com/wp-content/uploads/2009/07/31-300x149.gif" alt="Exporting SPGridView to Excel Spreadsheet" width="300" height="149" /></a><p class="wp-caption-text">Exporting SPGridView to Excel Spreadsheet</p></div>
<div id="attachment_533" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/41.gif" rel="lightbox[528]"><img class="size-medium wp-image-533" title="After exporting SPGridView items in to Excel spreadsheet" src="http://www.fivenumber.com/wp-content/uploads/2009/07/41-300x280.gif" alt="After exporting SPGridView items in to Excel spreadsheet" width="300" height="280" /></a><p class="wp-caption-text">After exporting SPGridView items in to Excel spreadsheet</p></div>
<pre name="code" class="c-sharp">
using System;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace ExportGridtoExcel
{
    [Guid("2fa65763-1ef1-4173-8a77-685e840f0196")]
    public class ExportGridtoExcel : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();
        Button oBtn_Export;

        protected override void CreateChildControls()
        {
            oBtn_Export = new Button();
            oBtn_Export.Text = "Export to Excel";
            oBtn_Export.CssClass = "ButtonHeightWidth";
            oBtn_Export.Click += new EventHandler(oBtn_Export_Click);
            this.Controls.Add(oBtn_Export);

            myGridView = new SPGridView();
            myGridView.Enabled = true;
            myGridView.AutoGenerateColumns = false;                       

            SPBoundField colTitle = new SPBoundField();
            colTitle.DataField = "Country";
            colTitle.HeaderText = "Country";
            this.myGridView.Columns.Add(colTitle);

            SPBoundField colMission = new SPBoundField();
            colMission.DataField = "State";
            colMission.HeaderText = "State";
            this.myGridView.Columns.Add(colMission);

            this.Controls.Add(myGridView);
        }

        void oBtn_Export_Click(object sender, EventArgs e)
        {
            ExportToExcel("CountryState.xls", myGridView);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            SPSite mySite = SPContext.Current.Site;
            SPWeb myWeb = SPContext.Current.Web;
            SPList list = myWeb.Lists["Countries"];
            myDataSource.List = list;
            myGridView.DataSource = myDataSource;
            myGridView.DataBind();
        }

        public static void ExportToExcel(string strFileName, SPGridView gv)
        {
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();

                    //  add the header row to the table
                    if (gv.HeaderRow != null)
                    {
                        PrepareControlForExport(gv.HeaderRow);
                        table.Rows.Add(gv.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", strFileName));
                    HttpContext.Current.Response.ContentType = "application/ms-excel";
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i &lt; control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }
    }
}</pre>
<p><script src="js/shCore.js"></script> <script src="js/shBrushCSharp.js"></script><br />
<script src="js/shBrushXml.js"></script> <script type="text/javascript">// <![CDATA[
  dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code');
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/export-spgridview-to-excel-spreadsheet-in-sharepoint-2007/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Retrieve current user profile in Sharepoint 2007</title>
		<link>http://www.fivenumber.com/retrieve-current-user-profile-in-sharepoint-2007/</link>
		<comments>http://www.fivenumber.com/retrieve-current-user-profile-in-sharepoint-2007/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 10:12:28 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=508</guid>
		<description><![CDATA[My last post was about Contact / Feedback webpart for Sharepoint 2007
In this post I am going to show you how to retrieve current user profile and show the properties like Title, First name, Last Name etc.
using Microsoft.Office.Server.UserProfiles.UserProfileManager()
It is a collection of user profile objects used to access user profile data we need to just [...]]]></description>
			<content:encoded><![CDATA[<p>My <a title="Contact/Feedback webpart for Sharepoint 2007" href="http://www.fivenumber.com/contact-feedback-webpart-for-sharepoint-2007/" target="_blank">last post</a> was about Contact / Feedback webpart for Sharepoint 2007</p>
<p>In this post I am going to show you how to retrieve current user profile and show the properties like Title, First name, Last Name etc.<br />
using Microsoft.Office.Server.UserProfiles.UserProfileManager()</p>
<p>It is a collection of user profile objects used to access user profile data we need to just call the <strong>UserProfileManager</strong>() class to access a specific user profile</p>
<p>Here I am going to do the same</p>
<div id="attachment_509" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/14.gif" rel="lightbox[508]"><img class="size-medium wp-image-509" title="Retrieve user profile" src="http://www.fivenumber.com/wp-content/uploads/2009/07/14-300x171.gif" alt="Retrieve user profile" width="300" height="171" /></a><p class="wp-caption-text">Retrieve user profile</p></div>
<p><a title="Retrieve user profile" href="http://www.fivenumber.com/wp-content/uploads/2009/07/Retrieve%20user%20profile.txt" target="_blank">Download complete source code</a></p>
<pre name="code" class="c-sharp">

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;

using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace RetrieveUserProfile
{
    [Guid("b95130c6-6bc0-4ce3-8596-778af2321354")]
    public class RetrieveUserProfile : System.Web.UI.WebControls.WebParts.WebPart
    {
        Label oLabelTitle;
        Label oLabelFirstName;
        Label oLabelLastname;
        Label oLabelAboutMe;
        Label oLabelDept;
        Label oLabelSipAdd;
        Label oLabelWorkPhone;
        Label oLabelWorkEmail;
        Label oLabelWebsite;
        Label oLabelResponsibility;

        Label oLabelMessage;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();           

            //Label for Retrieving user profiles
            oLabelTitle = new Label();
            this.Controls.Add(oLabelTitle);

            oLabelFirstName = new Label();
            this.Controls.Add(oLabelFirstName);

            oLabelLastname = new Label();
            this.Controls.Add(oLabelLastname);

            oLabelAboutMe = new Label();
            this.Controls.Add(oLabelAboutMe);

            oLabelDept = new Label();
            this.Controls.Add(oLabelDept);

            oLabelSipAdd = new Label();
            this.Controls.Add(oLabelSipAdd);

            oLabelWorkPhone = new Label();
            this.Controls.Add(oLabelWorkPhone);

            oLabelWorkEmail = new Label();
            this.Controls.Add(oLabelWorkEmail);

            oLabelWebsite = new Label();
            this.Controls.Add(oLabelWebsite);

            oLabelResponsibility = new Label();
            this.Controls.Add(oLabelResponsibility);

            oLabelMessage = new Label();
            this.Controls.Add(oLabelMessage);
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
            try
            {
                SPSite mySite = SPControl.GetContextSite(Context);
                SPWeb myWeb = SPControl.GetContextWeb(Context);
                ServerContext context = ServerContext.GetContext(mySite);
                UserProfileManager myProfileManager = new UserProfileManager(context);
                string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                UserProfile myProfile = myProfileManager.GetUserProfile(CurrentUser);
                if (myProfile[PropertyConstants.Title].Value != null)
                {
                    oLabelTitle.Text = myProfile[PropertyConstants.Title].Value.ToString();
                }
                if (myProfile[PropertyConstants.FirstName].Value != null)
                {
                    oLabelFirstName.Text = myProfile[PropertyConstants.FirstName].Value.ToString();
                }
                if (myProfile[PropertyConstants.LastName].Value != null)
                {
                    oLabelLastname.Text = myProfile[PropertyConstants.LastName].Value.ToString();
                }
                if (myProfile[PropertyConstants.AboutMe].Value != null)
                {
                    oLabelAboutMe.Text = myProfile[PropertyConstants.AboutMe].Value.ToString();
                }
                if (myProfile[PropertyConstants.Department].Value != null)
                {
                    oLabelDept.Text = myProfile[PropertyConstants.Department].Value.ToString();
                }
                if (myProfile[PropertyConstants.SipAddress].Value != null)
                {
                    oLabelSipAdd.Text = myProfile[PropertyConstants.SipAddress].Value.ToString();
                }
                if (myProfile[PropertyConstants.WorkPhone].Value != null)
                {
                    oLabelWorkPhone.Text = myProfile[PropertyConstants.WorkPhone].Value.ToString();
                }
                if (myProfile[PropertyConstants.WorkEmail].Value != null)
                {
                    oLabelWorkEmail.Text = myProfile[PropertyConstants.WorkEmail].Value.ToString();
                }
                if (myProfile[PropertyConstants.WebSite].Value != null)
                {
                    oLabelWebsite.Text = myProfile[PropertyConstants.WebSite].Value.ToString();
                }
                if (myProfile[PropertyConstants.Responsibility].Value != null)
                {
                    oLabelResponsibility.Text = myProfile[PropertyConstants.Responsibility].Value.ToString();
                }
            }
            catch (UserNotFoundException ex)
            {
                oLabelMessage.Text = ex.ToString();
            }
            });</pre>
<p><script src="js/shCore.js"></script> <script src="js/shBrushCSharp.js"></script><br />
<script src="js/shBrushXml.js"></script> <script type="text/javascript">// <![CDATA[
   dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code');
// ]]&gt;</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/retrieve-current-user-profile-in-sharepoint-2007/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Contact / Feedback webpart for Sharepoint 2007</title>
		<link>http://www.fivenumber.com/contact-feedback-webpart-for-sharepoint-2007/</link>
		<comments>http://www.fivenumber.com/contact-feedback-webpart-for-sharepoint-2007/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 16:09:36 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=502</guid>
		<description><![CDATA[On 12th November, 2009 I have published the Contact / Feedback webpart solution on to Codeplex
You can download the Contact / Feedback webpart from http://contact.codeplex.com/
Comments on this solution are very much appreciated  
Thanks for looking into this
]]></description>
			<content:encoded><![CDATA[<p>On 12th November, 2009 I have published the Contact / Feedback webpart solution on to <a href="http://www.codeplex.com/" target="_blank">Codeplex</a></p>
<p>You can download the Contact / Feedback webpart from <a title="Sharepoint Contact - Feedback Webpart" href="http://contact.codeplex.com/" target="_blank">http://contact.codeplex.com/</a></p>
<p>Comments on this solution are very much appreciated <img src='http://www.fivenumber.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Thanks for looking into this</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/contact-feedback-webpart-for-sharepoint-2007/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Displaying Sharepoint Custom List items in SPGridView</title>
		<link>http://www.fivenumber.com/displaying-sharepoint-custom-list-items-in-spgridview/</link>
		<comments>http://www.fivenumber.com/displaying-sharepoint-custom-list-items-in-spgridview/#comments</comments>
		<pubDate>Tue, 14 Jul 2009 17:08:34 +0000</pubDate>
		<dc:creator>GVK</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=479</guid>
		<description><![CDATA[Here is a simple SPGridView example, which displays rows from a Sharepoint Custom List.
Download complete source code

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace FiveNumber
{
    [Guid("e6a48f2e-8f31-4738-8ed6-6629f985956d")]
    public class DisplayListInSpGridView : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView myGridView;
    [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a simple SPGridView example, which displays rows from a Sharepoint Custom List.</p>
<div id="attachment_481" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/Custom-List.gif" rel="lightbox[479]"><img class="size-medium wp-image-481" title="Custom List" src="http://www.fivenumber.com/wp-content/uploads/2009/07/Custom-List-300x121.gif" alt="Custom List" width="300" height="121" /></a><p class="wp-caption-text">Custom List</p></div>
<div id="attachment_482" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/SPGridView.gif" rel="lightbox[479]"><img class="size-medium wp-image-482" title="Displaying custom list rows in SPGridView" src="http://www.fivenumber.com/wp-content/uploads/2009/07/SPGridView-300x121.gif" alt="Displaying custom list rows in SPGridView" width="300" height="121" /></a><p class="wp-caption-text">Displaying custom list rows in SPGridView</p></div>
<p><a href="http://www.fivenumber.com/wp-content/uploads/2009/07/Displaying%20custom%20list%20in%20SPGridView.txt" target="_blank">Download complete source code</a></p>
<pre name="code" class="c-sharp">
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace FiveNumber
{
    [Guid("e6a48f2e-8f31-4738-8ed6-6629f985956d")]
    public class DisplayListInSpGridView : System.Web.UI.WebControls.WebParts.WebPart
    {
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();

        protected override void CreateChildControls()
        {
            myGridView = new SPGridView();
            myGridView.Enabled = true;
            myGridView.AutoGenerateColumns = false;
            myGridView.ID = "gv_MyGridView";

            myGridView.AllowGrouping = true;
            myGridView.AllowGroupCollapse = true;
            myGridView.GroupField = "Country";
            myGridView.GroupDescriptionField = "Country";
            //myGridView.GroupFieldDisplayName = "Country Name";

            BoundField colTitle = new BoundField();
            colTitle.DataField = "Country";
            colTitle.HeaderText = "Country";
            this.myGridView.Columns.Add(colTitle);

            BoundField colMission = new BoundField();
            colMission.DataField = "State";
            colMission.HeaderText = "State";
            this.myGridView.Columns.Add(colMission);

            this.Controls.Add(myGridView);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists["Countries"];
            myDataSource.List = list;
            myGridView.DataSource = myDataSource;
            myGridView.DataBind();            

            myGridView.RenderControl(writer);
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/displaying-sharepoint-custom-list-items-in-spgridview/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Lightbox enabled custom webpart, displays images from sharepoint picture library</title>
		<link>http://www.fivenumber.com/lightbox-enabled-custom-webpart-displays-images-from-sharepoint-picture-library/</link>
		<comments>http://www.fivenumber.com/lightbox-enabled-custom-webpart-displays-images-from-sharepoint-picture-library/#comments</comments>
		<pubDate>Thu, 23 Oct 2008 12:52:47 +0000</pubDate>
		<dc:creator>GVK</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Lightbox]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[Webparts]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=429</guid>
		<description><![CDATA[Here is the simple Lightbox enabled custom webpart which displays the images from sharepoint picture library.
Instructions to use:

Download Lightbox
After downloading, copy all the Lightbox files or folders to sharepoint 2007 website using sharepoint designer 2007.
Add the lightbox javascript and css reference tags in the head section of sharepoint site master page.


Create a Picture Library in [...]]]></description>
			<content:encoded><![CDATA[<p>Here is the simple Lightbox enabled custom webpart which displays the images from sharepoint picture library.</p>
<div id="attachment_428" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2008/10/110.gif" rel="lightbox[429]"><img class="size-medium wp-image-428" title="110" src="http://www.fivenumber.com/wp-content/uploads/2008/10/110-300x95.gif" alt="Lightbox enabled webpart" width="300" height="95" /></a><p class="wp-caption-text">Lightbox enabled webpart</p></div>
<p><strong>Instructions to use</strong>:</p>
<ul>
<li>Download <a title="Lightbox 2" href="http://www.huddletogether.com/projects/lightbox2/" target="_blank">Lightbox</a></li>
<li>After downloading, copy all the Lightbox files or folders to sharepoint 2007 website using sharepoint designer 2007.</li>
<li>Add the lightbox javascript and css reference tags in the head section of sharepoint site master page.</li>
</ul>
<div id="attachment_430" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2008/10/22.gif" rel="lightbox[429]"><img class="size-medium wp-image-430" title="Add Lightbox reference tags" src="http://www.fivenumber.com/wp-content/uploads/2008/10/22-300x178.gif" alt="Add Lightbox reference tags" width="300" height="178" /></a><p class="wp-caption-text">Add Lightbox reference tags</p></div>
<ul>
<li>Create a Picture Library in sharepoint site naming <strong>Picture Library</strong> (you can also give any other name, but make sure to change the name in the downloaded source code too) upload few pictures to the library.</li>
<li>Create a webpart using visual studio, copy and paste the <a title="Lightbox Enabled Custom Webpart" href="http://www.fivenumber.com/wp-content/uploads/2008/10/lightbox-enabled-custom-webpart3.txt" target="_blank">source code</a>, build and import the webpart to sharepoint site.</li>
</ul>
<p>Finally looks like this when you click on  a image</p>
<div id="attachment_432" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2008/10/36.gif" rel="lightbox[429]"><img class="size-medium wp-image-432" title="Lightbox enabled custom webpart" src="http://www.fivenumber.com/wp-content/uploads/2008/10/36-300x191.gif" alt="Lightbox enabled custom webpart" width="300" height="191" /></a><p class="wp-caption-text">Lightbox enabled custom webpart</p></div>
<p><a title="Lightbox - download the complete source code" href="http://www.fivenumber.com/wp-content/uploads/2008/10/lightbox-enabled-custom-webpart3.txt" target="_blank">Download the complete source code</a></p>
<pre name="code" class="c-sharp">
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace NewLightBox
{
    [Guid("148b47a8-0e84-423d-bb3f-44e5f2e33dea")]
    public class NewLightBox : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void Render(HtmlTextWriter writer)
        {
            SPSite mysite = new SPSite("http://" + System.Environment.MachineName);
            mysite = SPControl.GetContextSite(Context);
            SPWeb myweb = mysite.OpenWeb();
            myweb = SPControl.GetContextWeb(Context);
            SPList mylist = myweb.Lists["Picture Library"];
            SPQuery myquery=new SPQuery();
            myquery.Query="";
            string path = mysite.ServerRelativeUrl.ToString() + "Picture Library/";
            SPListItemCollection mylstcol = mylist.GetItems(myquery);
            if (mylstcol.Count > 0)
            {
                foreach (SPListItem mylstitem in mylstcol)
                {
                    writer.Write("<a href='" + path + mylstitem["Name"].ToString() + "' rel='lightbox[PictureGroup]' title='" + mylstitem["Title"].ToString() + "'>");
                    writer.Write("<img src='" + path + mylstitem["Name"].ToString() + "' width='100px' height='75px' border='0'/>");
                    writer.Write("</a>&nbsp;");
                }
            }
            else
            {
                this.Page.Response.Write("No image found");
            }
            // TODO: add custom rendering code here.
            // writer.Write("Output HTML");
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/lightbox-enabled-custom-webpart-displays-images-from-sharepoint-picture-library/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
