Friday, March 30, 2012

How to set SharePoint 2010 web part chrome type to None programmatically

Sometimes you want to set the chrome type to none at the time of adding web parts to web part pages. Normally to set the chrome type to none, you will go to edit web parts and in the properties window you select the chrome type to none.


When you develop a custom web part in visual studio 2010, you can set this chrome type to none. So that the title will not appear at the time of web part adding.

To do this, open the .webpart file of relevant visual webpart, and set the following property under properties tag.

<property name="ChromeType" type="chrometype">None</property>

The complete .webpart file look like this.


 <?xml version="1.0" encoding="utf-8"?>

<webParts>

<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">

<metaData>

<type name="Gadgets.Weather.Weather, $SharePoint.Project.AssemblyFullName$" />

<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>

</metaData>

<data>

<properties>

<property name="Title" type="string">Weather</property>

<property name="Description" type="string">My Visual WebPart</property>

<property name="ChromeType" type="chrometype">None</property>

</properties>

</data>

</webPart>

</webParts>

Wednesday, March 14, 2012

Create a News Web Part with multiple news sources

In this section I am describing how to create a custom News Web part in SharePoint t 2010. Creating an Rss Viewer webpart is easy; it is an out of the box web part. But in RSS Viewer webpart you can give only one RSS Feed URL, you can’t give multiple Rss Feed urls.

This document is about creating a webpart with multiple Rss Feed sources. I’m using Rss feeds from various news source. For Ex: the Rss feed url for CNN is http://rss.cnn.com/rss/edition.rss.
Rss file is a xml type document where you can find tags , , , etc… Inside you can find title, description, pubDate, etc…


Following are the steps to create News web part:

1. Create an Empty sharepoint project, name it as ‘News’. Don’t forget to select .Net frame work 3.5.

2. Create a Class call Item.cs inside the project ‘News’, where you can hold Rss feeds metadata.
 public class Item

{

public string Link { get; set; }

public string Title { get; set; }

public string Content { get; set; }

public DateTime PublishDate { get; set; }

public Item()

{

Link = "";

Title = "";

Content = "";

PublishDate = DateTime.Today;

}

}


3. Next create a Class call FeedParser.cs.
The rss feed url is a xml based document. You need to parse the xml to get the required data.
Inside the class I have created a method call ‘ParseRss’ , which takes rss url as a parameter. This method goes through the rss document and gets the required data.
 public virtual IList<Item> ParseRss(string url)

{

try

{

System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

webRequest.Proxy = WebProxy.GetDefaultProxy();

webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

webRequest.Credentials = CredentialCache.DefaultCredentials;

using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())

{

using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))

{

XDocument doc = XDocument.Load(new System.IO.StringReader(sr.ReadToEnd()));

// RSS/Channel/item

var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")

select new Item

{

Content = item.Elements().First(i => i.Name.LocalName == "description").Value,

Link = item.Elements().First(i => i.Name.LocalName == "link").Value,

PublishDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "pubDate").Value),

Title = item.Elements().First(i => i.Name.LocalName == "title").Value

};

return entries.ToList();

}

}

}

catch

{

return new List<Item>();

}

}


The following lines of codes added to get the default proxy and the credentials.
 webRequest.Proxy = WebProxy.GetDefaultProxy();

webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

webRequest.Credentials = CredentialCache.DefaultCredentials;


Otherwise it throws ‘The remote server returned an error: (407) Proxy Authentication Required.’ Exception.
The method returns an ‘Item’ object, where you are holding rss metadata.

4. Now create a visual webpart, name it as NewsWebpart.
As I mentioned earlier, I’m going to enable multiple Rss Feed sources, the user can select whatever the news source they required. The news source is going to be a custom property; it will appear in the Edit web part properties box.

To add the custom property, open the NewsWebpart.cs file. Add the following property in side class declaration.


 [ToolboxItemAttribute(false)]

public class NewsWebpart : WebPart

{

[Personalizable(), WebBrowsable, Category("News Feed"), DefaultValue(NewsSources.AdaDerana)]

public NewsSources NewsSource { get; set; }


NewsSources is an enum type of news sources, it will display as a drop down in edit webpart properties window.

 public enum NewsSources

{

BBC,

CNN,

AdaDerana,

LankaNewsPapers

}



Modify the CreateChildControls method as follows.
 protected override void CreateChildControls()

{

//Control control = Page.LoadControl(_ascxPath);

//Controls.Add(control);

NewsWebpartUserControl control = Page.LoadControl(_ascxPath) as NewsWebpartUserControl;

if (control!=null)

{

control.Webpart = this;

}

Controls.Add(control);

}


5. Now open ‘NewsWebpartUserControl.ascx’ file in design mode, add an Asp Gridview control to display the news items.
 <asp:GridView ID="grdFeeds" runat="server" AutoGenerateColumns="False" GridLines="Vertical"

AllowPaging="True" Width="250px"

onpageindexchanging="grdFeeds_PageIndexChanging">

<AlternatingRowStyle BackColor="#EEEEEE" />

<Columns>

<asp:HyperLinkField HeaderText="News" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Medium" HeaderStyle-Font-Names="Calibri"

DataNavigateUrlFields="Link" DataNavigateUrlFormatString="{0}"

DataTextField="Title" Target="_blank" HeaderStyle-ForeColor="Gray">

<HeaderStyle Height="0px"></HeaderStyle>

</asp:HyperLinkField>

</Columns>

<RowStyle Font-Bold="True" Font-Names="Calibri" Height="45px"

BackColor="#DDDDDD" />

</asp:GridView>


I have set the pagination, so that you need to add PageIndexChanging event for the grid.

6. Next open ‘NewsWebpartUserControl.ascx.cs’ file. Create a variable of ‘NewsWebpart type as follows.
 public NewsWebpart Webpart { get; set; }

At the OnPreRender method you can get the values entered in edit webpart properties window and load the grid according to that.

 protected override void OnPreRender(EventArgs e)

{

base.OnPreRender(e);

FeedParser parser = new FeedParser();

System.Collections.Generic.IList<Item> items=null;

NewsSources news = this.Webpart.NewsSource;

switch (news)

{

case NewsSources.BBC:

items = parser.ParseRss("http://feeds.bbci.co.uk/news/world/asia/rss.xml");

break;

case NewsSources.AdaDerana:

items = parser.ParseRss("http://www.adaderana.lk/rss.php");

break;

case NewsSources.CNN:

items = parser.ParseRss("http://rss.cnn.com/rss/edition.rss");

break;

case NewsSources.LankaNewsPapers:

items = parser.ParseRss("http://www.lankanewspapers.com/news/rss.xml");

break;

default:

break;

}

grdFeeds.DataSource = items;

grdFeeds.DataBind();

}


This is the PageIndexChanging event.
 protected void grdFeeds_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

grdFeeds.PageIndex = e.NewPageIndex;

grdFeeds.DataBind();

}


7. You are done with development part. The solution explorer as follows:



You can deploy the solution. Once you deployed create a page call News in SharePoint site, go to edit page mode, in the Insert tab of the ribbon select Web Part. Find the NewsWebpart in Custom Category and click Add.

At the right side of the webpart you will find the Edit Web part link, select it. This will open the web part properties window.


Here you can find a category News Feed, there you have a dropdown to select the news source. Select a news source and click Apply, the news webpart is loading according to the selected newssource item.

Finally you will get the News webpart as this:




Following is the complete source code:

1. Item.cs

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace News

{

public class Item

{

public string Link { get; set; }

public string Title { get; set; }

public string Content { get; set; }

public DateTime PublishDate { get; set; }

public Item()

{

Link = "";

Title = "";

Content = "";

PublishDate = DateTime.Today;

}

}

}



2. FeedParser.cs
 using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Linq;

using System.Net;

namespace News

{

public class FeedParser

{

public virtual IList<Item> ParseRss(string url)

{

try

{

System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

webRequest.Proxy = WebProxy.GetDefaultProxy();

webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

webRequest.Credentials = CredentialCache.DefaultCredentials;

using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())

{

using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))

{

XDocument doc = XDocument.Load(new System.IO.StringReader(sr.ReadToEnd()));

// RSS/Channel/item

var entries = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")

select new Item

{

Content = item.Elements().First(i => i.Name.LocalName == "description").Value,

Link = item.Elements().First(i => i.Name.LocalName == "link").Value,

PublishDate = ParseDate(item.Elements().First(i => i.Name.LocalName == "pubDate").Value),

Title = item.Elements().First(i => i.Name.LocalName == "title").Value

};

return entries.ToList();

}

}

}

catch

{

return new List<Item>();

}

}

private DateTime ParseDate(string date)

{

DateTime result;

if (DateTime.TryParse(date, out result))

return result;

else

return DateTime.MinValue;

}

}

}



3. NewsWebpart.cs


 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 News.NewsWebpart

{

[ToolboxItemAttribute(false)]

public class NewsWebpart : WebPart

{

// Visual Studio might automatically update this path when you change the Visual Web Part project item.

private const string _ascxPath = @"~/_CONTROLTEMPLATES/News/NewsWebpart/NewsWebpartUserControl.ascx";

[Personalizable(), WebBrowsable, Category("News Feed"), DefaultValue(NewsSources.AdaDerana)]

public NewsSources NewsSource { get; set; }

protected override void CreateChildControls()

{

//Control control = Page.LoadControl(_ascxPath);

//Controls.Add(control);

NewsWebpartUserControl control = Page.LoadControl(_ascxPath) as NewsWebpartUserControl;

if (control!=null)

{

control.Webpart = this;

}

Controls.Add(control);

}

}

public enum NewsSources

{

BBC,

CNN,

AdaDerana,

LankaNewsPapers

}

}



4. NewsWebpartUserControl.ascx
 <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>

<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<%@ Import Namespace="Microsoft.SharePoint" %>

<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="NewsWebpartUserControl.ascx.cs" Inherits="News.NewsWebpart.NewsWebpartUserControl" %>

<div>

<asp:GridView ID="grdFeeds" runat="server" AutoGenerateColumns="False" GridLines="Vertical"

AllowPaging="True" Width="250px"

onpageindexchanging="grdFeeds_PageIndexChanging">

<AlternatingRowStyle BackColor="#EEEEEE" />

<Columns>

<asp:HyperLinkField HeaderText="News" HeaderStyle-HorizontalAlign="Left" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Medium" HeaderStyle-Font-Names="Calibri"

DataNavigateUrlFields="Link" DataNavigateUrlFormatString="{0}"

DataTextField="Title" Target="_blank" HeaderStyle-ForeColor="Gray">

<HeaderStyle Height="0px"></HeaderStyle>

</asp:HyperLinkField>

</Columns>

<RowStyle Font-Bold="True" Font-Names="Calibri" Height="45px"

BackColor="#DDDDDD" />

</asp:GridView>

</div>




5. NewsWebpartUserControl.ascx.cs



 using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

namespace News.NewsWebpart

{

public partial class NewsWebpartUserControl : UserControl

{

public NewsWebpart Webpart { get; set; }

protected void Page_Load(object sender, EventArgs e)

{

}

protected void grdFeeds_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

grdFeeds.PageIndex = e.NewPageIndex;

grdFeeds.DataBind();

}

protected override void OnPreRender(EventArgs e)

{

base.OnPreRender(e);

FeedParser parser = new FeedParser();

System.Collections.Generic.IList<Item> items=null;

NewsSources news = this.Webpart.NewsSource;

switch (news)

{

case NewsSources.BBC:

items = parser.ParseRss("http://feeds.bbci.co.uk/news/world/asia/rss.xml");

break;

case NewsSources.AdaDerana:

items = parser.ParseRss("http://www.adaderana.lk/rss.php");

break;

case NewsSources.CNN:

items = parser.ParseRss("http://rss.cnn.com/rss/edition.rss");

break;

case NewsSources.LankaNewsPapers:

items = parser.ParseRss("http://www.lankanewspapers.com/news/rss.xml");

break;

default:

break;

}

grdFeeds.DataSource = items;

grdFeeds.DataBind();

//lblHeading.Text = news.ToString() + " News";

}

}

}

Monday, March 12, 2012

MCTS: Microsoft SharePoint 2010, Application Development

I completed MCTS: Sharepoint 2010, Application Development Exam - 70-573 on 11th March 2012

Friday, January 6, 2012

Use Web services to access Sharepoint List Items

The SharePoint client object model can be used in .NET, Silverlight application and ECMAScript. But the client object model cannot be used if you are working on earlier version of .NET framework or any other technologies, such as java or PHP. SharePoint offers some set of SOAP services that can be used by these applications.

These services are built using mainly the Web Services engine of ASP.NET, and are based on a set of .asmx files. They are published under the /_vti_bin/ virtual directory of every web site that maps the SharePoint14_Root\ISAPI folder.

Here I’m explaining how to use web services to access SharePoint list items in a c# console application.

Create new C# console application and name it as ‘TestSOAP’. To use these services, you need to define a reference to them, using their Web Services Definition Language (WSDL). To add this, right click on references in solution explorer and select ‘Add Services Reference..’



Add the URL of the service. I have created a site collection call ‘mcts’ and my services URL is ‘http://sharepoint-pc:3395/sites/mcts/_vti_bin/lists.asmx’. Click the Go button to see available services.

Click on Advanced button.



Click Add Web Reference button.



Enter the service URL and browse, add a name to the service reference and click Add Reference. I have put the name as ‘TestWebService’.

You have added the service reference to your project. The solution explorer will look like this.



I have created a SharePoint list call ‘Project Details’ in ‘http://sharepoint-pc:3395/sites/mcts’. Our job is access the data in Project Details list through web service. The Project Details list as this:



Following is the code to access the list items. You have to add following references:

using TestSoap.TestWebService;

using System.Xml.Linq;

using System.Xml;

string targetListName = "Project Details";

string baseUrl = "http://sharepoint-pc:3395/sites/mcts/_vti_bin/";

Lists wsLists = new Lists();

wsLists.Url = baseUrl + "Lists.asmx";

wsLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

XElement listMetadata=XElement.Load(new XmlNodeReader(wsLists.GetList(targetListName)));

Guid targetListId = new Guid(listMetadata.Attribute("ID").Value);

XmlNode listItemsXmlNode = wsLists.GetListItems(

targetListId.ToString(), // ID of the target list

String.Empty, // ID of the view or String.Empty for default view

null, // CAML query or null

null, // ViewFields or null

"200", // RowLimit as a string

null, // Query options

null // ID of the web site or null for root website

);

XElement listItemsXml = XElement.Load(new XmlNodeReader(listItemsXmlNode));

var xmlItems = from x in listItemsXml.Descendants("{#RowsetSchema}row")

select x;

foreach (XElement xmlItem in xmlItems)

{

Console.WriteLine("{0} - {1} - {2}",

xmlItem.Attribute("ows_ID").Value,

xmlItem.Attribute("ows_Title").Value, xmlItem.Attribute("ows_Sponsor").Value);

//Console.WriteLine(xmlItem.Attribute("ows_Sponsor").Value);

}

Console.ReadLine();

Your output as follows: