Posts made in February, 2014

Using SP.UI.ModalDialog in SharePoint 2010

Using SP.UI.ModalDialog in SharePoint 2010

If you are looking for primarily ‘client side’ functionality, you can use the SP.UI.ModalDialog class. I find this class very useful when creating visual webparts in SharePoint 2010 that require some sort of administrative feature or user feedback. In fact, if you look at the SharePoint 2010 architecture, you’ll notice that Microsoft have tried to avoid moving you to different pages in favor of the modal view. The SP.UI.ModalDialog class is accessible through the SharePoint JavaScript file called SP.UI.Dialog.js which is located in the layouts directory. Here is an example of how you can quickly get the SP.UI.ModalDialog class working in your code:

First we create the JavaScript function that will open up the new modal view. Notice I’m passing variables to the function for the file path, width and height. I did this so I can reuse the function for a variety of modal view calls for different purposes.

functionModalDialog(FormPath, FormWidth, FormHeight) {
varoptions = SP.UI.$create_DialogOptions();
options.url = FormPath;
options.width = FormWidth;
options.height = FormHeight;
options.allowMaximize = false;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);

We now need to create our call back method called ‘CloseCallback’ as mentioned in the above function. This method will be used to capture the results of the modal and perform some sort of confirmation action.

functionCloseCallback(result, returnValue) {
alert(‘dialogResult’ + result + ‘\nreturnValue’+ returnValue);

if(result == SP.UI.DialogResult.OK)
SP.UI.Notify.addNotification(‘You chose the OK button’);
document.title = returnValue;

if(result == SP.UI.DialogResult.cancel)
SP.UI.Notify.addNotification(‘You chose the Cancel button’);

You’ll see from the above method that we provide an alert with the full feedback of the modal and then utilize the SP.UI.Notify class to provide additional methods of feedback.

Now all we need to do is add an onClick of onClientClick event to an object in your code.


This is a quick introduction, but it should be enough to get you going with the SP.UI.ModalDialog class.

Read More

Customizing the SharePoint 2010 Welcome Menu (PersonalActions)

Customizing the SharePoint 2010 Welcome Menu (PersonalActions)

I support a SharePoint 2010 environment at my company and was recently asked to add an extra item to the welcome dropdown box (also know as the Personal Actions Menu) usually located at the top right of your SharePoint pages. This item was a feedback feature where users at any given location on the site could provide feedback, report a bug or add a general enhancement request.

I decided to store the data in a simple SharePoint list and implement a CustomAction Element using Visual Studio. I could have used a list view to manage the capture of the data, however I didn’t need all of the bells and whistles that came with one of those views and ultimatley created a custom application page with a form.

Creating a CustomAction is pretty easy, you just need to identify the GroupId and Location of the menu you wish to modify and then you’re good to go. You even have a simple function called a URLAction where you can direct people to a page when they click on your custom action. What isn’t so obvious is if you actually wanted your application page to popup in a modal view. Here is the code I used to get this done.

The CustomAction

Create a new blank SharePoint project in Visual Studio and then add a new ‘Empty Element’ to your project (I called mine CustomActions). Open up the CustomActions file and you should see something like this:

<?xml version=”1.0” encoding=“utf-8“?>
<Elements xmlns=““>

Add the following so that your file now looks like this:

<?xml version=“1.0” encoding=“utf-8“?>
<Elements xmlns=““>
<CustomAction Id=“CustomGlobalLinks”
Description=“Provide feedback or Submit an Enhancement Request”
<UrlAction Url=“javascript:(function () { var o = { url:’/_layouts/CustomGlobalLinks/Feedback.aspx’, title: ‘Feedback’, allowMaximize: false, showClose: true, width: 480, height: 280 }; SP.UI.ModalDialog.showModalDialog(o); }) ();“/>

Let’s break this down. The ImageUrl will give you a logo to the left of your Action on the menu; this is optional. The location refers to where you want to put your action and the GroupId refers to which group on the menu you want to add it too. I’ve used the PersonActions group.

I added some custom JavaScript to the URLAction which executes SP.UI.ModalDialog.showModalDialog and displays your application page in a modal. I actually found this script on another blog, however I can’t find it any more to give credit. I’ll certainly add the credit when I find it again.

The Application Page

Add a new Application Page to your project (I called mine Feedback). Add your controls (e.g. drop downs, text boxes etc.) and then hook them up to your feedback list (already created in your SharePoint environment).

On the submission of your form, you can close your modal by calling ‘window.frameElement.commitPopup();’ Here is some quick code on pulling content from your SPList to popluate a dropdown and how to write back:

Categories Dropdown

SPList FeedbackList;
SPSite site = SPContext.Current.Site;

FeedbackType.Items.Add(“– SELECT –”);
SPFieldChoice cf = (SPFieldChoice)FeedbackList.Fields[“Category”];
foreach (string type in cf.Choices)

Write back to the SPList

SPWeb web = site.RootWeb;
SPListItemCollection ItemCollection = FeedbackList.Items;
SPListItem ListItem = ItemCollection.Add();
ListItem[“Category”] = FeedbackType.SelectedItem.Text;
ListItem[“Feedback”] = FeedbackText.Text;

Read More

Export Gridview to CSV in a SharePoint 2010 Webpart

Export Gridview to CSV in a SharePoint 2010 Webpart

I was recently tasked with creating a Gridview in a SharePoint 2010 Webpart. In addition to assigning data to the Gridview, I also needed to create a way to export the data. Typically you would go down the route of exporting to Excel so I looked at some code from another blogger

This worked, however Excel did not recognize the file format as the document is basically a text file. As a result the user would get an ugly prompt saying something like “cannot verify the file format, would you still like to open”. This was not acceptable. So I tried using the code from the blog mentioned above to create a CSV file, which opened with no error, although the document was not formatted with data correctly because a CSV is a comma delimited text file.

So I now know that I can overcome the Excel document open error with a CSV, I just need to create the code to do the export and here it is:

Convert the contents of the GridView Cells from controls to text

private string getGridCellText(TableCell tc)
string cellText = “”;
if (tc.HasControls())
foreach (Control c in tc.Controls)
if (c.GetType() == typeof(LinkButton))
LinkButton lb = c as LinkButton;
cellText = lb.Text;
else if (c.GetType() == typeof(HyperLink))
HyperLink h1 = c as HyperLink;
cellText = h1.Text;
cellText = tc.Text;
return cellText;

Process the export request

public void exporttoExcel(GridView grv)
StringBuilder sb = new StringBuilder();
GridViewRow grHeader = grv.HeaderRow;
int counter = 0;

foreach (TableCell tc in grHeader.Cells)
sb.Append(“\”” + grv.Columns[counter].HeaderText + “\”,”);

foreach (GridViewRow gr in grv.Rows)
foreach (TableCell tc in gr.Cells)
sb.Append(“\”” + getGridCellText(tc) + “\”,”);

Response.AddHeader(“content-disposition”, “attachment; filename=Export.csv”);
Response.ContentType = “text/csv”;
Response.AddHeader(“Pragma”, “public”);

Button click event

public void export(object sender, EventArgs e)

You now have the code to do your export and it should all work, however something went wrong! It only works once, and everything else on the page seems to be disabled.

Apparantly, SharePoint updates some kind of timestamp hash on the form before it is actually submitted to the server. This is done in order to prevent the form from being submit more than once if the user clicks before the Postback is completed, which is a good thing – except when trying to do what we are trying to do here. To get past this you will need to also add the following JavaScript to the onClientClick event for your button:

function postExport() {

window.WebForm_OnSubmit = function ()
{ return true; };


Read More

Using the AJAX Control Toolkit with SharePoint 2010

Using the AJAX Control Toolkit with SharePoint 2010

The AJAX Control Toolkit offers so much useful functionality, however for some reason Microsoft refuses to integrate it as part of their product. This has caused problems with SharePoint 2003 – 2010, however as SharePoint now has standard Ajax integration we are now faced with another problem.

With previous versions of SharePoint you would need to add the AJAX references to the Web.config file as well as register the AJAX assemblies. In addition you would need to do the same for the AJAX Control Toolkit as well as incorporating a script manager into your master pages.Well with SharePoint 2010, the AJAX stuff is already there, but the script managers do not work with the AJAX Control Toolkit. Here is how I finally managed to get this working:

Registering the AJAX Control Toolkit

First you need to download the AJAX Control Toolkit binaries. After some headaches I found out that the latest release does not work with SharePoint 2010. You get a bunch of ‘sys’ errors after implementation. You will therefore need to download the 30930 version which can be found here.

Copy the “AjaxControlToolkit.dll” file into the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin” SharePoint directory (obviously if you didn’t use port 80, the path would have a different port number).

Open up your Web.config file and find the <assemblies> section add the following entry (notice that the version includes *.28736, this took me a while to figure out):

<add assembly=”AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e” />

Also add the following entry in the Web.config file in the <SafeControls> section:

<SafeControl Assembly=”ajaxcontroltoolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e, processorArchitecture=MSIL”Namespace=”AjaxControlToolkit” TypeName=”*” />

Adding the AJAX Control Toolkit to Visual Studio 2010

Open up VSTO and start a new Web Part project. When you have the project open, add a new reference to the project by browsing to the “AjaxControlToolkit.dll” file in the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin”  directory.

Once you have this added to your project, go ahead and add the following line to your user control:

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit”TagPrefix=”asp” %>

Now, add a new Tab to your Toolbox, then right click and ‘choose items’. Browse to the “AjaxControlToolkit.dll” file in the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin”  directory and add the controls. You should see the following results:

WAIT! There’s more

OK, you have everything in place and you start to build a Web Part with the AJAX Toolkit Controls and find that the control is being rendered, but it is not functioning. You get a Javascript error pointing to your AJAX files being out of date. This is because SharePoint 2010 now has a ScriptManager added to every Master Page by default. You need to open up the Master Page you’re using (typically with SharePoint Designer) and remove the existing <asp:ScriptManager> tag and replace it with the following:

<asp:ToolkitScriptManager ID=”ToolkitScriptManager1″ runat=”server” />

as well as adding the following assembly reference:

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit”TagPrefix=”asp” %>

Woohoo. You now have the Toolkit fully functional in SharePoint 2010. Hope this helps you save some of the headaches I went through.

Read More

Embedding a PDF Object in a SharePoint 2010 Web part using C#

Embedding a PDF Object in a SharePoint 2010 Web part using C#

Recently I was assigned the task of displaying a PDF in a SharePoint Web part. I figured it’d be easy enough to display it in an <iframe> or simply embed it on the page, but unfortunately my assumption couldn’t have been further from the truth.

Attempting to load the PDF in an <iframe>

Quite simply, and by default, SharePoint does not allow users to automatically open documents within a browser window. There is a setting on the web application called Browser File Handling, which if set to Permissive is supposed to allow documents to open within the browser. Alas, this setting does not afford the ability to view PDFs within the browser window. Also, within the Document Library, there’s a setting called Opening Documents in the Browser, which defaults to opening files within the browser anyway… So SharePoint is working against us.

Using the <embed /> tag

The <embed /> tag was deprecated for XHTML in favor of the <object> tag, so it’s not “supported” in Visual Studio. There is however a way around this; create a Literal control in C# and then write it to your page at run-time to avoid any compile errors. Upon assigning the src attribute, this strategy proves fruitful as it simply embeds the PDF in the window as desired. This is great, except for the fact that this strategy is completely invalid. I wanted to do one better.

Using the <object> tag

The <object> tag is a not only a valid XHTML control; it’s also supported in Visual Studio. Unfortunately, it requires a Class, ClassID, or ProgID attribute. I wasted hours scouring the web for this specific ClassID, and in the end, I could not locate it. This drove me to create a new strategy; a hybrid of the <embed /> and <object> strategies. This way I can ensure maximum browser support while doing my best to implement valid code.

//Create your URL to the pdf file, including path and URL variablesstring url = web.Url + “/” + “DocumentLibrary” + “/” + CurrentMonday.ToString(“MM-dd-yyyy”) + “.pdf” +“#scrollbar=0&statusbar=0&navpanes=0&toolbar=1&zoom=75″;//Establish Literal controlLiteral l1 = new Literal();//Write the Object code to the Literall1.Text = “<object id=’AcrobatFrame’ type=’application/pdf’ classid=’clsid:CA8A9780-280D-11CF-A24D-444553540000′ width=’711′ height=’956′><param name=’src’ value=’” + url + “‘ /><a href=’” + url + “‘>Click here to download “ + CurrentMonday.ToString(“MM-dd-yyyy”) + “.pdf</a></object>”;
//Add the Literal to the Page

Acrobat URL variables

In the code above you can see that I am passing URL variables to define what application components are visible and the zoom of the pdf. This way I can set a static height and width for the object because I know the size of the document will always be the same. See a list of all URL variables.

Read More