<?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>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>Tue, 03 Jan 2012 16:33:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<image>
<link>http://www.fivenumber.com</link>
<url>http://www.fivenumber.com/wp-content/mbp-favicon/5.jpg</url>
<title>Sharepoint Server</title>
</image>
		<item>
		<title>SharePoint Document Counter Counts The Document Downloads</title>
		<link>http://www.fivenumber.com/sharepoint-document-counter-counts-the-document-downloads/</link>
		<comments>http://www.fivenumber.com/sharepoint-document-counter-counts-the-document-downloads/#comments</comments>
		<pubDate>Wed, 15 Dec 2010 19:26:36 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[SharePoint 2010 - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[download counter]]></category>
		<category><![CDATA[object model]]></category>
		<category><![CDATA[Sharepoint]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=914</guid>
		<description><![CDATA[In this post I&#8217;m going to show you how to count the document events of SharePoint site, after going through this post you will learn how to count the document downloads, views, updates, deletion, restoration etc. I remember this solution has been asked by few people on this blog. Before knowing the document events (add, [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;m going to show you how to count the document events of SharePoint site, after going through this post you will learn how to count the document downloads, views, updates, deletion, restoration etc.</p>
<p>I remember this solution has been asked by few people on this blog.</p>
<p>Before knowing the document events (add, delete, update, view etc) we have to configure the audit entry settings for the SharePoint site collection in site settings page under <strong>Site Collection Administration</strong> section (see figure 1)</p>
<div id="attachment_915" class="wp-caption aligncenter" style="width: 274px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/12/1.jpg" rel="lightbox[914]"><img class="size-medium wp-image-915" title="Figure 1 - Configure Site Collection Audit Settings" src="http://www.fivenumber.com/wp-content/uploads/2010/12/1-264x300.jpg" alt="Figure 1 - Configure Site Collection Audit Settings" width="264" height="300" /></a><p class="wp-caption-text">Figure 1 - Configure Site Collection Audit Settings</p></div>
<p>On <strong>Audit Settings</strong> page check the required events to track, in this example I&#8217;m configuring for <strong>Opening or downloading documents, viewing items in lists, or viewing item properties</strong>, <strong>Editing items</strong>, <strong>Deleting or restoring items</strong></p>
<div id="attachment_917" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/12/21.jpg" rel="lightbox[914]"><img class="size-medium wp-image-917" title="Figure 2 - Configure Audit Events" src="http://www.fivenumber.com/wp-content/uploads/2010/12/21-300x130.jpg" alt="Figure 2 - Configure Audit Events" width="300" height="130" /></a><p class="wp-caption-text">Figure 2 - Configure Audit Events</p></div>
<p>You can also configure audit entry settings programmatically with few lines of code, here it is:</p>
<pre class="brush: csharp; title: ; notranslate">
static void Main()
        {
            using (SPSite mySite = new SPSite(&quot;http://&lt;servername&gt;:port&quot;))
            {
                using (SPWeb myWeb = mySite.OpenWeb())
                {
                    mySite.Audit.AuditFlags = SPAuditMaskType.All; //Configures all settings

                    //you can even configure specific settings using the below lines of code

                    //mySite.Audit.AuditFlags = SPAuditMaskType.CheckIn | SPAuditMaskType.CheckOut | SPAuditMaskType.ChildDelete |
                    //     SPAuditMaskType.Copy | SPAuditMaskType.Delete | SPAuditMaskType.Move | SPAuditMaskType.ProfileChange |
                    //     SPAuditMaskType.SchemaChange | SPAuditMaskType.Search | SPAuditMaskType.SecurityChange |
                    //     SPAuditMaskType.Undelete | SPAuditMaskType.Update | SPAuditMaskType.View | SPAuditMaskType.Workflow;

                    //mySite.Audit.AuditFlags = SPAuditMaskType.None; //Configures to none
                    mySite.Audit.Update();

                }
            }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
<p>After configuring the settings, SharePoint audits the library events on item viewing, downloading, editing, deleting etc.,<br />
SharePoint also generates audit log reports on this events in .CSV format. In this example we are reading the data from the configured audit entry logs to know event actions on documents.</p>
<p>Use the below code to know the event count on documents</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel;
using System.Web;
using System.Text;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace DownloadCounter.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @&quot;~/_CONTROLTEMPLATES/DownloadCounter/DownloadCounterWebPart/DownloadCounterUserControl.ascx&quot;;
        SPGridView myGridView;
        SPDataSource myDataSource = new SPDataSource();
        string errorMessage = string.Empty;

        protected override void CreateChildControls()
        {
            Control control = Page.LoadControl(_ascxPath);
            Controls.Add(control);

            base.CreateChildControls();

            myGridView = new SPGridView();
            myGridView.AutoGenerateColumns = false;
            myGridView.Enabled = true;
            myGridView.AllowSorting = true;
            myGridView.AllowGrouping = true;
            myGridView.AllowGroupCollapse = true;
            myGridView.GroupField = &quot;Event&quot;;
            myGridView.DisplayGroupFieldName = false;
            myGridView.AllowPaging = true;
            myGridView.PageSize = 50;
            myGridView.PageIndexChanging += new GridViewPageEventHandler(myGridView_PageIndexChanging);

            BoundField colEvent = new BoundField();
            colEvent.DataField = &quot;Event&quot;;
            colEvent.HeaderText = &quot;Event&quot;;
            this.myGridView.Columns.Add(colEvent);

            BoundField colItemType = new BoundField();
            colItemType.DataField = &quot;ItemType&quot;;
            colItemType.HeaderText = &quot;ItemType&quot;;
            this.myGridView.Columns.Add(colItemType);

            BoundField colDocLocation = new BoundField();
            colDocLocation.DataField = &quot;DocLocation&quot;;
            colDocLocation.HeaderText = &quot;DocLocation&quot;;
            this.myGridView.Columns.Add(colDocLocation);

            BoundField colOccurred = new BoundField();
            colOccurred.DataField = &quot;Occurred&quot;;
            colOccurred.HeaderText = &quot;Occurred&quot;;
            this.myGridView.Columns.Add(colOccurred);

            BoundField colUserName = new BoundField();
            colUserName.DataField = &quot;UserName&quot;;
            colUserName.HeaderText = &quot;UserName&quot;;
            this.myGridView.Columns.Add(colUserName);

            Controls.Add(myGridView);
            myGridView.PagerTemplate = null;
            GetAudEntries();
            GroupByGridView();
        }
        private void GroupByGridView()
        {
            StringBuilder scriptFunction = new StringBuilder();
            scriptFunction.Append(&quot;&lt;script src='/SiteAssets/jquery-1.4.2.min.js' type='text/javascript'&gt;&lt;/script&gt;&quot;);
            scriptFunction.Append(&quot;&lt;script type='text/javascript'&gt;&quot;);
            scriptFunction.Append(&quot;$(document).ready(function(){$('.ms-gb').each(function(){var rowNums=$(this).nextUntil('.ms-gb').length;&quot;);
            scriptFunction.Append(&quot;$(this).children(0).append('('+rowNums+')');&quot;);
            scriptFunction.Append(&quot;$(this).children(0).children(0).trigger('onclick');&quot;);
            scriptFunction.Append(&quot;});&quot;);
            scriptFunction.Append(&quot;});&quot;);
            scriptFunction.Append(&quot;&lt;/script&gt;&quot;);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), &quot;GroupBy&quot;, scriptFunction.ToString());
        }

        private void GetAudEntries()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite mySite = SPContext.Current.Site;
                SPWeb myWeb = SPContext.Current.Web;
                DataTable myDataTable = new DataTable();
                DataRow myRow;
                SPUser user;
                try
                {
                    SPAuditQuery wssQuery = new SPAuditQuery(mySite);
                    SPAuditEntryCollection auditCol = mySite.Audit.GetEntries(wssQuery);

                    myDataTable.Columns.Add(&quot;Event&quot;);
                    myDataTable.Columns.Add(&quot;ItemType&quot;);
                    myDataTable.Columns.Add(&quot;DocLocation&quot;);
                    myDataTable.Columns.Add(&quot;Occurred&quot;, typeof(DateTime));
                    myDataTable.Columns.Add(&quot;UserName&quot;);

                    foreach (SPAuditEntry entry in auditCol)
                    {
                        if (entry.DocLocation.EndsWith(&quot;.xls&quot;) || (entry.DocLocation.EndsWith(&quot;.doc&quot;)) || (entry.DocLocation.EndsWith(&quot;.ppt&quot;)))
                        {
                            user = myWeb.SiteUsers.GetByID(entry.UserId);
                            myRow = myDataTable.NewRow();
                            myRow[&quot;Event&quot;] = entry.Event;
                            myRow[&quot;ItemType&quot;] = entry.ItemType.ToString();
                            myRow[&quot;DocLocation&quot;] = entry.DocLocation;
                            myRow[&quot;Occurred&quot;] = entry.Occurred.ToLocalTime();
                            myRow[&quot;UserName&quot;] = user.ToString();
                            myDataTable.Rows.Add(myRow);
                        }
                    }
                    myGridView.DataSource = myDataTable;
                    myGridView.DataBind();
                }
                catch (Exception ex)
                {
                    errorMessage = ex.ToString();
                }
            });

        }
        void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            myGridView.PageIndex = e.NewPageIndex;
            myGridView.DataBind();
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.Write(errorMessage);
            EnsureChildControls();
            RenderChildren(writer);
        }
    }
}
</pre>
<p>Use the above code or try to deploy the <a title="SharePoint Download Counter" href="http://www.fivenumber.com/wp-content/uploads/2010/12/DownloadCounter.wsp" target="_blank">DownloadCounter.wsp</a><br />
<strong>Note</strong>: In the above code we have used JQuery jquery-1.4.2.min.js files to show the count of the group by field, so please download the jquery-1.4.2.min.js file from <a href="http://code.jquery.com/jquery-1.4.2.min.js" target="_blank">http://code.jquery.com/jquery-1.4.2.min.js</a> and place in some location of the SharePoint site and also refer the same source location in the above code, in this example I have placed the Jquery file in Site Assets library, you can even place in the same location if you don&#8217;t want to change the code.</p>
<p>After deploying the downloaded solution, please try to activate<strong> Download Counter Feature</strong> see figure 3</p>
<div id="attachment_918" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/12/3.jpg" rel="lightbox[914]"><img class="size-medium wp-image-918" title="Figure 3 - Activate Download Counter Feature" src="http://www.fivenumber.com/wp-content/uploads/2010/12/3-300x19.jpg" alt="Figure 3 - Activate Download Counter Feature" width="300" height="19" /></a><p class="wp-caption-text">Figure 3 - Activate Download Counter Feature</p></div>
<p>Then add the webpart to the page see figure 4</p>
<div id="attachment_919" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/12/4.jpg" rel="lightbox[914]"><img class="size-medium wp-image-919" title="Figure 4 - Adding Download Counter WebPart to SharePoint Site" src="http://www.fivenumber.com/wp-content/uploads/2010/12/4-300x219.jpg" alt="Figure 4 - Adding Download Counter WebPart to SharePoint Site" width="300" height="219" /></a><p class="wp-caption-text">Figure 4 - Adding Download Counter WebPart to SharePoint Site</p></div>
<p>Then you can view the webpart updating on every action of documents see figure 5</p>
<div id="attachment_920" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/12/5.jpg" rel="lightbox[914]"><img class="size-medium wp-image-920" title="Figure 5 - Download counter webPart shows the count of events for the documents" src="http://www.fivenumber.com/wp-content/uploads/2010/12/5-300x250.jpg" alt="Figure 5 - Download counter webPart shows the count of events for the documents" width="300" height="250" /></a><p class="wp-caption-text">Figure 5 - Download counter webPart shows the count of events for the documents</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/sharepoint-document-counter-counts-the-document-downloads/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Most Common Custom WebParts Part 4 – Flash Media WebPart</title>
		<link>http://www.fivenumber.com/most-common-custom-webparts-part-4-%e2%80%93-flash-media-webpart/</link>
		<comments>http://www.fivenumber.com/most-common-custom-webparts-part-4-%e2%80%93-flash-media-webpart/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 21:33:53 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>
		<category><![CDATA[SharePoint 2010 - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=895</guid>
		<description><![CDATA[In my previous post you can view the most commonly used custom webparts, Tree View WebPart Shows Sites and Sub-Sites, Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode, Windows Media Player WebPart In this continuation series of most commonly used custom webparts, I come up with a simple Flash Player webpart which plays flash [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post you can view the most commonly used custom webparts, Tree View WebPart Shows Sites and Sub-Sites, Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode, Windows Media Player WebPart</p>
<p>In this continuation series of most commonly used custom webparts, I come up with a simple Flash Player webpart which plays flash files on Sharepoint sites, the webpart also supports to configure the properties as required.</p>
<p>Download the solution file <a title="Flash Media Player WebPart Solution" href="www.fivenumber.com/wp-content/uploads/2010/11/FlashWebPart.wsp" target="_blank">FlashWebPart.wsp</a></p>
<div id="attachment_896" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/11/18.jpg" rel="lightbox[895]"><img class="size-medium wp-image-896" title="Flash Media Player WebPart" src="http://www.fivenumber.com/wp-content/uploads/2010/11/18-300x218.jpg" alt="Flash Media Player WebPart" width="300" height="218" /></a><p class="wp-caption-text">Flash Media Player WebPart</p></div>
<div id="attachment_897" class="wp-caption aligncenter" style="width: 200px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/11/33.jpg" rel="lightbox[895]"><img class="size-medium wp-image-897" title="Flash Media Player WebPart Configuration" src="http://www.fivenumber.com/wp-content/uploads/2010/11/33-190x300.jpg" alt="Flash Media Player WebPart Configuration" width="190" height="300" /></a><p class="wp-caption-text">Flash Media Player WebPart Configuration</p></div>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace FlashWebPart.Flash
{
    [ToolboxItemAttribute(false)]
    public class Flash : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        //private const string _ascxPath = @&quot;~/_CONTROLTEMPLATES/FlashWebPart/Flash/FlashWebPartUserControl.ascx&quot;;

        private string flashFilePath = &quot;http://www.adobe.com/content/dam/Adobe/en/devnet/flash/samples/time_1/1_timer.swf&quot;;
        private string flashWidth = &quot;320&quot;;
        private string flashHeight = &quot;240&quot;;
        private string bgColor = string.Empty;
        private bool loopPlayBack = true;

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Specifies the media file location&quot;),
        Category(&quot;Flash Media Properties&quot;),
        WebDisplayName(&quot;Media File Location&quot;)]
        public string FlashFilePath
        {
            get { return flashFilePath; }
            set { flashFilePath = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Sets the width of the Media player&quot;),
        Category(&quot;Flash Media Properties&quot;),
        WebDisplayName(&quot;Width&quot;)]
        public string FlashWidth
        {
            get { return flashWidth; }
            set { flashWidth = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Sets the height of the Media player&quot;),
        Category(&quot;Flash Media Properties&quot;),
        WebDisplayName(&quot;Height&quot;)]
        public string FlashHeight
        {
            get { return flashHeight; }
            set { flashHeight = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Background Color: Specifies the back color&quot;),
        Category(&quot;Flash Media Properties&quot;),
        WebDisplayName(&quot;Background Color&quot;)]
        public string BGColor
        {
            get { return bgColor; }
            set { bgColor = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Loop Play Back: (True/False) Repeats the video automatically&quot;),
        Category(&quot;Flash Media Properties&quot;),
        WebDisplayName(&quot;Loop Play Back&quot;)]
        public bool LoopPlayBack
        {
            get { return loopPlayBack; }
            set { loopPlayBack = value; }
        }

        //protected override void CreateChildControls()
        //{
        //    Control control = Page.LoadControl(_ascxPath);
        //    Controls.Add(control);
        //}

        protected override void Render(HtmlTextWriter writer)
        {
            SPSite site = null;
            SPWeb web = SPContext.Current.Web;
            if (!string.IsNullOrEmpty(FlashFilePath) &amp;&amp; !string.IsNullOrEmpty(FlashWidth) &amp;&amp; !string.IsNullOrEmpty(FlashHeight))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        site = new SPSite(web.Site.ID);

                        using (site)
                        {
                            #region Script
                            writer.Write(&quot;&lt;OBJECT classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='&quot; + FlashWidth + &quot;' height='&quot; + FlashWidth + &quot;'&gt;&quot;);
                            writer.Write(&quot;&lt;param name='movie' value='&quot; + FlashFilePath + &quot;'&gt;&quot;);
                            writer.Write(&quot;&lt;param name='bgcolor' value='&quot; + BGColor + &quot;'&gt;&quot;);
                            writer.Write(&quot;&lt;param name='loop' value='&quot; + LoopPlayBack + &quot;'&gt;&quot;);
                            writer.Write(&quot;&lt;EMBED src='&quot; + FlashFilePath + &quot;' quality='high' bgcolor='#FFFFFF' width='&quot; + FlashWidth + &quot;' height='&quot; + FlashHeight + &quot;' loop='&quot; + LoopPlayBack + &quot;' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'&gt;&quot;);
                            writer.Write(&quot;&lt;/EMBED&gt;&quot;);
                            writer.Write(&quot;&lt;/OBJECT&gt;&quot;);
                            #endregion
                        }
                    });
                }
                catch (Exception ex)
                {
                    writer.Write(ex.Message);
                }
            }
            else
            {
                writer.Write(&quot;&lt;span class='ms-formvalidation'&gt;&quot;);
                writer.Write(&quot;Please configure the &lt;B&gt;Media WebPart&lt;/B&gt; properties in webpart properties section&quot;);
                writer.Write(&quot;&lt;/span&gt;&quot;);
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/most-common-custom-webparts-part-4-%e2%80%93-flash-media-webpart/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Most Common Custom WebParts Part 3 – Windows OR YouTube Media Player WebPart</title>
		<link>http://www.fivenumber.com/most-common-custom-webparts-part-3-%e2%80%93-windows-media-player-webpart/</link>
		<comments>http://www.fivenumber.com/most-common-custom-webparts-part-3-%e2%80%93-windows-media-player-webpart/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 10:35:09 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[SharePoint 2010 - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=887</guid>
		<description><![CDATA[In my previous post you can view the most commonly used custom webparts, Tree View WebPart Shows Sites and Sub-Sites and Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode Now I got one more chance to continue the series of most commonly used custom webparts, so once again I come up with a simple [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post you can view the most commonly used custom webparts, <a title="Tree View WebPart Shows Sites and Sub-Sites" href="http://www.fivenumber.com/most-common-custom-webparts-part1-tree-view-webpart-shows-sites-and-sub-sites/" target="_blank">Tree View WebPart Shows Sites and Sub-Sites</a> and <a title="Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode" href="http://www.fivenumber.com/most-common-custom-webparts-part-2-%E2%80%93-menu-webpart-shows-sites-and-sub-sites-in-fly-out-mode/" target="_blank">Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode</a></p>
<p>Now I got one more chance to continue the series of most commonly used custom webparts, so once again I come up with a simple Windows Or Youtube Media Player webpart which plays video on Sharepoint sites, the webpart also supports to configure the properties as required.</p>
<p>In the webpart properties section please enter the Windows media or Youtube link, the webpart automatically detects the media type and plays accordingly</p>
<p>Download the solution file <a title="Windows OR Youtube Media WebPart Solution" href="http://fivenumber.com/wp-content/uploads/2012/01/WindowsORYouTubeMediaWebPart.wsp" target="_blank">WindowsORYouTubeMediaWebPart.wsp</a></p>
<div id="attachment_941" class="wp-caption aligncenter" style="width: 269px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player.png" rel="lightbox[887]"><img class="size-medium wp-image-941" title="Windows Or YouTube Player WebPart (Playing Windows media Video)" src="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player-259x300.png" alt="Windows Or YouTube Player WebPart (Playing Windows media Video)" width="259" height="300" /></a><p class="wp-caption-text">Windows Or YouTube Player WebPart (Playing Windows media Video)</p></div>
<div id="attachment_938" class="wp-caption aligncenter" style="width: 277px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player-WebPart.png" rel="lightbox[887]"><img class="size-medium wp-image-938 " title="Windows Or YouTube Player WebPart (Playing Youtube Video)" src="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player-WebPart-267x300.png" alt="Windows Or YouTube Player WebPart (Playing Youtube Video)" width="267" height="300" /></a><p class="wp-caption-text">Windows Or YouTube Player WebPart (Playing Youtube Video)</p></div>
<pre></pre>
<div id="attachment_943" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player-WebPart-Properties1.png" rel="lightbox[887]"><img class="size-medium wp-image-943" title="Windows Or YouTube Player WebPart Properties" src="http://www.fivenumber.com/wp-content/uploads/2010/11/Windows-OR-YouTube-Player-WebPart-Properties1-300x292.png" alt="Windows Or YouTube Player WebPart Properties" width="300" height="292" /></a><p class="wp-caption-text">Windows Or YouTube Player WebPart Properties</p></div>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace WindowsMediaWebPart.MediaWebPart
{
    [ToolboxItemAttribute(false)]
    public class WindowsMedia : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        //private const string _ascxPath = @&quot;~/_CONTROLTEMPLATES/WindowsMediaWebPart/MediaWebPart/MediaWebPartUserControl.ascx&quot;;

        private string videoFilePath = string.Empty;
        private string videoWidth = &quot;320&quot;;
        private string videoHeight = &quot;240&quot;;
        private bool animationAtStart = true;
        private bool transparentAtStart = true;
        private bool autoStart = true;
        private bool showControls = true;
        private bool loopPlayBack = true;
        private string frameBorder = &quot;0&quot;;

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Specifies the media file location&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Media File Location&quot;)]
        public string VideoFilePath
        {
            get { return videoFilePath; }
            set { videoFilePath = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Sets the width of the Media player&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Width&quot;)]
        public string VideoWidth
        {
            get { return videoWidth; }
            set { videoWidth = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Sets the height of the Media player&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Height&quot;)]
        public string VideoHeight
        {
            get { return videoHeight; }
            set { videoHeight = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Animation At Start: (True/False)&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Animation At Start&quot;)]
        public bool AnimationAtStart
        {
            get { return animationAtStart; }
            set { animationAtStart = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Transparent At Start: (True/False)&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Transparent At  Start&quot;)]
        public bool TransparentAtStart
        {
            get { return transparentAtStart; }
            set { transparentAtStart = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Auto Start: (True/False) Starts the video automatically&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Auto Start&quot;)]
        public bool AutoStart
        {
            get { return autoStart; }
            set { autoStart = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Show Controls: (True/False) Displays media player controls&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Show Controls&quot;)]
        public bool ShowControls
        {
            get { return showControls; }
            set { showControls = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Loop Play Back: (True/False) Repeats the video automatically&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Loop Play Back&quot;)]
        public bool LoopPlayBack
        {
            get { return loopPlayBack; }
            set { loopPlayBack = value; }
        }

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription(&quot;Sets the border of the media (applicable for youtube videos)&quot;),
        Category(&quot;Media Properties&quot;),
        WebDisplayName(&quot;Allow Full Screen&quot;)]
        public string FrameBorder
        {
            get { return frameBorder; }
            set { frameBorder = value; }
        }

        protected override void CreateChildControls()
        {
            //Control control = Page.LoadControl(_ascxPath);
            //Controls.Add(control);
            this.TitleUrl = VideoFilePath;
        }

        protected override void Render(HtmlTextWriter writer)
        {
            SPSite site = null;
            SPWeb web = SPContext.Current.Web;
            if (!string.IsNullOrEmpty(VideoFilePath) &amp;&amp; !string.IsNullOrEmpty(VideoWidth) &amp;&amp; !string.IsNullOrEmpty(VideoHeight))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        site = new SPSite(web.Site.ID);

                        using (site)
                        {
                            if ((videoFilePath.ToLower()).Contains(&quot;youtube.com/&quot;))
                            {
                                Uri youtubeUri = new Uri(videoFilePath);
                                string query = youtubeUri.Query;
                                string mediaID = HttpUtility.ParseQueryString(query).Get(&quot;v&quot;);
                                string source = &quot;http://www.youtube.com/embed/&quot; + mediaID;
                                writer.Write(&quot;&lt;iframe width='&quot; + VideoWidth + &quot;' height='&quot; + VideoHeight + &quot;' src='&quot; + source + &quot;' frameborder='&quot; + FrameBorder + &quot;' allowfullscreen&gt;&lt;/iframe&gt;&quot;);
                            }
                            else
                            {

                                writer.Write(&quot;&lt;OBJECT id='mediaPlayer' width='&quot; + VideoWidth + &quot;' height='&quot; + VideoHeight + &quot;' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='fileName' value='&quot; + VideoFilePath + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='animationatStart' value='&quot; + AnimationAtStart + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='transparentatStart' value='&quot; + TransparentAtStart + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='autoStart' value='&quot; + AutoStart + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='showControls' value='&quot; + ShowControls + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;param name='loop' value='&quot; + LoopPlayBack + &quot;'&gt;&quot;);
                                writer.Write(&quot;&lt;EMBED type='application/x-mplayer2'pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'id='windowsmediaPlayer' name='windowsmediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='&quot; + ShowControls + &quot;' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='&quot; + VideoWidth + &quot;' height='&quot; + VideoHeight + &quot;' src='&quot; + VideoFilePath + &quot;' autostart='&quot; + AutoStart + &quot;' designtimesp='5311' loop='&quot; + LoopPlayBack + &quot;'&gt;&lt;/EMBED&gt;&quot;);
                                writer.Write(&quot;&lt;/OBJECT&gt;&quot;);

                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    writer.Write(ex.Message);
                }
            }
            else
            {
                writer.Write(&quot;&lt;span class='ms-formvalidation'&gt;&quot;);
                writer.Write(&quot;Please configure the &lt;B&gt;Media WebPart&lt;/B&gt; properties in webpart properties section&quot;);
                writer.Write(&quot;&lt;/span&gt;&quot;);
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/most-common-custom-webparts-part-3-%e2%80%93-windows-media-player-webpart/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Most Common Custom WebParts Part 2 – Menu WebPart Shows Sites and Sub-Sites in Fly-Out Mode</title>
		<link>http://www.fivenumber.com/most-common-custom-webparts-part-2-%e2%80%93-menu-webpart-shows-sites-and-sub-sites-in-fly-out-mode/</link>
		<comments>http://www.fivenumber.com/most-common-custom-webparts-part-2-%e2%80%93-menu-webpart-shows-sites-and-sub-sites-in-fly-out-mode/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 05:12:49 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>
		<category><![CDATA[SharePoint 2010 - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[object model]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=832</guid>
		<description><![CDATA[In my previous post can view the most common custom webparts part 1 From last post I want to continue the series of most commonly used custom webparts, so once again I come up with a simple and small custom menu webpart shows all the sites and sub-sites of a SharePoint site in fly-out style]]></description>
			<content:encoded><![CDATA[<p>In my previous post can view the <a title="Most common custom webparts part 1" href="http://www.fivenumber.com/most-common-custom-webparts-part1-tree-view-webpart-shows-sites-and-sub-sites/" target="_blank">most common custom webparts part 1</a></p>
<p>From last post I want to continue the series of most commonly used custom webparts, so once again I come up with a simple and small custom menu webpart shows all the sites and sub-sites of a SharePoint site in fly-out style</p>
<div id="attachment_833" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/10/11.png" rel="lightbox[832]"><img class="size-medium wp-image-833" title="SharePoint Menu WebPart in fly-Out Style" src="http://www.fivenumber.com/wp-content/uploads/2010/10/11-300x225.png" alt="SharePoint Menu WebPart in fly-Out Style" width="300" height="225" /></a><p class="wp-caption-text">SharePoint Menu WebPart in fly-Out Style</p></div>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomWebParts.VisualWebPart1
{
    [ToolboxItemAttribute(false)]
    public class VisualWebPart1 : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
       // private const string _ascxPath = @&quot;~/_CONTROLTEMPLATES/CustomWebParts/TreeView/TreeViewUserControl.ascx&quot;;

        System.Web.UI.WebControls.Menu menu = null;

        protected override void CreateChildControls()
        {
            //Control control = Page.LoadControl(_ascxPath);
            //Controls.Add(control);

            menu = new System.Web.UI.WebControls.Menu();
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;

            menu.StaticDisplayLevels = 1;
            menu.MaximumDynamicDisplayLevels = 200;
            menu.Orientation = System.Web.UI.WebControls.Orientation.Horizontal;
            menu.StaticEnableDefaultPopOutImage = false;
            menu.StaticPopOutImageUrl = &quot;/_layouts/images/menudark.gif&quot;;
            menu.SkipLinkText = &quot;&quot;;
            menu.DynamicHoverStyle.BackColor = System.Drawing.Color.FromName(&quot;#CBE3F0&quot;);
            menu.CssClass = &quot;ms-topNavContainer&quot;;

            menu.StaticMenuItemStyle.ItemSpacing = Unit.Pixel(0);
            menu.StaticSelectedStyle.CssClass = &quot;ms-topnavselected&quot;;
            menu.StaticHoverStyle.CssClass = &quot;ms-topNavHover&quot;;

            menu.DynamicMenuStyle.BackColor = System.Drawing.Color.FromName(&quot;#F2F3F4&quot;);
            menu.DynamicMenuStyle.BorderColor = System.Drawing.Color.FromName(&quot;#A7B4CE&quot;);
            menu.DynamicMenuStyle.BorderWidth = Unit.Pixel(1);

            menu.DynamicMenuItemStyle.CssClass = &quot;ms-topNavFlyOuts&quot;;
            menu.DynamicHoverStyle.CssClass = &quot;ms-topNavFlyOutsHover&quot;;
            menu.DynamicSelectedStyle.CssClass = &quot;ms-topNavFlyOutsSelected&quot;;

            MenuItemStyle stMenuStyle = menu.StaticMenuItemStyle;
            stMenuStyle.CssClass = &quot;ms-topnav&quot;;

            stMenuStyle.HorizontalPadding = 0;
            stMenuStyle.VerticalPadding = 0;
            stMenuStyle.ItemSpacing = Unit.Pixel(0);

            MenuItemStyle dyMenuStyle = menu.DynamicMenuItemStyle;
            dyMenuStyle.CssClass = &quot;ms-topNavFlyOuts&quot;;
            dyMenuStyle.HorizontalPadding = 0;
            dyMenuStyle.VerticalPadding = 0;

            System.Web.UI.WebControls.MenuItem mItem = new System.Web.UI.WebControls.MenuItem(web.Title);
            mItem.NavigateUrl = web.Site.Url;
            menu.Items.Add(mItem);

            GenerateMenu(menu, Context);
            menu.DataBind();
            this.Controls.Add(menu);
        }

        public static void GenerateMenu(System.Web.UI.WebControls.Menu menu, HttpContext context)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;

            foreach (SPWeb subsite in web.Webs)
            {
                System.Web.UI.WebControls.MenuItem mItem = new System.Web.UI.WebControls.MenuItem();
                mItem.NavigateUrl = subsite.Url;
                mItem.Text = subsite.Title;
                mItem.ToolTip = subsite.Title;
                menu.Items.Add(mItem);
                BuildMenu(subsite, mItem, context);
            }
        }

        private static void BuildMenu(SPWeb subweb, System.Web.UI.WebControls.MenuItem mItem, HttpContext context)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;

            foreach (SPWeb subsite in subweb.Webs)
            {
                System.Web.UI.WebControls.MenuItem mSubItem = new System.Web.UI.WebControls.MenuItem();
                mSubItem.NavigateUrl = subsite.Url;
                mSubItem.Text = subsite.Title;
                mSubItem.ToolTip = subsite.Title;
                mItem.ChildItems.Add(mSubItem);
            }
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/most-common-custom-webparts-part-2-%e2%80%93-menu-webpart-shows-sites-and-sub-sites-in-fly-out-mode/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Most Common Custom WebParts Part 1 &#8211; Tree View WebPart Shows Sites and Sub-Sites</title>
		<link>http://www.fivenumber.com/most-common-custom-webparts-part1-tree-view-webpart-shows-sites-and-sub-sites/</link>
		<comments>http://www.fivenumber.com/most-common-custom-webparts-part1-tree-view-webpart-shows-sites-and-sub-sites/#comments</comments>
		<pubDate>Fri, 29 Oct 2010 04:26:07 +0000</pubDate>
		<dc:creator>G Vijai Kumar</dc:creator>
				<category><![CDATA[MOSS - Object Model]]></category>
		<category><![CDATA[Sharepoint 2010]]></category>
		<category><![CDATA[SharePoint 2010 - Object Model]]></category>
		<category><![CDATA[Custom Webparts]]></category>
		<category><![CDATA[object model]]></category>
		<category><![CDATA[Sharepoint]]></category>

		<guid isPermaLink="false">http://www.fivenumber.com/?p=825</guid>
		<description><![CDATA[I desired to support most common custom webparts used by the SharePoint professional, so that these can be helpful for them. A custom tree view webpart shows all the sites and sub-sites of a SharePoint site Please use the below code and to get the exact look as show in the aboave image, the tree [...]]]></description>
			<content:encoded><![CDATA[<p>I desired to support most common custom webparts used by the SharePoint professional, so that these can be helpful for them.<br />
A custom tree view webpart shows all the sites and sub-sites of a SharePoint site</p>
<div id="attachment_826" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.fivenumber.com/wp-content/uploads/2010/10/1.png" rel="lightbox[825]"><img class="size-medium wp-image-826" title="SharePoint Custom Tree View WebPart" src="http://www.fivenumber.com/wp-content/uploads/2010/10/1-300x243.png" alt="SharePoint Custom Tree View WebPart" width="300" height="243" /></a><p class="wp-caption-text">SharePoint Custom Tree View WebPart</p></div>
<p>Please use the below code and to get the exact look as show in the aboave image, the tree view webpart can expand/collapse</p>
<pre class="brush: csharp; title: ; notranslate">
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomWebParts.CustomTreeView
{
    [ToolboxItemAttribute(false)]
    public class CustomTreeView : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        //private const string _ascxPath = @&quot;~/_CONTROLTEMPLATES/CustomWebParts/CustomTreeView/CustomTreeViewUserControl.ascx&quot;;

        TreeView myTree;
        LinkButton lnkBtnExpand;
        LinkButton lnkBtnCollapse;
        Label lblPipeDivider;
        Label lbl_ErrorMsg;
        private string errorMessage = string.Empty;
        private int level = 0;

        protected override void CreateChildControls()
        {
            //Control control = Page.LoadControl(_ascxPath);
            //Controls.Add(control);

            this.Controls.Clear();
            myTree = new TreeView();
            myTree.ExpandImageUrl = &quot;/_layouts/images/tvplus.gif&quot;;
            myTree.RootNodeStyle.ImageUrl = &quot;/_layouts/images/stsicon.gif&quot;;
            myTree.ParentNodeStyle.ImageUrl = &quot;/_layouts/images/stsicon.gif&quot;;
            myTree.LeafNodeStyle.ImageUrl = &quot;/_layouts/images/stsicon.gif&quot;;
            myTree.CollapseImageUrl = &quot;/_layouts/images/tvminus.gif&quot;;
            myTree.NoExpandImageUrl = &quot;/_layouts/images/stsicon.gif&quot;;            

            myTree.NodeWrap = true;
            myTree.ShowLines = true;
            myTree.ShowExpandCollapse = true;
            myTree.EnableClientScript = true;

            GenerateTreeView();
            myTree.CollapseAll();
            myTree.CssClass = &quot;ms-navitem a&quot;;
            this.Controls.Add(myTree);

            lnkBtnExpand = new LinkButton();
            lnkBtnExpand.Click += new EventHandler(expandAll_Click);
            lnkBtnExpand.Text = &quot;Expand all&quot;;
            lnkBtnExpand.CssClass = &quot;ms-navitem a&quot;;
            this.Controls.Add(lnkBtnExpand);

            lblPipeDivider = new Label();
            lblPipeDivider.Text = &quot;  |  &quot;;
            this.Controls.Add(lblPipeDivider);

            lnkBtnCollapse = new LinkButton();
            lnkBtnCollapse.Click += new EventHandler(collapseAll_Click);
            lnkBtnCollapse.Text = &quot;Collapse all&quot;;
            lnkBtnCollapse.CssClass = &quot;ms-navitem a&quot;;
            this.Controls.Add(lnkBtnCollapse);

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

            base.CreateChildControls();
        }

        private void GenerateTreeView()
        {
            SPSite mySite = null;
            SPWeb myWeb = SPContext.Current.Web;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    mySite = new SPSite(myWeb.Site.ID);
                    using (mySite)
                    {
                        level = 1;
                        foreach (SPWeb subWeb in myWeb.Webs)
                        {
                            TreeNode myTreeNode = new TreeNode(subWeb.Title);
                            myTreeNode.NavigateUrl = subWeb.Url;
                            ReadSubSites(subWeb, ref myTreeNode);
                            myTree.Nodes.Add(myTreeNode);
                        }

                    }
                }
                catch (Exception ex)
                {
                    errorMessage = ex.ToString();
                }
            });
        }

        private void ReadSubSites(SPWeb subWeb, ref TreeNode myTreeNode)
        {
            try
            {
                foreach (SPWeb myChildSubWeb in subWeb.Webs)
                {
                    TreeNode subnode = new TreeNode(myChildSubWeb.Title);
                    subnode.NavigateUrl = myChildSubWeb.Url;

                    myTreeNode.ChildNodes.Add(subnode);

                    if (myChildSubWeb.Webs.Count &gt; 0)
                    {
                        if (myTreeNode.ChildNodes.Count &gt; 0)
                        {
                            level = level + 1;
                            TreeNode myChildNode = myTreeNode.ChildNodes[myTreeNode.ChildNodes.Count - 1];
                            ReadSubSites(myChildSubWeb, ref myChildNode);
                            level = level - 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.ToString();
            }
        }

        void expandAll_Click(object sender, EventArgs e)
        {
            myTree.ExpandAll();
        }

        void collapseAll_Click(object sender, EventArgs e)
        {
            myTree.CollapseAll();
        }      

        protected override void RenderContents(HtmlTextWriter writer)
        {
            EnsureChildControls();
            lnkBtnExpand.RenderControl(writer);
            lblPipeDivider.RenderControl(writer);
            lnkBtnCollapse.RenderControl(writer);
            RenderChildren(writer);
        }
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/most-common-custom-webparts-part1-tree-view-webpart-shows-sites-and-sub-sites/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<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: //STS#0 &#8211; Team Site //STS#1 [...]]]></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>
<pre class="brush: csharp; title: ; notranslate">static void Main(string[] args)
        {
            SPSite site = new SPSite(&quot;http://servername:port&quot;);
            foreach (SPWeb web in site.AllWebs)
            {
                string template = web.WebTemplate + &quot;#&quot; + web.Configuration;
                if (template.ToUpper() == &quot;BLOG#0&quot;)
                {
                    Console.WriteLine(web.Title);
                }
            }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
<p><strong>Show services and status in Sharepoint server farm:</strong></p>
<pre class="brush: csharp; title: ; notranslate">static void Main(string[] args)
        {
            SPServiceCollection services = SPFarm.Local.Services;
            foreach (SPService service in services)
            {
                Console.WriteLine(&quot;Service Name: {0}&quot;, service.Name);
                Console.WriteLine(&quot;Service Status: {0}&quot;, service.Status);
                Console.WriteLine(&quot;-------------------------------------&quot;);
            }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
<p><strong>Adding/Retrieving values to property bag:</strong></p>
<pre class="brush: csharp; title: ; notranslate">static void Main(string[] args)
        {
            using (SPSite siteCollection = new SPSite(&quot;http://servername:port&quot;))
            {
                using (SPWeb site = siteCollection.RootWeb)
                {
                    site.Properties.Add(&quot;TempKey&quot;, &quot;TempValue&quot;);//Adding value
                    site.Properties.Update();

                    Console.WriteLine(site.Properties[&quot;TempKey&quot;]);//Reading value
                }
            }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
<p><strong>Read files in a folder:</strong></p>
<pre class="brush: csharp; title: ; notranslate">static void Main(string[] args)
        {
            SPSite site = new SPSite(&quot;http://servername:port&quot;);
            SPWeb web = site.OpenWeb();
            SPFolder folder = web.GetFolder(&quot;Shared Documents&quot;);
            SPFileCollection files = folder.Files;
            foreach (SPFile file in files)
            {
                Console.WriteLine(file.Name.ToString());
            }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
<p><strong>Get content database for all site collections:</strong></p>
<pre class="brush: csharp; title: ; notranslate">
 static void Main(string[] args)
        {
                SPSite site = new SPSite(&quot;http://CentralAdminSiteURL&quot;);
                SPFarm farm = site.WebApplication.Farm;
                SPWebService service = farm.Services.GetValue&lt;SPWebService&gt;(&quot;&quot;);
                foreach (SPWebApplication webapp in service.WebApplications)
                {
                    foreach (SPSite mysite in webapp.Sites)
                    {
                        Console.WriteLine(mysite.Url+&quot; ----- &quot;+ mysite.ContentDatabase.Name);
                    }
                }
            Console.WriteLine(&quot;Press any key to continue.....&quot;);
            Console.ReadLine();
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.fivenumber.com/a-quick-look-on-sharepoint-object-model-programs-part-2/feed/</wfw:commentRss>
		<slash:comments>3</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>21</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>
<p><strong>Show all Users in a group from UserCollection:</strong></p>
<pre name="code" class="c-sharp">
static void Main(string[] args)
        {
            SPSite mySite = new SPSite("http://servername:port");
            SPWeb myWeb = mySite.OpenWeb();
            SPUserCollection myUserCollection = myWeb.Groups["Group Name"].Users;
            foreach (SPUser myUser in myUserCollection)
            {
                Console.WriteLine(myUser.LoginName);
            }
            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>8</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>84</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 [...]]]></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>31</slash:comments>
		</item>
	</channel>
</rss>

