LavaBlast Software Blog

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

jQuery plugin to postback an ASP.NET button

clock August 20, 2012 10:52 by author EtienneT

We use jQuery a lot here at LavaBlast, but we also use ASP.NET webforms. We needed a simple reusable way to cause a postback on an asp.net managed Button or LinkButton.

Here is how it would be used for <asp:Button ID=”btShow” runat=”server” OnClick=”DoSomething” />

// Cause btShow to postback to the server
$('[id$="btShow"]').postback();

If you are not too familiar with jQuery, the selector [id$=”btShow”] search for any control with an id which ends with “btShow”.

Since ASP.NET 4.0, you could also use the new ClientIDMode=”Static” property on the server control to be able to have a static ID on the client and use a jQuery selector like this: $(‘#btShow’), but this is the matter of another discussion completely.

The postback() method is a jQuery plugin which I include here:

(function ($)
{
    $.fn.extend({
        postback: function ()
        {
            return this.each(function ()
            {
                if (this && "undefined" != typeof this.click)
                    this.click();
                else if (this && this.tagName.toLowerCase() == "a" && this.href.indexOf('javascript:') == 0)
                    eval(this.href.toString().replace('javascript:', ''));
            });
        }
    });    
})(jQuery);

Feel free to use this and let us know if you find any problems with the code.



Style ASP.NET Web Forms Validators with qTip 2

clock August 13, 2012 08:20 by author EtienneT

View demo | Download source

The default validators inside ASP.NET Web Forms are quite uninteresting and require some styling work to look adequate.  Recently, we’ve been using the qTip2 jQuery library and we love it.  qTip enables you to add visually pleasant tooltips to any element.  For example, you simply add a “title” attribute to any element and then apply qTip to this element and the “title” attribute will be used as the tooltip’s text.  This is the simplest use case.  Here’s an example; with our FranchiseBlast registration form.

image

When you try to submit this form and the validation doesn’t pass, we replaced the default ASP.NET validators with styled qTip tooltips beside each validated element.

SNAGHTML6770ee44

Like you can see, the validators have absolute positioning, which enables them to flow outside of the bounds of the registration panel.  We could also easily change the position of the bubble in relation to the validated element and also change the bubble tip position.

Let’s take a look at what was needed to accomplish this, using a simple ASP.NET project. Here is the main ASP.NET code for the ASPX page.  Nothing fancy: a simple form with some validators:

Default.aspx

<asp:ScriptManager ID="p" runat="server">
    <Scripts>
        <asp:ScriptReference Path="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" />
        <asp:ScriptReference Path="~/Scripts/qtip/jquery.qtip.min.js" />
        <asp:ScriptReference Path="~/Scripts/validators.js" />
    </Scripts>
</asp:ScriptManager>
<fieldset class="Validate" style="width: 300px">
    <legend>Tell us about yourself</legend>
    <div>
        <span class="label">Business Name:</span>
        <asp:TextBox ID="txtBusinessName" runat="server" />
        <asp:RequiredFieldValidator ID="rfvBusinessName" runat="server" ControlToValidate="txtBusinessName" Text="Your business name is required" SetFocusOnError="true" EnableClientScript="true" />
    </div>
    <div class="alternate">
        <span class="label">Your Name:</span>
        <asp:TextBox ID="txtYourName" runat="server" />
        <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtYourName" Text="Your name is required" SetFocusOnError="true" EnableClientScript="true" />
    </div>
    <div>
        <span class="label">Your Email:</span>
        <asp:TextBox runat="server" ID="txtEmail" />
        <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail" Text="Email is required" SetFocusOnError="true" EnableClientScript="true" />
        <asp:RegularExpressionValidator runat="server" ID="revEmail" Text="Invalid Email" ControlToValidate="txtEmail" SetFocusOnError="true" ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$" EnableClientScript="true" />
    </div>
</fieldset>
<asp:Button runat="server" ID="btnCreateAccount" CssClass="Next" Text="Create Account" />

Starting from the top, we need jQuery and also qTip to be added to our page.  The interesting JavaScript code in located in ~/Scripts/validators.js.  The rest of the code here is a simple ASP.NET form.  One important thing is that each element to be validated is enclosed in a <div> with his corresponding validators.  This is important because we will use this convention later in our script to find the associated validators for an input control.

I also have to mention that I added some lines in the .skin file of the App_Theme:

Default.skin

<asp:RequiredFieldValidator runat="server" CssClass="ErrorMsg" Display="Dynamic" />
<asp:CustomValidator runat="server" CssClass="ErrorMsg" Display="Dynamic" />
<asp:RangeValidator runat="server" CssClass="ErrorMsg" Display="Dynamic" />
<asp:CompareValidator runat="server" CssClass="ErrorMsg" Display="Dynamic" />
<asp:RegularExpressionValidator runat="server" CssClass="ErrorMsg" Display="Dynamic" />

This will force CssClass=”ErrorMsg” on validators.  This will be used next in our JavaScript code to find the validators:

validator.js

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () {
    function getValidator() {
        return $(this).parent().find('.ErrorMsg').filter(function () { return $(this).css('display') != 'none'; });
    }
 
    var inputs = '.Validate input:text, .Validate select, .Validate input:password';
 
    var submit = $('input:submit');
 
    var q = $(inputs).qtip({
        position: {
            my: 'center left',
            at: 'center right'
        },
        content: {
            text: function (api) {
                return getValidator.call(this).html();
            }
        },
        show: {
            ready: true,
            event: 'none'
        },
        hide: {
            event: 'none'
        },
        style: {
            classes: 'ui-tooltip-red ui-tooltip-shadow ui-tooltip-rounded'
        },
        events: {
            show: function (event, api) {
                var $this = api.elements.target;
                var validator = getValidator.call($this);
                if (validator.length == 0)
                    event.preventDefault();
            }
        }
    });
 
    if (window.Page_ClientValidate != undefined) {
        function afterValidate() {
            $(inputs).each(function () {
                var validator = getValidator.call(this);
 
                if (validator.length > 0) {
                    var text = validator.html();
 
                    $(this).addClass('Error').qtip('show').qtip('option', 'content.text', text);
//                    validator.hide();
 
                }
                else
                    $(this).removeClass('Error').qtip('hide');
            });
        }
 
        $(inputs).blur(afterValidate);
 
        var oldValidate = Page_ClientValidate;
 
        Page_ClientValidate = function (group) {
            oldValidate(group);
 
            afterValidate.call(this);
 
            submit.removeAttr('disabled');
        }
    }
});

There is much to explain in this code.  First we register a new function to be executed each time there’s an ASP.NET PostBack on the page here: Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () { … });

The function getValidator finds the visible ASP.NET validators associated to a control to be validated.  We use the fact that the control to validate and the validators are contained inside a <div>.

We apply qTip to the inputs to validate and we get the text of the message by finding the visible validators.  Also we have some logic to prevent showing the qTip element if there aren’t any visible validators.

We also do some monkey patching at the end where we inject our own code inside the Page_ClientValidate ASP.NET JavaScript method.  To do that, we simply get a reference to the Page_ClientValidate function, create a new function with our additional code (calling the old Page_ClientValidate) plus we override window.Page_ClientValidate with our new function.  This new function have both the new and old functionality.

You would probably have to modify this code a little bit to fit your needs, but this shows how you could integrate qTip2 for nicer validators in ASP.NET Web Forms.

View demo | Download source



Microsoft Excel on Multi-Monitor Machines

clock June 5, 2012 11:51 by author jkealey

All of the developers at LavaBlast use three monitors; utilizing multiple monitors has significantly increased our efficiency. However, Microsoft Excel doesn’t work particularly well in a multi-monitor setup. By default, every time you open a new Excel file, its contents are displayed within the same instance. You have to manually launch other instances of Excel to have one instance per monitor, which is time consuming.

It is possible to configure Microsoft Excel to load one Window per file, but it involves a number of obscure configuration settings & registry changes. Every time we move to a new machine, this configuration needs to be redone. The information is spread out on a number of sites/forums and it takes a while to re-discover the sources. his post aims at centralizing this information.

In particular, this post focuses on Microsoft Excel 2010 on Windows 7 64-bit. I believe the fix works on other versions as well; feel free to comment on this blog post if the steps are different.

Step 1) Force Excel To Open Multiple Windows

Excel 2010:

  • File –> Options –> Advanced –> Scroll down into the “General” section –> Check the “Ignore other applications that use Dynamic Data Exchange (DDE)” checkbox image

Excel 2007:

  • Office Icon in the top left corner of Excel –> Excel Options –> Advanced  -> Scroll down into the “General” section –> Check the “Ignore other applications that use Dynamic Data Exchange (DDE)” checkbox

Once this change is done, every time you double click on an Excel file in Windows Explorer, a new instance of Excel will open. However, you’ll probably encounter the following error.

Step 2) Fixing “There was a problem sending the command to the program”

Each Excel file you open from Windows Explorer now launches in its own separate window. However, Excel spits out “There was a problem sending the command to the program” and leaves the Excel window blank.  You can drag & drop your existing file to this window to open it, but this is still painful. We will need to change the system registry to solve this issue; please refrain from doing this is you are not comfortable with the reg edit tool.

  1. Launch regedit
  2. Rename the HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\ddeexec  key to HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\ddeexec.bak
  3. Edit HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\command\(Default).  Change /dde to “%1” in the value.
  4. As an example, mine was from "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" /dde to "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE" "%1"
  5. Edit HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\command\command. Change /dde to “%1” in the value.
  6. As an example, mine was from ykG^V5!!!!!!!!!MKKSkEXCELFiles>VijqBof(Y8'w!FId1gLQ /dde to ykG^V5!!!!!!!!!MKKSkEXCELFiles>VijqBof(Y8'w!FId1gLQ "%1"
  7. Rename the HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\ddeexec key to HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\ddeexec.bak
  8. Edit HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\command\(Default). Change /dde to “%1” in the value.
  9. Edit HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\command\command. Change /dde to “%1” in the value.

 

Excel should now load separate Windows for each file you open. This setup will consume more memory, but will vastly increase your productivity.

Troubleshooting note:

  • Ensure you used “%1” with the surrounding quotes (not this: %1) in the above registry changes. Otherwise, you will get an error message: “’{file}’ could not be found. Check the spelling of the file name, and verify that the file location is correct.”

Thanks to Turbo2001rt  for the final important tweaks.



      LavaBlast POS v4.0.0

      clock September 6, 2011 13:49 by author jkealey

      We’re just about to release the version 4.0.0 of our franchise point of sale system. One of the most noteworthy change is the fact we’ve given the look & feel a major overhaul, thanks to jQuery Mobile which we’ve blogged about previously. We thought we’d take a minute to share with you what makes it so special!

      First off, I’ve recorded a short video featuring a variation of our franchise POS for the Teddy Mountain franchise. Teddy Mountain provides the stuff your own teddy bear experience to children worldwide and have been using our POS since 2006.

       

      As you’ll see, I focus on a few of our differentiators in the point of sale space. We’re not a point of sale company and our POS is not conventional: we’re a franchise software company and we’ve created the best point of sale system for a franchise environment.

      We bake in a franchise’s unique business processes into the point of sale, making it very powerful while still extremely easy to use. By integrating our point of sale with FranchiseBlast, we’ve also eliminated dozens of standardization/uniformity issues which face small retail chains or franchises.

      Furthermore, we’ve given additional focus to cross-browser compatibility in this release as our POS is not only used regular POS hardware (in brick & mortar stores) but also on the Apple iPad for back office operations an for managing the warehouses that feed our franchise e-commerce websites.  We’re definitely excited by the potential tablets have for both retail and service-based franchises! Expect more news from us in this space soon!

      In the meantime, if you know of small chains / new franchises which want to explore disruptive technologies in their locations, we hope you’ll point them in our direction!



      Gotcha: Reporting Services Viewer bugs on Google Chrome

      clock June 28, 2011 11:09 by author jkealey

      We include the ASP.NET ReportViewer which comes with Microsoft SQL Reporting Services inside some of our applications. Simply put, it generates a web-based version of the report and can easily be integrated within a website. However, the ReportViewer has been plagued with numerous cross-browser compatibility bugs over the years. Some have been fixed, while others remain. Recently, we’ve had the following issues:

      • On Google Chrome, each button in the toolbar takes a separate line. You thus end up with 5 toolbars instead of one, taking up all the space.
      • On Google Chrome, the width & height were slightly off (50 to 100 pixels), causing scrollbars to appear.
        A quick search revealed some sample code for similar issues, but none of them fully resolved our issues. Mainly, we require AsyncRendering=”true” and most of the fixes didn’t work in this context. Here’s what we ended up rolling with (uses jQuery and Microsoft AJAX).
        ~/js/fixReportViewer.js
           1:  // container is either the ReportViewer control itself, or a div containing it. 
           2:  function fixReportingServices(container) {
           3:      if ($.browser.safari) { // toolbars appeared on separate lines. 
           4:          $('#' + container + ' table').each(function (i, item) {
           5:              if ($(item).attr('id') && $(item).attr('id').match(/fixedTable$/) != null)
           6:                  $(item).css('display', 'table');
           7:              else
           8:                  $(item).css('display', 'inline-block');
           9:          });
          10:      }
          11:  }
          12:  // needed when AsyncEnabled=true. 
          13:  Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function () { fixReportingServices('rpt-container'); });
          14:  /*$(document).ready(function () { fixReportingServices('rpt-container');});*/
        example .aspx
         1:  <div style="background-color: White; width: 950px" id="rpt-container">
         2:      <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Times New Roman"
         3:          Font-Size="8pt" Height="700px" Width="950px" ShowExportControls="true" ShowPrintButton="false" 
         4:          ShowRefreshButton="false" ShowZoomControl="false" SkinID="" AsyncRendering="true"
         5:          ShowBackButton="false">
         6:          <LocalReport ReportPath="contract.rdlc"
         7:              DisplayName="Contract">
         8:          </LocalReport>
         9:      </rsweb:ReportViewer>
        10:  </div>
        11:  <asp:ScriptManagerProxy ID="proxy" runat="server">
        12:      <Scripts>
        13:          <asp:ScriptReference Path="~/js/fixReportViewer.js" />
        14:      </Scripts>
        15:  </asp:ScriptManagerProxy>

      The fixes we found on other websites (setting the display to inline-block on the included tables) only worked for the first load – as soon as the report changed due to AsyncRendering=”true”, the toolbars were broken again. This was fixed by replacing jQuery’s ready function with Microsoft ASP.NET Ajax’s PageLoaded function.

      We also noticed that these fixes also broke down our width & height. We pinpointed the issue to the generated HTML table with the id ending with fixedTable, which needed to be left as display table instead of inline-block. We thus adapted the JavaScript.

      The HTML wraps the ReportViewer with a div, mostly for convenience (to avoid peppering our code with <%= ReportViewer1.ClientID %>). Furthermore, if my memory serves me well, we set the background-color manually because some browsers made the ReportViewer transparent.

      Hope this helps! If you find more elegant ways of doing this, or know of more gotchas, please let us know!



      Using Microsoft POS for .NET in 2011

      clock June 6, 2011 08:41 by author jkealey

      Five years ago, we decided to utilize Microsoft’s Point Of Service for .NET (POS for .NET) in our point of sale (POS) to integrate with the various peripherals used by POS systems. Simply put, POS for .NET enables developers to utilize receipt printers, cash drawers, barcode scanners, magnetic stripe readers (MSR), line displays (and many other peripherals) within their .NET applications. Back then, the .NET framework was at version 2.0. Obviously, many things have changed since then with the advent of .NET 3.0, 3.5 and, more recently, 4.0. However, the latest version of POS for .NET’s is v1.12 and it was released in 2008.

      Being forward-thinking as we are, we structured our point of sale as a web application from day one, to enable future deployment scenarios (being browser-based means we can easily use our point of sale on the iPad or any other hot hardware platform) and code-reuse within our e-commerce application and FranchiseBlast. However, this made it a bit harder on us to integrate with the peripherals as we weren’t using them in the traditional context of a desktop application (especially access Windows printers from a server-side web application). However, we solved those issues many years ago and have continued to evolve the solution ever since.

      Fast forward to 2011: POS for .NET has not been refreshed in three years, we’ve moved to 64-bit machines and .NET 4.0. This blog post is a collection of tips & tricks for issues commonly faced by .NET developers working with POS for .NET in 2011.

      Common Control Objects – don’t forget about them!

      This is just a reminder, as this was true back in 2006 too. You’d typically expect to be able to install the peripheral’s driver and then utilize it within your .NET application. However, you also need to install intermediary Common Control Objects.  I always end up downloading the CCOs from here.  I always forget the proper order and sometimes run into trouble because of this and end up having to uninstall and reinstall half a dozen times until it works (… pleasant…). I believe this is the installation order I use (you may need to reboot between each step).

      1. Install Epson OPOS ADK
      2. Install other drivers (scanners, etc.)
      3. Install the Common Control Objects
      4. Define logical device names (LDN) using Epson OPOS
      5. Install POS for .NET 

       

      POS for .NET doesn’t work in 64-bit

      Long story short, due to the legacy hardware it supports, POS for .NET only works in 32-bit. If you’re running an app on a 64-bit machine, it will fail with a cryptic error message or will simply be unable to find your peripherals. Example:

      System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {CCB90102-B81E-11D2-AB74-0040054C3719} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

      You can still use the peripherals on 64-bit operating systems, but you will need to compile your desktop application as 32-bit (Right click on your project –> Build –> Platform target: x86). You even need to do this with the example application that comes with POS for .NET (in C:\Program Files (x86)\Microsoft Point Of Service\SDK\Samples\Sample Application) if you want to use it.

      You’ll probably run into the same issues with all the .NET test applications supplied by the device manufacturers. Unless you can manage to find an updated sample, you’ll have to work your magic with a decompiler. In addition to probably being illegal, it is a pain and a half. Therefore, you’re better off using the test application that comes with POS for .NET.

      As for web applications, you need to force IIS to run your application in a 32-bit application pool.

      POS for .NET doesn’t work in .NET 4.0

      Another bad surprise is migrating your application to .NET 4.0 and then realizing the POS hardware stops working. Long story short, you’ll get this error:

      This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570

      The error message is fairly self-explanatory. Microsoft stopped supporting '”Code Access Security”, which is internally used by POS for .NET. You can either turn on a configuration option that re-enables the legacy CAS model or wait for Microsoft to release a new version of POS for .NET.  We’ve been told not to hold our breath, so the configuration option is the preferred flag. 

      If you’re creating a desktop application, the solution is in the error message – more details here.  Add this to your app.config:

      <configuration>
         <runtime>
            <NetFx40_LegacySecurityPolicy enabled="true"/>
         </runtime>
      </configuration>

       

      If you’re creating a web application, the flag is a bit different. Add this to your web.config:

      <configuration>
          <system.web>
            <trust legacyCasModel="true"/>
         </system.web>
      </configuration>

      POS for .NET doesn’t work with ASP.NET MVC / dynamic data/operations

      The above flag will cause your legacy code to run properly on .NET 4.0 but it does have a side-effect. You will not be able to use some of the newer .NET framework features such as the dynamic keyword. Not only can you not use it explicitly within your own code, but ASP.NET MVC 3 uses it internally within the ViewBag.

      Dynamic operations can only be performed in homogenous AppDomain.

      Thus, you have to choose between POS for .NET or ASP.NET MVC 3, unless you load up your POS objects in another AppDomain. Here’s some sample code to help you do that.

      You need to be able to create another AppDomain and specify that this AppDomain should use the NetFx40_LegacySecurityPolicy option, even if your current AppDomain doesn’t have this flag enabled.

         1:  var curr = AppDomain.CurrentDomain.SetupInformation;
         2:  var info = new AppDomainSetup()
         3:  {
         4:      ApplicationBase = curr.ApplicationBase,
         5:      LoaderOptimization = curr.LoaderOptimization,
         6:      ConfigurationFile = curr.ConfigurationFile,
         7:  };
         8:  info.SetCompatibilitySwitches(new[] { "NetFx40_LegacySecurityPolicy" });
         9:   
        10:  return AppDomain.CreateDomain("POS Hardware AppDomain", null , info);

       

      You can then use this AppDomain to create your POS peripherals. All our peripherals extend our own custom PosHardware base class with a few standard methods such as FindAndOpenDevice(), so we use the following code. For testing purposes, we created a configuration option (IsHardwareLibInSameAppDomain) to toggle between loading in the current AppDomain versus a separate one.

         1:  private T Build<T>(string id) where T : PosHardware, new()
         2:  {
         3:      T hardware = null;
         4:      if (IsHardwareLibInSameAppDomain)
         5:          hardware = new T();
         6:      else
         7:          hardware = (T)OtherAppDomain.CreateInstanceFromAndUnwrap(Assembly.GetAssembly(typeof(T)).Location, typeof(T).FullName);
         8:   
         9:      if (!string.IsNullOrEmpty(id))
        10:          hardware.DeviceName = id;
        11:      hardware.FindAndOpenDevice();
        12:      return hardware;
        13:  }

       

      Also, don’t forget to mark your classes as Serializable and MarshalByRefObject.

         1:  [Serializable]
         2:  public abstract class PosHardware : MarshalByRefObject

       

      Working with objects in other AppDomains is a pain.  Any object that you pass between the two app domains (such as parameters to functions or return values) must be marked as Serializable and extend MarshalByRefObject if you wish to avoid surprises.  If you marshal by value instead, you will be working on read-only copies of (which may or may not be desirable, depending on your context.)

      Conclusion

      It only took three years without a new release before POS for .NET started being a pain to work with – unless you stick with past technologies. With the advice provided here, however, you should be able to move forward without issue. Did you discover any other gotchas with POS for .NET?


      Gotcha: iPad versus ASP.NET

      clock May 29, 2011 14:19 by author JKealey

      Your web app looks awesome on the iPad, until…

      FranchiseBlast: Franchise Intranet on iPad You decide to save it to your home screen.

      If you’re doing this with a web application you’ve developed, you probably want to make it appear a bit more like a native app,  so you’ll add two meta tags to make the experience nicer (add an app icon and remove the navigation bar). Remember: Safari caches these tags when creating the shortcut, so you will need to delete/recreate the shortcut to force it to refresh.

      Everything will look fine, until you reload the web app on some other occasion: ASP.NET Ajax is now completely broken and many of your styles are missing. Simply put, an application that worked fine when you shut down your iPad minutes ago will be completely unusable. No amount of refreshing will solve the issue. Clearing Safari’s cache and using it outside of the home screen icon is the only workaround.

      Gotcha: Safari uses different HTTP User-Agent strings depending on context!

      The iPad (and iPhone/iPod Touch) don’t use the same HTTP User-Agent string when a website is accessed normally via the Safari application versus a webpage that was saved to the home screen (which still uses Safar internally). Here’s an example:

      • Normal Safari: Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2
      • Website as app: Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Mobile/8J2
        ASP.NET doesn’t recognize the latter as being Safari – it recognizes it as a generic browser with no capabilities. As an example: Supports JavaScript? Nope.
        Add this hack to your base page to fix it. It makes ASP.NET think that anything based on AppleWebkit is a newer browser – a much better default setting (for most of us) than assuming the browser was created back in 1994.
           1:     protected void Page_PreInit(object sender, EventArgs e)
           2:      {
           3:          if (Request.UserAgent != null && Request.UserAgent.IndexOf("AppleWebKit", StringComparison.CurrentCultureIgnoreCase) > -1)
           4:          {
           5:              this.ClientTarget = "uplevel";
           6:          }
           7:      }

      The long answer

      On and off over the course of a month, I spent dozens of hours investigating this issue. In the end, the fix is trivial and updated *.browser files will probably be produced by Microsoft over the next months/years. However, I did learn a lot about how to debug a web-app on the iPad in the process, and thought I’d share a few lessons learned. I’ve kept them purposefully brief as you can easily find detailed answers on Google or StackOverflow.

      Enable Safari’s Developer Debug Console

      That’s how I figured out ASP.NET AJAX wasn’t loading properly. Was getting JavaScript errors that you normally get when ASP.NET Ajax is not properly configured in the web.config file.

      • On the iPad: Settings –> Safari –> Developer –> Debug Console (on)

      Install Firebug Lite on your iPad

      I frequently use Firebug on my desktop computer to analyse web pages. The lite version on the iPad helped me review the HTML/JavaScript in greater detail. Install this bookmarklet (found it painful to do) then install the FireBug Lite bookmarklet. More info here.

      Setup an HTTP Proxy

      This helped me get in-depth information about exactly what HTML/JavaScript was being served in response to which HTTP Headers. That’s how I realized certain scripts were not being included when the User-Agent changed.

      • As I develop on a Windows machine, I made it run through Fiddler on my desktop. Other options found here.
      • In Fiddler, Tools > Fiddler Options > Connections –> Allow Remote Computers To Connect. Restart Fiddler. (Not working? Check Windows Firewall.)
      • On the iPad: Settings –> Wi-Fi –> Click on the right arrow for your connection –> HTTP Proxy –> Manual –> Set Server and Port. 

      Other limitations worth knowing about

      As everyone knows, Flash doesn’t work on the iPad/iPhone/iPod. It doesn’t come as a surprise to use that we have to eliminate it from our app (not a big detail for us).

      However, one gotcha that had not come to mind initially is that certain JavaScript functionality such as click&drag or drag&drop does not work on the iPad given the differences in gestures between a conventional computer and a tablet. That code needs to be rewritten.

      Did you experience any issues you’d like to share?



      Re-skin your existing web app using jQuery Mobile

      clock May 24, 2011 15:44 by author EtienneT

      IMG_3337Recently, for a new franchise client of ours, we had to add some new features to our web-based point of sale system.   This piece of software makes extensive use of touch screen functionality; we need to think about this when we design our UI.  The interface must be optimized to allow cashiers to perform their operations effectively and intuitively with a touch screen.  Our application isn’t traditionally used via a multi-touch interface like the iPhone or iPad; rather, operators use a traditional touch screen. In this project, we had to adapt existing pages and create completely new modules.

      In the past, we had played with jQuery Mobile and we were really impressed.  Take a look at the demo site – all you need to do is including a reference to jQuery Mobile’s JavaScript and follow some conventions with your HTML to get a nice mobile-friendly user interface. However, when you think about it, mobile-friendly (touch friendly) user interfaces are also very appropriate for traditional touch screen technologies utilized by the retail industry for over a decade.

      Given our point of sale was initially created to be compatible with IE6 back in the day, we felt it was time to enhance the look and feel utilizing new technologies. We liked jQuery Mobile’s look & feel and wanted to utilize some bits & pieces, without having to re-implement everything following their conventions.  When you peek at the jQuery Mobile source code on GitHub, you realize that each component is separated in it’s own little jQuery plugin.  Some plugins are not completely independent from the jQM (jQuery Mobile) page, but you can use most of them outside of that context; you can thus use them in your own applications without a jQM page that takes 100% of the screen real estate.  In a typical jQM scenario, you define a page and then jQM works it’s magic: it initializes all the controls for you - if you followed the conventions. In this post, we’ll cover using jQuery Mobile outside of the jQM page and mobile context.

      How to trick jQuery Mobile

      First, you simply have to trick jQM into thinking that there’s a jQM page in the HTML.  To do that, you have to bind to a special jQM event, mobileinit.  This is event is executed before any jQM code modifies your html:

      $(document).bind("mobileinit", function ()
      {
          if ($('div[data-role=page]').length === 0)
              $('<div data-role="page" id="pageTemp" style="display:none;"></div>').appendTo($('body'));
       
          $.mobile.ajaxEnabled = false;
       
          $('#pageTemp').live('pagebeforecreate', function (event)
          {
              return false;
          });
      })

      Here you insert a jQM page in your html if one hasn’t already been defined. This is required for some controls to work (like the dropdown list, if I remember correctly). We then disable AJAX page fetching and also disable the 'pagebeforecreate' event for the newly created dummy page.  Most of our pages utilize this placeholder (as we only use the UI controls), but we did – on a few occasions - utilize the standard jQM page in all its glory inside our point of sale. 

      If there’s a better way to do this, please let us know - with the current version of jQuery Mobile (1.0a4.1) it appears to be working pretty well.

      Interesting controls

      The plugins we found most interesting were the one dealing with forms controls. You can see a gallery of all forms elements in jQuery Mobile here.

      For example, some of the base HTML controls are not ideal in the context of a touch-enabled application. Take radio buttons, for example. They are way too small and hard to click on accurately - you have to manually change their styling via CSS to make them easy to touch.  Here is the jQM version of radio button list:

      Radio Button List

      radio

      To create this, first you need a little bit HTML plus the checkboxradio plugin from jQuery Mobile:

      <fieldset data-role="controlgroup">
          <input type="radio" name="radio-choice-1" id="radio-choice-1" value="Cat">
          <input type="radio" name="radio-choice-2" id="radio-choice-2" value="Dog">
          <input type="radio" name="radio-choice-3" id="radio-choice-3" value="Hamster" checked="checked">
          <input type="radio" name="radio-choice-4" id="radio-choice-4" value="Lizard">
      </fieldset>

      Basically the fieldset groups the radio input together and gives the rounded corners only to the top and bottom items.

      Then you can add this JavaScript to your page:

      $('input[type=checkbox], input[type=radio]').filter(function ()
      {
          return $(this).parent('.ui-checkbox').length == 0;
      }).checkboxradio();
      $("fieldset[data-role='controlgroup']").not('.ui-controlgroup').controlgroup();

      This piece of JavaScript will select all checkboxes or radios inputs, filter the ones we already applied the plugin and then call checkboxradio() to change them to follow the jQuery Mobile style.  We then use the controlgroup plugin to group the controls together visually.  Once again we don’t re-apply this code to fieldsets that were changed previously, for efficiency reasons.

      For an horizontal look, simply add data-style=”horizontal” to the fieldset grouping the elements.  It is still a radio button list, but the layout is different.

      radio-horiz

      Checkbox list

      You can even do the same thing with checkboxes:

      checkboxes

      Suddenly, your UI becomes much easier to use with a touchscreen.

      Dropdown

      Here is a dropdown list, in the jQuery Mobile style:

      dropdown

      You simply execute the following JavaScript code:

      $('select:not([multiple="multiple"])').selectmenu();

      We had some problems with multi-selection lists, so that’s why we don’t automatically style those.

      Button

      Buttons are pretty straightforward. In our application, we decided to automatically transform all of our buttons which utilize the CSS class ‘button’.  This could be an input[type=button], input[type=submit], a simple link <a></a>.  We’re using a mix of these in our application and modify them all like this:

      $('.button').not('.ui-btn').button();

      buttons2

      Above, the two buttons are inline (add the data-inline=”true” attribute to the HTML elements). The Save button has a different theme (specify data-theme=”b”)

      buttons

      You can also group buttons as above, by defining a horizontal controlgroup.

      <div data-role="controlgroup" data-type=”horizontal”>
          <a href="index.html" data-role="button">Yes</a>
          <a href="index.html" data-role="button">No</a>
          <a href="index.html" data-role="button">Maybe</a>
      </div>

      Working with controls

      Visit this page to know operations you can do on your controls once they are modified by jQM: Form Plugin Methods. This reference is very useful if you want to enable/disable controls or refresh them with new values.

      ASP.NET WebForms

      If you are using ASP.NET WebForms as is our case, you want to run these plugins every time your page is modified.  If you are using ASP.NET UpdatePanels, then you can bind a function to the following event handler where you could modify your controls each time an UpdatePanel is updated:

      Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function()
      {
          // Add the jQuery Mobile code modifing controls here
      });

      Normally this job is done automatically by jQM, but since we are not using the controls inside a jQM page, we have to update the DOM manually after each postback.

      Caveat

      In its current form, jQuery Mobile is not compatible with Internet Explorer. Depending on the version of IE, it is easier completely unusable or doesn’t look as good (rounded corner issues). In our context (point of sale), we ended up utilizing Google Chrome Frame for our IE users – at least for the time being. The jQM team appears to be working towards full IE support for their beta release.

      Future of jQuery Mobile

      In conclusion, we loved working with jQuery Mobile once we figured out how to utilize bits & pieces of it individually. Currently, jQM focuses on development for mobile devices (which is normal) but we would be thrilled if they made integration into existing projects simpler. As this is an open source project, we weren’t afraid to peek at the code to figure out why it wasn’t working the way we intended it to. Let’s hope the project keeps on improving both its modularity and the desktop-based functionality.  Thank you to the jQuery Mobile team, continue the great work!



      Slash your ASP.NET compile/load time without any hard work

      clock December 1, 2010 09:18 by author JKealey

      Jason has a cool eye :) FranchiseBlast, our franchise management platform, is a ‘large’ solution inside Visual Studio which currently contains 35 projects. In total, we manage over 60 interrelated projects, and have always been concerned at improving the compilation/load performance on our development machines. This post is a quick summary of what we did to keep things as fast as possible.

      Personally, when it starts taking over a minute to compile or load my application, I start throwing things. This was the case early this week and with a bit of work, I managed to cut down things by an order of magnitude (from around 140 seconds down to around 14 seconds) with only software changes.  This is what prompted me to write this post.

      There are three things worth improving:

      1. Compilation time
      2. First load time (ASP.NET)
      3. Application speed / database performance

       

      I only want to talk about the first two; the only tip I’ll give you for #3 is to get your hands on a profiler such as dotTrace as it is a real time saver. 

      Get better hardware (Big impact)

      You’ll get the best bang for your buck by upgrading your hard disk, especially if you’re using a single 5400 RPM or 7200 RPM drive (download benchmark software to evaluate your current disk). Our projects are stored on a solid state disk. We currently use Intel X25-M G2, but the RevoDrive x2 looks much faster (basically a RAID-0 array of SSDs) if you have an available PCI-Express x4 slot. If you’re cheap and find the SSDs to be too small, just get two large 7200 RPM drives and put them in RAID-0. Make sure you’ve got a robust backup solution.

      We have 12GB RAM on our development machines and a recent Core i7 processor, but nothing fancy. This is more than sufficient.

      Store your temporary IIS files on your fastest disk or a RAM disk

      Depending on the amount of RAM you have, it may make sense to use a RAM disk. I use my RAM disk for my temporary internet files and for IIS’s temporary folder (compilation results). I haven’t measured specific performance details but since I have so much free RAM, might as well try use it in creative ways.

      To speed up the first load time, you can tell IIS to store its temporary files on your RAM disk (or fastest disk) by changing the following setting in your web.config files:

      <compilation ... tempDirectory="q:\temp\iistemp\"> ... </compilation>

       

      You can either change your project files directly, or, if you’ve lazy and have numerous applications running on your development machine (like I do), update the system-wide web.config files. Note that you need to update this for each runtime version of the Framework and, if running a 64-bit machine, for both Framework and Framework64. On my machine, I needed to modify the following files:

         1:  C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\Web.config
         2:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Web.config
         3:  C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG\Web.config
         4:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\Web.config

       

      Trade-off: If you save your RAM disk when shutting down, you’ll notice how much longer it takes to reboot. I can live with that, rebooting only once every couple months.

      Review a few magical settings (Most impact)

      When an ASP.NET website is loaded for the first time, it pre-compiles all your pages and user controls. Once done, everything runs faster. This is great for production websites, but horrible for your development machine. Why?  When programming, you’re usually only modifying a page or two (or back-end code). You’ll iteratively make a change, compile, launch the website, test, and start over; often dozens of times. A two minute compile/load time (like we had) forces you to lose focus and get distracted. The following setting makes pre-compilation more selective, making the first load time massively faster in development scenarios. On my machine, it cut the first load time from around 74 seconds to 6 seconds.

      <compilation ... batch="false"> ...</compilation>

       

      While on the subject of random boolean flags that make your life better, I should mention the following:

      <compilation ... optimizeCompilations="true"> ... </compilation>

      This flag has a number of gotcha’s that are documented here. I’ve enabled it for now, although my quick tests didn’t show any significant performance improvements compared to the previous one. However, I was probably not testing the right thing.

      Restructure your projects

      Try multiple solutions

      About a year ago, we took 50% of our least used projects and moved them into a secondary solution. We compile that solution only when changing one of these projects, once every couple months. After rebuilding the secondary solution, we copy the *.dll files to a separate folder. Our primary projects reference those pre-generated libraries. I should repeat this process again, but I like having all my projects in one place and splitting them was a pain. However, this is probably the only sustainable way to manage extremely large solutions.

      Selectively build the necessary projects

      Using Visual Studio’s Configuration Manager, I also created different active solution configurations in my primary solution with only a subset of the projects included in the build.  I can thus swap between configurations depending on my primary task (working on our point of sale instead of FranchiseBlast, for example). This can drastically reduce compilation time, but I don’t use it as often as I should because:

      1. I find the user interface slow to refresh (Visual Studio).
      2. My dependency tree is complex and going through the list of projects to remove those I don’t want built is a pain.
      3. I context-switch a lot and often hit cases where I modify a project and forget that is not included in the build.

       

      A simpler option is to build only the current project (and its dependencies) instead of all projects. Just make sure you don’t accidentally break the build (recompile everything before a commit).

      Parallel compilation (Big impact)

      Following Scott Hanselman’s post, I setup my project to compile in parallel. I did add a few options to make it easier for me to see errors/warnings without MSBuild’s typical clutter. (I also had a post-build action using NAnt which I set to quiet). This reduced my full rebuild time from 96 seconds down to 16 (after a clean solution). In a typical recompilation, we’re talking roughly 8 seconds instead of around 66.

      Title: Parallel Build
      Command: C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe
      Arguments: /m $(SolutionFileName) /v:m /ds /nologo /clp:Summary;Verbosity=minimal
      Initial Directory: $(SolutionDir)
      Check: Use Output window.

      Trade-off: Error messages aren’t nicely presented in the Visual Studio Error List tab and you are not notified when the build is complete. 

      Other noteworthy attempts

      Over time, I’ve tried a few things that didn’t work out. In general, they improved things slightly but I don’t use them on a daily basis due to the tradeoffs.

      I tried putting the whole project (source and output folders) onto the RAM disk but its volatility scared me away, regardless of the performance enhancements (Off the top of my head, it was between 25% and 50%). I then tried putting my only project’s bin folders on my RAM disk (by creating symbolic links from my bin folders to my RAM disk). This also had a positive impact on performance, but not significant enough to warrant the kludge (around 25% reduction in compilation time).

      I also found a few tips & tricks for larger projects on Stack Overflow. First, I tried putting ‘Copy Local’ to false for all project references. This gave me a 25% reduction in compilation time, but broke my deployment scripts which needed all the files in the bin folder.  Separately, I configured all my projects Output Paths to the same folder, avoiding content duplication on the disk. This also gave me a 25% reduction in compilation time. Oddly enough, moving this folder to my RAM disk did not impact performance.

      Summary

      I hope this post gave you some ideas on how to improve your compilation speeds and first load times. I didn’t intend to give exact benchmarks, as performance will vary greatly depending on your projects. However, the main lesson learned is that there are dozens of improvements you can make; it’s up to you to try them out and keep what works for you.

      The top three time savers for us are:

      1. Setting batch=false in the ASP.NET configuration page. (Now ~10 times faster)
      2. Parallel compilation for our projects (Now ~8 times faster)
      3. Better hardware (Now between 2 and 5 times faster)

       

      Honorable mention goes to splitting your solution files, even though it’s painful and time consuming process to setup.

      Do you have any other tips & tricks you’d like to share with us?



      Collaboratively Defined Business Strategy

      clock March 31, 2010 13:54 by author jkealey

       

      bookingblast For those of you who’ve been keeping track, we launched LavaBlast Software back in April 2007. A year later, we posted three software startup lessons about how we got started and followed up the year after that with four more fun software startup lessons. Now that Year 3 is complete, I should write another set of software startup lessons, but that can wait. Today, I feel we’ve come full circle because we’ve begun working on the type of fun project that we would have enjoyed doing three years ago, but couldn’t afford the risk. In a sense, it feels like a full circle and a new beginning for LavaBlast even though we’re simply working on a new product.

      BookingBlast is going to be legen – wait for it – dary. Read on to know more!

      Starting from scratch

      Pretty much straight out of university, we started LavaBlast Software. We had no money so we had to be creative. By creative, I mean we had to be cheap, work hard and work on something low risk to pay the bills.  The recipe for success is simple and we’ve said it before. Let’s just say we sell to businesses and we keep the intellectual property. This strategy has allowed us to start from scratch and making a living. 

      We already have BookingBlast’s building blocks and now have enough runway to execute on our idea.

      Ramping up

      Some may stop here – but that’s not enough for us. We have greater ambitions - we’re looking for something bigger - for a greater reward. Based on the assumption that it takes a decade to launch a successful business, we’re not even a third through. We’ve passed through survival and have been growing steadily, but we’re now anxious to move to the next level.

      We feel we can get there by converting the enterprise-level software we’ve been producing to date into more scalable Software as a Service (SaaS) products. We’ve been wanting to do this since day 1, but needed short-term revenues.  We’re now re-investing into LavaBlast to give us this flexibility. (I guess that visit to an unspoiled private tropical island will have to wait.)  We toyed with a few concepts during the past year, looking for software products that:

      1. No per-client customizations (greater scalability)
      2. Sold to businesses, not individuals (faster revenue)
      3. Shorter sales cycle, lower recurring dollar amount per sale (easier to commercialize)
      4. Related to our existing work and/or future strategies (reuse and upsell synergies)

       

      Hold your horses! I’ll describe BookingBlast’s awesomeness in a minute.

      Context & Goal

      Our short-term goal with this project is knowledge. We’ve been building enterprise software for a while and want to dumb things down and start aiming for higher volume, but we need to adapt our know-how. We see BookingBlast as a practice run whereas our business is a marathon.

      Our long-term goal is growth, in terms of revenue and the size of the company.  Lots of the enterprise-level work we’ve done can be commercialized to a broader market but we need a longer runway.

      Spill the beans already! What’s BookingBlast?

      BookingBlast allows service-based businesses to accept online bookings. Reservations are accepted only during available time slots and deposits are paid online, in advance.

      To clarify, our software will allow customers to:

      • Book your child’s birthday party online
      • Book mobile clowns/magicians/comedians online
      • Reserve a massage / spa services online
      • Book your chiropractor from their website
      • Book a photographer from their Facebook page
      • … and accept bookings/reservations in many other industries.

      That’s it. It’s not rocket science. It’s been done already – there are many competitors in this space – the market exists. The barrier to entry is low. But that’s not stopping us, because we have a plan. What better way to test our plan than to go out and execute it?  The worst that will happen is sales will be lower than desired and we’ll still reach our short-term goal of knowledge. We’re not betting the farm on this – it’s a stepping stone in the context of our longer-term vision.

      How did you come up with your secret master plan?

      We understand that this is a marketing play more than a technical one. We’re not inventing a killer product, although we can be innovative in our implementation. We decided it was in our best interests to share our plans for BookingBlast with people from diverse backgrounds and get them involved in the process. Ian Graham of The Code Factory always says the engineering students/graduates from the University of Ottawa are more secretive than the ones from Carleton University and we decided to prove him wrong. We openly solicited feedback on Google Wave and at TeamCamp. In the end, we found that we’re not that crazy after all as this validated our initial opinions. We did discover a few interesting twists which we plan on using, however.

      Therefore, our plan is not secret – you’ll hear more about it when our product will be in beta. However, here a few lessons we learned from our experiences with collaborative planning.

      Phase 1: Internal research

      We looked around to find competitors and market penetration strategies. We discussed this internally over a coffee and did our homework. I produced a one-page executive summary of my initial plans.

      Phase 2: Feedback solicitation via Google Wave

      We published a private wave and invited two dozen random people. We made sure to invite people who were not extremely close to us because their feedback would be biased. We made it clear that the participants could feel free to ignore us as we didn’t care to force anyone into open collaboration, especially if they were busy with their own work. We found that the people least close to us were the ones who contributed the most to the discussion. Within 24h, the discussion had grown to approximately 8 times as long as the original executive summary. Within the next 48h, the discussion grew a bit more, with a few late-comers giving their comments.

      The early discussions were the most valuable. They brought in new elements and got everyone involved. They definitely changed our strategy. However, as the discussion grew, I felt that most people lost interest because there was too much to be read. The barrier to entry had been raised, which caused most of the late-comers to elect not to participate. Initially, we thought this was a bad thing as we wanted more feedback, but in retrospect, we feel that what needed to be said was said early on. Had we discussed the same material with each person individually, we would have elicited the same comments over and over. Redundant feedback is not useful (other than for validation) and is a huge time waster.

      In conclusion, open collaboration is a great technique to elicit feedback very quickly. I am greatly thankful to those who participated.

      Phase 3: Feedback solicitation via TeamCamp

      jkjp Ottawa’s primary co-working location, The Code Factory, hosts a bi-monthly event initiated by Chris Schmitt called TeamCamp. Once in a while, TeamCamp will have a pitch night where the participants pitch their idea to the group and get feedback. This is a very informal round-table setup but you get to chat with interesting people in Ottawa. A few weeks ago, I pitched BookingBlast to the group. This was great validation for our online booking software, as it proved that we had properly thought it out. Some new strategies were put on the table, but the biggest lesson learned is that you don’t need to spend months thinking about your project if you’re agile enough to adapt it along the way.

      Furthermore, we finally had someone stand up and say our idea wasn’t good enough, something we had been waiting for since we started planning BookingBlast. Given the small scale of the project and the low barrier to entry, I was expecting most people to shoot our idea down quickly. Maybe I watch Dragon’s Den too much and read too many angel investor/venture capitalist blogs. In any case, this brought forth great discussions where it appeared other individuals were reading my mind while defending our online reservation software for me.

      We’re now ready to start implementing the project! (In fact, we’ve already started and it is progressing nicely!) 

      We need your help

      We’ve posted a basic information request page on our website. If you know business owners that would be interested in participating in our alpha/beta programs, please have them sign-up to our newsletter.  We’re approaching the market in a different fashion that what the competition is doing, so we’d love to talk to business owners directly.

      Since a good portion of our readers builds software for other businesses, we’d also like to talk to web developers that manage business websites.

      Also, feel free to share your thoughts on BookingBlast and how to make it work in the comments. We’re thinking of openly blogging about thinks like SaaS pricing and gathering data concerning some of our strategies for future discussions and commentary.



      Disclaimer

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

      © Copyright 2013

      Sign in