A Quick Look On Sharepoint 2010 Managed Client Object Model Programs

10 June, 2012 (17:00) | Sharepoint 2010, SharePoint 2010 - Client Object Model, SharePoint 2010 - Object Model | By: G Vijai Kumar

I have a practice of posting handy code snippets which takes less time to read, understand and save in mind with very little space of memory
Please look into few of my previous handy code snippet articles below:

A quick look on SharePoint object model programs

A quick look on SharePoint object model programs – Part 2

A quick look on SharePoint object model programs – Part 3

So in this article I’m going to post SharePoint 2010 Managed Client Object Model programs

Create Site:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace CreateSite
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://SharePointSiteURL");
            Web web = context.Web;

            WebCreationInformation myWebCreationInformation = new WebCreationInformation();
            myWebCreationInformation.Title = "FiveNumber";
            myWebCreationInformation.Description = "It's all about SharePoint";
            myWebCreationInformation.Url = "fivenumber";
            myWebCreationInformation.Language = 1033; //locale ID that specifies the language the site example: English(US)-1033, Germany-1031, French(France)-1036.
            myWebCreationInformation.UseSamePermissionsAsParentSite = true;
            myWebCreationInformation.WebTemplate = "STS#0";

            Web myNewWeb = web.Webs.Add(myWebCreationInformation);

            context.Load(myNewWeb, website => website.Title);
            context.ExecuteQuery();

            Console.WriteLine("Website Created Successfully: " + myNewWeb.Title);
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

Get Website Properties:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace Get_Web_Site_Properties
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://SharePointSiteURL");
            Web web = context.Web;

            context.Load(web);
            context.ExecuteQuery();

            Console.WriteLine("Website site details: \n" + "=====================\n"+"Title: " + web.Title + "\nRelativeURL: " + web.ServerRelativeUrl + "\nDescription: " + web.Description + "\nCreated Date: " + web.Created + "\nLanguage: " + web.Language);
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

Create List:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace Create_List
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://SharePointSiteURL");
            Web web = context.Web;

            ListCreationInformation myListCreationInformation = new ListCreationInformation();
            myListCreationInformation.Title = "MyList";
            myListCreationInformation.TemplateType = (int)ListTemplateType.GenericList;
            myListCreationInformation.Description = "List created using managed object model";
            myListCreationInformation.QuickLaunchOption = QuickLaunchOptions.On;
            List list = web.Lists.Add(myListCreationInformation);

            context.ExecuteQuery();

            Console.WriteLine("List Created Successfully");
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

Create List Columns:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using sp = Microsoft.SharePoint.Client;
namespace Create_List_Columns
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext context = new ClientContext("http://SharePointSiteURL");
            Web web = context.Web;
            List list = web.Lists.GetByTitle("MyList");
            Field EmployeeID = list.Fields.AddFieldAsXml("", true, AddFieldOptions.DefaultValue);
            Field EmployeeName = list.Fields.AddFieldAsXml("", true, AddFieldOptions.DefaultValue);
            Field Designation = list.Fields.AddFieldAsXml("", true, AddFieldOptions.DefaultValue);

            context.ExecuteQuery();
            Console.WriteLine("List Fields Created Successfully");
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

Add new List Items To Existing List:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;

namespace Add_New_List_Item
{
    class Program
    {
        static void Main(string[] args)
        {

            ClientContext context = new ClientContext("http://SharePointSiteURL");
            List myList = context.Web.Lists.GetByTitle("MyList");
            ListItemCreationInformation myListItemCreationInformation= new ListItemCreationInformation();
            ListItem myListItem = myList.AddItem(myListItemCreationInformation);
            myListItem["Title"] = "Mr.";
            myListItem["EmployeeID"] = 500;
            myListItem["Name"] = "Raja";
            myListItem["Designation"] = "SharePoint Developer";
            myListItem.Update();
            context.ExecuteQuery();

            Console.WriteLine("New List Item Added Successfully");
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }
}

SharePoint Document Counter Counts The Document Downloads

15 December, 2010 (19:26) | SharePoint 2010 - Object Model | By: G Vijai Kumar

In this post I’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, delete, update, view etc) we have to configure the audit entry settings for the SharePoint site collection in site settings page under Site Collection Administration section (see figure 1)

Figure 1 - Configure Site Collection Audit Settings

Figure 1 - Configure Site Collection Audit Settings

On Audit Settings page check the required events to track, in this example I’m configuring for Opening or downloading documents, viewing items in lists, or viewing item properties, Editing items, Deleting or restoring items

Figure 2 - Configure Audit Events

Figure 2 - Configure Audit Events

You can also configure audit entry settings programmatically with few lines of code, here it is:

static void Main()
        {
            using (SPSite mySite = new SPSite("http://<servername>:port"))
            {
                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("Press any key to continue.....");
            Console.ReadLine();
        }

After configuring the settings, SharePoint audits the library events on item viewing, downloading, editing, deleting etc.,
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.

Use the below code to know the event count on documents

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 = @"~/_CONTROLTEMPLATES/DownloadCounter/DownloadCounterWebPart/DownloadCounterUserControl.ascx";
        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 = "Event";
            myGridView.DisplayGroupFieldName = false;
            myGridView.AllowPaging = true;
            myGridView.PageSize = 50;
            myGridView.PageIndexChanging += new GridViewPageEventHandler(myGridView_PageIndexChanging);

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

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

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

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

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

            Controls.Add(myGridView);
            myGridView.PagerTemplate = null;
            GetAudEntries();
            GroupByGridView();
        }
        private void GroupByGridView()
        {
            StringBuilder scriptFunction = new StringBuilder();
            scriptFunction.Append("<script src='/SiteAssets/jquery-1.4.2.min.js' type='text/javascript'></script>");
            scriptFunction.Append("<script type='text/javascript'>");
            scriptFunction.Append("$(document).ready(function(){$('.ms-gb').each(function(){var rowNums=$(this).nextUntil('.ms-gb').length;");
            scriptFunction.Append("$(this).children(0).append('('+rowNums+')');");
            scriptFunction.Append("$(this).children(0).children(0).trigger('onclick');");
            scriptFunction.Append("});");
            scriptFunction.Append("});");
            scriptFunction.Append("</script>");
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "GroupBy", 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("Event");
                    myDataTable.Columns.Add("ItemType");
                    myDataTable.Columns.Add("DocLocation");
                    myDataTable.Columns.Add("Occurred", typeof(DateTime));
                    myDataTable.Columns.Add("UserName");

                    foreach (SPAuditEntry entry in auditCol)
                    {
                        if (entry.DocLocation.EndsWith(".xls") || (entry.DocLocation.EndsWith(".doc")) || (entry.DocLocation.EndsWith(".ppt")))
                        {
                            user = myWeb.SiteUsers.GetByID(entry.UserId);
                            myRow = myDataTable.NewRow();
                            myRow["Event"] = entry.Event;
                            myRow["ItemType"] = entry.ItemType.ToString();
                            myRow["DocLocation"] = entry.DocLocation;
                            myRow["Occurred"] = entry.Occurred.ToLocalTime();
                            myRow["UserName"] = 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);
        }
    }
}

Use the above code or try to deploy the DownloadCounter.wsp
Note: 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 http://code.jquery.com/jquery-1.4.2.min.js 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’t want to change the code.

After deploying the downloaded solution, please try to activate Download Counter Feature see figure 3

Figure 3 - Activate Download Counter Feature

Figure 3 - Activate Download Counter Feature

Then add the webpart to the page see figure 4

Figure 4 - Adding Download Counter WebPart to SharePoint Site

Figure 4 - Adding Download Counter WebPart to SharePoint Site

Then you can view the webpart updating on every action of documents see figure 5

Figure 5 - Download counter webPart shows the count of events for the documents

Figure 5 - Download counter webPart shows the count of events for the documents

Understanding SharePoint Delegate Control

8 December, 2010 (15:25) | SharePoint 2010 - Object Model | By: G Vijai Kumar

In this article I’m going to explain about delegate control, before we jump start into the technical talk we will understand first what is the meaning of Delegates

As I believe most of us we know that in general delegates are also called as ambassadors, diplomats, representatives etc.

A delegate having high ranks has most importance for example ranks like 1, 2, 3. Rank1 delegate officer has most significant role than rank2 delegate officer.

There can be so many delegate officers or ambassadors serving for Country X for example: A delegate officer may look after the relations between Country X and Country A, another delegate ambassador may look after the relations between Country X and Country B, even some times the delegate officers have to visit to the Country A or Country B depending upon the call.

Now we will speak real technical vocabulary of delegates, SharePoint has a couple of delegate controls like

AdditionalPageHead
GlobalSiteLink0
GlobalSiteLink1
GlobalSiteLink2
PublishingConsole
QuickLaunchDataSource
SmallSearchInputBox
TopNavigationDataSource

Apart from the above controls, we can also create our own custom delegate controls

The XML schema for delegate control is below:

<?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
 <Control Id="SmallSearchInputBox" Sequence="100" Url="/templates/mysearchcontrol.ascx"/>
</Elements>

In the above schema you can view the properties for the delegate control as Control Id, Sequence and URL. We identify the delegate controls based on Control Id, Sequence number. The Sequence number defines the rank of the delegate, URL describes the source location of the control.

As we discussed already above that “Delegates having high ranks has most importance” in the same way delegate control who’s Sequence id is less has most significant role in SharePoint site and will render on the site as first preference.

Also we have discussed that “some times the delegate officers have to visit to the Country A or Country B depending upon the call” in the same way if we have custom delegate control deployed on site and activated, the least Sequence control will load on site depending upon the user action.

What is the use of delegate control?
Using the delegate control a developer can customize the SharePoint site controls without editing or even touching the master page.
Note: We are not customizing the existing (default) delegate control but we are creating our own control loading onto the SharePoint site.

Let’s suppose assume one scenario, if we want to customize the SharePoint search box (by default SharePoint 2010 site has got input search box with one textbox and one button beside) see figure 1

Figure 1 - SharePoint 2010 Default Search Box

Figure 1 - SharePoint 2010 Default Search Box

Now I will try to customize the default search box, the requirement is to display the search box with scope drop down list, and also customizing the search button image with a arrow image button.

First open Visual Studio 2010 and click New > Project see figure 2

Figure 2 - Creating New Visual Studio 2010 Project

Figure 2 - Creating New Visual Studio 2010 Project

After project got created, I have deleted the not in use file (you can keep it there won’t be any problem if you don’t delete) because of maintaing clean solution I have removed user control, webpart related files see figure 3

Figure 3 - Solution Explorer File Structure

Figure 3 - Solution Explorer File Structure

Then add the following code in Elements.xml file

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/" >
  <!--<Module Name="VisualWebPart1" List="113" Url="_catalogs/wp">
    <File Path="VisualWebPart1\VisualWebPart1.webpart" Url="CustomDelegateControl_VisualWebPart1.webpart" Type="GhostableInLibrary" >
      <Property Name="Group" Value="Custom" />
    </File>
  </Module>-->
  <Control
	 Id="SmallSearchInputBox"
	 Sequence="23"
	 ControlClass="Microsoft.SharePoint.Portal.WebControls.SearchBoxEx"
	 ControlAssembly="Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">
    <Property Name="QueryPromptString">This control is customized.....</Property>
    <Property Name="SearchBoxTableClass">search-box</Property>
    <Property Name="GoImageUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrl">/_layouts/images/goviewfiles.png</Property>
    <Property Name="GoImageActiveUrlRTL">/_layouts/images/goviewfiles.png</Property>
    <Property Name="UseSiteDefaults">true</Property>
    <Property Name="FrameType">None</Property>
  </Control>
</Elements>

In the Element.xml file I have commented the Module section see figure 4

Figure 4 - Custom Delegate Control Element.xml file

Figure 4 - Custom Delegate Control Element.xml file

Now we are almost done, try to build, deploy and activate the feature which will result in change of SharePoint default search box with your customized control on fly without modifying the master page see figure 5

Figure 5 - SharePoint 2010 Custom Search Input Box

Figure 5 - SharePoint 2010 Custom Search Input Box

Most Common Custom WebParts Part 4 – Flash Media WebPart

28 November, 2010 (21:33) | MOSS - Object Model, Sharepoint 2010, SharePoint 2010 - Object Model | By: G Vijai Kumar

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 files on Sharepoint sites, the webpart also supports to configure the properties as required.

Download the solution file FlashWebPart.wsp

Flash Media Player WebPart

Flash Media Player WebPart

Flash Media Player WebPart Configuration

Flash Media Player WebPart Configuration

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 = @"~/_CONTROLTEMPLATES/FlashWebPart/Flash/FlashWebPartUserControl.ascx";

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

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

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

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

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

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription("Loop Play Back: (True/False) Repeats the video automatically"),
        Category("Flash Media Properties"),
        WebDisplayName("Loop Play Back")]
        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) && !string.IsNullOrEmpty(FlashWidth) && !string.IsNullOrEmpty(FlashHeight))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        site = new SPSite(web.Site.ID);

                        using (site)
                        {
                            #region Script
                            writer.Write("<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='" + FlashWidth + "' height='" + FlashWidth + "'>");
                            writer.Write("<param name='movie' value='" + FlashFilePath + "'>");
                            writer.Write("<param name='bgcolor' value='" + BGColor + "'>");
                            writer.Write("<param name='loop' value='" + LoopPlayBack + "'>");
                            writer.Write("<EMBED src='" + FlashFilePath + "' quality='high' bgcolor='#FFFFFF' width='" + FlashWidth + "' height='" + FlashHeight + "' loop='" + LoopPlayBack + "' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'>");
                            writer.Write("</EMBED>");
                            writer.Write("</OBJECT>");
                            #endregion
                        }
                    });
                }
                catch (Exception ex)
                {
                    writer.Write(ex.Message);
                }
            }
            else
            {
                writer.Write("<span class='ms-formvalidation'>");
                writer.Write("Please configure the <B>Media WebPart</B> properties in webpart properties section");
                writer.Write("</span>");
            }
        }
    }
}

Most Common Custom WebParts Part 3 – Windows OR YouTube Media Player WebPart

28 November, 2010 (10:35) | MOSS - Object Model, SharePoint 2010 - Object Model | By: G Vijai Kumar

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 Windows Or Youtube Media Player webpart which plays video on Sharepoint sites, the webpart also supports to configure the properties as required.

In the webpart properties section please enter the Windows media or Youtube link, the webpart automatically detects the media type and plays accordingly

Download the solution file WindowsORYouTubeMediaWebPart.wsp

Windows Or YouTube Player WebPart (Playing Windows media Video)

Windows Or YouTube Player WebPart (Playing Windows media Video)

Windows Or YouTube Player WebPart (Playing Youtube Video)

Windows Or YouTube Player WebPart (Playing Youtube Video)


Windows Or YouTube Player WebPart Properties

Windows Or YouTube Player WebPart Properties

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 = @"~/_CONTROLTEMPLATES/WindowsMediaWebPart/MediaWebPart/MediaWebPartUserControl.ascx";


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

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

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

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


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


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

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

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

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

        [WebBrowsable(true),
        Personalizable(PersonalizationScope.User),
        WebDescription("Sets the border of the media (applicable for youtube videos)"),
        Category("Media Properties"),
        WebDisplayName("Allow Full Screen")]
        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) && !string.IsNullOrEmpty(VideoWidth) && !string.IsNullOrEmpty(VideoHeight))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        site = new SPSite(web.Site.ID);

                        using (site)
                        {
                            if ((videoFilePath.ToLower()).Contains("youtube.com/"))
                            {
                                Uri youtubeUri = new Uri(videoFilePath);
                                string query = youtubeUri.Query;
                                string mediaID = HttpUtility.ParseQueryString(query).Get("v");
                                string source = "http://www.youtube.com/embed/" + mediaID;
                                writer.Write("<iframe width='" + VideoWidth + "' height='" + VideoHeight + "' src='" + source + "' frameborder='" + FrameBorder + "' allowfullscreen></iframe>");                                
                            }
                            else
                            {
                                
                                writer.Write("<OBJECT id='mediaPlayer' width='" + VideoWidth + "' height='" + VideoHeight + "' 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'>");
                                writer.Write("<param name='fileName' value='" + VideoFilePath + "'>");
                                writer.Write("<param name='animationatStart' value='" + AnimationAtStart + "'>");
                                writer.Write("<param name='transparentatStart' value='" + TransparentAtStart + "'>");
                                writer.Write("<param name='autoStart' value='" + AutoStart + "'>");
                                writer.Write("<param name='showControls' value='" + ShowControls + "'>");
                                writer.Write("<param name='loop' value='" + LoopPlayBack + "'>");
                                writer.Write("<EMBED type='application/x-mplayer2'pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'id='windowsmediaPlayer' name='windowsmediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='" + ShowControls + "' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='" + VideoWidth + "' height='" + VideoHeight + "' src='" + VideoFilePath + "' autostart='" + AutoStart + "' designtimesp='5311' loop='" + LoopPlayBack + "'></EMBED>");
                                writer.Write("</OBJECT>");
                                
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    writer.Write(ex.Message);
                }
            }
            else
            {
                writer.Write("<span class='ms-formvalidation'>");
                writer.Write("Please configure the <B>Media WebPart</B> properties in webpart properties section");
                writer.Write("</span>");
            }
        }
    }
}