Saturday, March 29, 2008

I have moved to http://blogs.msdn.com/mahuja

From now on, all new posts will be posted on my "new" MSDN blog http://blogs.msdn.com/mahuja.

Please update your feeds.

Saturday, March 01, 2008

Switch the sharepoint webpart page Display Mode into Edit Mode and Vice Versa


Introduction


Recently one of my clients had a requirement to go into Edit mode of a sharepoint page using a manual link displayed in quick launch. He was lazy of going to Site Actions -> Edit Page and then again going somewhere else for Exit Edit Mode :)

To give some background for beginners, whenever we click Edit Page on Site Actions menu,
the pages switches into a different display mode called Design Mode. Its not a feature of
Sharepoint, but ASP.NET 2.0 Webparts Framework.

Background


According to the framework, the page can have 4 different modes:

  • BrowseDisplayMode : Represents the default display mode.
  • CatalogDisplayMode : Used for adding controls from a catalog of controls to a Web page
  • ConnectDisplayMode : Displays a special UI for users to manage connections between Web Part controls.
  • DesignDisplayMode : Used for changing the layout of Web pages containing Web Part controls.
  • EditDisplayMode : Displays a UI from which end users can edit and modify server controls

The WebPartManager control provides a programmatic interface, making it possible to switch the Web Part Page between browse, design, and edit display modes.

For example, to programmatically switch the current page into design mode, you can simply add a link control with an event handler that sets the DisplayMode property to DesignDisplayMode.


WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
Although this would work technically, but it would not give up the visible changes to page, like visibilty of Page Editing toolbar, webpart zones etc.

This visual magic is done by lot of Javascript which is executed when we click Edit Page on Site Actions menu.

To build this link control, we need to figure out the javascript code which causes this behaviour.

This would be present in default.master. If we open Site Actions menu and do the View Source on IE.
Here is the code of our interest :

<td class="ms-siteactionsmenu" id="siteactiontd">
<span><a href="javascript:MSOLayout_ToggleLayoutMode();">Edit Page</a></span>

As you must have figured out, its the MSOLayout_ToggleLayoutMode() function which does all the magic of turning the current page into Edit page. This javascript also calls the server side code which executes this statement


WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
//(This can also be demonstrated, but its beyond scope)

Building the Webcontrol

Armed with this knowledge, we can build a simple webcontrol which we will switch the page into Edit mode and vice versa.
Below is the code for the same. Its the simplest webcontrol you will see ever.


using System;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI;
namespace SPUtil
{
public class SPEditMode:System.Web.UI.WebControls.WebControl
{
HtmlAnchor btnLink;

protected override void CreateChildControls()
{
WebPartManager wp = WebPartManager.GetCurrentWebPartManager(Page);

const string url="javascript:MSOLayout_ToggleLayoutMode();";

btnLink = new HtmlAnchor();

if (wp.DisplayMode == WebPartManager.BrowseDisplayMode)

btnLink.InnerText = "Edit Page";
else if (wp.DisplayMode == WebPartManager.DesignDisplayMode)
btnLink.InnerText = "Exit Edit Mode";
else
btnLink.Visible = false;

btnLink.HRef = url;

Controls.Add(btnLink);
base.CreateChildControls();
}

}
}

I have used HtmlAnchor rather than LinkButton or SPLinkButton since its lightweight on the server and We are not performing any special processing which is present in server controls.

One point to be worth noting: This link would be visible to all including visitors. For used in practical scenarious, the control should be hidden for other than members and Administrators.

I was using this link in user's MySite and hence I did not have that case :)

Saturday, February 23, 2008

Passing multiple filter values to EWA pivot table filter cell

Filter webparts in WSS are a great way to provide filtering in many different webparts like List View, Business Data Catalog, Excel Web Access etc.

They are also great way to provide data view personalization when used with Excel services coupled with Analysis Services of SQL server.

This is described in detail on Excel Team blog here

In this post, we will see how to create a simple filter webart which provides values to pivot table filter cell.

I am mentioning pivot table filter cell exclusively because the filter webpart examples on MSDN has to be slightly modified to provide values
to filter cell.

Basically, we are building a filter provider which


  • Implements the ITransformableFilterValues interface.

  • The interface required few properties to be overridden, the most important of them is public virtual ReadOnlyCollection<string> ParameterValues.
    This parameter contains read only collection of strings which are passed to the consumer webpart.

  • The webpart returns the instance of itself through a public method SetConnectionInterface()

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using aspnetwebparts = System.Web.UI.WebControls.WebParts;
using wsswebparts = Microsoft.SharePoint.WebPartPages;
using System.Collections.ObjectModel;

namespace ExcelFilters
{
public class ExcelFilters : aspnetwebparts.WebPart, wsswebparts.ITransformableFilterValues
{
CheckBoxList cblRegionList;
ListItem cbitemRegion;
string[] countries = new string[]
{ "Canada", "Central America", "Mexico", "South America", "United States",
"Albania", "Andora", "Austria", "Aizerbejan", "Belarus", "belgium",
"Bosnia and Hersegovina", "Bulgaria" };

public virtual bool AllowMultipleValues
{
get
{
return false;
}
}
public virtual bool AllowAllValue
{
get
{
return true;
}
}

public virtual bool AllowEmptyValue
{
get
{
return false;
}
}
public virtual string ParameterName
{
get
{
return "Geography";
}
}

public virtual ReadOnlyCollection ParameterValues
{
get
{
string[] values = this.GetCurrentlySelectedGeographies();
List param=new List();

foreach (string str in values)
{
if(!string.IsNullOrEmpty(str))
param.Add(str);
}
return values == null ?null :new ReadOnlyCollection(param);
}
}

protected override void CreateChildControls()
{
cblRegionList = new CheckBoxList();
cblRegionList.AutoPostBack = true;
Controls.Add(cblRegionList);

foreach (string region in countries)
{
cbitemRegion = new ListItem();
cbitemRegion.Text = region;
cblRegionList.Items.Add(cbitemRegion);
cbitemRegion = null;
}

base.CreateChildControls();
}

[aspnetwebparts.ConnectionProvider("Region Filter", "ITransformableFilterValues", AllowsMultipleConnections = true)]
public wsswebparts.ITransformableFilterValues SetConnectionInterface()
{
return this;
}

public string[] GetCurrentlySelectedGeographies()
{
String[] choices = new String[countries.Length];
bool anythingSelected = false;

for (int i = 0; i < cblRegionList.Items.Count; i++)
{
if (cblRegionList.Items[i].Selected)
{
anythingSelected = true;
choices[i] = cblRegionList.Items[i].Text;
}

}
if (!anythingSelected)
choices = null;

return choices;
}

protected override void RenderContents(HtmlTextWriter output)
{
this.EnsureChildControls();
RenderChildren(output);

}
}
}

Now, rather than explaining the simple webpart, which is already explained by Microsoft, I will point out key points which differentiates it from the examples at many places.

If we notice GetCurrentlySelectedGeographies() method, it returns the string array of selected geographies. However, the length of this string array is constant and is equal to number of selectable items, which causes the other items in string array to become null.

In the MSDN example here the string array is directly passed by converting it to ReadOnlyCollection of strings. This will not work since it includes the null items
in the array as well.

string[] values = this.GetCurrentlySelectedGeographies();
return values == null ?null :new ReadOnlyCollection(values);

Pivot table Report filter cell, expects a Collection of values only which are selected. Thus we need to modify the code as follows

string[] values = this.GetCurrentlySelectedGeographies();      
List param=new List();
foreach (string str in values)
{
if(!string.IsNullOrEmpty(str))
param.Add(str);
}
return values == null ? null :new ReadOnlyCollection(param);

This code snippets, creates a new List which includes all the string objects except the null items from the original string array which is returned by GetCurrentlySelectedGeographies()

Sunday, February 10, 2008

Implementation of Logging and Instrumentation Application Block in MOSS 2007

Continuing the series of articles on Enterprise Library, I have written the first article
on the implementation of Logging Application Block in MOSS 2007. Due to inclusion of formatted code and images, I have directly uploaded this on Codeproject.

The article can be viewed here

Sunday, February 03, 2008

Microsoft Enterprise Library - Using Design Patterns and Best Practices with Sharepoint 2007 development

Patterns and Practices Group within Microsoft has provided developers with useful code libraries in form of Enterprise Library which solve the common programming tasks and provide the developers with best practices.

The patterns & practices Enterprise Library is a library of application blocks designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used "as is," extended, or modified by developers to use on enterprise development projects.

Note: The purpose of this article is introduction of Microsoft Enterprise library. I would cover each specific application block in subsequent blog articles and demonstrate how they can be effectively used in Sharepoint 2007 development environment.

The seven application blocks are:

  • Caching Application Block - allows developers to incorporate a local cache in their applications.
  • Configuration Application Block - allows developers to read and write configuration information.
  • Data Access Application Block - allows developers to incorporate standard database functionality in their applications
  • Cryptography Application Block - allows developers to include encryption and hashing functionality in their applications.
  • Exception Handling Application Block - allows developers and policy makers to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging and Instrumentation Application Block - allows developers to incorporate standard logging and instrumentation functionality in their applications.
  • Security Application Block - allows developers to incorporate security functionality in their applications.
Each of the application blocks uses similar design patterns and share similar deployment and configuration requirements.

Getting Started with Enterprise Library

In order to get rolling with the Enterprise Library you'll first need to download the library from Microsoft's site. The download is a near 9 MB file, which includes the complete Enterprise Library application block source code, Quick Start examples, off-line documentation, and the GUI tool.

During this installation process you can specify what application blocks to install, if you only want to install a subset of the seven. Upon completion of the installation, the files should be in the \Program Files\Microsoft Enterprise Library folder.

Saturday, January 26, 2008

RSS Reader webpart with tab support and asynchronous periodic data refresh using AJAX

I have recently written my first article on Codeproject.

The article describes the development of AJAX enabled webpart on MOSS 2007 SP1.

The cool thing about it is the that it also utilizes the AJAX Control Toolkit including programmatically adding and styling TabContainer and TabPanel controls which can be quite tricky for a beginner. The article can be found here:
http://www.codeproject.com/KB/sharepoint/RssReaderAjax.aspx


Sunday, January 20, 2008

Get RSS Url for a list or Document Library Programmatically

Recently I developed an RSS Reader webpart which would take the RSS URL of list to render its feeds. Very much same like the out of the box webpart with the exception that it was AJAX enabled. I would post the details of that part on the blog when I am finished.


An idea came to me that wouldn’t it be nice to also enable users to just give the list URL rather than RSS URL since would reduce the few steps on the user’s side. I thought it would be just a matter of accessing the RssUrl property of SPList object, but to my surprise it was not to be. There is no property such property in the API, so I decided to write my own function for it.


Let’s analyze the RSS URL of a list or a library. Whenever the user clicks on View RSS feed on a library, here is how SharePoint constructs the URL:


http://<server>/<site>/_layouts/listfeed.aspx?List=%7B14206B18%2DF68F%2D479B%2DBC84%2D15EE48D19D7D%7D


Listfeed.aspx is the inbuilt RSS viewer of sharepoint which accepts a parameter which is the GUID of the list. %2D tokens refer to ‘-‘characters which exist inside the GUID. Considering all this, it’s easy to write a function which will return the RSS URL. Here is the code for the same:


private string MakeRssUrl(string rawurl)

{

try

{

Uri url = new Uri(rawurl, UriKind.Absolute);

if (url.GetLeftPart(UriPartial.Path).Contains(“_layouts/listfeed.aspx”))

{

return rawurl;

}

else

{

string rssurl;

using (SPWeb web = new SPSite(rawurl).OpenWeb())

{

SPList list = web.GetListFromUrl(rawurl);

rssurl = web.Url + "/_layouts/listfeed.aspx?list=" + list.ID;

return rssurl;

}

}

}

catch (UriFormatException e)

{

return string.Empty;

}

}


The code is pretty self explanatory. The argument to function is list URL or RSS url. We first check if the URL is RSS URL itself, and if it is we just return. Otherwise, if it’s a list URL, we create a SPList instance, grap the GUID and contatenate it with the site URL and listfeed.aspx.


Note that the function does not validate if the given URL was actually a valid list URL or not. The exception handling for that case should be left to the caller of the function.

Monday, January 14, 2008

Reveal Unknown Error on Sharepoint 2007 pages

How often you have encountered the infamous Unknown Error on Sharepoint 2007 pages. If you are a Sharepoint developer, chances are that innumerable times :)

However, if you are also seasoned ASP.NET developer as well, you also know the trick behind it to reveal them., which I am going to give it here.

The trick is that ASP.NET Framework wants to show the real error message, but its the sharepoint which abstracts the message from the user. This is good for production systems since those cryptic error message may not be user friendly. Or revealing those full stack trace could cause potential security concerns.

But for an experienced developer, this is almost must to turn them off. This is achieved by turning off custom errors in web.config

Find the web.config for the site you normally use as your development site. Locate this tag

<SafeMode ... CallStack="false" ...> and change it to CallStack="true"
Set <customErrors mode="On" /> to mode="Off"
Set <compilation batch="false" debug="false"> to <compilation batch="true" debug="true">

Now you will get the full stack trace as soon as the error is raised.

Sunday, January 06, 2008

Unknown Error on Manage Form Templates Page (Manageformtemplates.aspx)

Getting Unknown Error on this page?.

No helpful clue in Sharepoint log or Event Viewer?


This can happen if database record in the list of published InfoPath forms had a null where it shouldn't be.


Thanks to this blog, there is small code snippet given here which will delete the culprit entry.


http://geekswithblogs.net/HammerTips/archive/2007/12/07/unable-to-manage-form-templates.aspx



But make sure that you run this script under the debugger and only execute the delete operation for the offending form, otherwise it will delete all the published forms in your farm.

Unable to Join the Game: Age on Kings (Conquerors)

This is a first off topic post on my blog about a lovely game from Microsoft: Age

of Kings also called as Age of Empires II : Conquerors. I have been a fan of this

game from my schooldays and been playing multiplayer matches on zone.com

during my college days. Lately Microsoft has closed zone.com. However there

are few third party multiplayer sites going on which are exactly same as

Zone.com. For ex:


http://www.igzones.com/

http://www.gamepark.eu/en/


However I was facing the famous issue Unable to Join the Game. Forwarded all

the required ports, turned of firewalls , still no issue. I even installed the

TCP sniffer to see if incoming packets were hitting my system. To my surprise

they were and still no luck in connection. Finally after 3 days of trying, I found a

hidden setting in my wireless router which was causing this issue. I had Upnp

enabled in my router by default and disabling it completely resolved the

issue. To anyone curious who want to know what the Upnp is : J


http://en.wikipedia.org/wiki/Universal_Plug_and_Play

Monday, December 24, 2007

Performing Operations on Infopath 2007 Contact Selector Control using Managed Code

Infopath 2007 provides an out of the box contact selector control to select the user and validate against the Active Directory.


In this blog, We will see, how to get more out of this control. Performing some advanced functions using managed code.


For basic usage of this control, see this blog entry on infopath blog:

http://blogs.msdn.com/infopath/archive/2007/02/28/using-the-contact-selector-control.aspx


To start with basics, this control has predefined schema, since it simultaneously stores the display name, account id and account type.

  user display name
  DOMAIN/user account
  user or group type
 
It is interesting to note that this control behaves like a repeating control, in a sense,
the user can select multiple users from the same control. Internally, the XML schema
shown above is repeated for multiple users.
 
2. Get the Display Names and Login Names for all users in contact Selector Control
 
To get the display names and login names, we just need to parse the generated XML
schema. We will store the names and login names as comma separated values.
Assuming that our control name is gpContactSelector, the code below extracts the
display names and login names.
 

XPathNavigator xNavMain = this.XmlFormView2.XmlForm.MainDataSource.CreateNavigator();

XmlNamespaceManager xNameSpace = new XmlNamespaceManager(new NameTable());

xNameSpace.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2007-11-20T20:01:12");

XPathNodeIterator[] nodes = new XPathNodeIterator[4];

nodes[0] = xNavMain.Select("/my:myFields/my:gpContactSelector/my:Person/my:DisplayName", xNameSpace);

nodes[1] = xNavMain.Select("/my:myFields/my:gpContactSelector/my:Person/my:AccountId", xNameSpace);

nodes[2] = xNavMain.Select("/my:myFields/my:gpContactSelector/my:Person/my:AccountType", xNameSpace);

string names=string.Empty;

string accid=string.Empty;

for (int j = 0; j <>

{

for (int i = 0; i <>

nodes[i].MoveNext();

if (nodes[2].Current.ToString() == "User")

{

names = names + nodes[0].Current.ToString()+";";

accid = accid + nodes[1].Current.ToString()+";";

}

        }
 
The code above is pretty self explanatory. It parses the generated XML Schema
and stores the Names and login ids in two variables, names and accid as semicolon
separated values. Further operations can be then performed on these.
 
2. Sending Emails to All users selected in Contact Selector
 
To send emails, we obviously need email addresses of the contacts selected.
However, contact selector does not automatically grabs out the email addresses
of the contacts. To get the email addresses, we will first extract the login names
from the XML schema and then use the Microsoft.SharePoint.Utilities.SPUtility.GetFullNameandEmailfromLogin
class to get the email addresses.
 
The code below accepts the login names as semicolon separated values and builds
a string containing email addresses as semicolon separated values.
 

private string GetEmails(string final)

{

char[] a = { ';' };

string[] loginIds = final.Split(a, StringSplitOptions.RemoveEmptyEntries);

string[] emailids = new string[loginIds.Length];

for (int i = 0; i <>

{

Microsoft.SharePoint.Administration.SPGlobalAdmin ga = new Microsoft.SharePoint.Administration.SPGlobalAdmin();

string dispname, email;

Microsoft.SharePoint.Utilities.SPUtility.GetFullNameandEmailfromLogin(ga, loginIds[i], out dispname, out email);

emailids[i] = email;

}

string finalstring = string.Empty;

for (int i = 0; i <>

finalstring = finalstring + emailids[i] + ";";

return finalstring;

}

 
 
 
Now, we can use using System.Net.Mail namespace to send mails. This namespace
overrides the System.Web.Mail used in .NET 1.1. For those who are new to this
namespace, below is the sample code given to send mail.

private void SendMail()

{

MailMessage mail = new MailMessage();

mail.From = new MailAddress("Admin@domain.com", "Administrator");

char[] a = { ';' };

string[] emailIds = to.Split(a, StringSplitOptions.RemoveEmptyEntries);

for (int i = 0; i < style="">

mail.To.Add(new MailAddress(emailIds[i]));

mail.Subject = "New Meeting Request";

mail.Priority = MailPriority.Normal;

mail.IsBodyHtml = true;

mail.Body = GetBody();

new SmtpClient("smtpserver").Send(mail);

}

Sunday, December 16, 2007

Doing Data Validations in Infopath 2007 Programmatically

Infopath 2007 provides rich validation function for each of its controls. For ex, you can validate a text box or a field

For conditions such as equal to, is blank, is greater than and if that field fails the validation, we can display a message box.


One important thing to be noted is that, Infopath 2007 would not submit the form unless all the controls pass the validation.


Now, let’s talk about the complex validation, let’s say, I want to validate whether or not the textbox contains email address or not.

Surprisingly, this can be also done out of the box using pattern matching. If we look at the validation options in Infopath, one finds the options matches pattern, does not matches pattern. Here one can specify a complex regular expression to be matched.


Custom Validation


Now we come to our main topic, custom validation, means validation using some business logic which Infopath cannot provide out of the box.

To implement custom validation, each control in Infopath provides a validating event, which is usually called when the value of the control Changes. This is almost same as Changed event, with one difference that during the execution of validating event, the whole document tree is read only. That is, we cannot write to any field in Infopath while validating event is being executed.


The reason for this is that, the values of Infopath fields can change due to the change in values of other fields, which will result in Validating event to be called again and again, until the stack runs out of memory.


Now, coming to our main point, validating event, here we will see how to validate a simple field in Infopath, programmatically.

To write managed code in Infopath, you must have either VSTO or VSTA installed.


To write a validating event for a field, right click the field and choose Programming ->validating event


The code editor will open up the desired function for inserting the code for the validating event for particular field.

Below is an example of one of the typical implementation of validating event




public void OtherAttendees_Validate(object sender, XmlEventArgs e)


{


try


{


this.Errors.Delete("Invalid Value");


}

catch (Exception) { }


string str = e.Site.Value;

bool flag = CheckAttendees(str);



if (flag == false)

{


this.Errors.Add(e.Site, "Invalid Value", "The value of the "+ e.Site.LocalName + " field must be email addresses seperated by ;");


}


}



To understand the above code, we must first realize that this function will be called as soon as the value of the field will be changed.


We clean up the Errors collection prior to validating our field using this.Errors.Delete();

CheckAttendees function implements the business logic which determines that weather the field is valid or not. The input to the function is nothing but the value of the field.


Now, if the decide that field validation has failed, we add an error into the Error Collection using this.Errors.Add(), indicating the value and the custom error message we want to be displayed.


You can find out about the Errors collection here:

http://msdn2.microsoft.com/en-us/library/bb229714.aspx


Now the point is, if the Errors Collection contains an item, the Infopath will not allow to submit the form. And, if you try to submit it, it will highlight the particular field and display the custom error message.



Tip about Validation and Submit in Browser Forms


This sort of validation works fine in client form since everything is executed on client. However in browser based forms, the user would not come to know about the failure in validation until he clicks submit and this would cost an expensive server page postback.


To overcome this limitation, we can implement the same logic in Changed event handler and set a value of hidden field which would indicate the validity of the form at the time of submission. Now on submit button, we can use custom rules to check the value of the hidden field and prevent the submission at the client side only. This prevents considerable overhead of page postback.