Sunday, May 31, 2009

RSS Aggregator webpart using DataView webpart

Scenario:
RSS Aggregator web part


Points( +/- ):

+ Full XSLT support
+ Data caching support

- Need to edit every time you want to add a new RSS url
- Untested for maximum limit

RSSAggregator.webpart:

<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="Microsoft.SharePoint.WebPartPages.DataFormWebPart, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name="DataSourcesString" type="string">
&lt;%@ Register TagPrefix="sharepoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %&gt;&lt;sharepoint:AggregateDataSource runat="server" SeparateRoot="" RootName="" RowsName="" ID="merged1"&gt;&lt;Sources&gt;
&lt;sharepoint:XmlUrlDataSource runat="server" HttpMethod="GET" SelectCommand="http://feeds.feedburner.com/sandeepnahta" AuthType="None" XPath=""&gt;&lt;/sharepoint:XmlUrlDataSource&gt;
&lt;sharepoint:XmlUrlDataSource runat="server" HttpMethod="GET" SelectCommand="http://codename-srini.blogspot.com/feeds/posts/default?alt=rss" AuthType="None" XPath=""&gt;&lt;/sharepoint:XmlUrlDataSource&gt;
&lt;/Sources&gt;
&lt;Aggregate&gt;
&lt;concat name="data source"&gt;&lt;datasource name="sandeepnahta" id="0" Type="SPXml"/&gt;&lt;datasource name="default" id="1" Type="SPXml"/&gt;&lt;/concat&gt;&lt;/Aggregate&gt;
&lt;/sharepoint:AggregateDataSource&gt;
</property>
<property name="ParameterBindings" type="string">
&lt;ParameterBinding Name="dvt_apos" Location="Postback;Connection"/&gt;
&lt;ParameterBinding Name="UserID" Location="CAMLVariable" DefaultValue="CurrentUserName"/&gt;
&lt;ParameterBinding Name="Today" Location="CAMLVariable" DefaultValue="CurrentDate"/&gt;
</property>
<property name="Xsl" type="string">
&lt;xsl:stylesheet xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:agg="http://schemas.microsoft.com/sharepoint/aggregatesource" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:atom10="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" xmlns:media="http://search.yahoo.com/mrss/" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal"&gt;
&lt;xsl:output method="html" indent="no"/&gt;
&lt;xsl:decimal-format NaN=""/&gt;
&lt;xsl:param name="dvt_apos"&gt;'&lt;/xsl:param&gt;
&lt;xsl:variable name="dvt_1_automode"&gt;0&lt;/xsl:variable&gt;
&lt;xsl:template match="/"&gt;
&lt;xsl:call-template name="dvt_1"/&gt;
&lt;/xsl:template&gt;
&lt;xsl:template name="dvt_1"&gt;
&lt;xsl:variable name="dvt_StyleName"&gt;Table&lt;/xsl:variable&gt;
&lt;xsl:variable name="Rows" select="/dsQueryResponse/rss/channel"/&gt;
&lt;table border="0" width="100%" cellpadding="2" cellspacing="0"&gt;
&lt;tr valign="top"&gt;
&lt;xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1"&gt;
&lt;th class="ms-vh" width="1%" nowrap="nowrap"&gt;&lt;/th&gt;
&lt;/xsl:if&gt;

&lt;/tr&gt;
&lt;xsl:call-template name="dvt_1.body"&gt;
&lt;xsl:with-param name="Rows" select="$Rows"/&gt;
&lt;/xsl:call-template&gt;
&lt;/table&gt;
&lt;/xsl:template&gt;
&lt;xsl:template name="dvt_1.body"&gt;
&lt;xsl:param name="Rows"/&gt;
&lt;xsl:for-each select="$Rows"&gt;

&lt;xsl:call-template name="dvt_1.rowview"/&gt;

&lt;/xsl:for-each&gt;
&lt;/xsl:template&gt;
&lt;xsl:template name="dvt_1.rowview"&gt;

&lt;tr&gt;

&lt;xsl:if test="position() mod 2 = 1"&gt;
&lt;xsl:attribute name="class"&gt;ms-alternating&lt;/xsl:attribute&gt;
&lt;/xsl:if&gt;
&lt;xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1"&gt;
&lt;td class="ms-vb" width="1%" nowrap="nowrap"&gt;
&lt;span ddwrt:amkeyfield="" ddwrt:amkeyvalue="string($XPath)" ddwrt:ammode="view"&gt;&lt;/span&gt;
&lt;/td&gt;
&lt;/xsl:if&gt;
&lt;td class="ms-vb"&gt;
&lt;strong&gt;&lt;xsl:value-of select="title" /&gt;&lt;/strong&gt;
&lt;xsl:call-template name="dvt_2" /&gt;
&lt;/td&gt;
&lt;/tr&gt;

&lt;/xsl:template&gt;
&lt;xsl:variable name="dvt_2_automode"&gt;0&lt;/xsl:variable&gt;
&lt;xsl:template name="dvt_2"&gt;
&lt;xsl:variable name="dvt_StyleName"&gt;RepForm3&lt;/xsl:variable&gt;
&lt;xsl:variable name="Rows" select="item" /&gt;
&lt;table border="0" width="100%"&gt;
&lt;xsl:call-template name="dvt_2.body"&gt;
&lt;xsl:with-param name="Rows" select="$Rows" /&gt;
&lt;/xsl:call-template&gt;
&lt;/table&gt;
&lt;/xsl:template&gt;
&lt;xsl:template name="dvt_2.body"&gt;
&lt;xsl:param name="Rows" /&gt;
&lt;xsl:for-each select="$Rows"&gt;
&lt;xsl:call-template name="dvt_2.rowview" /&gt;
&lt;/xsl:for-each&gt;
&lt;/xsl:template&gt;
&lt;xsl:template name="dvt_2.rowview"&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;table border="0" cellspacing="0" width="100%"&gt;
&lt;tr&gt;
&lt;td width="2%" class="ms-vb"&gt;
&lt;img alt="rect" src="http://spvm/_layouts/images/rect.gif" /&gt;
&lt;/td&gt;
&lt;td width="95%" class="ms-vb"&gt;
&lt;a href="{link}"&gt;&lt;xsl:value-of select="title" /&gt;&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;xsl:if test="$dvt_2_automode = '1'" ddwrt:cf_ignore="1"&gt;
&lt;tr&gt;
&lt;td colspan="99" class="ms-vb"&gt;
&lt;span ddwrt:amkeyfield="" ddwrt:amkeyvalue="string($XPath)" ddwrt:ammode="view"&gt;&lt;/span&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/xsl:if&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
</property>

<property name="DataFields" type="string">atom:id;lastBuildDate;title;description;link;managingEditor;generator;openSearch:totalResults;openSearch:startIndex;openSearch:itemsPerPage;atom10:link/@rel,atom10:link/rel;atom10:link/@href,atom10:link/href;atom10:link/@type,atom10:link/type;</property>
<property name="Title" type="string">RSS Aggregator</property>
</properties>
</data>
</webPart>
</webParts>
DataSource section in above it
This is the section need to be modified to add more RSS Urls. Below you can see i have used two RSS Urls, replace them with the ones you need.
 <property name="DataSourcesString" type="string" >  
<%@ Register TagPrefix="sharepoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><sharepoint:AggregateDataSource runat="server" SeparateRoot="" RootName="" RowsName="" ID="merged1"><Sources>
<sharepoint:XmlUrlDataSource runat="server" HttpMethod="GET" SelectCommand="http://feeds.feedburner.com/sandeepnahta" AuthType="None" XPath=""></sharepoint:XmlUrlDataSource>
<sharepoint:XmlUrlDataSource runat="server" HttpMethod="GET" SelectCommand="http://codename-srini.blogspot.com/feeds/posts/default?alt=rss" AuthType="None" XPath=""></sharepoint:XmlUrlDataSource>
</Sources>
<Aggregate>
<concat name="data source"><datasource name="sandeepnahta" id="0" Type="SPXml"/><datasource name="default" id="1" Type="SPXml"/></concat></Aggregate>
</sharepoint:AggregateDataSource>
</property >

Tip for creating master page using sharepoint designer

Scenario:
I haven't explored Sharepoint Designer that much in past, in-spite of the fact that its offers great webparts and editing functionality. On top of it , its free now. So while working on a new master page using SPD , I discovered 2 new things.

Tip 1:
SPD offers special toolbar for Master page for easy management

-- SPD > View Menu > Toolbars > Master Page

now its very easy to find any Content Placeholder

Tip 2:
Also another option SPD offers is to list all the Content Placeholders

-- SPD > Format > Master Page > Manage Content Region

RSS Viewer webpart

Scenario:
RSS Viewer webpart for WSS

Code:

using System;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

namespace TrainingSKN
{
public class RSSWebpart : System.Web.UI.WebControls.WebParts.WebPart
{
Table table;

private string rssUrl;
[Personalizable(true)]
[WebBrowsable()]
public virtual string RssUrl
{
get { return rssUrl; }
set { rssUrl = value; }
}
protected virtual void AddContainer()
{
table = new Table();
table.CellSpacing = 5;
Controls.Add(table);
}
protected virtual void AddItemToContainer(XmlReader reader)
{
string link = string.Empty; ;
string title = string.Empty;
string description = string.Empty;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "link")
link = reader.ReadElementContentAsString();
else if (reader.Name == "title")
title = reader.ReadElementContentAsString();
else if (reader.Name == "description")
description = reader.ReadElementContentAsString();
}
}
TableRow row = new TableRow();
table.Rows.Add(row);
TableCell cell = new TableCell();
row.Cells.Add(cell);
HyperLink hyperLink = new HyperLink();
hyperLink.NavigateUrl = link;
hyperLink.Text = title;
hyperLink.Font.Bold = true;
cell.Controls.Add(hyperLink);

Label label = new Label();
label.Text = description;
cell.Controls.Add(label);
}
protected override void CreateChildControls()
{
Controls.Clear();

if (string.IsNullOrEmpty(rssUrl))
{
ChildControlsCreated = true;
return;
}
using (XmlReader reader = XmlReader.Create(rssUrl))
{
AddContainer();
reader.MoveToContent();
reader.ReadToDescendant("channel");
reader.ReadToDescendant("item");
do
{
using (XmlReader itemReader = reader.ReadSubtree())
{
AddItemToContainer(itemReader);
}
} while (reader.ReadToNextSibling("item"));
}
ChildControlsCreated = true;
}
}
}
Future Enhancement:
Accepting multiple RSS feeds ( DataTable.Merge() )

Configuring SMTP using WebConfig

Scenario:
Sending mail is one of the most common requirements for any Web Application. Usually SMTP server name change for different environments and there is a need for easily changing the value of SMTP server.

Solution:
Its possible to use a have SMTP server name as AppSetting but then you need to read it in Code and assign it to Smtp Client object.

Here's a shortcut.

Code:

string body = "This mail is from SMTP configured in Web.Config" ;

MailMessage message = new MailMessage("admin@server.com","EnterToEmailAddress", "Item Updated", body);

SmtpClient client = new SmtpClient();

client.Send(message);
WebConfig:
<configuration>
<system.net>
<mailSettings>
<smtp from="myemail@email.com">
<network host="smtp.company.com" port="25" />
</smtp>
</mailSettings>
</system.net>
</configuration>

Quickly getting the public token key

Scenario:
In Sharepoint every assembly we deploy , need to strongly names. Deploying the assembly to GAC and getting the public token key from them can be length process.

Solution:


Visual Studio External Tools is here for rescue.

1. Open Visual Studio
2. Go to Tools > External Tools > Add a new tool with below settings

Setting 1:

Title : GetPublicTokenKey

Command : C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\sn.exe

Arguments : -T $(TargetPath)

Use Output Window : Checked
OR
Setting 2 ( Need Reflector):
Title : GetPublicTokenKey

Command : C:\Reflector\reflector.exe <-- Change accordingly

Arguments : "$(BinDir)$(TargetName)$(TargetExt)" -debug

Use Output Window : Checked


Now anytime you need to read the public token key , no need to deploy the assembly to GAC .

Just go to Tools >> GetPublicTokenKey and you will get the public token key value in your output window.

Displaying Activated features using Application Page

Scenario:
Quickly displaying all the activated feature for a site collection / web

Code:

SPFeatureCollection siteFeatures = SPContext.Current.SiteFeatures;

foreach (SPFeature siteFeature in siteFeatures)
{
Response.Write(siteFeature.Definition.Name);
}

SPFeatureCollection webFeatures = SPContext.Current.SiteFeatures;

foreach (SPFeature webFeature in webFeatures)
{
Response.Write(webFeature.Definition.Name);
}

Saturday, May 30, 2009

Validating Content type name

Scenario:
Validating content type name while creating programaticaly

Solution:
Code:

// Decide on a name for the new content type.
string contentTypeName = "R&D";
try
{
SPContentType.ValidateName(contentTypeName);

}
catch (SPException ex)
{
Console.WriteLine(ex.Message);
}
Output
The content type name cannot contain: \  / : * ? " # % < > { } | ~ &, two consecutive periods (..), or special characters such as a tab.

Friday, May 29, 2009

Checklist for ASP.Net and Sharepoint

Version Control:
-- All the code changes should be checked in
-- Label the build with proper Product Version Number

Refactoring Checklist:

-- Remove the extra namespace references, you can use VS to do this
-- Add some inline comments
-- Make sure you not using System.Data.SqlClient in UI code-behind class, it should only be used in Data Layer
-- Remove the Source Control binding
-- Make sure to Encrypt the connection strings and other sensitive information
-- Remove any hard-coded test accounts
-- Compile the project to RELEASE mode
-- If using any timer job, make the timer interval configurable
-- For any Window Service, make the timer interval configurable
-- Set some standard in-term of maximum lines of code per file ( 100-200 lines ) , and refactor accordingly.
-- Make sure assemblies are strongly named
-- Compile the project for minimum .net framework
-- Use Try Catch Finally blocks to handle exception
-- Use a robust logging framework ( i.e. log4net ) in-spite of redeveloping your own

Database Checklist:
-- Use a naming conversion for all the tables ( Users , Employees )
-- Make sure to create limited SPs per table ( GetAll, Get, Add, Update, Delete or Remove)
-- Only grant ‘execute' permission on all stored procedures, and grant that permission only for the application domain group.
You can use the Database roles with EXEC permissions to Stored Procedure.
-- Do not use "exec @sql" construct in your stored procedures , only use stored procedures.

Deployment Checklist:

-- If you using AppSettings make sure all of them point to proper server (Production server)
-- Prepare script for retracting the solutions and of-course for deploying the solutions
-- Prepare pre-install / post-install scripts for any additional operation which need to executed on each individual server
-- In case you are replacing system files , make sure you back them up and need to be restored when you back-out

Code Quality Checklist:

-- Unit Tests
-- Address Cross Scripting issues
-- Address for SQL Injection issues, use Stored Procedures
-- Address Blind SQL Injection

What is FxCop ?

FxCop is a code analysis tool that checks .NET managed code assemblies for conformance to the Microsoft .NET Framework Design Guidelines. It uses MSIL parsing, and callgraph analysis to inspect assemblies for more than 200 defects in the following areas:

Library design
Globalization
Naming conventions Performance
Interoperability and portability
Security

Usage
FxCop includes both GUI and command line versions of the tool and supports analyzing .NET 1.x, .NET 2.0 and .NET 3.x components.Release

FxCop is intended for class library developers. However, anyone creating applications that should comply with the .NET Framework best practices will benefit. FxCop is also useful as an educational tool for people who are new to the .NET Framework or who are unfamiliar with the .NET Framework Design Guidelines.

FxCop is designed to be fully integrated into the software development cycle and is distributed as both a fully featured application that has a graphical user interface (FxCop.exe) for interactive work, and a command-line tool (FxCopCmd.exe) suited for use as part of automated build processes or integrated with Microsoft Visual Studio® .NET as an external tool.

Download fxCop

What is CAT.NET ?

CAT.NET is command line tool that helps you identify security flaws within a managed code (C#, Visual Basic .NET, J#) application you are developing. It does so by scanning the binary and/or assembly of the application, and tracing the data flow among its statements, methods, and assemblies. This includes indirect data types such as property assignments and instance tainting operations. The engine works by reading the target assembly and all reference assemblies used in the application -- module-by-module -- and then analyzing all of the methods contained within each. It finally displays the issues its finds in a list that you can use to jump directly to the places in your application's source code where those issues were found.

The following rules are currently support by this version of the tool.

- Cross Site Scripting
- SQL Injection
- Process Command Injection
- File Canonicalization
- Exception Information
- LDAP Injection
- XPATH Injection
- Redirection to User Controlled Site.

Download

Wednesday, May 27, 2009

Access Denied for Central Administration

Scenario:
We were configuring Form Based Authentication for our web application and after configuring we can go to CA home page easily but were getting Access Denied on all other pages. It was not accepting the Windows Credential and was prompting repeatedly.

Solution:
By mistake we added the Role Manager to CA. While configuring the CA , you need to configure only your Membership provider. You will get Access Denied when you try to access other pages if you have configured the Role Manager for CA.

Removing Role Manager solved the issue

Wednesday, May 20, 2009

Customizing site template or list template

Scenario:
First of all you might be thinking , is it possible ? Yes it is possible. SharePoint always have something to surprise you. Till date I was under the impression that Site Template is binary file and can't be edit with editor like Notepad. So I admit i was wrong.

Solution:
Here's the steps to make modification to list template ( stp files )

01. Create a new document library and list.
02. Add items / documents to it
03. Customize the look and feel.
04. Go to List Settings > Save List as template > Give a meaningful name > Submit
05. Download the .stp file locally
06. Rename the .stp file to .cab file
07. Extract the .cab file
08. You will find a manifest.xml file which is the main file
09. Open the Manifest.xml with some XML editor and make changes
10. Save it back and rename it back to .stp file
11. Upload the stp file to List Template Gallery and now you all set use it.

Follow the same set of steps in context of site template ( .stp file ) to make the required modification.

Leave a comment if you having problem understanding the XML.

Tuesday, May 19, 2009

What is .NET RIA Services?

Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. The RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

Friday, May 15, 2009

Event Handler exceptional behaviour

Scenario:
Programming events can cause exceptional behaviors, depending on the contexts in which you implement the event handlers. The following table describes event behaviors related to specific contexts that you might encounter when writing code.

Few known behaviour:

1. A request to delete an item through a list form does not have an associated content type ID, but this causes an ItemDeleting or ItemDeleted event to fire on all items, not just on items of a specific content type, even though the event was registered only for the content type.

2. The BeforeProperties property applies only to DocumentLibrary type lists.

3. List events do not fire on the UserInfo list.

4. Event handlers will not fire when bulk operation is occurring. For example, when a new list is created, the FieldAdding event will not fire.

5. Using element file to register an event handler attaches it to all the list of particular type. Most of the requirements need event handler to be attached to a particular list which can only be done through code.

Article:
MSDN

Event Handlers- Everything you need to know

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.

:-)

What is STSADM ?

STSADM is the command-line tool provided with SharePoint.This command-line tool allows you to interact with the SharePoint object model to complete common administrative tasks.Several STSADM commands are available via the command line but not in the Central Admin user interface.STSADM is beneficial to system administrators who want to create scripts to efficiently manage common tasks.STSADM is also extendible, allowing the creating of custom commands.

What is NHibernate ?

NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks. 

NHibernate 3.0 will be the first version to use .Net 3.5. NHibernate's primary feature is mapping from .NET classes to database tables (and from CLR data types to SQL data types). NHibernate also provides data query and retrieval facilities. NHibernate generates the SQL commands and relieves the developer from manual data set handling and object conversion, keeping the application portable to most SQL databases, with database portability delivered at very little performance overhead.

Thursday, May 14, 2009

Using different application master and simple master page

Scenario:
We wanted to have a more fancy master page for our login page, being the first page users hitting the site. Out of box login page uses Simple.master which is very basic, so we designed a new master page ( newsimple.master ). Now how to consume it.

Solution:
1. We could have back-up login page and point the exisiting one to new master page.
2. Another option is attaching the new master page using Web.Config, I will say this was much cleaner approach.
Navigate to 12HIVE > Templates > Layouts > Edit Web Config and add following lines in Web.Config

Code:

<configuration>
<location path="login.aspx">
<system.web>
<pages masterPageFile="~/_layouts/newsimple.master" />
</system.web>
</location>
</configuration>
Article:
http://blogs.msdn.com/webdevelopertips/archive/2008/12/31/tip-40-did-you-know-how-to-scope-master-pages.aspx

What is Forefront Security ?

Microsoft Forefront™ Security for SharePoint (FSSP) is the solution for the SharePoint virus problem. Forefront for SharePoint is designed to protect servers running Microsoft Office SharePoint Portal Server 2007 or Microsoft Windows® SharePoint Services 2007. Both versions run on either the 32-bit or 64-bit version of the SharePoint server and have identical functionality.

The configuration data for the Forefront for SharePoint Realtime Scan is stored in the SharePoint Portal Server or Windows SharePoint Services configuration database, and not in a separate Forefront for SharePoint database. This means that you can access the configuration data from either the Microsoft Forefront Server Security Administrator or from the SharePoint Administrator.Forefront for SharePoint also supports the Microsoft Forefront Server Security Management Console (FSSMC). The FSSMC provides administrators with central installation and reporting functionality.

Site Collection Policies - Access Denied

Scenario:
I got the following error while accessing the Site Collection Policies page
"Site Collection Policies - Access Denied"

Solution:
I was using Form Authentication for this web application and so I suspected that as my first culpit and that's what it was. I browsed the same page from my extended Web Application using Windows Authentication and it worked.

So if you are getting the same error , try extending the Web Application on another port with Windows Authentication and you are all set.

Controlling permission for application pages

Scenario:
While designing Application pages we need to also consider security. We need to configure correct permission required to access the page.

Solution:
We usually inherit LayoutPageBase class for our application pages and it support various properties to handle such security. Override the RightRequired properties.

Code:

public override string PageToRedirectOnCancel
{
get
{
return "/_layouts/settings.aspx";
}
}

protected override SPBasePermissions RightsRequired
{
get
{
return SPBasePermissions.ManageWeb | SPBasePermissions.ManageLists ;
}
}

SharePoint Security

Scenario:
I think this is one of the most common topic, everyone need to know and understanding within sharepoint world.

Again depending upon WSS or MOSS , permissions and permission levels varies.
Here's a very nice vision diagram to explain the high level details of sharepoint security.

Article:

http://go.microsoft.com/fwlink/?LinkID=73118&clcid=0x409

Wednesday, May 13, 2009

Form Based Authentication and Client integration

Scenario:
For most of the extranet facing website, Form based authentication is most suitable form of authenticating users. But in past one big dis-advantage to use Form Based Authentication was to loose client integration features. Users cant open documents in native applications ( like Word ) and so they need to download a document edit it and upload it , which is very painful.

Some good news:
There were some workaround done in CKS ( Codeplex project ) to deal with this situation, but again they were limited to Windows XP only.

Today while reading my feed , I got some more good news on the same topic. There are some changes done the way Form Authentication was handled for client integration.

These changes allow Office applications to display whatever forms login page is being used for the site in a pop up dialog box. The Office application renders the HTML from that login page and allows the user to enter credentials. The credentials are sent back to the server and if the server returns a redirect response for the document that was originally requested, the Office application assumes that the identity has been successfully established. It is then able to use the authorization cookie it was given to retrieve the document and any associated metadata, and open the item up.

Requirement for Client machine:
-- XP machines need to be have patched and require some Registry change
-- Vista machine will require
-- IE 7.0 or higher

Article:
http://blogs.msdn.com/sharepoint/archive/2009/05/13/update-on-sharepoint-forms-based-authentication-fba-and-office-client.aspx

http://msdn.microsoft.com/en-us/library/bb977430.aspx

http://support.microsoft.com/kb/960499/

Office Sharepoint 2010

I know these days , this is the hottest topic in sharepoint world. Lot of predictions, rumors , expectations from the new baby ( about to arrive ).

So let me share what I know.

-- Its a baby boy.. :-)

-- 64 Bit only

-- Windows Server 2008 only , IIS 7.0

-- 64-bit versions of SQL Server 2005 or 2008 only

-- IE 7.0 /8.0, Firefox 3.0 supported

-- Silverlight 2.0 support and some bare minimal controls

-- .Net Framework 3.0 only, but i think should not be difficult to use 3.5/4.0

-- Powershell

-- Social Networking and Enterprise 2.0

-- Better support for Wiki's and Blog Template

-- Mobile Support , I am sure they cant skip IPhone support.

-- Tagging , Tag cloud

-- Rich media support , not sure PODCAST kit might be it

Some guesses:

-- Bi-directional BDC support

-- Chart controls

-- Performance point server integration

-- FAST should still be a separate product but easier to install

-- Microsoft Portfolio Server should look more like Microsoft now

-- Improved support for bigger lists

-- Permission improvements , more discoverable options

-- More JQuery stuff

-- Claims-based authentication ( may be in 2010 SP1 )

-- Better client integration support for Form Authentication

-- Url Rewiting support

-- XHTML-compliant output

-- MVC framework ( Doubtful )

Article:
http://blog.sharepointproducts.com/archive/2009/05/12/microsoft-sharepoint-2010-news-from-teched-us-2009.aspx

Sunday, May 10, 2009

Host Header for site collection

Scenario:
Yes , you read it right. I came to know about this few min back only while reading MSDN article.

Solution:
STSADM -o createsite operation has an undocumented property host header ( -hhurl )

Code:

stsadm -o createsite -url http://training.localhost.com -sitetemplate STS#1 -owneremail administrator@localhost.com -ownerlogin Domain\administrator -title TestHostHeader -hhurl http://localhost
Article:
http://msdn.microsoft.com/en-us/library/dd578332.aspx
http://sharepoint.microsoft.com/blogs/zach/Lists/Posts/Post.aspx?List=90bbfd11-c9a5-45cf-a77e-19559aae81ae&ID=38

Restricting users to see other's information

Scenario:
By default, if you have even Read permission to sharepoint site, you can easily see other's details by clicking on People and Group link. May not be a good idea, if people are storing their personal information.Thanks God, there is a way to restrict it.

Solution:
1. Login as site owner
2. Navigate to people and group
3. Click on Site Permissions
4. Navigate to Settings > Permission Level
5. Select the permission level ( in my case Read )
6. Un-check Browse User Information ( View information about users of the Web site.)

Downside
Un-checking Browse User Information permission will also take away Check Edit Personal User Information ( Allows a user to change his or her own user information, such as adding a picture.) permission , so users will not be able to view/edit their own information. You can design a webpart to do that separatly.

You are all set. Comments ?

RSS feed for complete site collection or a full web

Scenario:
By default , sharepoint comes with the option to expose RSS feed for any list or document library , which is good in so many ways.But one of the most common requirement is RSS for full web or may be for full site collection.

Workaround:
1. Create a new page.
2. Drop a Content Query Webpart
3. Edit the webpart properties
4. Add the filtering / grouping crieteria for the items of interest. I chose all documents from site collection added or modified today.
5. Under presentation, I choose to Enable RSS feed for the webpart with proper title for my RSS feed.
6. You will see a RSS feed icon for the webpart.
7. Subscribe by clicking it or pass the url to anyone who is interested in this RSS feed.

Note:
1. This will only work with MOSS as CQWP is not available in WSS
2. Dont delete the webpart as Url is tied to webpart, so if webpart is deleted , rss will also not work.

Article:
http://msdn.microsoft.com/en-us/library/bb608445.aspx

Friday, May 8, 2009

Some of my favorite STSADM enumeration commands

Scenario:
I use some of the stsadm command more often , specially the enumeration related.Just wanted to list them for quick reference

Code:


stsadm -o enumusers -url http://localhost

This command will lists all users that are explicitly assigned to permission levels in this site. So if you have a site administrator or user added through policy setting..they may not be listed. And of-course if you added AD groups ( best practice ) , they will not be expanded.
stsadm.exe -o enumsites -url http://localhost  -showlocks 

Displays a list of sites that are hosted in a Web application.
stsadm.exe -o enumsubwebs -url http://localhost

Lists the subsites that have been created immediately below a particular site, that means only level 1 sites will be displayed
stsadm -o enumsolutions
Lists all the solution (*.wsp) and Web Part packages located in the solution store of the farm.
stsadm -o enumzoneurls -url http://localhost
Lists all of the public URL and the zones to which they are mapped.
stsadm -o enumalternatedomains   -url  http://localhost
Lists the internal URLs and specifies the URL zones and public URLs to which they are mapped.Article:
STSADM Commands

Sunday, May 3, 2009

Securing / Hacking Sharepoint

Scenario:
Security is most crucial requirement for any sharepoint implementation, we wanted to secure the documents/information and also wanted to make sure that we identify all the different holes from where someone can get into the sharepoint environement.

How many places someone can get permission:
- CA> Operations> Update Farm Administrator

- CA> Application Management> Policy for Web Application
Strange thing about setting permission here is it doesn't even show up in code , if you enumerate Site Collection AllUsers property . Also this is the only place to Deny All

- CA> Application Management> Update Site Collection Administrator

- Site Action> Site Settings> Site Collection Administrator ( In site collection Root Web only )

- List Settings> Manage Permission , no way to restrict break inheritance option by site owner. Data in sharepoint is in lists only. So I will say another risky spot.

- Item level Settings> Manage Permission , no way to restrict break inheritance option by list owner

Other Options:
- Save a list or document library as template ( AlwaysIncludeContent=TRUE by default) and restore in another environment.
Mininum Permission required : ManageLists

- Save a site template and restore in another environment
Mininum Permission required : Site Owner

- List Definition AllowEveryoneViewItems Attribute = FALSE by default, but can be set to TRUE by a small utility, i think most dangerous. As this will open files to anyone with Anonymous rights.
Mininum Permission required : ManageLists

- There is no concept of restricting permissions on list view

- Audit logs are not accurate ( don't show all the downloaded entries as long as have tested, comments welcome )

- People and Group - Privacy issues ( http://localhost/_layouts/people.aspx ), anyone can see other users information , like email and cell number etc. I know this is better in MOSS but in WSS, its an issue.

Developer's Code

- AllowUnsafeUpdate = TRUE , most of developer's do this.
- RunAtElevatedPriveldges() , that's another birth right of developers
- SPList.WriteSecurity & SPList.ReadSecurity

Friday, May 1, 2009

Using resources with webpart definitions

Scenario:
I was working on a site definition and wanted to drop a Content Editor Webpart on default page. I was not sure about his content.

Solution:
I thought of using resource files and hacked the webpart we see when we land to Report Center site.

WebPart Content Tag Declaration:

<Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor">$Resources:spscore,ReportCenterOnet_CEWP_Content;</Content>
Resource File:
<Data Name="ReportCenterOnet_CEWP_Content">
<Value><DIV class="ms-vb">
<SPAN class="ms-announcementtitle">Report Center features include:</SPAN>
<UL>
<LI><A title="" href="../Lists/Sample KPIs/KPIListViewPage.aspx" target="">Key Performance Indicators</A> (KPIs) enable you to communicate goals, trends and track progress.</LI>
<LI><A title="" href="../ReportsLibrary/sample dashboard.aspx" target="">Dashboards</A> enable you to give a more detailed explanation of your information using Excel workbooks and KPIs. Dashboard filters make it easy to select a range of information to view. To create your own dashboard go to the <A title="" href="../ReportsLibrary/Forms/scsummpg.aspx" target="">Dashboards</A> view of the Reports library and click 'New'.</LI>
<LI>The <A title="" href="../ReportsLibrary/forms/current.aspx" target="">Reports</A> library is designed to store files containing reports and dashboards and allow easy access to information from previous time periods.</LI>
</UL>
<SPAN class="ms-announcementtitle">To prepare this Report Center for use, the following actions are suggested:</SPAN>
<UL>
<LI>View the sample <A href="../ReportsLibrary/sample dashboard.aspx">dashboard</A> and <A title="" href="../ReportsLibrary/sampleworkbook.xlsx" target="">workbook</A> to understand some of the capabilities of this Report Center</LI>
<LI>If the samples do not work correctly ask an administrator to ensure that Excel Services are enabled and that this Report Center is a Trusted Location</LI>
<LI>If you plan to use Excel to analyze information from existing data servers, create and upload data connection (ODC) files to the <A title="" href="../Data Connections" target="">Data Connection Library</A>. If you want users to create new KPI Lists then add them to the "Owners" group. Users in the "Members" group can edit pages but can not create KPI Lists.</LI>
<LI>Update or remove sample content</LI>
</UL>
</DIV></Value>
</Data>