ACC seating will be changed from Platinum/Gold etc. to an even split of Blue / Red and in addition to a general price increase, seat prices will probably increase while at the game for no apparent reason. If you want to switch from the Blue to Red section you’ll have to pay a cancellation fee, and may be forced to sign up for season’s tickets. Arena blackouts will become common in unplug to reset scenarios, video feeds may fail or become unresponsive (especially in bad weather), frequently hardwood will be laid for Leafs games, and there will be more commercials stating the Leafs have more or even the most players in HD than any other NHL team!?@#! If you have to leave the game early they will charge you a $100 2nd/ 3rd period cancellation fee etc. Getting tickets will be really easy over the phone or online, however you’ll never be totally sure you got the right Leafs/Raptors/TFC/Marlies or Blue Jays tickets until the bill arrives in the mail. Rogers will bait and switch Leafs tickets for Blue Jays. The CRTC will start regulating Pheneauf hits and be a major contributor to banning fighting in hockey. The Leafs will frequently stop playing, or significantly slow down to the point where you wonder if they have crashed. It will become impossible for the Raptors to beat the shot clock and should someone “catch fire”, they will be throttled. If you drink beer at the game, you will have to pay a second fee, in addition to the $11 for the beer to compensate Bell/Rogers for subsidizing your subsequent buzz. Should it be determined you were drunk when leaving the arena you would have to pay an overage fee on said service. Moreover, if a game went into overtime, you would automatically be charged an additional 35% on ticket price again, as an overage fee. Should a shootout occur, you will be charged the maximum. If you call to complain about any of this, you will need to provide the 10 digit account number clearly written on the part of the ticket that is torn off and disposed of by ACC staff when entering the venue. Moreover should you have any further problems, you will be directed to contact Rogers, who will direct you to contact Bell, who will direct you to contact Rogers, who will direct you to contact Bell, who will... Meanwhile … in Leaf Land …
- Philosophy, Idiocy, Internet Strategy, .Net Development and JavaScript Web Development
10/12/2011
My Thoughts on Bell/Rogers purchasing the Toronto Maple Leafs
04/02/2011
Hack Fix For typeface.js JavaScript Error " 'undefined' is null or not an object"
In IE the following JavaScript error is thrown in circumstances where there is no match for an individual character code in your font glyph map (you know that file you generated for your font):
Error " 'undefined' is null or not an object"
Line: 601 (uncompressed source code).
At time of posting I am using typeface-0.14.js.
The visual result of this error is the sudden disappearance of all headings after the heading which contains the erroneous character on your page. If you inspect your markup, you will notice your missing head tags ALL contain style="visible: hidden" yet have no VML content. This is a result of typeface hiding markup elements before ensuring it can successfully emit the resulting vml syntax & an error.
The Hack fix, which merely seeks to allow typeface to continue processing all "non-corrupt" words on the page (rather than an ugly fail & missing headings) is to modify typeface.js with the following:
1) In the _renderWord method, wrap all calls to: "this.renderGlyph" in a try catch statement.
2) If an Exception occurs return null.
You will find renderGlyph is invoked VIA the renderWord & recursively VIA the renderGlyph method(s). Fortunately for us, the method that calls renderWord (getRenderedText) performs a null check on the renderWord result. If the return from the renderWord method is null, the word will be "ignored" by the portion of the method responsible for creating the VML, and therefore will NOT cause a catastrophic failure in typeface enabling rendering of subsequent words & headings.
So that's the solution. It works. To be honest, I don't like this solution for a bunch of reasons:
1) I don't like try ... catch oriented programming. If there is an error, I want to be told of it so I can treat its root cause rather than at its symptoms. However, circumstances do arise which make it difficult to ensure issues are treated for root cause (EX// CMS Systems which do not impose such limitations on user generated content).
2) The primary reason: This is a 3rd party library for my app. Inevitably, at some point in the SDLC, someone smart is going to take over this project and say: "I can't believe they are using typeface-0.14.js, don't they know it's at version 3 right now". Other than the fact the file is named typeface-0.14-CUSTOM.js & loaded with customization comments, there is no indication to developers that this file has been customized (devs tend to look at code & runtime behavior vs ReadMe files & comments). And you know the rest of the story that starts with: I,E,6; Ends with: "hack fix"; and resounds in a high pitched user saying: "Everything was working fine until your last deployment".
3) A "JavaScript plugin" with such a pervasive behaviors, to a certain degree could be better programmed to isolate and tolerate faults. NO, this is not a contradiction to #1 above, but rather, represents an authors conscious decision to say: "Ok, with respect to what I'm trying to do, I CAN tolerate this fault, but I CANNOT tolerate that fault". In the case of this fix, I have made a conscious decision to say: "It's better if I just fail this one word than risk failing every subsequently unprocessed heading and word on the document".
4) 1#: I am in no way speaking down or pointing a finger at the typespace developers. I think everyone in the community owes them a stand up applause. Seriously. Amazing work & great contribution guys! I have contributed this fix. But in developing a site, and having to decide on how typography would be handled, and being in an " obviously IT" time crunch, I really don't have time for errors like this. More specifically, having written & proofed an opposable dynamic font solution to typeface, when I saw these errors, I immediately sought to rip typeface out of my application. This developer decision directly contradicts mass adoption of these technologies. Let's be honest, with the typeface source code, and a web browser, it's pretty easy to figure out this work around, but for the 90% of users that don't have the skill, it's a three point shot into the garbage bin. In not patching this gap, the door swings open (insert firm kick from behind) for developers to consider alternatives & for this to never truly mature. For example my train of thought: P - "undefined error in typeface (3rd party js lib??)" -- TOT - "another hack library not doing null checks" -- R - "ctrl+f5 on browser" -- NEXT - P "undefined error in typeface" -- TOT - "this is a third party library, is it even reasonable to try to crack the hood?" -- R - "build new matrix of reasons I'm using typeface and not my guaranteed image based solution" -- NEXT -- P "is typeface the right tool for this?" -- TOT "evaluate guaranteed solution vs. unexplored option" -- R "how much time required to fix" -- NEXT -- P "what is the quickest means to an end: risk debugging typeface VS. introducing jQuery convention" -- TOT "I can justify spending 10mins debugging typeface, after that, I'm pulling out and inserting my fontSprite". OUTCOME: typeface is a really well designed script that is easy to diagnose and repair problems in therefore 10 mins spent investing and repairing problem in typeface source was worth the effort. I conclude this is true ONLY because the resolution was simple. And this is my reservation: we use these scripts to gain a level footing on different platforms. When platform comparability issues are prevalent in X-Platform platforms, it's difficult to remain confident about that platform. Aren't the five lines of code required to implement this fix / ensure failure is logged (nice logging BTW) worth the end user inconvenience even if it is merely makeup? The vs. personality of the algorithm/argument is: "Nice headings dude, but, but, but, a word isn't printed because a) it contains illegal characters, b) etc. reasons. Sorry dude, I tried my best." vs. "Rookie Undefined Error dude. LOL - you seriously want me printing mo headings after that BS!". IE sucks, but the point of using typeface is to eliminate this issue. I don't think putting this fix on hold or on me is the way it should be. I get the point.
At EOD, typeface was used and the project was a success. However, it is unrealistic to expect shops to jump into 3rd party JavaScript libraries & build custom fixes. I fully understand the philosophy behind not fixing this problem however, I fail to see how not fixing this problem works in the best interest of typeface or the JS community.
Moreover, and to set the record straight for concerned readers: this problem is really uncommon. In any controlled environment it would be completely avoidable. This is a manifestation of how our lazy CMS (SharePoint 2010) emits character data with hexadecimal encoding (you know those invisible characters with "" values and character codes in the 80k range).
Typeface is there for you on the 99.9% side, my point merely talks to one specific circumstance in what is otherwise a really amazing product.
Over and Out.
Matt
01/06/2010
Need Help Moving Boat June 11th - Cleveland to Welland
I need help moving my C&C 40 Centerboard from Cleveland to Welland.
Please leave your contact information in a comment (will be moderated so nobody will see except me).
Please leave your contact information in a comment (will be moderated so nobody will see except me).
26/02/2010
SharePoint Folder Icon Changer JSON MetaData Provider Control
This is a follow up to my original post on How To Change Folder Icons in SharePoint MOSS Using JavaScript.
I'd encourage you to read that post first so you have at least a basic understanding of the JavaScript involved in actually changing the folder icons.
The .Net Custom Control is much simpler. Here is the complete code C# file fully commented:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EventPhotoGallery.Data;
using Microsoft.SharePoint;
namespace EventPhotoGallery
{
// Create a sub control object we can use on our ASPX page to define content type to icon mappings
[AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
public class IconMapping : WebControl
{
public string ContentTypeName { get; set; }
public string IconUrl { get; set; }
public string ThumbnailUrl { get; set; }
public string ToJSON()
{
return string.Format("'{0}': {{ ContentTypeName: '{0}', IconUrl: '{1}', ThumbnailUrl: '{2}' }}",
ContentTypeName.QuoteEscape(), IconUrl.QuoteEscape(), ThumbnailUrl.QuoteEscape());
}
}
// Create The master web control which compiles the ASPX arguments and registers a script
[ParseChildren(true, "IconMappings")]
[ToolboxData("<{0}:FolderContentTypeIconChanger runat=server>{0}:FolderContentTypeIconChanger>")]
public class FolderContentTypeIconChanger : WebControl, INamingContainer
{
// Define a key to register the MetaData JSON object with the .Net Page Rendering process
private const string FOLDERTYPESCRIPTKEY = "FolderContentTypeIconChanger";
// A list of our MetaData Controls defined above that will be subcontrols in ASPX
private List _IconMappings = new List();
public List IconMappings { get { return _IconMappings; } set { _IconMappings = value; } }
public string ListName { get; set; }
public string RootFolder { get; set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// when the AllItems.aspx page loads the current folder is always in the QueryString so let's grab it
if (!string.IsNullOrEmpty(Page.Request.QueryString["RootFolder"]))
RootFolder = Page.Request.QueryString["RootFolder"];
}
protected override void OnPreRender(EventArgs e)
{
// During prerendering let's build the JSON structure that the _AllItems object consumes.
if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), FOLDERTYPESCRIPTKEY))
Page.ClientScript.RegisterStartupScript(GetType(),
FOLDERTYPESCRIPTKEY, CreateScript(), true);
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
// Do nothing with the rendering cancel it - we don't need any html with this control the
// JavaScript has already been registered
//base.Render(writer);
}
// The worker horse - does all the work compiling the MetaData
private string CreateScript()
{
SPFolder folder;
// if there is no folder defined then we should use the root folder from the current context list
if (!string.IsNullOrEmpty(RootFolder))
folder = SPContext.Current.Site.RootWeb.GetFolder(RootFolder);
else
folder = SPContext.Current.Web.Lists[ListName].RootFolder;
// Get the SharePoint ContentType for the folder
string folderContentType = folder.Item != null ? (folder.Item.GetString(PhotoData.CONTENTTYPE) != null ?
folder.Item.GetString(PhotoData.CONTENTTYPE) : "Folder") : "Folder";
// Create a StringBuilder into which we will be appending JSON atoms
StringBuilder builder = new StringBuilder("var _FolderContentTypes = {");
// this is a custom data tier object which you're going to have to figure out on
// your own - if there is enough demand I can write another article with a
// comprehensive pattern to support folders in your document libraries
EPGData data = new EPGData();
// get all subfolders and list in json to the UI.
if (folder != null && folder.SubFolders.Count > 0)
{
// iterate all subfolders appending JSON Atoms to the script
foreach(SPFolder subFolder in folder.SubFolders)
builder.AppendLine(CreateFolderReference(subFolder.ServerRelativeUrl,
data.Folder.GetContentTypeName(subFolder), subFolder.Name));
// data.Folder.GetContentTypeName(subFolder) merely returns the name of the content type
builder.Remove(builder.Length - 3, 3); // remove the last comma
}
builder.AppendLine(string.Format("}};\n_FolderContentTypes.RootUrl = '{0}';", SPContext.Current.Site.Url.QuoteEscape()));
// QuoteEscape is an extension method which escapes all single quotes so the JavaScript is compliant
// add the icon mappings to the control
if (IconMappings.Count > 0)
{
builder.AppendLine("var _FolderContentTypeIconMaps = {");
foreach (IconMapping mapping in IconMappings)
{
builder.AppendLine(mapping.ToJSON() + ",");
}
builder.Remove(builder.Length-3,3).AppendLine("};");
}
builder.AppendLine(string.Format("\nvar _CurrentFolder = {{ Name: '{0}', ContentTypeName: '{1}' }};", folder.Name.QuoteEscape(), folderContentType.QuoteEscape()));
return builder.ToString();
}
private string CreateFolderReference(string folderUrl, string contentTypeName, string folderName)
{
return string.Format("'{0}':{{FolderName: '{2}', FolderUrl:'{0}', ContentType: '{1}'}},",
folderUrl.QuoteEscape(), contentTypeName.QuoteEscape(), folderName.QuoteEscape());
}
}
}
So there are a couple things you still have to figure out in your own implementation, but the above is a good starting point.
Now how do you add this to the page you may say - well - first, add the assembly to the GAC.
Then within the appropriate Template Folder find your AllItems.aspx page and add a directive to register the assembly as such:
<%@ Register TagPrefix="my" Namespace="EventPhotoGallery" Assembly="EventPhotoGallery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" %>
Next, somewhere in your ASPX code you can now add the JSON FolderContentTypeIconChanger control as such:
<my:FolderContentTypeIconChanger id="folderTypes" runat="server"
ListName="Event Photo Gallery Photographs">
<my:IconMapping ContentTypeName="Location Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Location_Folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Location_Folder-48x48.png" />
<my:IconMapping ContentTypeName="Event Photo Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Photo_folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Photo_folder-48x48.png" />
<my:IconMapping ContentTypeName="User Upload Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Upload_Folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Upload_Folder-48x48.png" />
</my:FolderContentTypeIconChanger>
I'm sure you can imagine what means what etc. but ya - this should get you going in adding custom icons to your SharePoint Folders.
Let me know if you have any other questions!
Over and Out
I'd encourage you to read that post first so you have at least a basic understanding of the JavaScript involved in actually changing the folder icons.
The .Net Custom Control is much simpler. Here is the complete code C# file fully commented:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EventPhotoGallery.Data;
using Microsoft.SharePoint;
namespace EventPhotoGallery
{
// Create a sub control object we can use on our ASPX page to define content type to icon mappings
[AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand,
Level = AspNetHostingPermissionLevel.Minimal)]
public class IconMapping : WebControl
{
public string ContentTypeName { get; set; }
public string IconUrl { get; set; }
public string ThumbnailUrl { get; set; }
public string ToJSON()
{
return string.Format("'{0}': {{ ContentTypeName: '{0}', IconUrl: '{1}', ThumbnailUrl: '{2}' }}",
ContentTypeName.QuoteEscape(), IconUrl.QuoteEscape(), ThumbnailUrl.QuoteEscape());
}
}
// Create The master web control which compiles the ASPX arguments and registers a script
[ParseChildren(true, "IconMappings")]
[ToolboxData("<{0}:FolderContentTypeIconChanger runat=server>{0}:FolderContentTypeIconChanger>")]
public class FolderContentTypeIconChanger : WebControl, INamingContainer
{
// Define a key to register the MetaData JSON object with the .Net Page Rendering process
private const string FOLDERTYPESCRIPTKEY = "FolderContentTypeIconChanger";
// A list of our MetaData Controls defined above that will be subcontrols in ASPX
private List
public List
public string ListName { get; set; }
public string RootFolder { get; set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// when the AllItems.aspx page loads the current folder is always in the QueryString so let's grab it
if (!string.IsNullOrEmpty(Page.Request.QueryString["RootFolder"]))
RootFolder = Page.Request.QueryString["RootFolder"];
}
protected override void OnPreRender(EventArgs e)
{
// During prerendering let's build the JSON structure that the _AllItems object consumes.
if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), FOLDERTYPESCRIPTKEY))
Page.ClientScript.RegisterStartupScript(GetType(),
FOLDERTYPESCRIPTKEY, CreateScript(), true);
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
// Do nothing with the rendering cancel it - we don't need any html with this control the
// JavaScript has already been registered
//base.Render(writer);
}
// The worker horse - does all the work compiling the MetaData
private string CreateScript()
{
SPFolder folder;
// if there is no folder defined then we should use the root folder from the current context list
if (!string.IsNullOrEmpty(RootFolder))
folder = SPContext.Current.Site.RootWeb.GetFolder(RootFolder);
else
folder = SPContext.Current.Web.Lists[ListName].RootFolder;
// Get the SharePoint ContentType for the folder
string folderContentType = folder.Item != null ? (folder.Item.GetString(PhotoData.CONTENTTYPE) != null ?
folder.Item.GetString(PhotoData.CONTENTTYPE) : "Folder") : "Folder";
// Create a StringBuilder into which we will be appending JSON atoms
StringBuilder builder = new StringBuilder("var _FolderContentTypes = {");
// this is a custom data tier object which you're going to have to figure out on
// your own - if there is enough demand I can write another article with a
// comprehensive pattern to support folders in your document libraries
EPGData data = new EPGData();
// get all subfolders and list in json to the UI.
if (folder != null && folder.SubFolders.Count > 0)
{
// iterate all subfolders appending JSON Atoms to the script
foreach(SPFolder subFolder in folder.SubFolders)
builder.AppendLine(CreateFolderReference(subFolder.ServerRelativeUrl,
data.Folder.GetContentTypeName(subFolder), subFolder.Name));
// data.Folder.GetContentTypeName(subFolder) merely returns the name of the content type
builder.Remove(builder.Length - 3, 3); // remove the last comma
}
builder.AppendLine(string.Format("}};\n_FolderContentTypes.RootUrl = '{0}';", SPContext.Current.Site.Url.QuoteEscape()));
// QuoteEscape is an extension method which escapes all single quotes so the JavaScript is compliant
// add the icon mappings to the control
if (IconMappings.Count > 0)
{
builder.AppendLine("var _FolderContentTypeIconMaps = {");
foreach (IconMapping mapping in IconMappings)
{
builder.AppendLine(mapping.ToJSON() + ",");
}
builder.Remove(builder.Length-3,3).AppendLine("};");
}
builder.AppendLine(string.Format("\nvar _CurrentFolder = {{ Name: '{0}', ContentTypeName: '{1}' }};", folder.Name.QuoteEscape(), folderContentType.QuoteEscape()));
return builder.ToString();
}
private string CreateFolderReference(string folderUrl, string contentTypeName, string folderName)
{
return string.Format("'{0}':{{FolderName: '{2}', FolderUrl:'{0}', ContentType: '{1}'}},",
folderUrl.QuoteEscape(), contentTypeName.QuoteEscape(), folderName.QuoteEscape());
}
}
}
So there are a couple things you still have to figure out in your own implementation, but the above is a good starting point.
Now how do you add this to the page you may say - well - first, add the assembly to the GAC.
Then within the appropriate Template Folder find your AllItems.aspx page and add a directive to register the assembly as such:
<%@ Register TagPrefix="my" Namespace="EventPhotoGallery" Assembly="EventPhotoGallery, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5" %>
Next, somewhere in your ASPX code you can now add the JSON FolderContentTypeIconChanger control as such:
<my:FolderContentTypeIconChanger id="folderTypes" runat="server"
ListName="Event Photo Gallery Photographs">
<my:IconMapping ContentTypeName="Location Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Location_Folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Location_Folder-48x48.png" />
<my:IconMapping ContentTypeName="Event Photo Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Photo_folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Photo_folder-48x48.png" />
<my:IconMapping ContentTypeName="User Upload Folder"
IconUrl="/_layouts/EventPhotoGallery/images/Upload_Folder-16x16.png"
ThumbnailUrl="/_layouts/EventPhotoGallery/images/Upload_Folder-48x48.png" />
</my:FolderContentTypeIconChanger>
I'm sure you can imagine what means what etc. but ya - this should get you going in adding custom icons to your SharePoint Folders.
Let me know if you have any other questions!
Over and Out
Change Folder Icons In MOSS / SharePoint Using JavaScript
I hope you guys find this code useful in changing default folder icons using JavaScript.
Before that - I want to point out that many people are of the opinion that Folders should be avoided at all costs in SharePoint. While I appreciate the perspective there, I believe it merely shows there is a gap in the technology platform.
I believe that once that gap is filled (EX// through CustomActions, EventReciever Methods) they actually become a pretty valuable resource in allowing old school business users to transition from windows based folder system - to a web based folder system - which opens them up to the more modern ways of locating resources VIA search / taxanomy. Moreover, how many SharePoint business developers out there haven't had a client ask for Folders?
OK - to the JavaScript. I want to start off by pointing out that this entire methodolgy will most likely be ineffective if you've customized the List Views (if the HTML structure is different the JavaScript below will not be able to find the correct HTML elements to change).
Before you start - you're going to need to grab a copy of this cross browser getElementsByClassName method and add it to your script (It's tha bomb if your architecture prohibits the use of jQuery :().
First, I create a couple JSON objects to hold Meta Data about my ContentTypes / Folders (I actually use a .Net Custom Control to auto generate this dynamically when the View loads - check here for that code):
// This data structure contains information about the folders at this particular level
// in the folder hierarchy within the current AllItems view
var _FolderContentTypes = {
// Key the list By Folder URL as we'll use it as a Lookup later
'/Lists/EventPhotoGalleryPhotographs/User Uploads':
{
// All metadata related to above folder
FolderName: 'User Uploads',
FolderUrl:'/Lists/EventPhotoGalleryPhotographs/User Uploads',
ContentType: 'User Upload Folder'
},
// next folder
'/Lists/EventPhotoGalleryPhotographs/Forms':
{
// more metadata
FolderName: 'Forms',
FolderUrl:'/Lists/EventPhotoGalleryPhotographs/Forms',
ContentType: 'Folder'
}
};
// next we'll setup the root url to use as a reference
_FolderContentTypes.RootUrl = 'http://mtw-sharepoint';
// The second data structure we create maps ContentTypes to Icon Urls as such
var _FolderContentTypeIconMaps = {
// The SharePoint ContentType 'Location Folder'
'Location Folder':
{
ContentTypeName: 'Location Folder',
// icon to use in details view
IconUrl: '/_layouts/EventPhotoGallery/images/Location_Folder-16x16.png',
// icon to use in thumbnails view
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Location_Folder-48x48.png'
},
// Another SharePoint Folder ContentType
'Event Photo Folder':
{
// more meta data
ContentTypeName: 'Event Photo Folder',
IconUrl: '/_layouts/EventPhotoGallery/images/Photo_folder-16x16.png',
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Photo_folder-48x48.png'
},
// Another SharePoint ContentType etc...
'User Upload Folder': {
ContentTypeName: 'User Upload Folder',
IconUrl: '/_layouts/EventPhotoGallery/images/Upload_Folder-16x16.png',
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Upload_Folder-48x48.png'
}
};
Next I'll create a worker object I can use in my _AllItems view that actually does the dirty work. This can be saved in a JavaScript file / cached in the client browser:
var _AllItems = {
// create the initialization method which will execute when the window has loaded
Initialize: function() {
// This section sets the small icons when in details view
var folders = getElementsByClassName("ms-vb-icon");
// if there are no folders then don't try changing icons
if (folders.length > 0) { // this method works when we are in details view
// define a constant to recognize if we are in the root folder
var rf = "RootFolder=";
// loop through each HTMLElement that was returned with the ms-vb-icon class selector
for (var intCnt = 0; intCnt < folders.length; intCnt++) {
// perform some string parsing in order to figure out the URL of the folder as
// this is what we use as our Key in determining which Icon to apply to the folder var startPos = folders[intCnt].firstChild.search.indexOf(rf) + rf.length;
var endPos = folders[intCnt].firstChild.search.indexOf("&", folders[intCnt].firstChild.search.indexOf(rf) + rf.length + 1);
// get the folder URL and replace all SharePoint Url Hexidecimal's to get a pure Url reference var listUrl = folders[intCnt].firstChild.search.substr(startPos, endPos - startPos);
listUrl = listUrl.replace(/%2f/g, "/").replace(/%20/g, " ");
// double check to make sure this particular folders' URL exists in our _FolderContentTypes
// meta data object
if (_FolderContentTypes[listUrl] != null) {
// double check that our _FolderContentTypeIconMaps data structure contains the ContentType
// for which we want to apply a custom icon to
if (_FolderContentTypeIconMaps[_FolderContentTypes[listUrl].ContentType] != null) {
// now actually change the icon url to the new URL we have specified in our iconmap folders[intCnt].firstChild.firstChild.src = _FolderContentTypes.RootUrl + _FolderContentTypeIconMaps[_FolderContentTypes[listUrl].ContentType].IconUrl; }
}
}
}
// The following section repeats the above methodology for the _AllItems
// thumbnail view using larger custom icons folders = getElementsByClassName("thumbnail"); if (folders.length > 0) {
// this method works when we are in thumbnail view
for (var intCnt = 0; intCnt < folders.length; intCnt++) {
// you can see just how sketchy this method is - I surround it in a try catch blatantly
// because I'm too lazy to code the massive statement required to make sure each
// element exists programatically try { var imgObj = folders[intCnt].firstChild.firstChild
.firstChild.firstChild.firstChild.firstChild
.firstChild.firstChild.firstChild.firstChild; } catch (ex) { }
// The difference here is we'll see every thumbnail icon on the page so we have // to double check the icon is actually the default SharePoint folder icon
if (imgObj != null && imgObj.src.indexOf("fldrnew.gif") > -1) {
var folder =
this.GetFolderByName(folders[intCnt].firstChild.firstChild.children[1].firstChild.innerText);
// Again, ensure the icon map contains an icon for this folders content type
if (_FolderContentTypeIconMaps[folder.ContentType] != null) {
// Actually change the thumbnail icon source
imgObj.src = _FolderContentTypes.RootUrl + _FolderContentTypeIconMaps[folder.ContentType].ThumbnailUrl;
// The icons I used were a specific constant size so I adjusted the style props as required
imgObj.style.width = "auto";
imgObj.style.height = "48px";
imgObj.title = folder.ContentType;
}
}
imgObj = null; // Just kill the obj ref
}
}
},
// This method gets the real folder name
GetFolderByName: function(folderName) {
if (folderName != null) {
folderName = folderName.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
for (var f in _FolderContentTypes) {
if (_FolderContentTypes[f].FolderName == folderName)
return _FolderContentTypes[f];
}
}
},
// This is the startup method that should be called when the window loads
StartUp: function() {
var ol = window.onload;
if (ol != null) {
window.onload = function(e) {
ol(e);
_AllItems.Initialize();
}
} else {
window.onload = function() { _AllItemsInit.ialize(); }
}
}
};
// Wire up object initialization
_AllItems.StartUp();
And that's about it. When the window has completed loading _AllItems.Initialize() is called which changes the src property on all SharePoint icons. With the metadata provided the above example changes one folders' icons - the "User Upload" ContentType folder.
Obviously the above could be greatly simplified using jQuery - you could probably do it in about 15 lines (I'd encourage someone to do that and flip a trackback below).
Blah Blah Blah - The .Net Control which produces the JSON metadata
Before that - I want to point out that many people are of the opinion that Folders should be avoided at all costs in SharePoint. While I appreciate the perspective there, I believe it merely shows there is a gap in the technology platform.
I believe that once that gap is filled (EX// through CustomActions, EventReciever Methods) they actually become a pretty valuable resource in allowing old school business users to transition from windows based folder system - to a web based folder system - which opens them up to the more modern ways of locating resources VIA search / taxanomy. Moreover, how many SharePoint business developers out there haven't had a client ask for Folders?
OK - to the JavaScript. I want to start off by pointing out that this entire methodolgy will most likely be ineffective if you've customized the List Views (if the HTML structure is different the JavaScript below will not be able to find the correct HTML elements to change).
Before you start - you're going to need to grab a copy of this cross browser getElementsByClassName method and add it to your script (It's tha bomb if your architecture prohibits the use of jQuery :().
First, I create a couple JSON objects to hold Meta Data about my ContentTypes / Folders (I actually use a .Net Custom Control to auto generate this dynamically when the View loads - check here for that code):
// This data structure contains information about the folders at this particular level
// in the folder hierarchy within the current AllItems view
var _FolderContentTypes = {
// Key the list By Folder URL as we'll use it as a Lookup later
'/Lists/EventPhotoGalleryPhotographs/User Uploads':
{
// All metadata related to above folder
FolderName: 'User Uploads',
FolderUrl:'/Lists/EventPhotoGalleryPhotographs/User Uploads',
ContentType: 'User Upload Folder'
},
// next folder
'/Lists/EventPhotoGalleryPhotographs/Forms':
{
// more metadata
FolderName: 'Forms',
FolderUrl:'/Lists/EventPhotoGalleryPhotographs/Forms',
ContentType: 'Folder'
}
};
// next we'll setup the root url to use as a reference
_FolderContentTypes.RootUrl = 'http://mtw-sharepoint';
// The second data structure we create maps ContentTypes to Icon Urls as such
var _FolderContentTypeIconMaps = {
// The SharePoint ContentType 'Location Folder'
'Location Folder':
{
ContentTypeName: 'Location Folder',
// icon to use in details view
IconUrl: '/_layouts/EventPhotoGallery/images/Location_Folder-16x16.png',
// icon to use in thumbnails view
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Location_Folder-48x48.png'
},
// Another SharePoint Folder ContentType
'Event Photo Folder':
{
// more meta data
ContentTypeName: 'Event Photo Folder',
IconUrl: '/_layouts/EventPhotoGallery/images/Photo_folder-16x16.png',
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Photo_folder-48x48.png'
},
// Another SharePoint ContentType etc...
'User Upload Folder': {
ContentTypeName: 'User Upload Folder',
IconUrl: '/_layouts/EventPhotoGallery/images/Upload_Folder-16x16.png',
ThumbnailUrl: '/_layouts/EventPhotoGallery/images/Upload_Folder-48x48.png'
}
};
Next I'll create a worker object I can use in my _AllItems view that actually does the dirty work. This can be saved in a JavaScript file / cached in the client browser:
var _AllItems = {
// create the initialization method which will execute when the window has loaded
Initialize: function() {
// This section sets the small icons when in details view
var folders = getElementsByClassName("ms-vb-icon");
// if there are no folders then don't try changing icons
if (folders.length > 0) { // this method works when we are in details view
// define a constant to recognize if we are in the root folder
var rf = "RootFolder=";
// loop through each HTMLElement that was returned with the ms-vb-icon class selector
for (var intCnt = 0; intCnt < folders.length; intCnt++) {
// perform some string parsing in order to figure out the URL of the folder as
// this is what we use as our Key in determining which Icon to apply to the folder var startPos = folders[intCnt].firstChild.search.indexOf(rf) + rf.length;
var endPos = folders[intCnt].firstChild.search.indexOf("&", folders[intCnt].firstChild.search.indexOf(rf) + rf.length + 1);
// get the folder URL and replace all SharePoint Url Hexidecimal's to get a pure Url reference var listUrl = folders[intCnt].firstChild.search.substr(startPos, endPos - startPos);
listUrl = listUrl.replace(/%2f/g, "/").replace(/%20/g, " ");
// double check to make sure this particular folders' URL exists in our _FolderContentTypes
// meta data object
if (_FolderContentTypes[listUrl] != null) {
// double check that our _FolderContentTypeIconMaps data structure contains the ContentType
// for which we want to apply a custom icon to
if (_FolderContentTypeIconMaps[_FolderContentTypes[listUrl].ContentType] != null) {
// now actually change the icon url to the new URL we have specified in our iconmap folders[intCnt].firstChild.firstChild.src = _FolderContentTypes.RootUrl + _FolderContentTypeIconMaps[_FolderContentTypes[listUrl].ContentType].IconUrl; }
}
}
}
// The following section repeats the above methodology for the _AllItems
// thumbnail view using larger custom icons folders = getElementsByClassName("thumbnail"); if (folders.length > 0) {
// this method works when we are in thumbnail view
for (var intCnt = 0; intCnt < folders.length; intCnt++) {
// you can see just how sketchy this method is - I surround it in a try catch blatantly
// because I'm too lazy to code the massive statement required to make sure each
// element exists programatically try { var imgObj = folders[intCnt].firstChild.firstChild
.firstChild.firstChild.firstChild.firstChild
.firstChild.firstChild.firstChild.firstChild; } catch (ex) { }
// The difference here is we'll see every thumbnail icon on the page so we have // to double check the icon is actually the default SharePoint folder icon
if (imgObj != null && imgObj.src.indexOf("fldrnew.gif") > -1) {
var folder =
this.GetFolderByName(folders[intCnt].firstChild.firstChild.children[1].firstChild.innerText);
// Again, ensure the icon map contains an icon for this folders content type
if (_FolderContentTypeIconMaps[folder.ContentType] != null) {
// Actually change the thumbnail icon source
imgObj.src = _FolderContentTypes.RootUrl + _FolderContentTypeIconMaps[folder.ContentType].ThumbnailUrl;
// The icons I used were a specific constant size so I adjusted the style props as required
imgObj.style.width = "auto";
imgObj.style.height = "48px";
imgObj.title = folder.ContentType;
}
}
imgObj = null; // Just kill the obj ref
}
}
},
// This method gets the real folder name
GetFolderByName: function(folderName) {
if (folderName != null) {
folderName = folderName.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
for (var f in _FolderContentTypes) {
if (_FolderContentTypes[f].FolderName == folderName)
return _FolderContentTypes[f];
}
}
},
// This is the startup method that should be called when the window loads
StartUp: function() {
var ol = window.onload;
if (ol != null) {
window.onload = function(e) {
ol(e);
_AllItems.Initialize();
}
} else {
window.onload = function() { _AllItemsInit.ialize(); }
}
}
};
// Wire up object initialization
_AllItems.StartUp();
And that's about it. When the window has completed loading _AllItems.Initialize() is called which changes the src property on all SharePoint icons. With the metadata provided the above example changes one folders' icons - the "User Upload" ContentType folder.
Obviously the above could be greatly simplified using jQuery - you could probably do it in about 15 lines (I'd encourage someone to do that and flip a trackback below).
Blah Blah Blah - The .Net Control which produces the JSON metadata
20/02/2010
JavaScript / C# Hack to For Latency Simulation In ASP.Net Web Applications
When developing AJAX functionality sometimes a latency simulation can be quite revealing. The following four lines of code serve as an interception point injecting a user specified network delay in serving network resources for UI testing purposes.
If you use your imagination a bit, and leverage the power of jQuery selectors, one can quickly build a network latency injector for help in developing those tough to test RIA interfaces. I hope you enjoy:
1) Create a new WebForm Called ImageLatencySimulator.aspx in the root of your web application.
2) Within the .aspx file delete all the html markup so only the @Page level declaration is visible (optional).
3) In the Page Load event of the .aspx.cs(.vb) file add the following code (C#, message me for VB):
int delay = Convert.ToInt32( Request.QueryString["delay"] );
string redirectTo = Request.QueryString["redirect"];
System.Threading.Thread.Sleep(delay);
Response.Redirect(Page.ResolveUrl(redirectTo));
// quite simple really isn't it? ya ya ya parse the int properly and perform appropriate null checks ... play your little violin for me before commenting ...
4) Add an image to the images directory within the root of your web application named.gif;
5) Add another WebForm or Html File to your project in the same level in the hierarchy as ImageLatencySimulator.aspx called LatencyTest.aspx|html.
5) Within the body tag in the LatencyTest.html file add an image tag with the src attribute pointing to ImageLatencySimulator.aspx with the appropriate get params as such:
.gif" alt="latency example redirect" />
6) Run the project.
You should notice all requests for your image resource are now being redirected through the ImageLatencySimulator.aspx and therefore are subject to your user defined delay parameter of 5000 miliseconds. Your waterfall diagram is now visibly apparent as the page loads.
OK - so why is this cool at all you may ask? We'll, imagine I add a #if declaration to my .Net assembly which registers a piece of JavaScript on my page when running in debug mode that does the following (using jQuery):
$(document).ready(function() {
$("img").each(function() {
$(this).attr("src") = "ImageLatencySimulator.aspx?delay=500&redirectTo=" + $(this).attr("src");
});
});
// coded the above in WYSIWYG editor so message me if it doesn't work.
If you can read jQuery code then it should be obvious - the previous code injects a network delay against every image on your entire web page simulating network latency in any and every web browser!! Now go add an eTag (PageOutput Cache in ASP.Net) to your ImageLatencySimulatory.aspx file and test out your cache layer. Just add a random parameter at the end of the GET string to invalidate the cache and you have an extremely simple network latency simulator for use in development.
I'd encourage you to get creative with the jQuery part of this algorithm, add the appropriate type checks to the C# component - see what else you can simulate latency for - use templates for urls - I personally find this technique invaluably simple - simple to implement, simple to expalin, simple to advocate for - and in the spirit of KISS, that makes me warm and fuzzy.
Over and Out
If you use your imagination a bit, and leverage the power of jQuery selectors, one can quickly build a network latency injector for help in developing those tough to test RIA interfaces. I hope you enjoy:
1) Create a new WebForm Called ImageLatencySimulator.aspx in the root of your web application.
2) Within the .aspx file delete all the html markup so only the @Page level declaration is visible (optional).
3) In the Page Load event of the .aspx.cs(.vb) file add the following code (C#, message me for VB):
int delay = Convert.ToInt32( Request.QueryString["delay"] );
string redirectTo = Request.QueryString["redirect"];
System.Threading.Thread.Sleep(delay);
Response.Redirect(Page.ResolveUrl(redirectTo));
// quite simple really isn't it? ya ya ya parse the int properly and perform appropriate null checks ... play your little violin for me before commenting ...
4) Add an image to the images directory within the root of your web application named
5) Add another WebForm or Html File to your project in the same level in the hierarchy as ImageLatencySimulator.aspx called LatencyTest.aspx|html.
5) Within the body tag in the LatencyTest.html file add an image tag with the src attribute pointing to ImageLatencySimulator.aspx with the appropriate get params as such:
6) Run the project.
You should notice all requests for your image resource are now being redirected through the ImageLatencySimulator.aspx and therefore are subject to your user defined delay parameter of 5000 miliseconds. Your waterfall diagram is now visibly apparent as the page loads.
OK - so why is this cool at all you may ask? We'll, imagine I add a #if declaration to my .Net assembly which registers a piece of JavaScript on my page when running in debug mode that does the following (using jQuery):
$(document).ready(function() {
$("img").each(function() {
$(this).attr("src") = "ImageLatencySimulator.aspx?delay=500&redirectTo=" + $(this).attr("src");
});
});
// coded the above in WYSIWYG editor so message me if it doesn't work.
If you can read jQuery code then it should be obvious - the previous code injects a network delay against every image on your entire web page simulating network latency in any and every web browser!! Now go add an eTag (PageOutput Cache in ASP.Net) to your ImageLatencySimulatory.aspx file and test out your cache layer. Just add a random parameter at the end of the GET string to invalidate the cache and you have an extremely simple network latency simulator for use in development.
I'd encourage you to get creative with the jQuery part of this algorithm, add the appropriate type checks to the C# component - see what else you can simulate latency for - use templates for urls - I personally find this technique invaluably simple - simple to implement, simple to expalin, simple to advocate for - and in the spirit of KISS, that makes me warm and fuzzy.
Over and Out
18/02/2010
AOP: Aspect Oriented Programming
AOP goes like this: If it's not part of your core logic it's an aspect and should in some way be separated from your core algorithm.
In a more literal sense, Aspects are application infrastructure components, as a foundation is to a house, Aspects are to a software application. Now how does this differ from OOP?
The intention of Aspect Oriented Programming is two fold:
Some of you may argue AOP is no more than another level of abstraction in OOP, and you'd be correct in saying that. I personally find the theory interesting, but the practice a bit defeatist. As a .Net developer, I'm sure I'd prefer using the built in .Net Roles & Members over AOP, but, heck, if I can make my code more readable I'm up for giving it a shot.
Here are some interesting articles which talk to AOP, and a simple AspectF implementation (which isn't real AOP) by the creator of pageflakes.com:
Aspect Oriented Programming Wikipedia
AspectF Fluent Way to Add Aspects for Cleaner Maintainable Code
AspectF Simple way to cache objects and collections for greater performance and scalability
What do you think about AOP?
Over and Out
In a more literal sense, Aspects are application infrastructure components, as a foundation is to a house, Aspects are to a software application. Now how does this differ from OOP?
The intention of Aspect Oriented Programming is two fold:
- Separation of Concern: the separation and centralization of application logic in a non redundant fashion.
- Cross Cutting: entanglement of application logic within a program resulting in scattering tangling or both.
Some of you may argue AOP is no more than another level of abstraction in OOP, and you'd be correct in saying that. I personally find the theory interesting, but the practice a bit defeatist. As a .Net developer, I'm sure I'd prefer using the built in .Net Roles & Members over AOP, but, heck, if I can make my code more readable I'm up for giving it a shot.
Here are some interesting articles which talk to AOP, and a simple AspectF implementation (which isn't real AOP) by the creator of pageflakes.com:
Aspect Oriented Programming Wikipedia
AspectF Fluent Way to Add Aspects for Cleaner Maintainable Code
AspectF Simple way to cache objects and collections for greater performance and scalability
What do you think about AOP?
Over and Out
09/11/2009
Uri Extension Method: AbsolutePathNoFile()
How often do you want to determine the absolute URI from any url without the specific file reference and without the query string variables. This is especially useful in many SharePoint tasks.
Here is a little extension method that can do just that. Pop this in a static class and try calling it on your Uri object:
public static UriExtensions {
public static string AbsolutePathNoFile(this Uri theUri)
{
string retVal = "http://" + theUri.Host + (theUri.Port == 80 ? "" : ":" + theUri.Port.ToString());
for (int intCnt = 0; intCnt < theUri.Segments.Length-1; intCnt++) {
retVal += theUri.Segments[intCnt];
}
return retVal;
}
}
// somewhere else:
Uri u = new Uri(Request.Url);
MessageBox.Show(u.AbsolutePathNoFile());
Over and Out
Here is a little extension method that can do just that. Pop this in a static class and try calling it on your Uri object:
public static UriExtensions {
public static string AbsolutePathNoFile(this Uri theUri)
{
string retVal = "http://" + theUri.Host + (theUri.Port == 80 ? "" : ":" + theUri.Port.ToString());
for (int intCnt = 0; intCnt < theUri.Segments.Length-1; intCnt++) {
retVal += theUri.Segments[intCnt];
}
return retVal;
}
}
// somewhere else:
Uri u = new Uri(Request.Url);
MessageBox.Show(u.AbsolutePathNoFile());
Over and Out
02/11/2009
Google Wave Is Here: But I have no Friends
I am online with the Google Wave beta. It is cool, takes a bit of getting use to. But this is NOT going to replace my normal email account anytime soon - This is no Tsunami. I do however hope it does replace my email account ASAP - Especially on my iPhone!
The most major thing I don't understand about Google Wave is: How can I message people that do not have Google Wave accounts? Wouldn't this be the obvious way to get other people on board (is this merely not happening because this is a VERY early preview version)? Right now I can't so this means I can't use it for much (start playing little violin here).
My main contacts did not jump at the chance to subscribe to the Beta so I am now sitting in an ocean waiting to catch a wave.
Stay tuned for Google Wave invitation give away. I have nominated 20 of my closest digital friends for Google Wave accounts and am waiting for google to lick the stamps.
And so goes the life of a surfer.
Over and Out.
The most major thing I don't understand about Google Wave is: How can I message people that do not have Google Wave accounts? Wouldn't this be the obvious way to get other people on board (is this merely not happening because this is a VERY early preview version)? Right now I can't so this means I can't use it for much (start playing little violin here).
My main contacts did not jump at the chance to subscribe to the Beta so I am now sitting in an ocean waiting to catch a wave.
Stay tuned for Google Wave invitation give away. I have nominated 20 of my closest digital friends for Google Wave accounts and am waiting for google to lick the stamps.
And so goes the life of a surfer.
Over and Out.
16/10/2009
Comments Open To Everyone
As an experiment I have decided to open my comments to everyone to see if it impacts my site traffic. This will be a fun experiment.
Happy Birthday To Me
My birthday is today, was yesterday, is tomorrow or is at some point next / last week.
I wanted to wish myself a Happy Birthday on my blog ... so ... Happy Birthday to me ...
I wanted to wish myself a Happy Birthday on my blog ... so ... Happy Birthday to me ...
06/10/2009
SharePoint Tips: Content Type Visibility on NewMenu
I've built a solution with a few custom ContentTypes in a list definition. Now, removing these from the NewMenu has to be easy right? Just add a HideCustomAction definition to your instance file. Not so easy to find the ID's that will be used for those content types is it? Well, here is a solution that will remove the ContentTypes from the NewMenu but allow them to hang around for use in defining whatever it is your heart desires.
To specify visibility on the Microsoft.SharePoint.StandardMenu.NewMenu in a document library, try changing the RequiredClientRenderingOnNew option to false, and update the content type definition as below:
The correct solution for document libraries is the following:
SPWeb web = SPContext.Current.Site.RootWeb;
web.AllowUnsafeUpdates = true;// if done on get
SPList list = web.Lists["LIST NAME LIST NAME PUT LIST NAME OR GUID HERE"];
foreach (SPContentType ct in list.ContentTypes)
{
if (ct.Name == "Content Type Name")
{
ct.Hidden = true;
ct.RequireClientRenderingOnNew = false;
ct.Update();
}
}
web.AllowUnsafeUpdates = false;// if done on get
I'm doing this in a feature receiver and it works by design. If done in AllItems.aspx (or any GET request it seems) you need to refresh the page twice for this to work by design (one refresh appears to set the value in content type but this is done after it's read into the display).
The other thing I've got in that habit of doing is force deleting lists when I make changes. I'm not sure how "required" this is but in order to get stability in my test results this seems to make a difference.
Here is how I was force deleting the offending lists:
stsadm -o forcedeletelist -url http://SERVERNAME:PORT/Lists/LISTNAMELISTURLNAMELISTURLNAME
Wish SharePoint would work as advertised ... sigh ...
To specify visibility on the Microsoft.SharePoint.StandardMenu.NewMenu in a document library, try changing the RequiredClientRenderingOnNew option to false, and update the content type definition as below:
The correct solution for document libraries is the following:
SPWeb web = SPContext.Current.Site.RootWeb;
web.AllowUnsafeUpdates = true;// if done on get
SPList list = web.Lists["LIST NAME LIST NAME PUT LIST NAME OR GUID HERE"];
foreach (SPContentType ct in list.ContentTypes)
{
if (ct.Name == "Content Type Name")
{
ct.Hidden = true;
ct.RequireClientRenderingOnNew = false;
ct.Update();
}
}
web.AllowUnsafeUpdates = false;// if done on get
I'm doing this in a feature receiver and it works by design. If done in AllItems.aspx (or any GET request it seems) you need to refresh the page twice for this to work by design (one refresh appears to set the value in content type but this is done after it's read into the display).
The other thing I've got in that habit of doing is force deleting lists when I make changes. I'm not sure how "required" this is but in order to get stability in my test results this seems to make a difference.
Here is how I was force deleting the offending lists:
stsadm -o forcedeletelist -url http://SERVERNAME:PORT/Lists/LISTNAMELISTURLNAMELISTURLNAME
Wish SharePoint would work as advertised ... sigh ...
18/09/2009
14/08/2009
Clear | Remove Query Strings From Post Backs (ASP.Net, SharePoint)
As part of an unorthodox request I was asked to make a TabStrip component SEO friendly. My first thought was to completely rewrite the control to make use of GET requests rather than continuing to POST the data back to the server.
Immediately I ran into a problem with this approach as the developers of this site have implemented the majority of these TabStrip controls inside the ASP.Net UpdatePanel (don't get me started with these) which does not recognize GET requests as Async events.
The architect of this site (actually a SharePoint site) failed to recognize that the SharePoint indexing service would not be able to index information on any tab other than the default one (as subsequent requests for tab data are done using Asynchronous Events). When project management asked him to modify the tabs for accessibility he told them it was impossible without a complete redesign.
As a solution to this problem I modified the TabStrip control such that it renders an anchor tag rather than a link button and added some fancy JavaScript to cancel the Anchor tag click event and trigger the appropriate __doPostBack option. I now have a crawl able anchor tag, which works like a link button, and triggers the appropriate update.
Moreover, when the TabStrip is initialized (OnInit) it looks for a specific query string variable indicating the ID of the selected tab. This is when the real problem starts:
My quest turned to the Google.
First I found this approach which actually removes the query string VIA triggering a post back and is therefore too wasteful to be my solution.
I then found the following approach which unfortunately fails to load as it uses the ugly document.all JavaScript method which isn't available until after page load (therefore causes a client side exception - even when registered properly as a StartupScript).
I put together a slightly different JavaScript routine that looks like this:
if(window.onload != null) {
var wol = window.onload;
window.onload = function(e) {
wol(e);
document.forms[0].action = "Index.aspx";
}
} else {
window.onload = function() {
document.forms[0].action = "Index.aspx";
}
}
This JavaScript Method then rolls nicely into an ASP.Net Server Control like so:
///
/// Attempt to remove the tab id from the query string
///
private void AddRemoveTabIdQueryString()
{
const string key = "REMOVETABIDQUERYSTRING";
if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), key))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), key,
string.Format("if(window.onload != null) {{var wol = window.onload;window.onload = function(e) {{wol(e);{0};}}}} else {{window.onload = function() {{document.forms[0].action = \"{0}\";;}}}}", GetRequestPageName()), true);
}
// Get the page Name of the request
private string GetRequestPageName()
{
string rawUrl = Page.Request.RawUrl;
int pos = rawUrl.LastIndexOf("/");
int qpos = rawUrl.LastIndexOf("?");
return qpos > -1 ? rawUrl.Substring(pos + 1, qpos - pos - 1) :
rawUrl.Substring(pos + 1, rawUrl.Length - pos - 1);
}
I hope this is helpful to others.
Over and Out
Immediately I ran into a problem with this approach as the developers of this site have implemented the majority of these TabStrip controls inside the ASP.Net UpdatePanel (don't get me started with these) which does not recognize GET requests as Async events.
The architect of this site (actually a SharePoint site) failed to recognize that the SharePoint indexing service would not be able to index information on any tab other than the default one (as subsequent requests for tab data are done using Asynchronous Events). When project management asked him to modify the tabs for accessibility he told them it was impossible without a complete redesign.
As a solution to this problem I modified the TabStrip control such that it renders an anchor tag rather than a link button and added some fancy JavaScript to cancel the Anchor tag click event and trigger the appropriate __doPostBack option. I now have a crawl able anchor tag, which works like a link button, and triggers the appropriate update.
Moreover, when the TabStrip is initialized (OnInit) it looks for a specific query string variable indicating the ID of the selected tab. This is when the real problem starts:
- Indexing service crawls the anchor and builds a GET string reference to the selected tab id.
- Page is loaded into browser.
- User selects different tab.
- TabStrip is initialized finding the previous (last selected tab) tab id.
- TabStrip raises MenuItem Click event ignoring the actual new selected tab id.
My quest turned to the Google.
First I found this approach which actually removes the query string VIA triggering a post back and is therefore too wasteful to be my solution.
I then found the following approach which unfortunately fails to load as it uses the ugly document.all JavaScript method which isn't available until after page load (therefore causes a client side exception - even when registered properly as a StartupScript).
I put together a slightly different JavaScript routine that looks like this:
if(window.onload != null) {
var wol = window.onload;
window.onload = function(e) {
wol(e);
document.forms[0].action = "Index.aspx";
}
} else {
window.onload = function() {
document.forms[0].action = "Index.aspx";
}
}
This JavaScript Method then rolls nicely into an ASP.Net Server Control like so:
///
/// Attempt to remove the tab id from the query string
///
private void AddRemoveTabIdQueryString()
{
const string key = "REMOVETABIDQUERYSTRING";
if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), key))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), key,
string.Format("if(window.onload != null) {{var wol = window.onload;window.onload = function(e) {{wol(e);{0};}}}} else {{window.onload = function() {{document.forms[0].action = \"{0}\";;}}}}", GetRequestPageName()), true);
}
// Get the page Name of the request
private string GetRequestPageName()
{
string rawUrl = Page.Request.RawUrl;
int pos = rawUrl.LastIndexOf("/");
int qpos = rawUrl.LastIndexOf("?");
return qpos > -1 ? rawUrl.Substring(pos + 1, qpos - pos - 1) :
rawUrl.Substring(pos + 1, rawUrl.Length - pos - 1);
}
I hope this is helpful to others.
Over and Out
13/08/2009
SPJobDefinition Quirks For Developers
I wanted to write a quick heads up on a couple quirks relating to the SPJobDefinition and wiring up Timer Jobs (may be relevant for deployments where the Timer Jobs are modified). We are building our solutions on Windows 2003 Server with MOSS 2007.
To debug SPJobDefinitions attach VS debugger to OWSTIMER.exe process after following install instructions below.
OWSTIMER is caching the SPJobDefinition somewhere and is tricking Visual Studio into thinking we are actually debugging the most recent compiled version when we are debugging the last loaded version.
To fix this, kill the OWSTIMER process in process explorer (or restart the Windows Sharepoint Services Timer by typing the following at the command prompt: net stop sptimerv3 & net start sptimerv3) and then refresh the portal you are performing development on (this will force a restart of OWSTIMER.EXE and clear the cache).
Between tests ensure you completely remove the SharePoint feature (deactivate + uninstall) from Sharepoint (see below). Then kill the OWSTIMER process, iisreset, rebuild the solution and reinstall / activate the solution again (see below).
Here are a couple batch files convenient for removing / installing the jobs (where ProvisioningVX is the name of the feature you are trying to install):
Uninstall Batch File
@ECHO OFF
set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server extensions\12\BIN\stsadm.exe
set TargetUrl=http://servername/sites/name
echo "Deactivating Feature"
"%SPAdminTool%" -o deactivatefeature -name ProvisioningVX -url %TargetUrl% -force
echo "Uninstalling Feature"
"%SPAdminTool%" -o uninstallfeature -name ProvisioningVX -force
iisreset
PAUSE
Installing and activating the feature
@ECHO OFF
set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server extensions\12\BIN\stsadm.exe
set TargetUrl=http://servername/sites/name
echo "installing feature"
"%SPAdminTool%" -o installfeature -name ProvisioningVX -force
echo "activating feature"
"%SPAdminTool%" -o activatefeature -name ProvisioningVX -url %TargetUrl% -force
iisreset
PAUSE
To debug SPJobDefinitions attach VS debugger to OWSTIMER.exe process after following install instructions below.
OWSTIMER is caching the SPJobDefinition somewhere and is tricking Visual Studio into thinking we are actually debugging the most recent compiled version when we are debugging the last loaded version.
To fix this, kill the OWSTIMER process in process explorer (or restart the Windows Sharepoint Services Timer by typing the following at the command prompt: net stop sptimerv3 & net start sptimerv3) and then refresh the portal you are performing development on (this will force a restart of OWSTIMER.EXE and clear the cache).
Between tests ensure you completely remove the SharePoint feature (deactivate + uninstall) from Sharepoint (see below). Then kill the OWSTIMER process, iisreset, rebuild the solution and reinstall / activate the solution again (see below).
Here are a couple batch files convenient for removing / installing the jobs (where ProvisioningVX is the name of the feature you are trying to install):
Uninstall Batch File
@ECHO OFF
set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server extensions\12\BIN\stsadm.exe
set TargetUrl=http://servername/sites/name
echo "Deactivating Feature"
"%SPAdminTool%" -o deactivatefeature -name ProvisioningVX -url %TargetUrl% -force
echo "Uninstalling Feature"
"%SPAdminTool%" -o uninstallfeature -name ProvisioningVX -force
iisreset
PAUSE
Installing and activating the feature
@ECHO OFF
set SPAdminTool=%CommonProgramFiles%\Microsoft Shared\web server extensions\12\BIN\stsadm.exe
set TargetUrl=http://servername/sites/name
echo "installing feature"
"%SPAdminTool%" -o installfeature -name ProvisioningVX -force
echo "activating feature"
"%SPAdminTool%" -o activatefeature -name ProvisioningVX -url %TargetUrl% -force
iisreset
PAUSE
12/08/2009
How To: Debug SPJobDefinition in Visual Studio
The solution is remarkably simple.
Click Debug -> Attach To Process
Note: At this point, ensure the checkbox "Select processes from all users" is selected.
Select OWSTIMER.EXE from the list.
Setup a breakpoint on the Execute override method.
Be patient and wait for the timed job to execute.
Click Debug -> Attach To Process
Note: At this point, ensure the checkbox "Select processes from all users" is selected.
Select OWSTIMER.EXE from the list.
Setup a breakpoint on the Execute override method.
Be patient and wait for the timed job to execute.
06/08/2009
My First Zune Badge: A Lesson in mediocrity
I finally got my first Zune badge today and with it, a lesson in mediocrity. Microsoft may want to rethink their strategy as to how these badges are issued as I now feel that I listen to a bunch of kindof sortof artists..
The Bronze Artist Power Listener award! Wooo Hooo. Are you kidding me? Thanks for this bronze mediocre accomplishment. What if it was a Platinum Artist Power Listener award? Does that mean I've listened to the most commercial music possible - that I am a power listener of platinum artists? What about, Gold. What about Silver.
Either way, I'm still happy that Microsoft has finally allowed me to create a Zune account. Thanks for the good work.
Over and Out
The Bronze Artist Power Listener award! Wooo Hooo. Are you kidding me? Thanks for this bronze mediocre accomplishment. What if it was a Platinum Artist Power Listener award? Does that mean I've listened to the most commercial music possible - that I am a power listener of platinum artists? What about, Gold. What about Silver.
Either way, I'm still happy that Microsoft has finally allowed me to create a Zune account. Thanks for the good work.
Over and Out
26/06/2009
Setup Visual Studio To Easily Pull PublicKeyTokens
Interesting article here: http://blogs.msdn.com/kaevans/archive/2008/06/18/getting-public-key-token-of-assembly-within-visual-studio.aspx
The article explains a couple tricks as to how to get PublicKeyTokens out of your signed assemblies in a quick and simple manner.
Enjoy.
Over And Out
The article explains a couple tricks as to how to get PublicKeyTokens out of your signed assemblies in a quick and simple manner.
Enjoy.
Over And Out
18/06/2009
Apple Is Spamming Me
Every time I get an email from Apple I:
1) Feel like I'm dumb.
2) Ignore it.
3) Get annoyed and unsubscribe from the mailing list.
Only I continue to get at least one email from Apple every two days that I do not want. Has anyone else had this problem? Does anyone know how to make it so Apple never contacts me again?
If so, please enlighten me!
Over And Out
1) Feel like I'm dumb.
2) Ignore it.
3) Get annoyed and unsubscribe from the mailing list.
Only I continue to get at least one email from Apple every two days that I do not want. Has anyone else had this problem? Does anyone know how to make it so Apple never contacts me again?
If so, please enlighten me!
Over And Out
17/06/2009
Bing.com is Amazing!
I’ve been using Bing for one week to see if it can replace Google.
I can now say that Bing does 100% replace Google and in many circumstances I’ve found it not only easier to use, but faster, and more relevant.
Try switching your search engine to Bing and give it a test – I’d love to see what other people think!
Feel free to leave hateful comments, it's all part of the game.
Over and Out
I can now say that Bing does 100% replace Google and in many circumstances I’ve found it not only easier to use, but faster, and more relevant.
Try switching your search engine to Bing and give it a test – I’d love to see what other people think!
Feel free to leave hateful comments, it's all part of the game.
Over and Out
Labels:
Bing,
Google,
Microsoft,
Search,
Windows Live Search
Subscribe to:
Posts (Atom)