Showing posts with label Controls. Show all posts
Showing posts with label Controls. Show all posts

Saturday, August 8, 2009

WSS Custom Layouts

Scenario:
In most of my implemenation there was always some need to create extra site pages other than default.aspx. Requirement is to have another page on root level and deciding the number of zones and their layout can be time consuming.

Solution:
SharePoint does give you options to create web part pages as shown below. So these out of box layouts are good options to choose a layout from.
layouts

So after a simple File System search I was able to find out these sample layouts @

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\1033\STS\DOCTEMP\SMARTPGS
Simple make a copy of the one which is closest to your requirement and use it.

SharePoint is all about discovering.

Wednesday, July 29, 2009

Reading values from People picker control

Scenario:
Reading values from People picker control

Solution:
Here's I am posted sample code, Sorry for hardcoding the item id and other values.Please make changes according to requirement.

Single User/Group selection:


using(SPSite site = new SPSite("http://localhost"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Tasks"];
SPListItem item = list.GetItemById(1);

SPFieldUserValue userValue = new SPFieldUserValue(web, item["AssignedTo"].ToString());
Console.WriteLine(userValue.User.Email);

}
}
Multi User/Group selection:
using(SPSite site = new SPSite("http://localhost"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Tasks"];
SPListItem item = list.GetItemById(1);

SPFieldUserValueCollection userValue = new SPFieldUserValueCollection(web, item["AssignedTo"].ToString());
Console.WriteLine(userValue[0].User.Email);
}
}

Sunday, July 19, 2009

Locking webparts in webpart zone

Scenario:
We wanted to lock some of company wide Web parts in some of web part zones so they cannot be deleted or modified by another one for consistency purpose.

Solution:
WebPartZone supports a property LockLayout.Setting it to true did the trick.

This property basically controls whether or not Web Parts within the zone can be added, deleted, resized, or moved. The LockLayout property works the same regardless of whether the Web Part Page is in personal or shared view.

Sample Declaration:

 <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Left" Title="loc:Left" AllowCustomization="false"   AllowLayoutChange="false" AllowPersonalization="false" LayoutOrientation="Vertical" LockLayout="true"  />
 locked

How does it work:
If set to True, the specific Web Part properties for each Web Part in the zone that are affected are: Zone (ZoneID), Part Order (PartOrder), Visible on Page (IsVisible), Height (Height), Width (Width), Allow Close (AllowRemove), and IsIncluded (the Close command on the Web Part menu). Other Web Part properties are not affected.

If set to False, the Web Part properties determine whether modifications can be made (along with the appropriate site permissions).

Sunday, June 14, 2009

XmlUrlDataSource sharepoint answer to XML based data

Scenario:
I was trying to bind one RSS feed to my grid and so started investigating and found another great control

Solution:
You can create a XMLUrlDataSource instance and bind it to grid.

Example:

 var source = new XmlUrlDataSource()
{
HttpMethod = "GET",
EnableCaching = true,
ErrorCacheDuration = 300,
CacheDuration = 0x1c20,
AuthType = "None",
SelectCommand = "http://feeds.feedburner.com/sandeepnahta",
XPath = ""
};



Follow me on Twitter

SPDataSource another powerful sharepoint control

Scenario:
I think I mentioned about this one in my previous blogs but I binged and couldn't find anything. So thought of writing about it.

We have seen many powerful controls of sharepoint and one of them is SPDataSource

I am sure you heard about SqlDataSource data source control which represents data in an SQL relational database to data-bound controls. You can use the SqlDataSource control in conjunction with a data-bound control to retrieve data from a relational database and to display, edit, and sort data on a Web page with little or no code.

On the same lines , SPDataSource data source control represents Windows SharePoint Services data to data-bound controls. You can use the control in conjunction with a data-bound control to retrieve data from lists, list items, and Web sites and to display, edit, and modify data with little or no code.

-- Like other data source controls,SPDataSource can also be used in UI and Code behind.
-- Unlike other data source controls, the SPDataSource control is associated with only one view. The GetViewNames method always returns a collection that contains the name of just one data view.

Example:
Here's a quick view to get datasource instance from Announcement List

Code:

  var datasource = new SPDataSource
{
DataSourceMode = SPDataSourceMode.List,
List = SPContext.Current.Web.Lists["Announcements"]
};
Article:
MSDN SPDataSource , SPDataSource every sharepoint developer friend 1 , SPDataSource every sharepoint developer friend 2 , SPdatasource-every-developer-friend , spdatasource-mystery-modes-webs-listoflists , Another very good example


Follow me on Twitter

Friday, May 15, 2009

SqlDataSource is not allowed on this page

Scenario:
One of my friend was working on a new Application page and used SQLDataSource. It works fine when you access the page in ASP.Net Context but when it was moved to SharePoint context , he got the following error

Error : SqlDataSource is not allowed on this page

Solution:
Short and simple , use code behind for all the custom pages, sharepoint doesn't allow code block ( ie. Eval and Bind functions ) for security reasons. Mostly SQLDataSource control uses lot of inline code blocks.

Its not like that you can never have a page with inline code, but its not recommended. You can use SQLDataSource control , if all the binding's are done in code-behind and not in ASPX itself.

Also one more observation, if you really made the page with inline code work somehow, as soon as that page is touched by Designer for any reason, you are back to square with the same message. So dont try too hard on using inline code.

Why microsoft made it so hard ?
Because sometime server security is more important that Developer's comfort.

:-)

Monday, April 13, 2009

Recursively reading file title

Scenario:
Some one asked me how to recursively read file titles from all the subfolders.

Solution:
Here's a recursive way to get. Not the very best as you can use CAML query to get the same information. But for treeview below code will work.

Code:

SPWeb web= SPContext.Current.Web; 
SPList list = web.Lists["List_Name"];

foreach(SPFolder rootfolder in list.Folders)
ReadFilesfromFolder(rootfolder);
Code:
public void ReadFilesfromFolder(SPFolder folder)
{
foreach (SPFile file in folder.Files)
{
Console.WriteLine("File Title: " + file.Title) ;
foreach (SPFolder subfolder in folder.SubFolders)
ReadFilesfromFolder(subfolder);
}
}
Article:
http://blog.krichie.com/2007/01/30/traversing-sharepoint-list-folder-hierarchies/

Monday, March 30, 2009

Using ListView by Query in webpart

Scenario:
I wanted to display information into grid using a CAML query

Solution:
Share Point has a ListViewByQuery Control which can help.

Code:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace Training
{
public class myWebPart: System.Web.UI.WebControls.WebParts.WebPart
{
public override void RenderControl(HtmlTextWriter writer)
{
ListViewByQuery view = new ListViewByQuery();

SPWeb currentweb = SPContext.Current.Web;
SPList list = currentweb.Lists["Shared Documents"];
view.List = list;
SPQuery query = new SPQuery(view.List.DefaultView);
query.ViewFields = "<FieldRef Name='Title'/>";
query.Query = "<Where><Contains><FieldRef Name='Subject'/><Value Type='Text'>Sample</Value></Contains></Where>";
view.Query = query;
EnsureChildControls();
view.RenderControl(writer);
RenderChildren(writer);
}
}
}
Article:

Thursday, March 5, 2009

Using SPSecurityTrimmedControl in code behind

Scenario:
I was suppose to write a webpart that display edit panel only if the user has certian permissions.

Solution:
I used SPSecurityTrimmedControl in my code behind

Code:

public void override CreateChildcontrols(){
SPSecurityTrimmedControl stcEdit= new SPSecurityTrimmedControl();
stcEdit.Permissions = SPBasePermissions.EditListItems;

Panel pnlEdit = new Panel();
stcEdit.Controls.Add(pnlEdit);
this.Controls.Add(stcEditItem);
}

Monday, February 16, 2009

Site Column with RichText support

Scenario:
I was suppose to write a site Column with RichText with HTML support.

Solution:
Field tag exposes RichText and RichTextMode properties.

Code:

  <Field ID="{GUIDwithBraces}"
Name="Details"
SourceID="http://schemas.microsoft.com/sharepoint/v3"
StaticName="Details"
Type="Note"
RichText="TRUE"
RichTextMode="FullHtml"
IsolateStyles="TRUE"
DisplayName="Details"
Sortable="FALSE"
NumLines="15" />

Friday, February 13, 2009

Site Column with Radio Button choices

Scenario:
Creating a new site column with Radio button choices

Solution:
Declare a field tag with Type="Choice" and then using Format option u can display it as radio button.

Code:

<Field Type="Choice" DisplayName="Gender" 
Required="FALSE" Format="RadioButtons"
FillInChoice="FALSE"
ID="{8e153ed9-7960-409d-9a5c-7c3ccf204c5b}"
StaticName="Gender"
Name="Gender">
<Default>male</Default>
<CHOICES>
<CHOICE>male</CHOICE>
<CHOICE>female</CHOICE>
</CHOICES>
</Field>

Wednesday, January 28, 2009

The folder may be located in an unavailable location, protected with a password, or the filename contain illegal characters

Scenario:
You got the following error while trying to access the sharepoint site using SharePoint Designer.

Error : The folder 'http://localhost' isn't accessible. The folder may be located in an unavailable location, protected with a password, or the filename contains a / or \.

Solution:
This can be because of many reasons, lets see

1. There is no such site or folder ?
2. This location is unaccessible because you are using FORM Authentication ? You need to extend the web application on another port to connect to SPD.
3. Url contains illegal characters ?
4. Url contains file names i.e. default.aspx

Got one for from comments :-)

Another thing to check in Central Administration > Application Management > Authentication Providers
Make sure "Enable Client Integration" is set to "Yes".

Fix any of the above issues, close the SPD fully and open again..access the site you should be able to get to it.

Wednesday, January 7, 2009

Using SPLinkButton ( link with context information)

Scenario:
I wanted to have a link in my master page relative to the site.

Solution:
Sharepoint already have solution out of box. SPLinkButton control understand expression token ( ~site , ~sitecollection ) and was very handy.
Code:

<SharePoint:SPLinkbutton id=idAdminLink Text="View All Site Content" NavigateUrl="~sitecollection/_layouts/viewlsts.aspx" runat="server" CssClass="ms-descriptiontext" />


Happy programming :-)

Monday, December 22, 2008

Using SPSecurityTrimmedControl to show a section depending upon user permission

Scenario:
If you are writing a master page or a content page, you might have a requirement to display a section depending upon the user permissions.

Solution:
SPSecurityTrimmedControl is your best friend.

Code:

<SharePoint:SPSecurityTrimmedControl PermissionsString="AddAndCustomizePages, ManageLists" runat="server">
You can see me because you have Manage List and Customize Pages permission
</SharePoint:SPSecurityTrimmedControl>
Article:
Other posssible permission strings

Thursday, September 18, 2008

Using the SPGridView in custom code

ApplicationPage.aspx


<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Assembly Name="CustomApplicationPages, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=d4e5777b16a5749f" %>

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master"
Inherits="CustomApplicationPages.ApplicationPage" EnableViewState="false" EnableViewStateMac="false" %>

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

<asp:Content ID="Main" contentplaceholderid="PlaceHolderMain" runat="server">

<SharePoint:SPGridView runat="server"
ID="grid"
AutoGenerateColumns="false"
RowStyle-BackColor="#DDDDDD"
AlternatingRowStyle-BackColor="#EEEEEE" />
</asp:Content>

<asp:Content ID="PageTitle" contentplaceholderid="PlaceHolderPageTitle" runat="server">SharePoint GridView</asp:Content>

<asp:Content ID="PageTitleInTitleArea" contentplaceholderid="PlaceHolderPageTitleInTitleArea" runat="server">
Application Page : Using the SPGridView control
</asp:Content>
ApplicationPage.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomApplicationPages {

public class ApplicationPage : LayoutsPageBase {

// add control fields to match controls tags on .aspx page
protected SPGridView grid;

protected override void OnLoad(EventArgs e) {

grid = new SPGridView();
grid.AutoGenerateColumns = false ;
grid.CssClass = "ms-listviewtable";
grid.AlternatingRowStyle.CssClass = "ms-alternating";
grid.Width = new Unit(50, UnitType.Percentage);
grid.GridLines = GridLines.None;
grid.HeaderStyle.Font.Bold = true;
grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

DataTable table = new DataTable();
//TO DO : Populate the DataTable here <-----

SPBoundField col= new SPBoundField();
col.HeaderText = "Product Name";
col.DataField = "ProductName";

grid.Columns.Add(col);
Controls.Add(grid);

grid.DataSource = table.DefaultView;
grid.DataBind();

}
}
}

Wednesday, September 17, 2008

Using ListView control in custom code

SPListView.aspx

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" 
Inherits="SPListView, ListView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=566105bsandeepbe" %>

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

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<sharepoint:ListView ID="SPListView" runat="server" />
</asp:Content>


SPListView.cs
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class SPListView : LayoutsPageBase
{
protected ListView SPListView;

protected void Page_Load(object sender, EventArgs e)
{
SPListView.ListId = Request.QueryString["ListId"];
}
}

Using ListViewByQuery control in your custom code

Code:

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" 
Inherits="SPListViewPage, ListView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=566105b43a7965be" %>

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

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<sharepoint:ListViewByQuery ID="SPListViewByQuery" runat="server" />
</asp:Content>

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class SPListViewPage : LayoutsPageBase
{
protected ListViewByQuery SPListViewByQuery;

protected void Page_Load(object sender, EventArgs e)
{
SPList list = this.Web.Lists["Contacts"];
SPView view = list.Views["All contacts"];
SPQuery query = new SPQuery(view);
query.ViewFields = "<FieldRef Name='LinkTitle'/>" +
"<FieldRef Name='FirstName'/>" +
"<FieldRef Name='Company'/>" +
"<FieldRef Name='WorkCity'/>";
query.Query = "<Where>" +
"<Eq>" +
"<FieldRef Name='Company' />" +
"<Value Type='Text'>Sandeep Training Company</Value>" +
"</Eq>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='LinkTitle' />" +
"</OrderBy>";
SPListViewByQuery.List = list;
SPListViewByQuery.Query = query;
}
}

Wednesday, August 6, 2008

Using relative Url ( $SPUrl )

Scenario:
You need to reference a file ( image , css or javascript file ) stored in one of the local Library using a relative Url

Option:
You can refer to the file like this "/LibraryName/filename.extension" . This works fine only when you are working with the site collection at root level. The browser doesn't know or care about site collections, and interprets the path as being relative to the website.

In this case, in a site collection at "/sites/NewSiteCollection" this path will still resolve to
http://servername/LibraryName/filename.extension
and not
http://servername/sites/NewSiteCollection/LibraryName/filename.extension

Solution:
Use $SPUrl token as shown below

<% $SPUrl:~SiteCollection/LibraryName/filename.extension %>
<% $SPUrl:~Site/LibraryName/filename.extension %>
Another important thing to note is that you can only use this with controls having runat="server" , otherwise sharepoint will not be able to resolve the $SPUrl token.

Applies to:
MOSS only ( out of box ) ,
For WSS you need to write your own Expression Builder and register it in WebConfig

:-)