Friday 15 October 2010

Creating an interactive Sharepoint 2010 Web Part with Visual Studio 2010 using forms and web services.

A web part is one of the most common controls you can add, in a Sharepoint distribution. They have been always there but it has been always difficult to develop anything reliable for previous versions (2003/2007). On Sharepoint 2010 Microsoft decided to do something about it, and try to make the life easier for the software developers. as a result we can count with a very nice environment to program and DEPLOY , Visual Studio 2010.

Of course you have plenty of out-of-the-box web parts, or just by going to Codeplex you will be able to find tons, but you never knows what your organization is going to need.

Because of this I have decided to create a sophisticated web part, that gets the weather from a web service and post it into a textbox. This web part includes events, so we will be able how to interact with events and web parts.

The easiest way to create a from is by using our new classes coming from System.Web.UI.WebControls,
I am going to list all of them so you know what you can do after this tutorial:


1- Create an Empty Sharepoint project, select where you want to debug your project and select "deploy as farm solution". Type the name WeatherWebpart as name of the project.

2- Go to your project Right-Click add new Item and select "Web part" (DO NOT CLICK ON VISUAL WEB PART).

AccessDataSource
AccessDataSourceView
AdCreatedEventArgs
AdRotator
AssociatedControlConverter
AuthenticateEventArgs
AutoGeneratedField
AutoGeneratedFieldProperties
BaseCompareValidator
BaseDataBoundControl
BaseDataList
BaseValidator
BoundColumn
BoundField
BulletedList
BulletedListEventArgs
Button
ButtonColumn
ButtonField
ButtonFieldBase
Calendar
CalendarDay
ChangePassword
CheckBox
CheckBoxField
CheckBoxList
CircleHotSpot
CommandEventArgs
CommandField
CompareValidator
CompleteWizardStep
CompositeControl
CompositeDataBoundControl
Content
ContentPlaceHolder
ContextDataSource
ContextDataSourceContextData
ContextDataSourceView
ControlIDConverter
ControlParameter
ControlPropertyNameConverter
CookieParameter
CreateUserErrorEventArgs
CreateUserWizard
CreateUserWizardStep
CustomValidator
DataBoundControl
DataControlCommands
DataControlField
DataControlFieldCell
DataControlFieldCollection
DataControlFieldHeaderCell
DataGrid
DataGridColumn
DataGridColumnCollection
DataGridCommandEventArgs
DataGridItem
DataGridItemCollection
DataGridItemEventArgs
DataGridPageChangedEventArgs
DataGridPagerStyle
DataGridSortCommandEventArgs
DataKey
DataKeyArray
DataKeyCollection
DataList
DataListCommandEventArgs
DataListItem
DataListItemCollection
DataListItemEventArgs
DataPager
DataPagerCommandEventArgs
DataPagerField
DataPagerFieldCollection
DataPagerFieldCommandEventArgs
DataPagerFieldItem
DayRenderEventArgs
DetailsView
DetailsViewCommandEventArgs
DetailsViewDeletedEventArgs
DetailsViewDeleteEventArgs
DetailsViewInsertedEventArgs
DetailsViewInsertEventArgs
DetailsViewModeEventArgs
DetailsViewPageEventArgs
DetailsViewPagerRow
DetailsViewRow
DetailsViewRowCollection
DetailsViewUpdatedEventArgs
DetailsViewUpdateEventArgs
DropDownList
EditCommandColumn
EmbeddedMailObject
EmbeddedMailObjectsCollection
EntityDataSource
EntityDataSourceChangedEventArgs
EntityDataSourceChangingEventArgs
EntityDataSourceContextCreatedEventArgs
EntityDataSourceContextCreatingEventArgs
EntityDataSourceContextDisposingEventArgs
EntityDataSourceSelectedEventArgs
EntityDataSourceSelectingEventArgs
EntityDataSourceValidationException
EntityDataSourceView
FileUpload
FontInfo
FontNamesConverter
FontUnitConverter
FormParameter
FormView
FormViewCommandEventArgs
FormViewDeletedEventArgs
FormViewDeleteEventArgs
FormViewInsertedEventArgs
FormViewInsertEventArgs
FormViewModeEventArgs
FormViewPageEventArgs
FormViewPagerRow
FormViewRow
FormViewUpdatedEventArgs
FormViewUpdateEventArgs
GridView
GridViewCancelEditEventArgs
GridViewCommandEventArgs
GridViewDeletedEventArgs
GridViewDeleteEventArgs
GridViewEditEventArgs
GridViewPageEventArgs
GridViewRow
GridViewRowCollection
GridViewRowEventArgs
GridViewSelectEventArgs
GridViewSortEventArgs
GridViewUpdatedEventArgs
GridViewUpdateEventArgs
HiddenField
HierarchicalDataBoundControl
HotSpot
HotSpotCollection
HyperLink
HyperLinkColumn
HyperLinkControlBuilder
HyperLinkField
Image
ImageButton
ImageField
ImageMap
ImageMapEventArgs
Label
LabelControlBuilder
LinkButton
LinkButtonControlBuilder
LinqDataSource
LinqDataSourceContextEventArgs
LinqDataSourceDeleteEventArgs
LinqDataSourceDisposeEventArgs
LinqDataSourceInsertEventArgs
LinqDataSourceSelectEventArgs
LinqDataSourceStatusEventArgs
LinqDataSourceUpdateEventArgs
LinqDataSourceValidationException
LinqDataSourceView
ListBox
ListControl
ListItem
ListItemCollection
ListItemControlBuilder
ListView
ListViewCancelEventArgs
ListViewCommandEventArgs
ListViewDataItem
ListViewDeletedEventArgs
ListViewDeleteEventArgs
ListViewEditEventArgs
ListViewInsertedEventArgs
ListViewInsertEventArgs
ListViewItem
ListViewItemEventArgs
ListViewPagedDataSource
ListViewSelectEventArgs
ListViewSortEventArgs
ListViewUpdatedEventArgs
ListViewUpdateEventArgs
Literal
LiteralControlBuilder
Localize
Login
LoginCancelEventArgs
LoginName
LoginStatus
LoginView
MailDefinition
MailMessageEventArgs
Menu
MenuEventArgs
MenuItem
MenuItemBinding
MenuItemBindingCollection
MenuItemCollection
MenuItemStyle
MenuItemStyleCollection
MenuItemTemplateContainer
MonthChangedEventArgs
MultiView
MultiViewControlBuilder
NextPreviousPagerField
NumericPagerField
ObjectDataSource
ObjectDataSourceDisposingEventArgs
ObjectDataSourceEventArgs
ObjectDataSourceFilteringEventArgs
ObjectDataSourceMethodEventArgs
ObjectDataSourceSelectingEventArgs
ObjectDataSourceStatusEventArgs
ObjectDataSourceView
PagedDataSource
PageEventArgs
PagePropertiesChangingEventArgs
PagerSettings
Panel
PanelStyle
Parameter
ParameterCollection
PasswordRecovery
PlaceHolder
PlaceHolderControlBuilder
PolygonHotSpot
ProfileParameter
QueryableDataSource
QueryableDataSourceEditData
QueryableDataSourceView
QueryContext
QueryCreatedEventArgs
QueryExtender
QueryStringParameter
RadioButton
RadioButtonList
RangeValidator
RectangleHotSpot
RegularExpressionValidator
Repeater
RepeaterCommandEventArgs
RepeaterItem
RepeaterItemCollection
RepeaterItemEventArgs
RepeatInfo
RequiredFieldValidator
RoleGroup
RoleGroupCollection
RouteParameter
SelectedDatesCollection
SendMailErrorEventArgs
ServerValidateEventArgs
SessionParameter
SiteMapDataSource
SiteMapDataSourceView
SiteMapHierarchicalDataSourceView
SiteMapNodeItem
SiteMapNodeItemEventArgs
SiteMapPath
SqlDataSource
SqlDataSourceCommandEventArgs
SqlDataSourceFilteringEventArgs
SqlDataSourceSelectingEventArgs
SqlDataSourceStatusEventArgs
SqlDataSourceView
StringArrayConverter
Style
StyleCollection
SubMenuStyle
SubMenuStyleCollection
Substitution
Table
Table.RowControlCollection
TableCell
TableCellCollection
TableCellControlBuilder
TableFooterRow
TableHeaderCell
TableHeaderRow
TableItemStyle
TableRow
TableRow.CellControlCollection
TableRowCollection
TableSectionStyle
TableStyle
TargetConverter
TemplateColumn
TemplatedWizardStep
TemplateField
TemplatePagerField
TextBox
TextBoxControlBuilder
TreeNode
TreeNodeBinding
TreeNodeBindingCollection
TreeNodeCollection
TreeNodeEventArgs
TreeNodeStyle
TreeNodeStyleCollection
TreeView
UnitConverter
ValidatedControlConverter
ValidationSummary
View
ViewCollection
WebColorConverter
WebControl
Wizard
WizardNavigationEventArgs
WizardStep
WizardStepBase
WizardStepCollection
WizardStepControlBuilder
Xml
XmlBuilder
XmlDataSource
XmlDataSourceView
XmlHierarchicalDataSourceView


3- Call this new Web part "GlobalWeatherWebPart".

4- Go to your project, right-click, add service reference->advanced->Add web Reference... (on the bottom) and paste this address: http://ws.cdyne.com/WeatherWS/Weather.asmx?wsdl

5- Call the wen reference WSWeather.

6- On the project menu, right click .

7- On "GlobalWeatherWebPart.cs" copy and paste the following code and deploy it, now you can go to your web->Site Actions->New Page->Insert Ribbon->Web Part->Categories->Custom->Select "GlobalWeatherWebPart"->Add->Format Text->Save and Close:

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;

using Microsoft.SharePoint.Utilities;

 

namespace WeatherWebpart.GlobalWeatherWebPart

{

[ToolboxItemAttribute(false)]

public class GlobalWeatherWebPart : WebPart

{

//## We declare these variables global in order

//## to be able to capture the text

TextBox _txtCountryName = null;

TextBox _txtZipCode = null;

TextBox _txtForecast = null;

Button _cmdSendForecast = null;

 

 

public GlobalWeatherWebPart()

{

}

 

protected override void CreateChildControls()

{

base.CreateChildControls();

 

//## Table

Table _tWeatherTable = null;

TableRow _trRow = null;

TableCell _tcCell = null;

 

//## Controls

Label _lblTitle = null;

Label _lblCountry = null;

Label _lblCity = null;

Label _lblForecast = null;

 

try

{

//## Creating the table...

_tWeatherTable = new Table();

 

//################################################################

//## Creating the columns ## And Rows

//################################################################

 

//## 1 ROW

_trRow = new TableRow();

_tcCell = new TableCell();

_tcCell.ColumnSpan = 2;

_tcCell.VerticalAlign = VerticalAlign.Top;

_lblTitle = new Label();

_lblTitle.Text = "Real-Time Forecast Checker";

_lblTitle.Font.Bold = true;

_lblTitle.Font.Size = 14;

_tcCell.Controls.Add(_lblTitle);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

//## 2 ROW COUNTRY ##

//-- [LABEL PART] --

_trRow = new TableRow();

_tcCell = new TableCell();

_tcCell.Style["padding-top"] = "7px";

_tcCell.VerticalAlign = VerticalAlign.Top;

_lblCountry = new Label();

_lblCountry.Text = "Name of the country:";

_tcCell.Controls.Add(_lblCountry);

_trRow.Controls.Add(_tcCell);

 

//## 2 ROW COUNTRY ##

//-- [TEXTBOX PART] --

_tcCell = new TableCell();

_tcCell.VerticalAlign = VerticalAlign.Top;

_txtCountryName = new TextBox();

_txtCountryName.ID = "_txtCountryName";

_txtCountryName.Width = Unit.Pixel(200);

_tcCell.Controls.Add(_txtCountryName);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

 

//## 3 ROW CITY ##

//-- [LABEL PART] --

_trRow = new TableRow();

_tcCell = new TableCell();

_tcCell.Style["padding-top"] = "7px";

_tcCell.VerticalAlign = VerticalAlign.Top;

_lblCity = new Label();

_lblCity.Text = "Name of the city:";

_tcCell.Controls.Add(_lblCity);

_trRow.Controls.Add(_tcCell);

 

//## 3 ROW CITY ##

//-- [TEXTBOX PART] --

_tcCell = new TableCell();

_tcCell.VerticalAlign = VerticalAlign.Top;

_txtZipCode = new TextBox();

_txtZipCode.ID = "_txtZipCode";

_txtZipCode.Width = Unit.Pixel(200);

_tcCell.Controls.Add(_txtZipCode);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

 

//## 4 ROW FORECAST Label ##

_trRow = new TableRow();

_tcCell = new TableCell();

_tcCell.ColumnSpan = 2;

_tcCell.VerticalAlign = VerticalAlign.Top;

_lblForecast = new Label();

_lblForecast.Text = "Forecast:";

_tcCell.Controls.Add(_lblForecast);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

 

//## 5 ROW FORECAST TEXTBOX ##

//-- [TEXTBOX PART] --

_trRow = new TableRow();

_tcCell = new TableCell();

_tcCell.ColumnSpan = 2;

_tcCell.VerticalAlign = VerticalAlign.Top;

_txtForecast = new TextBox();

_txtForecast.ID = "_txtForecast";

_txtForecast.Height = Unit.Pixel(100);

_txtForecast.Width = Unit.Pixel(200);

_txtForecast.TextMode = TextBoxMode.MultiLine;

_txtForecast.Wrap = true;

_txtForecast.Enabled = false;

_tcCell.Controls.Add(_txtForecast);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

 

//## 6 ROW Empty

_trRow = new TableRow();

_tcCell = new TableCell();

_trRow.Controls.Add(_tcCell);

 

//## 7 ROW Nice Submit button

_trRow = new TableRow();

_tcCell = new TableCell();

_cmdSendForecast = new Button();

_cmdSendForecast.Text = "Check weather forecast";

_cmdSendForecast.Width = 200;

_cmdSendForecast.Height = 30;

_cmdSendForecast.Click += new EventHandler(_cmdSendForecast_Click);

_tcCell.Controls.Add(_cmdSendForecast);

_trRow.Controls.Add(_tcCell);

_tWeatherTable.Controls.Add(_trRow);

 

this.Controls.Add(_tWeatherTable);

}

catch

{

LiteralControl Literal = new LiteralControl("<H5>Error uploading the webpart, please contact with your administrator</H5>");

}

}

 

void _cmdSendForecast_Click(object sender, EventArgs e)

{

WSWeather.Weather WS = new WSWeather.Weather();

WS.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

WSWeather.ForecastReturn ReturnWeather = WS.GetCityForecastByZIP(_txtZipCode.Text);

 

_txtForecast.Text = "";

_txtForecast.Text += ReturnWeather.City + "\r\n";

_txtForecast.Text += ReturnWeather.State + "\r\n";

_txtForecast.Text += ReturnWeather.WeatherStationCity + "\r\n";

_txtForecast.Text += ReturnWeather.ResponseText + "\r\n";

 

foreach (WSWeather.Forecast item in ReturnWeather.ForecastResult)

{

_txtForecast.Text += item.Date + "\r\n";

_txtForecast.Text += item.Desciption + "\r\n";

_txtForecast.Text += item.ProbabilityOfPrecipiation + "\r\n";

_txtForecast.Text += item.Temperatures + "\r\n";

}

 

_txtForecast.Enabled = true;

}

}

}

 

 


Conclusion
Visual Studio will allow you to create anything with Web Parts but be aware you have what we call "Visual Web Parts", where you can design the forms in a ASP.NET way... in 5 minutes...

No comments: