LavaBlast Software Blog

Help your franchise business get to the next level.
AddThis Feed Button

Gotcha: WebKit (Safari 3 and Google Chrome) Bug with ASP.NET AJAX

clock October 20, 2008 23:38 by author JKealey

image Tonight we fixed a severe compatibility issue that I feel you should all be aware of.

Executive summary: ASP.NET AJAX breaks down completely in some circumstances when using WebKit-based browsers. Reference the JavaScript provided below to solve these problems.

As you know, we develop web applications using ASP.NET AJAX and tonight we were notified that one of our users was not able to proceed to the payment page on one of our e-commerce websites. (As you can imagine, preventing payment is the worst thing that can happen in an e-commerce site!). After some investigation, we discovered the user was using Safari 3 on an Intel-based MacBook Pro just like the one I recently purchased. I picked up my MBP and re-tested the site, going through exactly the same steps this user did (thanks to the auditing capabilities we've built into the e-commerce engine). The site works fine in general, except at one particular page deep within the bowels of the website, when clicking on a button, the ASP.NET UpdateProgress control would show and never go away during the asynchronous postback.

I first thought this was an SSL issue such as the evil IE White Screen Bug, but I managed to replicate on my local machine without using SSL. This button is contained inside a dozen layers of user controls. Fortunately, I use this user control in another location. I tested one of these locations (where it isn't as nested) and this one worked. I then proceeded to hide my user controls, layer by layer and narrowed the issue to ASP.NET validators on one of my pages.

<asp:RequiredFieldValidator ID="rfvName" runat="server" ErrorMessage="Required"
    Display="Dynamic" ControlToValidate="txtName"="true" />


Adding Visible="false" to this (and the other validators) on my user control unfroze the UpdateProgress. My first thought was that I must have reached a limit in identifier name lengths because my validator was nested very deeply. I proceeded to rename a few layers to make the name shorter. This changed nothing. I then discovered how to enable a FireBug-like tool in Safari called Web Inspector. This helped me discover an obscure JavaScript error.

Sys.ScriptLoadFailedException: The script 'http://localhost:2241/ScriptResource.axd?[...]' failed to load.


After changing from ScriptMode="Release" to ScriptMode="Debug", I got additional details.

Check for:
Inaccessible path.
Script errors. (IE) Enable 'Display a notification about every script error' under advanced settings.
Missing call to Sys.Application.notifyScriptLoaded().


This finally lead me to an old post on the ASP.NET forums. It appears that Safari 2 needed a few hacks in the ASP.NET AJAX JavaScript code to work properly. These hacks are no longer needed in Safari 3 (or Google Chrome) because WebKit works out of the box. However, these hacks sometimes broke WebKit-based browsers as I discovered today. The first solution in the forums is to change the JavaScript files used by the framework but we didn't like that solution very much. The second comment provided a solution which we found reasonable. 

Workaround

The workaround simply tells ASP.NET AJAX that Safari 3 and Google Chrome are a new type of browser instead of the old Safari for which workarounds had to be programmed.

1) Create a new file called webkit.js

Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
{
  Sys.Browser.agent = Sys.Browser.WebKit;
  Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]);
  Sys.Browser.name = 'WebKit';
}


2) Reference this webkit.js from your ScriptManager

<ajax:ToolkitScriptManager ID="scripts" runat="server" ScriptMode="Release" EnableHistory="true" 
EnableSecureHistoryState="false" EnablePageMethods="True" CombineScripts="true" 
OnAsyncPostBackError="Page_OnAsyncError" OnNavigate="OnHistoryNavigate">
    <Scripts>
        <asp:ScriptReference Path="~/js/webkit.js" />
    </Scripts>
</ajax:ToolkitScriptManager>


We hope this will help some of you!

kick it on DotNetKicks.com


SQL Server - Restore a database backup via the command line

clock October 14, 2008 12:45 by author EtienneT

image Anyone who's ever developed a web application in .NET has had to play with a database management system, most probably SQL Server or its free cousin, SQL Server Express.  One of the tasks I personally hate doing with our SQL Server Express 2005 databases is restoring them from a backup, using SQL Management Studio.  We sometimes restore the point of sale database used by our customers to track down various issues or to build reports using their data as our test set. The process is not that long when you restore a backup from your own machine (restoring the MDF and LDF files to their original directory). If you restore databases from foreign systems, the process is simple only if both systems stored their databases in the same directory, which is rarely the case.

For example, I use Windows Vista x64 and our dedicated server uses a 32-bit version of Windows 2003.  Our data is stored in the default SQL Server directory, which is in the Program Files folder.  However, when using a 64-bit operating system, the program files directory is different (C:\Program Files (x86)).  Since the location of the MDF and LDF files are encoded directly in the bak file generated by SQL Server, restoring them via the command line is especially challenging when you don't control the original locations of the MDF and LDF files, nor their Logical Names.

Our goal is to be able to restore a database by executing a simple command such as this:

restore.bat LavaBlast

This command would look for LavaBlast.bak in the current directory and would restore the LavaBlast database to a default location on your computer where you want to store your MDF and LDF files.

Here is the code for restore.bat:

sqlcmd -S .\SQLEXPRESS -i attachDB.sql -v database="%1" -v root="%CD%"

We are simply calling sqlcmd (added to our path) to connect to our local instance of SQL Server Express and we are executing an SQL file (attachDB.sql) which includes two variables: database and root (the current path).

Here is the code for attachDB.sql:

USE MASTER
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[$(database)]') AND type in (N'U'))
  ALTER DATABASE $(database) SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
 
create table #backupInformation (LogicalName varchar(100),
PhysicalName varchar(100),
Type varchar(1),
FileGroupName varchar(50) ,
Size bigint ,
MaxSize bigint,
FileId int,
CreateLSN int,
DropLSN int,
UniqueId uniqueidentifier,
ReadOnlyLSN int,
ReadWriteLSN int,
BackupSizeInBytes int,
SourceBlockSize int,
FileGroupId int,
LogGroupGUID uniqueidentifier,
DifferentialBaseLSN bigint,
DifferentialBaseGUID uniqueidentifier,
IsReadOnly bit, IsPresent bit )
 
insert into #backupInformation exec('restore filelistonly from disk = ''$(root)\$(database).bak''')
 
DECLARE @logicalNameD varchar(255);
DECLARE @logicalNameL varchar(255);
 
select top 1 @logicalNameD = LogicalName from #backupInformation where Type = 'D';
select top 1 @logicalNameL = LogicalName from #backupInformation where Type = 'L';
 
DROP TABLE #backupInformation 
 
RESTORE DATABASE $(database)
FROM DISK = '$(root)\$(database).bak'
WITH REPLACE,
MOVE @logicalNameD TO 'C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data\$(database).mdf',
MOVE @logicalNameL TO 'C:\Program Files (x86)\Microsoft SQL Server\MSSQL.1\MSSQL\Data\$(database).ldf'
GO

Simply put, we are extracting the logical names (and other metadata) from the .bak file into a temporary table. We then use those values to restore the MDF and LDF to the correct location, instead of the ones specified in the .bak file.

If you want to use this script, simply ensure you change the location of your SQL Server data files (the last lines in the SQL file) and you should be good to go. Please note that in its current form, the script only supports files with one MDF and one LDF file in the database backup. Furthermore, it assumes your .bak file has the same name as the database you want to import. We could also enhance the script by automatically adding permissions to the ASP.NET user after restoring the database. Feel free to post any enhancements you make in this post's comments and I hope you'll find this script useful! Enjoy.

kick it on DotNetKicks.com


Jason Kealey and Etienne Tremblay featured in National Capital Scan

clock September 11, 2008 22:39 by author JKealey

jketTwo of LavaBlast's founders (Etienne and myself) are featured in this month's National Capital Scan, an independent news leader for Ottawa's Tech Community. As we are proud to be University of Ottawa alumni, it is always a pleasure to keep in touch with the university and new software engineering students. In addition to this article about our launching our software company, I will be sharing lessons learned at the Students As Innovators workshop later this month at the School of Information Technology and Engineering.

Additionally, we're actively helping other startups in the Ottawa and Montreal regions, many of which we met at The Code Factory, the Ottawa-based co-working location.  Ian Graham is busy organizing tons of events which we strongly recommend you attend if you're interested in getting known in the Ottawa software community.




LavaBlast Selected as a Red Herring Canada Top 50 Finalist

clock August 29, 2008 14:02 by author JKealey

We've been busy these lasts few weeks on a number of projects, but I thought I'd like you know that we were selected as an innovative Canadian software start-up.

Red Herring Magazine has named LavaBlast Software a finalist for the "Red Herring Top 50 Canada" award, a prestigious list honoring this year’s most promising private technology ventures in Canada. The Red Herring editorial team used an intensely competitive process to select the most innovative companies from a pool of over 300, leaving 100 finalists vying for this prestigious award. The names of all 100 companies short–listed as finalists for the "Red Herring Top 50 Canada 2008" can be found online at: http://www.herringevents.com/canada08/Canada50.html

RHCanada finalist logoRead more in our press release

While I was enjoying the weather, Toronto Tech Jobs took the time to peruse everyone's website to figure out who's hiring software engineers!

Congratulations to the other finalists.



BlogEngine.net Post Security

clock August 13, 2008 15:23 by author EtienneT

BlogEngine.net 1.3/1.4 supports user roles.  But we can't seem to be able to make it mandatory for users to sign in to see blog posts.  That's not something you usually want on a public blog, but for a corporate blog, maybe you want to make sure your news only gets to the people you want.  This seemed like a perfect candidate for a BlogEngine extension.

User Filtering

In our scenario, we don’t want any unregistered users to be able to see blog posts.  This can be easily checked by calling Membership.GetUser() and ensuring the returned value is not null.  We could filter out specific users as well, but we didn’t implement this feature in our extension.

Post Filtering

It could be interesting to restrict who can see the posts in a specific blog category.  For example, a blog category “Top Secret” which can only be read by your company's upper management…  Not very likely in a blog, but you get the point.  Our extension does this filtering by associating a blog Category with a membership Role in the extension’s settings.

image

By associating a membership role with a blog category name, the extension ensures the user has this role before displaying a post associated with this blog category name.  If you add two roles for the same category, posts with this category will only be served if the user has both roles.

Adding a setting with an empty category name will ensure that all posts require a particular role.

Code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System.Collections.Generic;
 
/// <summary>
/// Summary description for PostSecurity
/// </summary>
[Extension("Checks to see if a user can see this blog post.",
            "1.0", "<a href=\"http://www.lavablast.com\">LavaBlast.com</a>")]
public class PostSecurity
{
    static protected ExtensionSettings settings = null;
 
    public PostSecurity()
    {
        Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);
 
        ExtensionSettings s = new ExtensionSettings("PostSecurity");
 
        s.AddParameter("Role", "Role", 50, true);
        s.AddParameter("Category", "Category", 50);
 
        // describe specific rules for entering parameters
        s.Help = "Checks to see if the user has any of those roles before displaying the post. ";
        s.Help += "You can associate a role with a specific category. ";
        s.Help += "All posts having this category will require that the user have the role. ";
        s.Help += "A parameter with only a role without a category will enable to filter all posts to this role. ";
 
        s.AddValues(new string[] { "Registered", "" });
 
        ExtensionManager.ImportSettings(s);
        settings = ExtensionManager.GetSettings("PostSecurity");
    }
 
    protected void Post_Serving(object sender, ServingEventArgs e)
    {
        Post post = (Post)sender;
        bool continu = false;
 
        MembershipUser user = Membership.GetUser();
 
        continu = user != null;
 
        if (user != null)
        {
            List<string> categories = new List<string>();
            foreach (Category cat in post.Categories)
                categories.Add(cat.Title);
 
            string[] r = Roles.GetRolesForUser();
 
            List<string> roles = new List<string>(r);
 
            DataTable table = settings.GetDataTable();
            foreach (DataRow row in table.Rows)
            {
                if (string.IsNullOrEmpty((string)row["Category"]))
                    continu &= roles.Contains((string)row["Role"]);
                else
                {
                    if (categories.Contains((string)row["Category"]))
                        continu &= roles.Contains((string)row["Role"]);
                }
            }
        }
 
        e.Cancel = !continu;
    }
}

 

Simply saving this code in a .cs and putting it in your App_Code/Extensions for BlogEngine.net shall enable the plugin.

kick it on DotNetKicks.com


SubSonic v2.1 Controller and Utilities

clock August 4, 2008 11:45 by author JKealey

We've done a few posts about how we use SubSonic here at LavaBlast. Recently, SubSonic v2.1 was released and we upgraded the code we've previously published to support this new version. We've blogged about our changes in the past and not much has changed since, but we did get a request to post our source code, so here it is. I've actually included a bit more code in this release so that this blog post has a bit more substance!

Download the source code.

The file contains our SubSonicController, SubSonicHelper, and our associated code generation templates. Nothing new to see here, except that you get downloadable code. We unfortunately did not have time to play with the new Query engine all that much, so our controller still uses the old one (which is used throughout our codebase). If anyone would like to augment our code to support the new query engine and post it in the comments, that would be great! Moving to the new query engine would circumvent the OR query limitation related to the search fields we've mentioned in the past.

Auditing using SubSonic

We like to log certain things in our Electronic Journal as it gives us ways to debug more efficiently, and provides us with a way to keep track of who changed what in case something breaks. We've included an SQL script that generates our ElectronicJournal table, and code which allows us to save events in the table. We've wired it up to our SubSonicController so that we can log all object updates, for example. What you log is your own business and it depends on your needs and performance requirements.

ej

We've built an administrative interface over this table allowing us to navigate efficiently through the events. (Each of our pages in FranchiseBlast extends from generic controls which list/filter/page rows using our ObjectDataSource, effectively re-using the code we're presenting here.)

Various notes

  • Remember not to mix AND and OR in the current version of this code, with the old query engine.
  • Don't log everything on high volume sites, for obvious reasons.
  • Issue 3 is still open and waiting to be committed. The others bugs I previously reported (and a new one) have been committed.
  • We removed the ToList() which we added last time, because GetList() is already present. (Thanks to our readers for noticing!)
  • We replaced all calls to IsLoaded() to !IsNew() in our codebase. Click here to learn why.
kick it on DotNetKicks.com


The Code Factory in the News

clock July 24, 2008 08:41 by author JKealey

We're happy to see that our client The Code Factory, an Ottawa-based software co-working franchise, was recently featured on the local news. Some of us were on site while the spot was filmed and it was an interesting (yet stressful) experience to be filmed when you're trying to draft out the features to include in the next release!

ctv

Twitter + Co-working

This coincides with our recent addition of a cool little feature to The Code Factory's interactive kiosk. We're now publishing events to Twitter when people check-in and check-out of the location. Of course, members can choose to hide their activities for privacy reasons, but this serves as an interesting off-site complement to the in-store kiosk which indicates who's currently on location. If you follow TheCodeFactory on Twitter, you can see when your friends arrive and decide to head out there yourself!



jQuery Content Slider Tutorial

clock July 22, 2008 15:22 by author EtienneT

Simple Demo (Firefox, IE7, IE6, Opera, Safari) | Demo with content | Source Code

LavaBlast launched a new front page recently and we have incorporated a new jQuery slider. You can see it in action below (in the Flash animation) or you can go see it directly on our website home page.

Scroll down to find out how this little puppy was implemented!

 

 

HTML & CSS

HTML

This is the basic ASP.NET in the ASPX page:

<div class="FrontMenu">
    <div class="Bar">
        <asp:Repeater ID="Repeater" runat="server" onitemdatabound="Repeater_ItemDataBound">
            <ItemTemplate>
                <span class="item">
                    <a href="#" class="jFlowControl">
                        <asp:Label ID="lbl" runat="server" />
                    </a>
                    <div class="spike" style="z-index:999999">
                    </div>
                    <div class="right">
                    </div>
                </span>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    <div class="Panel">
        <div><cms:Paragraph ID="paragraph1" runat="server" ContentName="frontMenu1" /></div>
        <div><cms:Paragraph ID="paragraph2" runat="server" ContentName="frontMenu2" /></div>
        <div><cms:Paragraph ID="paragraph3" runat="server" ContentName="frontMenu3" /></div>
        <div><cms:Paragraph ID="paragraph4" runat="server" ContentName="frontMenu4" /></div>
        <div><cms:Paragraph ID="paragraph6" runat="server" ContentName="frontMenu5" /></div>
    </div>
</div>

This is pretty simple HTML.  Everything is enclosed in the main div with the css class FrontMenu.  We have the animated bar at the top and the content panel underneath it.  The menu bar is generated by a simple repeater control bound to data in our ASP.NET page. Each menu item is a span containing a link that we’ll use to change the selected menu item.  The Panel div contains multiple dynamic paragraphs from our content management system (SubSonic CMS).  You could easily change this code to bind to data from another source.

Here is the code behind for this control.  We kept it pretty simple:

public partial class FrontPageMenu : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<string> list = new List<string>();
            list.Add("How can we help?");
            list.Add("Our Products");
            list.Add("Hot Features");
            list.Add("Testimonials");
            list.Add("Read");
 
            Repeater.DataSource = list;
            Repeater.DataBind();
        }
    }
 
    protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lbl = e.Item.FindControl("lbl") as Label;
            lbl.Text = (string)e.Item.DataItem;
        }
    }
}

 

image

The following picture shows how the html menu item elements are rendered.  The CSS section of this article will dive deeper in the inner workings of the menu.

image

JQuery

jFlow

We used jFlow to scroll our panels when we click on a menu item.  The code was fairly straightforward to use.  We included this script in our user control.

$(".FrontMenu").jFlow({
    slides: ".FrontMenu .Panel",
    width: "974px",
    height: "344px",
    duration: 300
});

And then we included a simple reference to our script manager.

<asp:ScriptManagerProxy ID="proxy" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/js/jquery.flow.1.0.min.js" />
    </Scripts>
</asp:ScriptManagerProxy>

 

We could have used Next and Previous buttons but decided not to.

 

IE6 Problems

This menu did require some basic jQuery.  Except for the scrolling animation, we could have built almost all of this in pure CSS thanks to the hover pseudo-class. However, Internet Explorer 6 came back from the grave to haunt us…  As we still have some visitors who are using IE6, we could not afford to let our home page break down in IE6.  Microsoft gods: please please, hear our prayers and find a way to erase IE6 from the face of earth.  But hey, we've got work to do and can't wait five years for the browser to die like IE 5 did.

We discovered that using a:hover in IE6 to change our background image will make the browser crash.  We used IETester to test the menu in IE6: it made IETester crash.  We then tried Virtual PC running Win98 and IE6: Internet Explorer crashed again when we hovered over one of the links with a:hover CSS styles.

The solution to this problem was simply to apply a style to the hovered link (.hover). Then we could easily style the children of this element to our liking without breaking IE6.

$(".FrontMenu .Bar a").mouseover(function() { $(this).addClass("hover"); });
$(".FrontMenu .Bar a").mouseout(function() { $(this).removeClass("hover"); });

To change the style of the selected item we added the css class .sel to the span.item (the parent of the clicked link).  First of all, when a link is clicked, remove the currently selected item.  Second, set the parent of the link as the current selected item.  It’s important to return false as otherwise the browser will follow the link and scroll to the top of the page.

$("div.FrontMenu div.Bar a").click(function()
{
    $("div.FrontMenu div.Bar").children("span.sel").removeClass("sel");
    $(this).parent().addClass("sel");
    return false;
});

 

CSS

Let’s take a deeper look at the menu’s CSS.  Let’s start with the FirstMenu class which is not too complicated.

.FrontMenu
{
    padding: 5px 5px 0px 5px;
    margin-left: 2px;
    margin-top: -4px;
}
 
.FrontMenu .Bar
{
    background: #F6ECA4 url(images/MainPage/bar.jpg) no-repeat top left;
    width: 980px;
    height: 48px;
    position: relative;
}
 
.FrontMenu .Bar a
{
    color: #FFFFFF;
    font-size: large;
    font-family: Tahoma;
    position: relative;
    top: 7px;
    display: block;
    text-decoration: none;
    padding-right: 6px;
    margin-right: -6px;
    cursor: pointer;
}

Now let’s take a closer look at the Bar menu.  Here are the images we used to style our menu items.

CSS Images    
.FrontMenu .Bar span.sel

selLeft.gif

selLeft

selRight.gif

selRight

spike.gif

spike

.FrontMenu .Bar a.hover span

hoverLeft.gif

hoverLeft

hoverRight.gif

 

 

hoverRight

 

Like you saw in the jQuery part, we change the class in JavaScript to bypass some IE6 issues, so you should not be surprised by the CSS.

The code for the main span for each menu item:

.FrontMenu .Bar span.item
{
    line-height: 30px;
    margin: 0px 0px;
    float: left;
    position: relative;
    display: inline;
    cursor: pointer;
    width: 188px;
    text-align: center;
    margin-left: 6px;
}

Here is the code when you hover over the link inside the menu item:

/* We have to handle hover with jQuery because :hover makes IE6 crash when we change the background image. */
.FrontMenu .Bar a.hover
{
    background: transparent url(images/MainPage/hoverRight.gif) no-repeat top right;
    height: 30px;
}
 
/* We have to handle hover with jQuery because :hover makes IE6 crash when we change the background image. */
.FrontMenu .Bar a.hover span
{
    background: transparent url(images/MainPage/hoverLeft.gif) no-repeat top left;
    height: 30px;
    display: block;
}

 

Like you can see, the link contains the hoverLeft  background image and the span inside the link contains the hoverRight.  This enables the link to have any length and the control will resize easily.  If you ever get a link that is wider than the left image, simply make the image wider...

Then we only needed the CSS to change the menu item to make it look selected.

 

 

 

 

.FrontMenu .Bar span.sel a:hover { background: none; padding-left: 0px; margin-left: 0px; }
.FrontMenu .Bar span.sel a:hover span { background: none; padding-left: 0px; margin-left: 0px; }
 
.FrontMenu .Bar span.sel
{
    background: transparent url(images/MainPage/selLeft.gif) no-repeat top left;
    height: 48px;
}
 
.FrontMenu .Bar span.item .spike, .FrontMenu .Bar span.sel .spike
{
    background: transparent url(images/MainPage/spike.gif) no-repeat top left;
    display:none;
    position: absolute;
    top: 44px;
    left: 50%;
    margin-left: -11px;
    width: 22px;
    height: 17px;
    z-index: 9999;
}
 
.FrontMenu .Bar span.sel .spike
{
    display: block;
}
 
.FrontMenu .Bar span.sel .right
{
    background: transparent url(images/MainPage/selRight.gif) no-repeat top right;
    position: absolute;
    height: 48px;
    width: 4px;
    right: 0px;
    top: 0px;
}
 
.FrontMenu .Bar span.sel a { color: #d43300; }

 

The parent span for the menu item with the .sel class contains the selLeft image and the div.right inside this span contains the selRight image.  We have to make sure too that the hover style does not get applied when the item is selected.

The spike spike is applied in absolute position in the center.  To do that in absolute position, you have to set the following:

left: 50%;
margin-left: -11px;  // <—This is the width/2
width: 22px;

Even with a higher z-index, we were not able to make the spike go on top of the content panel in IE6.  Therefore, we had to put a margin on top of content panel just to make sure the spike was not overlapping the content panel below:

.FrontMenu div.Panel
{
    height: 328px;
    width: 974px;
    margin-top: 15px;
}

 

 

Simple Demo (Firefox, IE7, IE6, Opera, Safari) | Demo with content | Source Code

kick it on DotNetKicks.com



Would you put cartoons on your software startup's website?

clock July 17, 2008 20:42 by author JKealey

We've revamped our website home page and wanted to invite you to visit it and let us know what you think.   The general template of the site hasn't changed, as our enhancements focused on five core elements:

  1. Simpler menu structure. When we first launched our website, our pages were never nested more than one level deep. We've since added new content and our site was getting harder to navigate. By going with a tree-like structure and adding markers to indicate which page you are currently viewing, we feel this solves our main usability problem.
  2. Testimonials. Ian Graham, the man behind The Code Factory, an Ottawa-based software co-working location, talks about how he enjoyed doing business with us. We feel this touch increases our credibility, and the fact that we get things done. 
  3. Concise information. We've integrated much more information on our home page and re-worked the text to make it very concise. The home page leads you to numerous inner pages which feature more detailed information about our products. We're always re-working the innards of our site and we're never "done", but we feel this new home page will help drive traffic to the appropriate locations.... only time Google Analytics will tell.
  4. Web 2.0 slider. We wanted to have a bit of fun even if it meant requiring JavaScript on our pages.
  5. Cartoons. This is the most controversial aspect of our new home page. We've integrated cartoons on our homepage.... cartoons on a franchise software corporate site? Allow us to explain.

LavaBlast Software home page

Why are we using cartoons?

Simply put, everyone we've talked to is divided in two completely distinct camps. One camp feels our cartoons makes our website unprofessional and inappropriate for the franchise industry's decision makers (one of the more vocal people in this camp is Michael Webster, Ph.D, LL.B.). Others feel it gives us a more personalized feel (a human touch) which increases their trust in our company.

There are hundreds of companies building software for the franchise industry and we want to show that we have a different philosophy from many of the old-school companies. Simply put, we (as web visitors) distrust generic consulting websites littered with stock photography and we didn't want to repeat the same mistake. We love to use pictures, but bad quality pictures or video are often worse than not having any.  After a year and a half of having a more corporate feel (without using stock photography), we decided it was time to do something wilder. We hope to impress our target market with an atypical corporate website, even if it ruffles a few feathers.  

We target small yet energetic franchise systems. These franchisors are not heads of billion dollar corporate empires, they are entrepreneurs who want to grow a concept which worked in their flagship store and scale it to the next level, via franchising. At their growth stage, these franchisors are looking for someone who can listen to their needs, build cost-effective software solutions, and help them grow. The franchises we deal with don't have large IT departments: they're looking to get outside help with technology, as they don't have the knowledge in-house. Outsourcing allows them to get more bang for their buck than hiring software engineers to build everything from scratch.

Why don't you like stock photos?

Does the following image incite you to contact a software firm for custom development?

handshake stock photo

When we shop around and find a company featuring such a picture, it reveals that they botched their web development work and they're probably going to botch any work we give them. Attention to detail is one characteristic we always want to see; however, we're not completely against stock photography but we disapprove of stock photography abuse. For example, if a company has a page talking about their team, and the team picture is actually a stock photo... they're taking it too far.

As a sidenote, Toronto-based Idée Inc. created an image search engine that not only helps identify stock photography but also people that have stolen your copyrighted images. Here's a screenshot of the results returned by TinEye for the previous image: 

TinEye Image Search

TinEye even found this modified image... very nice technology!

modified handshake

What do you think?

In summary, we decided to go with a cartoonish feel because we felt it was the best way to distinguish ourselves from our stereotypical competition. We purposefully project more youthful brand image, as we are targeting smaller franchise systems. Do you think differently? Are you an ardent defender of stock photo or do you think you've found the perfect balance of web 2.0 styling with the warm fuzzy feeling of seeing people? Do you agree with us? Let us know!

kick it on DotNetKicks.com

blast it on Franchise NewsBlast


Image Post Processing Caching

clock July 15, 2008 13:41 by author EtienneT

Complete Source Code | Small Demo

This article present a small class library that abstracts opening, modifying (applying effects, resizing, etc.), and caching images in ASP.NET.  Everything needs to be abstracted to ensure the code is easily testable (opening, modifying, and caching of the images).  You may want to resize your images or convert them to black and white and cache the result, and want to test these operations.

You want to be able to read image data from different sources:

  • An image on the local disk on the web server
  • A remote image on the Internet that you want to download and cache
  • An image in your database

You want to be able to apply any number of post processing algorithms to the resulting image:

  • Resize the image (generate thumbnails)
  • Apply an image filter such as convert to black and white
  • Do anything on the image that requires computing and where caching the result proves beneficial from a performance standpoint. 

CacheManager

First of all, let's look at a nice caching class I found on a DotNetKicks kicked story.  Zack Owens gave a nice piece of code in his blog to help you manage your ASP.NET cached objects.  The goal of this class is simply to let you have a strongly typed way to access your cached objects.  Here is the code for the class with some slight modifications:

public class CacheManager<T> where T : class
{
    private Cache cache;
    private static CacheItemRemovedCallback callback;
    private static object _lock = new object();
 
    private TimeSpan cacheTime = new TimeSpan(1, 0, 0, 0); // Default 1 day
 
    public CacheManager(Cache cache)
    {
        this.cache = cache;
        if(callback == null)
            callback = new CacheItemRemovedCallback(RemovedFromCache);
    }
 
    public T Get(string key)
    {
        try
        {
            lock (_lock)
            {
                if (cache[key] == null)
                    return default(T);
 
                T b = CastToT(cache[key]);
 
                return b;
            }
        }
        catch (ArgumentException ex) // The object was disposed by something! return null;
        {
            return null;
        }
    }
 
    public void Add(string key, T obj, TimeSpan cacheTime)
    {
        lock (_lock)
        {
            if (obj != null)
                cache.Add(key, CastFromT(obj), null, DateTime.Now.Add(cacheTime), Cache.NoSlidingExpiration, CacheItemPriority.Default, callback);
        }
    }
 
    protected void RemovedFromCache(string key, object o, CacheItemRemovedReason reason)
    {
        T obj = o as T;
        if (obj != null)
        {
            lock (_lock)
            {
                DisposeObject(obj);
            }
        }
    }
 
    protected virtual void DisposeObject(T obj) { }
 
    protected virtual T CastToT(object obj) { return obj as T; }
 
    protected virtual object CastFromT(T obj) { return obj as T; }
 
    public TimeSpan CacheTime
    {
        get { return cacheTime; }
        set { cacheTime = value; }
    }
}

As you can see, this is a pretty simple class.  We defined some virtual methods to be implemented in our child class, for example DisposeObject if you want to cache disposable objects (continue to read if you want to know why this is a really bad idea).

The constructor requires a Cache object; we can simply pass along the Page's Cache (Page.Cache) to make it happy.  We now want to derive from CacheManager to help us in our main task which is to cache modified images.

ImageCacheManager

To create our image-specific cache manager, we defined a new class called ImageCacheManager which is a subclass of CacheManager  and will cache byte arrays (our images).  We implemented this feature in the past, but did a big mistake that led to a mysterious bug.  We were caching Bitmap objects in the ASP.NET cache but this was a big, big mistake.  Bitmap objects are GDI+ managed objects and they need to get disposed.  Even if we had methods to dispose the Bitmap when they were removed from the cache, some Bitmap objects were disposed while still in the cache (because of a memory leak elsewhere in the application). This caused errors downstream when we tried to use those objects later.  The lesson: we'll only cache only byte[] of the images.

The default image format is PNG in our case, but you can specify your own in the constructor.  In our case we are using PNG because we are in a controlled environment where we know everyone is using IE7, so we can use transparent PNG.  You probably want to use a different format for general public web sites since IE6 doesn't support transparent PNG.

This class will enable to download remote images and cache them locally, as well.  We needed this feature since we have a lot of remote point of sales which synchronize their product list from a central database.  We didn't want to send product images during synchronization because it would have been too much data.  Instead we decided to store our images on a central server and since our stores always have Internet access, they download and cache the images via this image cache manager.  In our product, when a franchisor changes a product image in the main database, the cached version of the picture in the point of sale will expire within the next day and the new picture would be downloaded when used.

ImageCacheManager is an abstract class.  It implements image caching and handles the fact that you want to apply post processing to an image with options (interface IImagePostProcess) and it abstracts the way you load the image (interface IImageReader).  Here is the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Caching;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using System.Net;
using LavaBlast.ImageCaching.PostProcess;
using LavaBlast.ImageCaching.Reader;
 
namespace LavaBlast.ImageCaching
{
    /// <summary>
    /// This class specialize in caching modified images.  Images are cached as
    /// byte[].  You can apply different modifications in serial to the image
    /// before caching it.
    /// 
    /// Construct a cache key depending on the options of your image post processing.
    /// This enables to cache copies of an image with different post processing applied to it.
    /// 
    /// Control how the image will be read.  On local disk, via Internet etc.
    /// </summary>
    public abstract class ImageCacheManager : CacheManager<byte[]>
    {
        public ImageCacheManager(Cache cache) : this(cache, ImageFormat.Png) { }
 
        protected Dictionary<string, IImagePostProcess> postProcess = new Dictionary<string, IImagePostProcess>();
 
        protected ImageFormat format = ImageFormat.Png; // Default image format PNG
 
        public ImageCacheManager(Cache cache, ImageFormat format) : base(cache)
        {
            this.format = format;
 
            InitImagePostProcess();
        }
 
        /// <summary>
        /// Determine which image reader will be used to read this image.
        /// </summary>
        /// <param name="uriPath"></param>
        /// <returns></returns>
        protected abstract IImageReader GetReader(Uri uriPath);
 
        /// <summary>
        /// Fill the variable postProcess with post processing to apply
        /// to an image each time.
        /// </summary>
        protected abstract void InitImagePostProcess();
 
        /// <summary>
        /// This method shall return a unique key depending on the path of the
        /// image plus the options of it's post processing process.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        protected abstract string ConstructKey(Uri path, Dictionary<string, object> options);
 
        /// <summary>
        /// Get an image from the following path.  Use the provided options to use in post processing.
        /// If refresh is true, don't use the cached version.
        /// </summary>
        /// <param name="uriPath"></param>
        /// <param name="options"></param>
        /// <param name="refresh"></param>
        /// <returns></returns>
        protected byte[] GetImage(Uri uriPath, Dictionary<string, object> options, bool refresh)
        {
            string key = ConstructKey(uriPath, options);
            byte[] cached = Get(key);
 
            if (cached != null && !refresh)
                return cached;
            else
            {
                try
                {
                    byte[] image = ReadBitmap(uriPath); // Get the original data from the image
 
                    byte[] modified = PostProcess(image, options); // Do any post processing on the image (resize it or apply some effects)
 
                    Add(key, modified, CacheTime); // Add this modified version to the cache
 
                    return modified;
                }
                catch
                {
                    return null;
                }
            }
        }
 
        /// <summary>
        /// Run all post processing process on the image and return the resulting image.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        protected byte[] PostProcess(byte[] input, Dictionary<string, object> options)
        {
            byte[] result = input;
 
            foreach (string key in postProcess.Keys)
                result = postProcess[key].Process(result, options[key]);
 
            return result;
        }
 
        /// <summary>
        /// From a path, return a byte[] of the image.
        /// </summary>
        /// <param name="uriPath"></param>
        /// <returns></returns>
        protected byte[] ReadBitmap(Uri uriPath)
        {
            using (Stream stream = GetReader(uriPath).GetData(uriPath))
            {
 
                byte[] data = new byte[0];
 
                Bitmap pict = null;
 
                try
                {
                    pict = new Bitmap(stream);
                    data = ImageHelper.GetBytes(pict, format);
                }
                catch
                {
                    return null;
                }
                finally
                {
                    if (pict != null)
                        pict.Dispose();
                }
 
                stream.Close();
 
                return data;
            }
        }
    }
}

Because this is an abstract base class, we need a concrete implementation of ImageCacheManager.  We created ThumbnailCacheManager.  ThumbnailCacheManager checks the URI if it’s a local or remote file and uses the right image reader.  It has only one post processing task (resizing the image), but it could have more.  It construct the unique key for the cache from the processing task’s options.

Image Resizing

Here is a quick example of a typical image processing task: resizing it.  The class implement the simple method Process(byte[] input, object op) where op is in fact the options of the post processing process.  I could not use generics in my IImagePostProcess interface because of the way I store them later…  Here is a quick code example of how to resize an image.

namespace LavaBlast.ImageCaching.PostProcess
{
    /// <summary>
    /// Post processing that take an image and resize it
    /// </summary>
    public class ImageResizePostProcess : IImagePostProcess
    {
        public byte[] Process(byte[] input, object op)
        {
            byte[] oThumbNail;
 
            ImageResizeOptions options = (ImageResizeOptions)op;
 
            Bitmap pict = null, thumb = null;
 
            try
            {
                using (MemoryStream s = new MemoryStream(input))
                {
                    pict = new Bitmap(s); // Initial picture
 
                    s.Close();
                }
 
                thumb = new Bitmap(options.Size.Width, options.Size.Height); // Future thumb picture
 
                using (Graphics oGraphic = Graphics.FromImage(thumb))
                {
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    oGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Rectangle oRectangle = new Rectangle(0, 0, options.Size.Width, options.Size.Height);
 
                    oGraphic.DrawImage(pict, oRectangle);
 
                    oThumbNail = ImageHelper.GetBytes(thumb, options.ImageFormat);
 
                    oGraphic.Dispose();
 
                    return oThumbNail;
                }
            }
            catch
            {
                return null;
            }
            finally
            {
                if (thumb != null)
                    thumb.Dispose();
                if (pict != null)
                    pict.Dispose();
            }
        }
    }
 
    public class ImageResizeOptions
    {
        public Size Size = Size.Empty;
        public ImageFormat ImageFormat = ImageFormat.Png;
    }
}

 

Reading the picture

Reading the picture is the easy part and I have included two implementations of IImageReader: one for a local images and one for a remote images.  You could easily implement one which loads images from you database.

LocalImageReader

/// <summary>
    /// An image reader to read images on local disk.
    /// </summary>
    public class LocalImageReader : IImageReader
    {
        public Stream GetData(Uri path)
        {
            FileStream stream = new FileStream(path.LocalPath, FileMode.Open);
 
            return stream;
        }
    }

RemoteImageReader

/// <summary>
    /// Image reader to read remote image on the web.
    /// </summary>
    public class RemoteImageReader : IImageReader
    {
        public Stream GetData(Uri url)
        {
            string path = url.ToString();
            try
            {
                if (path.StartsWith("~/"))
                    path = "file://" + HttpRuntime.AppDomainAppPath + path.Substring(2, path.Length - 2);
 
                WebRequest request = (WebRequest)WebRequest.Create(new Uri(path));
 
                WebResponse response = request.GetResponse() as WebResponse;
 
                return response.GetResponseStream();
            }
            catch { return new MemoryStream(); } // Don't make the program crash just because we have a picture which failed downloading
        }
    }

HttpHandler

Finally, you want to serve those images with an HttpHandler. The code for the HttpHandler is pretty simple as you only need to parse the parameters from the QueryString and pass them to the ThumbnailCacheManager presented above.  The handler receives a parameter “p” for the path of the image (local or remote) and a parameter “refresh” which can be used to ignore the cached version of the image.  Additionally, we can pass parameters such as “width” and “height” for our image resizing.  Warning: you must adapt this code to your environment otherwise you are exposing a security hole because of the path parameter.

When debugging your image caching HttpHandler, don't forget to clear your temporary Internet files from IE or FireFox because your images will also be cached in your web browser otherwise your code will not be executed!

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using LavaBlast.ImageCaching;
 
namespace WebApplication
{
    /// <summary>
    /// Really simple HttpHandler to output an image.
    /// </summary>
    public class ImageCaching : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Request.Params["p"] ?? "";
            bool refresh = context.Request.Params["refresh"] == "true";
 
            int width, height;
            if (!int.TryParse(context.Request.QueryString["width"], out width))
                width = 300;
            if (!int.TryParse(context.Request.QueryString["height"], out height))
                height = 60;
 
            byte[] image = null;
            ThumbnailCacheManager manager = new ThumbnailCacheManager(context.Cache);
            image = manager.GetThumbnail(path, width, height);
 
            if (image != null)
            {
                context.Response.ContentType = "image/png";
                try
                {
                    context.Response.OutputStream.Write(image, 0, image.Length);
                }
                catch { }
 
                context.Response.End();
            }
        }
 
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

 

 

Source Code | Small Demo

kick it on DotNetKicks.com



Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Sign in