Nik Kalyani's Blog

Irrationally Exuberant Technology Musings

Nik Kalyani photo

Visual: DotNetNuke Enterprise Deployment Scenario

January 26, 2010

Here’s an illustration depicting a common scenario for DotNetNuke Deployment in the Enterprise. Click the image for a higher-res version. If you find the image helpful, feel free to use it as needed without any restrictions or attribution requirements.

DNN-Deployment-Scenario

Redirecting to Canonical URL in IIS7

January 14, 2010

If you are using IIS7, it’s very easy to ensure that all requests always go to your preferred canonical URL. It’s a two step process:

Step 1: Install the UrlRewrite module for IIS: http://www.iis.net/expand/URLRewriteIIS Rewrite

Step 2: Add the following rule to your applications web.config file:

<configuration>
 <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect from www" stopProcessing="true">
           <match url=".*" />
           <conditions>
              <add input="{HTTP_HOST}" pattern="^www.yoursite.com$" />
           </conditions>
           <action type="Redirect" url="http://yoursite.com/{R:0}" redirectType="Permanent" />
        </rule>
     </rules>
   </rewrite>
 </system.webServer>
</configuration>

IMPORTANT: When using the above code, take care to merge it with your existing web.config without duplicating any existing elements.

I like my URL’s to be in the format http://mysite.com. If you prefer http://www.mysite.com, simply remove “www.” from the <add> element and add it to the <action> element’s “url” attribute.

DotNetNuke Widgets Guide (Part 4 of 4)

January 12, 2010

This is the last post in my four-part series on DotNetNuke Widgets. Here’s a review of the other posts in this series:

  • Part 1 – Overview of DotNetNuke Widgets
  • Part 2 – DotNetNuke Widgets reference
  • Part 3 – Insights into how you can develop your own Widgets for DotNetNuke

In this post, I’ll walk you through the code of the TechBubble CatalogWidget. This Widget displays a carousel of Product thumbnail images. You can click on any thumbnail to see a larger version of the image. You can then move your cursor over any portion of the larger image to see a zoomed in image of the area below the cursor. I created this Widget to convey multiple concepts:

  • Passing data through Widget markup parameters
  • Using a Widget to integrate multiple jQuery plugins seamlessly
  • Using behavior injection to dynamically add event-handling to UI elements
  • Dynamically injecting stylesheets and scripts into the page
  • Using jQuery UI themes

Let’s start by looking at a mockup of the Widget (created using my favorite mockup tool – Balsamiq).

CatalogWidget Mockup

In order to implement this UI, I decided to use two jQuery plugins:

(These are arbitrary choices…I am sure that there are other plugins that would work equally well or better.)

I have setup two live demos of the Widget so you can get a feel for the Widget’s UI:

You can download the Widget at the link below and follow along with the technical discussion that follows. I have also included a short slideshow that shows a screen grab of the installation process and the two demos.

[smooth=id:1;]

Here are the properties that supported by the CatalogWidget:

photoUrl (required) – A URL to the location where the images for the Widget will be found. The Widget uses the following convention for image names: {label}.{extension} for hi-res image displayed in zoom area, {label}_thumb.{extension} for thumbnail image and {label}_small.{extension} for small image displayed when thumbnail is clicked. {label} and {extension} are explained in the description for other parameters.

theme (optional, default=ui-lightness) – Name of the jQuery UI theme that should be loaded from Google’s CDN for jQuery themes. The list of supported themes can be found on the jQuery Themeroller page. The theme name should match the defined name on the Themeroller page, with spaces in the name replaced with the hyphen character.

carouselWidth (optional, default=500) – Width of the carousel used to display the thumbnails in pixels. The number of thumbnails displayed will depend on the width of each thumbnail and the value of this parameter.

zoomWidth (optional, default=250) – Width of the zoomed image area in pixels.

zoomHeight (optional, default=250) – Height of the zoomed image area in pixels.

moreInfoHandler (optional) – Name of a function that will be called with a parameter of {label} when the information icon that appears to the right of the product name link is clicked. If this parameter is not specified, the information icon will not be displayed.

extension (optional, default=jpg) – The file extension for all images.

Product Data – In addition to these parameters, the Widget supports an unlimited number of additional product data parameters. Any parameter specified other than the above, is treated as product data. The value of the “name” attribute of the parameter will be used for the product {label} and the value of the “value” attribute will be used for the product’s descriptive name. Example: <param name=”ABC1000″ value=”ABC 1000 Super Duper Product” />.

OK, now we have that out of the way, let’s get started with building the Widget. The Widget is going to exist in the namespace “TechBubble.Widgets,” so by convention, the Widget file will be named “TechBubble.Widgets.CatalogWidget.js” and it will be located in ~/Resources/Widgets/User/TechBubble. All resources for this Widget will be in ~/Resources/Widgets/User/TechBubble/CatalogWidgetResources. Here’s the code for namespace registration and the Widget constructor:

Type.registerNamespace(&quot;TechBubble.Widgets&quot;);
TechBubble.Widgets.CatalogWidget = function(widget)
{
    TechBubble.Widgets.CatalogWidget.initializeBase(this, [widget]);
    this.catalogResourcesUrl =
                    $dnn.baseResourcesUrl +
                    &quot;Widgets/User/TechBubble/CatalogWidgetResources/&quot;;
    this.photoUrl = &quot;&quot;;
    this.theme = &quot;ui-lightness&quot;;
    this.carouselWidth = &quot;800&quot;;
    this.zoomWidth = &quot;250&quot;;
    this.zoomHeight = &quot;250&quot;;
    this.moreInfoHandler = &quot;&quot;;
    this.extension = &quot;jpg&quot;;
    this.products = [];
    this.hasProducts = false;

    if (!TechBubble.Widgets.CatalogWidget.Initialized)
    {
        $.getScript(this.catalogResourcesUrl +
                    &quot;scripts/jQuery-ui-1.7.2.custom.min.js&quot;);

        $.getScript(this.catalogResourcesUrl +
                    &quot;scripts/jquery.metadata.js&quot;);

        TechBubble.Widgets.CatalogWidget.Initialized = true;
    }
}
TechBubble.Widgets.CatalogWidget.inheritsFrom(
            DotNetNuke.UI.WebControls.Widgets.BaseWidget);
TechBubble.Widgets.CatalogWidget.registerClass(
            &quot;TechBubble.Widgets.CatalogWidget&quot;,
            DotNetNuke.UI.WebControls.Widgets.BaseWidget);

In the constructor, we define default values for the various properties (parameters) that the Widget supports. In addition the variable TechBubble.Widgets.CatalogWidget.Initialized is used as a flag to prevent the jQuery UI and jQuery metadata plugin from being loaded. A nice optimization for this code would be to check for the actual existence of the plugin, instead of using a flag. In addition to the constructor, the calls to inheritsFrom() and registerClass() are standard calls for every Widget for setting inheritance and registering the class.

TechBubble.Widgets.CatalogWidget.prototype =
{
    render:
        function()
        {
            // Parse widget parameters
            this._getParams();

            // Load some sample data to display if none
            // has been specified
            if (!this.hasProducts)
                this._getSampleData();

            // Create a DIV element and swap out the Widget's
            // defining &lt;object&gt; element with it by calling
            // the base render() method (can't use jQuery
            // shortcut to create element)
            var div =document.createElement(&quot;div&quot;);
            div.setAttribute(&quot;style&quot;,&quot;width:&quot; + this.carouselWidth + &quot;px&quot;);
            TechBubble.Widgets.CatalogWidget.callBaseMethod(this, &quot;render&quot;, [div]);

            this._renderCarousel();

            this._renderZoomer();
        },

        _getParams:
        function()
        {
		// Enumerate and retrieve parameters
		// . . . code omitted
        },

        _renderCarousel:
        function()
        {
		// Render the Carousel plugin
		// . . . code omitted
        },

        _renderZoomer:
        function()
        {
		// Render the Zoomer plugin
		// . . . code omitted
        },

        _injectStyleSheet:
        function(name, isTheme)
        {
		// Inject a stylesheet into the page
		// . . . code omitted
        },

        _getThumbnailList:
        function(list, photoUrl)
        {
            return(productList);
        },

         _getSampleData:
         function()
         {
		// Use and display Widget with sample data
		// . . . code omitted
         }
}

Next, let’s review the code for the Widget’s prototype where the required method render() is declared along with various private methods (prefixed with underscore). In the render() method, we start by getting the parameters. Then, if no products are defined, we use some sample product information. Next, we swap out the <object> element defining the Widget with a <div> element. This <div> element will become the parent container for the rest of the Widget which is rendered in the _renderCarousel() and the _renderZoomer() methods. Next in the code are a number of helper methods. I won’t go into a line-by-line explanation, but highlight a few things I think are noteworthy:

Script Injection: I use the jQuery method $.getScript(scriptUrl, anonymous function) in several places. This is a useful method when you want to inject a script into the DOM and want to ensure that any dependent code is not executed until the asynchronous loading of the script is completed. By putting all the dependent code in an anonymous function defined in the second parameter of this method I could achieve this goal.

Behavior Injection: In _renderZoomer(), I iterate through each thumbnail in the carousel and use the shortcut for the jQuery bind() method $(this).click() to inject a click handler for each of the thumbnail images. This is cleaner and more efficient than adding an onClick attribute when defining the HTML markup for each thumbnail.

DotNetNuke.UI.WebControls.Widgets.renderWidgetType(&quot;TechBubble.Widgets.CatalogWidget&quot;);

We wrap-up the Widget code by telling the Widget framework to render all Widgets of the type TechBubble.Widgets.CatalogWidget.

This also wraps-up my series on DotNetNuke Widgets. I hope you found the content and examples useful and are inspired to build your own DotNetNuke Widgets.

DotNetNuke Widgets Guide (Part 3 of 4)

January 4, 2010

Widgets

Continuing my series on DotNetNuke Widgets, here is Part 3 where I provide insights into how you can develop your own Widgets for DotNetNuke. If you haven’t already done so, read Part 1 (overview of DotNetNuke Widgets) and Part 2 (DotNetNuke Widgets reference) to better understand the concepts explored in this post. Let’s get started.

Location and Naming Conventions

Widgets are located in two places: ~/Resources/Widgets/DNN for Core Widgets and ~/Resources/Widgets/User/<CompanyName> for user Widgets. The Widget file names are <WidgetName>.js for Core Widgets and <CompanyName>.Widgets.<WidgetName>.js for user Widgets.

Widget Anatomy

Let’s walk through the three basic sections of code that constitute a Widget:

Namespace, Inheritance and Constructor

Using the ASP.NET AJAX library, we register the namespace for our widget and define its inheritance from the BaseWidget class. Finally, we define the constructor.

Type.registerNamespace(&quot;YourCompany.Widgets&quot;);
YourCompany.Widgets.SampleWidget.inheritsFrom(DotNetNuke.UI.WebControls.Widgets.BaseWidget);
YourCompany.Widgets.SampleWidget = function(widget)
{
    YourCompany.Widgets.SampleWidget.initializeBase(this, [widget]);
}

Render Method

Every Widget must implement the render() method. Typically, this method will follow a pattern consisting of two steps: (1) enumerate the parameters specified in the Widget declaration (i.e. <param> elements) and assign them to local variables, (2) do some processing based on the parameters and call the render() method. When you call the render() method in Step 2, you pass in a DOM element that you create. The framework will replace the <object> element with which the Widget was defined with your DOM element and assign it the original ID that the <object> element was given. What your code does during Step #2 in order to populate the contents of the DOM element you create or manipulate other elements of the page is entirely up to you. Your Widget has access to any DOM element and can make calls to any other custom scripts, ASP.NET AJAX library functions, jQuery plugins etc.

YourCompany.Widgets.SampleWidget.prototype =
{
   render:
   function()
   {
      var params = this._widget.childNodes;
      if (params != null)
      {
          // Do something
      }

      var div = document.createElement(&quot;div&quot;);
      // Do some work here to add content to the div
      YourCompany.Widgets.SampleWidget.callBaseMethod(this, &quot;render&quot;, [div]);
   }
}

Registration and Rendering

The last thing you have to do in your Widget is to register its class and tell the Widget framework that it can render all instances of your Widget present on the page.

YourCompany.Widgets.SampleWidget.registerClass(&quot;YourCompany.Widgets.SampleWidget&quot;, DotNetNuke.UI.WebControls.Widgets.BaseWidget);
DotNetNuke.UI.WebControls.Widgets.renderWidgetType(&quot;YourCompany.Widgets.SampleWidget&quot;);

The above is all you need in order to create the basic scaffolding for a Widget. Add your custom code, save the file following the expected name and location conventions and you can start using your Widget right away (you’ll have to do some more work to package the Widget if you want it to be installable using the DotNetNuke Extension Wizard).

If you would like to see the code for a functional user Widget, you can download and install the Module Print Widget. The module displays a dropdown that allows a page viewer to select from a list of modules on the page and print any single module thus eliminating the need to display a print icon on every module.

Stay tuned for the last part in this series where I take you step-by-step through the process of building a Product Catalog Widget that makes use of third-party jQuery plugins, injects stylesheets dynamically and renders a nice UI using the jQuery UI extensions.

Module Print Widget for DotNetNuke

December 29, 2009

If you are like me and want your websites to have a clean, unblemished look, then most likely you have either turned off the Print functionality in your DotNetNuke module settings or just use containers that don’t display the icon. While this does make the site look cleaner, it also takes away the functionality. I gave this some thought and concluded that a Widget would be a great way to provide the functionality for printing the content of modules on a page. I envisioned a selector that the user would click on that would allow them to print the content for a single module. A skin designer could embed the Widget directly into the skin, or a site administrator could selectively add it to pages using an HTML module.

Module Print Widget

A couple hours of hacking later I present to you the ModulePrintWidget for DotNetNuke. It’s simple and easy to use. When added to a page, it creates a drop-down list of each module on the page. A user can select a module from the list to see a preview, then click a Print icon to print the contents of that module. Here’s a short 45-second YouTube video that demonstrates the Widget in action: TechBubble ModulePrintWidget

You can download the Widget package at the link below (install as Superuser from the Extensions page):

You can also see a live demo of the ModulePrintWidget.

To use the Widget, add the following HTML so that it appears once on a page. You can add the markup anywhere that HTML is supported (module, skin, skin object, container):

&lt;object id=&quot;MyWidget&quot; codetype=&quot;dotnetnuke/client&quot; codebase=&quot;TechBubble.Widgets.ModulePrintWidget&quot;&gt;&lt;/object&gt;

If you want to customize the appearance and language, use the optional parameters:

&lt;object id=&quot;MyWidget&quot; codetype=&quot;dotnetnuke/client&quot; codebase=&quot;TechBubble.Widgets.ModulePrintWidget&quot;&gt;
 &lt;param name=&quot;selectorCssClass&quot; value=&quot;Class-to-style-dropdown&quot; /&gt;
 &lt;param name=&quot;selectText&quot; value=&quot;Default-text-for-dropdown&quot; /&gt;
&lt;/object&gt;

DotNetNuke Widgets Guide (Part 2 of 4)

December 29, 2009

WidgetsThis is Part 2 of my four-part series on DotNetNuke Widgets. In Part 1 of the series, I covered some fundamental concepts related to DotNetNuke Widgets. In this post, I will introduce you to a few of the Widgets that are included with the DotNetNuke distribution. Before getting started I’d like to make one observation…these widgets were created prior to the inclusion of jQuery within the DotNetNuke Core. While the Widgets are production-ready, they could use some refactoring to take advantage of jQuery’s efficient engine for selecting and manipulating DOM elements.

All Widgets follow the same format for embedding in any extension (module, skin, skin object, container)

&lt;object codebase=&quot;{WidgetType}&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;{WidgetId}&quot;&gt;
	&lt;param name=&quot;{WidgetParameterName}&quot; value=&quot;{WidgetParameterValue}&quot; /&gt;
&lt;/object&gt;

{WidgetType} (required) = fully qualified Type name of the Widget
{WidgetId} (required) = arbitrary ID for the Widget’s DOM element (must be unique on the page)

A Widget can have zero or more child elements, each with a “name” and “value” attribute with corresponding {WidgetParameterName} and {WidgetParameterValue} values. Widget parameter names are case-insensitive. Widget parameter values are always case-sensitive.

StyleScrubberWidget

The purpose of this Widget is to “scrub” the appearance of a DotNetNuke page by removing undesirable attributes from specific elements on the page. For example, you may have a module that has a hard-coded “style” or “width” attribute that is disrupting the appearance of a page. You don’t really want to change the source code for the module (if it’s available) and you really want to use the module. This is where StyleScrubber Widget comes to the rescue. It enumerates a series of rules you provide and removes the undesirable attributes allowing elements to be fully styled with CSS. This Widget may appear any number of times on a page.

Parameters

classNames (required) – A list of class names separated by semi-colons. The Widget will only act on elements with a matching “class” attribute. At least one value must be specified. Example: head; normal; topic

tag (optional) – A HTML element tag name which acts as a filter in selecting elements. The default value is * which implies all elements. Example: div

removeAttribute (optional) – The name of the attribute which should be stripped from all elements that match the classNames and tag conditions. The removeAttribute parameter may be repeated multiple times to specify more than one attribute that should be removed. Example: style (strips the “style” attribute)

recursive (optional) – Value of true or false to indicate if the scrubbing cascades indiscriminately through all child elements of a matched element. Default is false.

Example

Remove all “width” and “style” attributes from TABLE elements that have a class value of “Normal” or “NormalBold”

&lt;object codebase=&quot;StyleScrubberWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;ScrubTable&quot;&gt;
	&lt;param name=&quot;classNames&quot; value=&quot;Normal;NormalBold&quot; /&gt;
	&lt;param name=&quot;tag&quot; value=&quot;table&quot; /&gt;
	&lt;param name=&quot;removeAttribute&quot; value=&quot;width&quot; /&gt;
	&lt;param name=&quot;removeAttribute&quot; value=&quot;style&quot; /&gt;
&lt;/object&gt;
RelocationWidget

The purpose of this Widget is to move or “relocate” content so that they visual location of the content differs from the physical location of the content in the page. The primary use-case is SEO. Using the RelocationWidget it is possible to have content as close to the top of the page as possible while moving the navigation lower down on the page. Since search bots do not run scripts, this arrangement is optimal for them. Users with script-enabled browsers will see the navigation in its intended location. This Widget may appear any number of times on a page.

Parameters

sourceId (required) – ID of the DOM element that contains the HTML content that will be relocated. It is recommended that you apply a CSS style of “display:none” to this element so it is not initially visible in the user’s browser.

targetId (required) – ID of the DOM element where the HTML content from the sourceId element will be moved. It is recommended that you apply a CSS style for “width” and “height” matching the dimensions that the relocated content will occupy. Doing so prevents other elements on the page from visually moving around when the Widget performs its action.

Example

Move all content from element “NavTemp” to “Nav”

&lt;object codebase=&quot;RelocationWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;MoveIt&quot;&gt;
	&lt;param name=&quot;sourceId&quot; value=&quot;NavTemp&quot; /&gt;
	&lt;param name=&quot;targetId&quot; value=&quot;Nav&quot; /&gt;
&lt;/object&gt;
RotatorWidget

Changes content within an element at a pre-defined interval. The content can be sourced from a location on the page, an RSS feed or sequentially numbered images. This widget is ideal for scenarios in which the content to be rotated is not known ahead of time and no interactivity is desired from the end-user. This Widget may appear any number of times on a page.

Parameters

elementId (required) – ID of the DOM element where the rotating content will be rendered.

height (required) – Height of the rotated content in pixels.

width (required) – Width of the rotated content in pixels

interval (optional) – Time interval in milliseconds for content rotation. Default is 2500 milliseconds.

direction (optional) – Direction in which new content slides. Values are UP, DOWN, RIGHT, LEFT (default), BLEND

transition (optional, experimental) – Transition effect for new content. Values are SLIDE, SNAP (default)

The RotatorWidget can rotate content from three sources. Content from all the sources is aggregated, then displayed so you can combine multiple sources in the same RotatorWidget instance if desired.

RSS Feed Source

feedUrl (required for RSS feeds) – URL of the RSS 2.0 feed from which content will be sourced

feedAttribute (required for RSS feeds) – Name of the element that contains the content to be rotated. Yahoo Pipes is used to retrieve the feed.

Sequential Image Source

imageUrl (required for images) – The base URL where the images to be rotated are located. Must end in slash (“/”).

imageTemplate (required for images) – The file name template for each image. The token {INDEX} may be used to indicate where the sequence number will be injected. The sequence begins at 1. Example: portrait{INDEX}.jpg for images names portrait1.jpg, portrait2.jpg, portrait3.jpg etc.

imageCount (required for images) – The number of images available for rotation.

imageScale (optional) – Indicates if images should be scaled by width or by height. Values are WIDTH and HEIGHT or blank (default) for no scaling.

Page Content Source

contentElementId (required for content) – ID of the DOM element that contains the content to be rotated. The Widget expects the DOM element to have zero or more child elements. The content of each child element is treated as a separate rotation item. Example: A <UL> element with multiple <LI> elements where each <LI> element contains one item of content.

Example

Rotate 10 images stored in a folder at an interval of 5 seconds.

&lt;object codebase=&quot;RotatorWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;Animate&quot;&gt;
	&lt;param name=&quot;elementId&quot; value=&quot;PageHeader&quot; /&gt;
	&lt;param name=&quot;height&quot; value=&quot;100&quot; /&gt;
	&lt;param name=&quot;width&quot; value=&quot;400&quot; /&gt;
	&lt;param name=&quot;interval&quot; value=&quot;5000&quot; /&gt;
	&lt;param name=&quot;imageUrl&quot; value=&quot;/Portals/0/HeaderImages/&quot; /&gt;
	&lt;param name=&quot;imageTemplate&quot; value=&quot;header{INDEX}.png&quot; /&gt;
	&lt;param name=&quot;imageCount&quot; value=&quot;10&quot; /&gt;
&lt;/object&gt;
StyleSheetWidget

The purpose of this Widget is to provide a user interface that enables users to switch stylesheets in order to customize their browsing experience. This Widget may appear any number of times on a page.

Parameters

template (required) – The StyleSheetWidget renders an interface element for each stylesheet that the user can select from. The template parameter is used to specify the HTML markup that will be rendered for each stylesheet in the set. The HTML markup must be encoded and can use the tokens {TEXT} (replaced with the name of each stylesheet as specified in other parameters), {ID} (replaced with a unique identifier for each interface element that is rendered) and {CLASS} (replaced with “class” attribute and value). Example: <div title=”{TEXT}” {ID} {CLASS}></div>

default (required) – The value of the stylesheet that should be selected by default.

baseUrl (required) – The URL where the stylesheets are located.

cssClass (required) – The CSS class value to be used on interface elements corresponding to a stylesheet that is not selected.

selectedCssClass (required) – The CSS class value to be used on the interface element corresponding to the selected stylesheet.

In addition to the above, one parameter (name and value) is required for each stylesheet. The “name” attribute should contain the stylesheet filename and the “value” attribute should contain the human-friendly label associated with the stylesheet.

Example

Allow the user to select from five different color palettes.

&lt;object codebase=&quot;StyleSheetWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;ColorSelector&quot;&gt;
	&lt;param name=&quot;template&quot; value=&quot;&amp;lt;div title=&quot;{TEXT}&quot; {ID} {CLASS}&amp;gt;&amp;lt;/div&amp;gt;&quot; /&gt;
	&lt;param name=&quot;default&quot; value=&quot;blue&quot; /&gt;
	&lt;param name=&quot;baseUrl&quot; value=&quot;&lt;%= SkinPath %&gt;css/&quot; /&gt;
	&lt;param name=&quot;cssClass&quot; value=&quot;Icon&quot; /&gt;
	&lt;param name=&quot;selectedCssClass&quot; value=&quot;Icon-Selected&quot; /&gt;
	&lt;param name=&quot;red&quot; value=&quot;Fire-engine Red&quot; /&gt;
	&lt;param name=&quot;blue&quot; value=&quot;Midnight Blue&quot; /&gt;
	&lt;param name=&quot;yellow&quot; value=&quot;Sunflower Yellow&quot; /&gt;
&lt;/object&gt;
EmbedWidget

This Widget is somewhat unique in that its purpose is to provide a standard way for embedding any embeddable content from other websites. Using this Widget, you create a “snippet” for any such content once using whatever unique requirements the source site may have. Once the snippet is created, you can then use the embeddable content multiple times within DotNetNuke using the standard Widget embedding syntax.

Parameters

publisher (required for user content) – This parameter tells the EmbedWidget where to look for the embeddable content. If it is not specified, the Widget looks for content in the folder “~/Resources/Widgets/DNN/EmbedWidgetResources/{type parameter value}/” If this parameter is specified, the Widget looks for content in the folder “~/Resources/Widgets/User/{publisher parameter value}/EmbedWidgetResources/{type parameter value}/”

type (required) – The type of content to embed. This value must correspond to a file named “{lowercase type parameter value}.snippet.htm” in the folder location specified above. The file must be a plain-text file containing solely the HTML markup necessary for rendering the content.

In addition to the above parameters, you can specify and arbitrary number of name/value parameters that are passed to the content snippet file when the content is rendered by the Widget. The value may be a single value or multiple values concatenated using a delimiter character. The default delimiter is “;”. You can overrride the delimiter by specifying the “multiValueDelimiter” parameter described below. Review the individual snippet file for each type of embeddable content for supported parameters specific to that content type.

multiValueDelimiter (optional) – Character used to delimit multi-value parameters.

When the Widget is rendered, the snippet file is parsed and token substitution is performed using values specified in the parameters. The syntax for tokens is:

{ parameter name : token template : default template }

For each token, the Widget checks to see if a corresponding named parameter is available. If so, it replaces the token with the token template otherwise it uses the default template. In order to substitute parameter values in the token template, placeholders are used. Placeholders are numeric and in the format {0}, {1}, {2} etc. The Widget substitutes values in the order they are specified.

For example: { width : width=”{0}” : width=”500″ } OR { coordinates : x={0},y={1} : x=100,y=100 }

Example

Embed a Flickr slideshow

&lt;object codebase=&quot;EmbedWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;Flickr&quot;&gt;
	&lt;param name=&quot;type&quot; value=&quot;Flickr&quot; /&gt;
&lt;/object&gt;
VisibilityWidget

The purpose of this Widget is to enable an HTML element on a page to toggle the visibility of a container element located elsewhere on the page. The Widget included with DotNetNuke is now deprecated. Joe Brinkman has updated the Widget’s code and the updated one will be available in a future DotNetNuke release. You can read all about Joe’s enhancements in his blog post DotNetNuke Tips and Tricks #15: DotNetNuke Visibility Widget.

DotNetNuke Skin Proxy Re-visited

December 28, 2009

Some years ago, I had presented a solution for dynamically loading a skin layout based on the user’s browser type. Fast-forward to the present — at the Fall 2009 OpenForce Conference in Amsterdam I had a chance to speak to Armand Datema (@nokiko) on the same topic. The conversation occurred following my session on Advanced Skinning with DotNetNuke where I presented an early prototype of “Skinfigurator,” my module for rule-based skin loading. Armand was looking for a solution to dynamically choose a skin at run-time while overcoming the pesky ContentPane issue. If you are unfamiliar with the issue, here’s a quick synopsis…

DotNetNuke skins require the presence of a container HTML element with an ID of “ContentPane” and a runat=”Server” attribute. This is fine for most skins as it’s no big deal to define an area that serves as the default location for content (i.e. ContentPane). In the case of dynamic skin proxies (i.e. skins that load a layout based on some arbitrary set of conditions) this requirement is a problem since different layouts may want the ContentPane to be located in different places within the layout HTML.

In any event, as a result of my tinkering with skin proxies I found a clean solution for this problem. Ultimately I decided not to use it for Skinfigurator (more about the how/why in another post), however the technique is still quite useful. I promised Armand I would share it with him, and although I have been slow in making this post, it’s better late than never 🙂

The solution is trivially simple and involves just one file — the skin proxy layout. Basically what this proxy does is tap into the Init event in the page life-cycle to dynamically load the skin layout control. Since this event happens prior to the point where the DotNetNuke framework skin loader does its thing, you don’t have to bother with creating ContentPane elements in the skin proxy layout. All you need is the logic for dynamically selecting which layout to display to the user. Your Here’s the code for the skin proxy layout (I called mine LayoutSelector.ascx)

&lt;%@ Control language=&quot;vb&quot; AutoEventWireup=&quot;false&quot; Explicit=&quot;True&quot; Inherits=&quot;DotNetNuke.UI.Skins.Skin&quot; %&gt;
&lt;script runat=&quot;server&quot;&gt;
	Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

		Dim layout = &quot;Portal.ascx&quot;
		If (Request.Querystring(&quot;layout&quot;) &lt;&gt; &quot;&quot;) Then
			layout = Request.Querystring(&quot;layout&quot;) + &quot;.ascx&quot;
		End If
		Controls.Add(LoadControl(TemplateSourceDirectory + &quot;/layouts/&quot; + layout))
	End Sub
&lt;/script&gt;

In my example, I have the code checking for a querystring variable and loading a control based on the value provided. Of course, this is not something you will want to do in production use. More likely you will want to have conditional logic based on the user, portal, browser, tab or some other controlling factor that determines which skin layout will be loaded.

There is one other thing to be aware of that is related to usability. By default, DotNetNuke lists all layouts (i.e. user controls) it finds in a skin folder in any skin layout selector in the UI. To ensure that your proxy logic is used, you will want your proxy layout control to be the only control in the skin’s root folder. All the dynamically selectable layouts should be in a sub-folder. In my example, I use a sub-folder called “layouts.” The folder structure for your skin will look something like this:

[MyCoolSkin]
— LayoutSelector.ascx
— skin.css
— [layouts]
—– Portal.ascx
—– Portal2.ascx
—– Portal3.ascx

Using this approach, the user will only be able to choose “LayoutSelector” and the Portal, Portal2 and Portal3 layouts will be hidden from the skin layout selector UI.

DotNetNuke Widgets Guide (Part 1 of 4)

December 25, 2009

WidgetsStarting with Release 5.x, the DotNetNuke platform has included a Javascript-based Widgets framework for dynamically injecting client-side interactivity into skins and modules. Like most Open Source developers, I thoroughly enjoyed coding the Widget framework but neglected to document it properly. In this four-part series I hope to correct this shortcoming. In Part 1, I will introduce some fundamental concepts of the DotNetNuke Widget Framework. In Part 2, I will provide a reference for existing widgets that are included with DotNetNuke. In Part 3, I will step through the process of developing a Widget. Finally, in Part 4 I will create a working Widget that you can download and use to increase your understanding of the framework and to build your own Widgets.

Widget Fundamentals

Just as you can add modules to a DotNetNuke page to add application functionality, so also can you add Widgets to DotNetNuke skins and modules to add interactivity. For example, in a skin, Widgets may enable a user to dynamically switch a stylesheet to change page appearance, add a photo gallery, embed a video etc. In a module, Widgets can provide interface elements for navigation, drag-and-drop sorting capabilities etc. Widgets are first-class citizens of DotNetNuke’s extensibility model and can therefore be packaged individually or in combination with DotNetNuke modules and skins using the familiar DotNetNuke manifest and zip file model. Widgets are created using Javascript code that builds on the Microsoft ASP.NET AJAX client-side library and can leverage jQuery or any other client-side framework for additional capabilities. They can be embedded into any extension type that manifests itself in the client browser (module, skin, skin object, container) and use a syntax that should be familiar to skin designers. Here’s an example of a Flickr Widget:

&lt;object codebase=&quot;EmbedWidget&quot; codetype=&quot;dotnetnuke/client&quot; id=&quot;MyWidget&quot;&gt;
    &lt;param value=&quot;Flickr&quot; name=&quot;type&quot; /&gt;
&lt;/object&gt;

That’s it…three lines of HTML markup to embed a Flickr slideshow like the image below instantly into a DotNetNuke page. Go ahead…try it out by adding the above markup in an HTML module (in source)…I’ll wait.

Flickr slideshow using EmbedWidget

At this point you are probably wondering what the benefit of Widgets is if they are coded in Javascript and make use of pre-existing client-side libraries. After all it’s not that difficult to embed a simple <script> element into your skin or module and add any code that you desire directly at the appropriate location. And using my simplistic example of a Flickr slideshow, you could just as easily get the embed code for the slideshow and use it directly.

Five Reasons for using the Widget framework

Let’s address these questions by reviewing the five primary reasons for using the Widgets framework:

Clean Markup: Using Widgets enables you to keep the HTML markup for your skin or module clean and script-free. Since Widgets are embedded using the standard <object> element, you can add functionality without sacrificing readability. In fact, Widgets lend themselves to more semantic markup as the intent of the markup is usually evident from the name of the Widget and the parameter name/value pairs. Embedding script directly or referencing an external script makes your markup harder to read and maintain.

Reusability: If you have some Javascript code that needs to be used in multiple skins or modules, wrapping it into a Widget makes it easy for you to re-use the code while taking advantage of DotNetNuke’s packaging and versioning capabilities. Sure, you could store a script file in a central location and reference it, but Widgets afford you greater control in using, deploying and maintaining the code. Furthermore, by implementing the code as a Widget, you now have the ability to easily pass parameters without messing around with querystring parameters to script file references or in-line Javascript variable declarations. Such reusability does come at a small price in terms of time and effort required, so it’s probably not a good idea to create a Widget for a single-use script.

Testability and Maintainability: Unlike context-less Javascript files or embedded script, Widgets are stand-alone, contextual entities. Therefore they can be tested and debugged in a variety of scenarios quickly and easily with minimal effort. If you just add a <script> reference to a Javascript file in your HTML markup, you have no way of knowing if the dependencies for the script are being loaded or not. You have no idea if any variable necessary to pass parameters to the script are already on the page or not. These issues are eliminated using Widgets. When you use a Widget, you know that its dependencies will be correctly loaded and its parameters are available in the Widget’s HTML markup itself.

Performance: Browsers execute inline script and fetch scripts referenced using the <script> element synchronously while rendering a page (you could use the “defer” attribute, but browser support for this is not consistent). This puts an unnecessary wait penalty on the site visitor. Using jQuery’s document.ready() method mitigates this somewhat, but remember, the browser still has to switch context from HTML to Javascript, parse the script and then switch context back to HTML. Widgets provide a cleaner way to add client-side interactivity as they are loaded at the end of a page when the DOM is ready. Thus, the visitor will have a better user experience as HTML, CSS and images will already have been rendered. If you would like to learn more about how browsers handle script, read Timing and Synchronization in JavaScript.

Behavior Injection and Modification: It’s quite easy to add “onclick” and “onmouseover” attributes to HTML elements to add client-side interactivity. Unfortunately, this results in horrible markup that is difficult to maintain and difficult to debug. Widgets force you to use behavior injection and modification in order to attach events to DOM elements. This keeps all behavioral code in one location and makes it incredibly easy to maintain through good use of jQuery selectors. It’s also results in a cleaner separation between the markup and the script.

Hopefully this information has provided you with enough knowledge to understand when Widgets are a good idea and when they are not. Now let’s take a deeper look at the client-side page life-cycle to understand the Widget rendering process.

Widget Rendering Process

Widgets are rendered only if the Site Setting “Enable Skin Widgets” is checked. This value is checked by default, so you can be assured that Widgets will render on most DotNetNuke sites. (We should probably re-name this setting to “Enable Client-side Widgets”…when I was first coding the Widget framework, I was focused on usage scenarios involving skins and used the term “skin widgets.” The term stuck even though Widgets can be used in any DotNetNuke extension that renders code to the browser.) By enabling this setting, a single reference to a Javascript file is injected into the very end of the page:

&lt;script type=&quot;text/javascript&quot; src=&quot;/Resources/Shared/scripts/initWidgets.js&quot;&gt;&lt;/script&gt;

When the script loads, it initiates a four-step process: Framework Initialization, Widget Detection, Widget Instantiation and Widget Rendering. This process is illustrated below:

Widget Rendering Process

The Widget framework uses jQuery to load all required scripts in an asynchronous manner. When a script is done loading, an event is fired to carry out the next step in the rendering process. All of this happens pretty fast, and most notably, after the page is already rendered in the browser. If you view the HTML source for the page, you will see no difference in the markup from what was originally sent by the server (i.e. <object> elements). However, if you query the DOM using FireBug or a similar tool, you will see that each <object> Widget element has been replaced with a <div> or similar element with the same ID as originally given to the <object> element. This enables you to use CSS for styling the Widget using an ID selector (i.e. #MyWidget).

In this post, I provided an introduction to the DotNetNuke Widget Framework. In the next post in this series, I will introduce you to the Widgets included with DotNetNuke and provide a usage reference for each Widget.

Newer Posts
Older Posts