Add a Stylesheet to a Page from a Sharepoint 2010 Sandbox WebPart

I have a module in my project that deploys a style.css document to the site Style Library.  I wanted to add a reference to this Stylesheet from within my WebPart code to the page.  I never anticipated that this would be a problem, even in a sandbox solution and the restrictions that came with it.

I couldn't use the Microsoft.Sharepoint.WebControls.CssRegistration class becuase I was in a sandbox solution.  So I thought let's try using standard .Net methods, like adding to the Page.Headers collection, but in my sandbox WebPart that property was always null.

I couldn't find anyway of adding the Stylesheet reference server side from a WebPart in a sandbox environment.  The only option left was to use client side javascript to dynamically add the reference to the DOM.

Here is a snippet of code from my WebPart that accomplishes this:
protected override void RenderContents(HtmlTextWriter writer)
        {
            StringBuilder js = new StringBuilder();

            js.AppendLine("var added = false");
            js.AppendLine("for (i = 0; (a = document.getElementsByTagName(\"link\")[i]); i++)"); 
            js.AppendLine("{");
            js.AppendLine("  if (a.getAttribute(\"rel\").indexOf(\"style\") != -1");
            js.AppendLine("      && a.getAttribute(\"href\").indexOf(\"kwsresourcebooking365\") != -1)");
            js.AppendLine("  {");
            js.AppendLine("    added = true;");
            js.AppendLine("  }");
            js.AppendLine("}");
            js.AppendLine("if(!added)");
            js.AppendLine("{");
            js.AppendLine("  var head = document.getElementsByTagName(\"head\")[0];");  
            js.AppendLine("  if(document.createStyleSheet)");
            js.AppendLine("  {");
            js.AppendLine("    document.createStyleSheet('" + SPContext.Current.Site.Url + "/style%20library/folder/style.css" + "');");
            js.AppendLine("  } else {");
            js.AppendLine("    var css = document.createElement('link');");
            js.AppendLine("    css.type = 'text/css';");
            js.AppendLine("    css.rel = 'stylesheet';");
            js.AppendLine("    css.href = '" + SPContext.Current.Site.Url + "/style library/folder/style.css" + "';");
            js.AppendLine("    head.appendChild(css);");                        
            js.AppendLine("  }");
            js.AppendLine("}");
           
            base.RenderContents(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine(js.ToString());
            writer.RenderEndTag();
        }
The Javascript will first check to see if the Stylesheet link exists in the head. If it doesn't exist then it will check to see if the createStyleSheet method is available, which essentially means that we are in Internet Explorer or else manually create link tag. I did consider using the Sharepoint client script manager, but I think there maybe sandbox restrictions there too and I was growing tired of hitting sandbox brick walls. I hope this saves you some time and frustration!

SQL Server timeout in Profiler but executes ok in SSMS

Recently, I had a problem where I profiled a query which was timing out in my web application, but ran in under a second when I executed the same query in SQL Server Management Studio.

I found that forcing SQL Server to recompile the execution plan at runtime resolved the issue for the web application.

Here's a snippet of a CREATE PROCEDURE script that uses the WITH RECOMPILE option


CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
-- Add the parameters for the stored procedure here
<@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
<@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
WITH RECOMPILE
AS
BEGIN


Sharepoint 2010 Weather WebPart

Here's my latest CodePlex Sharepoint 2010 project, it's a WebPart that displays a 5 day weather forecast.


The weather feed is from the Microsoft "Dallas" Project, you must sign up at www.sqlazureservices.com and subscribe to the Weather Central Global Forecast and Data Services - Weather Central, LLC (CTP2). You will need to enter your Account Key into the WebPart properties.

The location of the forecast is controlled by entering Latitude and Longitude values in the WebPart properties. I found this site very useful to search for a location and get the Latitude and Longitude values.

The images and stylesheet are loaded into the Site Collection Style Library. Any user who has access to this can change the weather icons or styles that the WebPart uses.

Note: Please make sure you have the necessary permissions/rights to use the icon images.

Sharepoint 2010 "Hyperlink with Picture" Column Type

I've recently published my latest CodePlex project. It's a Sharepoint 2010 Custom Field Type that extends the SPUrlField type to allow you to have an image instead of a text description as the link.

When creating a new column, the feature adds a new type called "Hyperlink with Picture"



The new column is exactly the same as a Hyperlink type column, but instead of displaying the link as the description text, it shows an image instead.



When editing a list item you enter the target url and the url to the image you want to display for the link



When you view the list item the image will display and open the target url link when clicked

Sharepoint 2010: Resource Booking WebPart

I had a request to build a simple generic, configurable, weekly resource booking web part for Sharepoint 2010.  Here is a list of the design goals that we set:
  • Ability to have multiple resource booking webparts on a single Sharepoint Web
  • The available resources should be configurable by the end users
  • A weekly view of bookings
  • Ability to easily identify resources that can be booked and to filter the weekly view
  • Validation to guard against double bookings
  • Ability to delete bookings you created
  • Defaults to make creating new bookings quick and easy
  • Use AJAX to avoid ugly post backs (page reloads)
The resulting Sharepoint Feature contains a WebPart which is deployed at Site level and can be used in any site within the Site Collection.  A Web level Feature contains List Templates for the Resource list and the Bookings list which can be activated by any site administrator that wants to use the Resource Bookings WebPart.

The Resource Booking WebPart has two custom properties to link it to the Resource list and the Bookings list.  The Resource list is included on the Quick Launch menu, while the Bookings list in not.  It's possible to change this, of course, along with list permissions and adding your own views to the Bookings list to extend functionality for the users.

Below is a screenshot of the Resource Booking WebPart.


The Resource Booking WebPart defaults to show the current week starting on a Monday.  At the top it shows the week start date and end date, there are arrow buttons to navigate to the previous and next weeks.

Each box shows the Bookings for a particular day sorted in time order.  Bookings with a red cross next to them are one's made by the currently logged on user, clicking the red cross will delete the booking.  You can only delete your own bookings using the WebPart, you could open the Bookings list and delete bookings from there if you have sufficient permissions.  Hovering the mouse over a booking will popup who own's that booking, as shown in the screenshot.

In the bottom right hand corner is a list of all the resources that are available for booking.  This list is created from the Resources list which is managed by the users.  Checking the boxes against the resources will filter the view to show only those bookings against the selected resources.  You can filter the view and still navigate to previous or next weeks keeping the chosen filter in effect.

To create a new booking simply click on the icon.  Below is a screenshot of the New Resource Booking view:


The From time defaults to the current time and the To time to the current time plus one hour.  The Owner will default to the currently logged on user.  All of the fields are required and there is validation in place to ensure there is no double booking of resources.  The validation error message will tell you who has the resource booked when the times they have it reserved.

T-SQL to list processes and their running sql

select sp.spid, sp.status, sp.blocked, sp.hostname, db_name(sp.dbid), object_name(objectid), qt.text
from sys.sysprocesses sp
cross apply sys.dm_exec_sql_text(sp.sql_handle) qt
where sp.status <> 'sleeping'

Credits to Phil Hendry

Sharepoint: Document Control

This is a 10 minute video demo of Sharepoint Document Control.  It shows the creation of a new Controlled Document and it's lifecycle through approval and revision.  You can see the integration with Microsoft Word and how the document can be revised whilst the original published document remains the only version  available to the readers. 

It is built on a standard Sharepoint Document Library which has versioning enabled and enforced check-in and check-out.  There are no additional webparts, only standard views and workflow tasks.  You can customise everything around the famework that is in place including the views, fields, word template and tasks.

I hope you find the video informative, please post any questions as comments and I will do my best to answer them.  I hope to produce some further videos that show the document review workflows and change request features.

Depending on your screen resolution you might find watching the video on the YouTube site in full screen provides a better view of the demo.  Please click here to open the YouTube page.