Adding a ListView to a custom Web Part
The ListView Class (Microsoft.SharePoint.WebControls) renders a list by using a specified view.
[code:c#]
ListView listView;
protected override void CreateChildControls()
{
listView = new ListView();
SPList list = SPContext.Current.Web.Lists["MyListName"];
listView.ListId = list.ID.ToString();
listView.ViewId = list.DefaultView.ID.ToString();
Controls.Add(listView);
}
protected override void Render(HtmlTextWriter writer)
{
listView.RenderControl(writer);
}
[/code]
RSS Web Part on Publishing Page
During trying to add a standard RSS Web Part on my publishing page I came accross some issues.
1) The RSS WebPart was not visible in the WebPart gallery. This could be solved by enabling the Office Server Enterprise Site Collection Features (if you have an Enterprise license).
2) After adding a RSS-Url in the Web Part properties I got the next error:
3) The SharePoint Log says: "RssWebPart: Exception handed to HandleRuntimeException.HandleException System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable host". Since I use this WebPart on a server containing a Proxy, I modified the web.config.
<system.net>
<defaultProxy>
<proxy autoDetect="true" proxyaddress="http://YOURPROXYSERVER" bypassonlocal="true" />
</defaultProxy>
</system.net>
[/code]
4) After modifying the web.config I got the next error (this looks like trial on error).
The SharePoint log says: "RssWebPart: Exception handed to HandleRuntimeException.HandleException System.Net.WebException: The remote server returned an error: (400) Bad Request. at Microsoft.SharePoint.WebControls.BaseXmlDataSource.GetXmlDocument() at Microsoft.SharePoint.WebPartPages.DataFormWebPart.GetHierarchicalDocument(IHierarchicalDataSource ds) at Microsoft.SharePoint.WebPartPages.DataFormWebPart.GetHierarchicalXPathNavigator(IHierarchicalDataSource ds) at Microsoft.SharePoint.WebControls.SingleDataSource.GetXPathNavigatorInternal() at Microsoft.SharePoint.WebControls.SingleDataSource.GetXPathNavigator() at Microsoft.SharePoint.WebControls.SingleDataSource.GetXPathNavigator(IDataSource datasource, Boolean originalData) at Microsoft.SharePoint.WebPartPages.DataFormWebPart.GetXPathN..."
One of the scenarios when "400 Bad Request" is returned is if the value of the content-length header is smaller then the actual length of the message body.
Note: After adding a Page Viewer Web Part and setting the url to the RSS url I get the xml back...
5) After changing the proxy "again" in the web.config it works fine
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy usesystemdefault="false" proxyaddress="http://yourserver:yourport" bypassonlocal="false" />
</defaultProxy>
</system.net>
6) The result:
Using SharePoint Designer for adding the Data Form Web Part
The Data Form Web Part (in SharePoint 2003 called the Data View Web Part) is probably the most used functionality in SharePoint Designer. Using the Data Form Web Part, you are able to use multiple data sources, including data coming from external data sources. This functionality is added without programming
1. Open your Site in SharePoint Designer 2007 and open a Web Part Page where you want to insert the Data Form Web Part.
2. Insert Data View from the Data View menu in SharePoint Designer.
3. The Data Form Web Part is added to the page.
4. The next step is selecting a datasource for creating a Data View. You can use an excisting Data View or create a new one.
5. Select a datasource and select show data from the dropdown.
6. The Data Source Details panel containing the fields is opened. You can choose the fields you want to show from here. In the dropdown you can choose how you want to insert your selected fields. I choose Single Item View.
7. The data will be shown in the Data Form Web Part.
8. Note: Take a look at the inserted source code (XSL).
Best way to discover the power of this Web Part is play around with the options and some configurations of this Web Part.
You can read more about this topic on the Microsoft Office Site.
FREE World Clock and Weather Web Part
Bamboo Solutions offer a free World Clock & Weather WebPart. This WebPart allows users to display local time and weather for selected major cities around the globe.
Google Maps in Content Editor WebPart
You can use Google Maps on your website by registering for an API Key on the Google Maps API Site. After getting the API key you can use Google Maps by inserting a Javascript to you site. The problem is that most code examples use the <body onload> Javascript. By using the "Body Onload" event it is not possible to make Google Maps working using the Content Editor WebPart. After changing the javascript a little bit it is possible to simply past the Javascript in the SharePoint Content Editor WebPart. In this case you can use Google Maps in a few minutes. Note that the next code is not only useful for SharePoint but also for example BlogEngine.NET. Using this script needs no modifications in a masterpage
<script src="http://maps.google.com/maps?file=api&v=1&key=YOURKEY" type="text/javascript"></script>
<div id="map" style="width: 400px;height:300px"></div>
<script type="text/javascript">
var map = new GMap(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng( 51.03275840574761, 5.81451416015625), 9);
map.setMapType(G_NORMAL_MAP);
// You can use your favourite Map properties (like markers)
</script>
[/code]
Sample output:
Google Maps
Creating a Publishing page from code
In some cases it could be necessary to create a page from code. Because
the publishing page is the hardest way to create from code (checkin /
approval) the next code example will help you completing this job.
Notice that I skipped complete error handling.
/// <summary>
/// Create a Publishing page based on an excisting Page Layout
/// Remember that a SPSite is a top-level site (collection) and
/// a SPWeb is the current site
/// </summary>
/// <param name="site">Current Site</param>
/// <param name="pageName">Name of the new page to create including .aspx</param>
/// <param name="pageLayoutName">Name of the Page Layout</param>
private void CreatePublishingPage(SPWeb site, string pageName, string pageLayoutName)
{
PublishingSite pubSiteCollection = new PublishingSite(site.Site);
PublishingWeb pubSite = null;
if (pubSiteCollection != null)
{
// Assign an object to the pubSite variable
if (PublishingWeb.IsPublishingWeb(site))
{
pubSite = PublishingWeb.GetPublishingWeb(site);
}
}
// Search for the page layout for creating the new page
PageLayout currentPageLayout = FindPageLayout(pubSiteCollection, pageLayoutName);
// Check or the Page Layout could be found in the collection
// if not (== null, return because the page has to be based on
// an excisting Page Layout
if (currentPageLayout == null)
{
return;
}
PublishingPageCollection pages = pubSite.GetPublishingPages();
PublishingPage newPage = pages.Add(pageName, currentPageLayout);
newPage.Description = pageName.Replace(".aspx", "");
// Here you can set some properties like:
newPage.IncludeInCurrentNavigation = true;
newPage.IncludeInGlobalNavigation = true;
// End of setting properties
SPFile publishFile = newPage.ListItem.File;
publishFile.Update();
newPage.Update();
// Check the file in (a major version)
publishFile.CheckIn("Initial", SPCheckinType.MajorCheckIn);
publishFile.Publish("Initial");
// In case of content approval, approve the file
if (pubSite.PagesList.EnableModeration)
{
publishFile.Approve("Initial");
}
}
/// <summary>
/// Find a page layout in the layoutcollection based on the templatename
/// </summary>
/// <param name="pubSiteCollection">The toplevel publishing site</param>
/// <param name="templateName">Name of the pagelayout</param>
/// <returns>Pagelayout if excists or null</returns>
private PageLayout FindPageLayout(PublishingSite pubSiteCollection, string templateName)
{
PageLayoutCollection plCollection = pubSiteCollection.GetPageLayouts(true);
foreach (Microsoft.SharePoint.Publishing.PageLayout layout in plCollection)
{
// String Comparison based on the Page Layout Name
if (layout.Name.Equals(templateName, StringComparison.InvariantCultureIgnoreCase))
{
return layout;
}
}
return null;
}
[/code]
Adding a List - ListFields and Items from code
Often it is required to insert a list, listitem and listitems from code. An
example is creating a list if it not exists from a Feature or WebPart. By
creating a list we out of the box get the Title field. The next code shows the
process of creating a custom list, columns and items from code. It also shows
how you can change to out-of-the-box Title column.
// Option 1) Inside SharePoint
SPSite siteCollection = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
// Option 2) From an external tool
SPSite siteCollection = new SPSite("http://myurl");
SPWeb site = siteCollection.RootWeb;
// Get a ListCollection from the current site
SPListCollection lists = site.Lists;
// Add a custom List to the SharePoint site
lists.Add("Employee", "List containing employees", SPListTemplateType.GenericList);
// Put the new list in a variable
SPList employeeList = lists["Employee"];
// Get the out of the box fields (Title, Attachment etc)
SPFieldCollection fields = employeeList.Fields;
// Change the default title column
SPField field = fields["Title"];
field.Title = "Name";
// Don't forget the update to commit changes
field.Update();
// Add a new field
SPField fieldAdd = fields[fields.Add("Address", SPFieldType.Text, true)];
SPView view = employeeList.DefaultView;
SPViewFieldCollection viewFields = view.ViewFields;
// Add the field to the defaultview (all items)
viewFields.Add(fieldAdd);
view.Update();
// Add a record to the new list
SPListItem item = employeeList.Items.Add();
item["Name"] = "Name of the Employee";
item["Address"] = "Address of the employee";
item.Update();
[/code]
SPGridView and SPMenuField
Paul Robinson (alias Powlo) wrote a nice post about the SPGridView and SPMenuField. The Paging described in this post didn't work for me. If anyone got the paging work using SPGridView, please contact me. The next lines describe the using of the SPGridView and SPMenuField. Even a custom link for editing the item (e.g. you wrote a custom web part page for data input to the list).
private SPGridView grid;
private SPList dataList;
private DataTable dt;
private void PopulateDataList()
{
dataList = SPContext.Current.Web.Lists["MyList"];
dt = new DataTable();
DataColumn dc = new DataColumn("MyDataColumn");
dt.Columns.Add(dc);
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
foreach (SPItem item in dataList.Items)
{
DataRow dr = dt.NewRow();
if (item[Column1"] != null)
dr["Column1"] = item["Column1"].ToString();
else
dr["Column1"] = "";
if (item["Column2"] != null)
dr["Column2"] = item["Column2"].ToString();
else
dr["Column2"] = "";
dt.Rows.Add(dr);
}
}
private void CreateGrid()
{
try
{
SPMenuField colMenu = new SPMenuField();
colMenu.HeaderText = "MyList";
colMenu.TextFields = "MyList";
colMenu.MenuTemplateId = "ItemListMenu";
colMenu.NavigateUrlFields = "ID";
colMenu.NavigateUrlFormat = Context.Request.Url.ToString() + "?ItemID={0}";
colMenu.TokenNameAndValueFields = "EDIT=ID";
colMenu.SortExpression = "MyList";
MenuTemplate itemListMenu = new MenuTemplate();
itemListMenu.ID = "ItemListMenu";
MenuItemTemplate menu = new MenuItemTemplate(
"Edit Item", "/_layouts/images/EDIT.gif");
menu.ClientOnClickNavigateUrl = "do.aspx?this=%EDIT%&that=%NAME%";
itemListMenu.Controls.Add(menu);
this.Controls.Add(itemListMenu);
grid.Columns.Add(colMenu);
BoundField boundField1 = new BoundField();
colWorkflowStatus.DataField = "Column1";
colWorkflowStatus.HeaderText = "Column1";
this.grid.Columns.Add(boundField1 );
BoundField boundField1 = new BoundField();
colRequestType.DataField = "Column2";
colRequestType.HeaderText = "Column2";
this.grid.Columns.Add(boundField1);
}
catch (Exception ex)
{
// handle exception
}
}
private void RenderGrid(HtmlTextWriter writer)
{
try
{
grid.RenderControl(writer);
}
catch (Exception ex)
{
// handle exception
}
}
protected override void CreateChildControls()
{
PopulateDataList();
this.grid = new SPGridView();
this.grid.DataSource = dt;
this.grid.AutoGenerateColumns = false;
//Create the SP Gridview containing items
CreateGrid();
this.Controls.Add(grid);
this.grid.DataBind();
}
protected override void Render(HtmlTextWriter writer)
{
try
{
RenderGrid(writer);
}
catch (Exception ex)
{
// handle exception
}
}
}
}
[/code]
Unable to add selected Web Part - Incompatible Web Part markup detected
During developing a custom toolpart using WSS extensions for Visual Studio 2005
I got the following error by adding my webpart to the webpart page:
"Incompatible Web Part markup detected. Use *.dwp web part XML instead of
*.webpart web part xml". By overriding the GetToolParts() method we have to
derive or Web Part class from the Microsoft.SharePoint.WebPartPages.WebPart
class. A Web Part derived from this class expects a .dwp file. But the
solutionpackage (.wsp) created by the WSS Extensions creates a .webpart-file. We
can simply solve this error by making a custom .dwp file:
<?xml version="1.0"?>
<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
<Assembly>AssemblyName(with no .dll extension),
Version=VersionNumber, Culture=Culture,
PublicKeyToken=PublicKeyToken</Assembly>
<TypeName>WebPartNamespace.WebPartClassName</TypeName>
<Title>DefaultWebPartTitle</Title>
<Description>WebPartDescription</Description>
</WebPart>
Delete your .webpart file from you Feature directory in the 12-hyve and place here your new .dwp file. Go to Site Settings --> Web Parts (= Web Part Gallery) and delete your Web Part (which currently reffers to a .webpart file). Upload your new .dwp file. Now you can add your Web Part to your Web Part page!
Loading UserControls (.ASCX) in a Web Part
One of the things we are missing is the ability to Visual Design WebParts in Visual Studio. We can load a UserControl into a WebPart by calling the Page.LoadControl method. It's a best practice to make a directory in your virtual directory called usercontrols and place the UserControls in it to load it from a WebPart. Note that this is the key concept of the SharePoint SmartPart.
[code:c#]
private UserControl usercontrol;
private Button button;
private TextBox textbox;
private Label label;
public UserControlWebPart()
{
}
protected override void CreateChildControls()
{
try
{
usercontrol = (UserControl)Page.LoadControl(@"/_controltemplates/usercontrols/MyUserControl.ascx");
this.Controls.Add(usercontrol);
if (usercontrol != null)
{
button = (Button)usercontrol.FindControl("Button1");
button.Click += new EventHandler(button_Click);
label = (Label)usercontrol.FindControl("Label1");
textbox = (TextBox)usercontrol.FindControl("TextBox1");
}
}
catch (Exception ex)
{
EventLog.WriteEntry("WebParts", "Custom WebPart" + ex.ToString());
}
}
void button_Click(object sender, EventArgs e)
{
label.Text = textbox.Text;
}