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.



      FranchiseBlast Wins Bootstrap Award

      clock February 27, 2012 10:07 by author jkealey
      FranchiseBlast Wins Bootstrap Award

      We’re proud to announce that 2012 is off to a great start! We’ve recently received lots of local recognition and thought we’d share this great news with you.

      First, we’ve been listed as a Startup To Watch for 2012 by the Ottawa Business Journal. Past nominees (Chide.it, FaveQuest, Select Start Studios and PatientWay to name a few) have had a tremendous impact on the Ottawa-Gatineau startup community  and we strive to do the same. For decades, our region has featured a tremendous wealth of engineering talent and we’re proud to be a part of the group of companies rebuilding our digital economy. 

      Second, we’ve won a Bootstrap Award for Best Sales/Value Proposition. This award recognizes companies who’ve grown their companies without the use of external funding (such as venture capital). We’ve been growing organically since our creation in 2007 and bootstrapping has enabled us to focus on creating value for our customers from day one. Today, we have an awesome product that is a perfect fit for our target market. If we had to name a single element which helped us refine our value proposition (other than listening to our customers for five years), I would have to name Lead To Win.

      Lead To Win is a startup ecosystem/accelerator (which takes no equity)  which helps companies get to market faster and/or accelerate their growth. We strongly recommend the program to other high-tech entrepreneurs, especially engineering students who don’t have a background in business.

      Thank you to everyone who’s vouched for us over the years. 2012 will be a year of great growth for us and we hope to share more good news soon!



      FranchiseBlast Now Member of the CFA and CQF

      clock February 17, 2012 11:25 by author jkealey

      LavaBlast Software Inc. (creator of FranchiseBlast) is proud to announce that it is now a member of both the CFA (Canadian Franchise Association) and the CQF (Conseil Québécois de la Franchise / Quebec Franchise Association). Over the past five years, we’ve helped numerous franchises grow thanks to improved operational software and we feel the time is now ripe to get involved in these franchise associations. We hope to have the pleasure to meet you at one of the upcoming CFA or CQF events, such as the CFA’s National Convention in April 2012.

      franchiseblast     CFA      cqf



      New Grant for Canadian Franchises to Adopt Tech

      clock November 15, 2011 11:18 by author jkealey

      (From left to right) Jason Kealey (President, LavaBlast Software), The Honourable Christian Paradis (Minister of Industry) Yesterday, the Minister of Industry announced a new grant pilot program (DTAPP) offering up to $99,999 in financial support to Canadian small- and medium-sized enterprises (SMEs) to facilitate the adoption of digital technologies. The announcement featured FranchiseBlast as an example of such a digital technology and was made inside one of the Boomerang Kids stores, our newest franchise client (see photo).

      This pilot program is great news for Canadian franchises as it includes the adoption of business systems (franchise management, customer/work order management, inventory management, etc.). In the context of a franchise, these are often customized systems ensuring the uniformity of their proprietary business processes across all franchisees. Off-the-shelf hardware and software are not covered by this grant, but the following are:

      • Internal labour costs: franchisor’s time spent elaborating the system
      • Contractors: technology firm helping the franchisor adopt the technology
      • Travel & Training
      • Hiring of recent college graduates as a part of the adoption process

      The new grant program is managed by NRC-IRAP. As with all NRC-IRAP grants, the process starts with the franchisor developing a relationship with an Industrial Technology Advisor (ITA). Over 240 ITAs, located all over Canada, will work with you to determine the best course of action for your business, whether is be via the new Digital Technology Adoption Pilot Program (DTAPP) or one of the numerous existing grant program­s.

      As our specialty is creating franchise-specific software solutions, we’ve gone through the process in the past. Our team can work with both you and your ITA to establish the scope and requirements for your project.

      For more information about DTAPP, please visit this site and call toll-free 1-855-453-3940 to be assigned an ITA in your area. 



      LavaBlast and Boomerang Kids: When helping local families meets the Cloud

      clock November 14, 2011 20:17 by author jkealey

      (From left to right): Jason Kealey (President LavaBlast Software Inc.), Honourable Christian Paradis (Minister of Industry), Bogdan Ciobanu (Director General NRC-IRAP), Lynne Plante (Directrice NRC-IRAP), Heather Meek (co-owner, Boomerang Kids Consignment Shops) LavaBlast, a leading provider of cloud-based franchise management solutions, announced today the deployment of its flagship product, FranchiseBlast, to the first of four Boomerang Kids locations. This state of the art software solution enables Boomerang Kids to grow their consignment franchise nationwide while allowing local families to shop smarter.

      "Using the FranchiseBlast system will allow employees to focus more on helping local families," said Heather Meek, owner of Boomerang Kids. "We are expanding our franchise throughout Canada and we want to ensure the success of our current and future franchisees. FranchiseBlast will allow us to offer a complete easy-to-use system that helps store owners, employees and their customers. And now, I can even manage my business on my iPad!"

      The FranchiseBlast deployment consists of an integrated suite of local and cloud-based tools that allow Boomerang Kids to automate the management recipes they’ve perfected throughout the years and replicate them in a franchise environment. FranchiseBlast will boost Boomerang Kids’ efficiency and customer service with:

      • Point of Sale (POS) stations to allow employees manage and sell all items under consignment.
      • In-store interactive kiosks and web-based tools to making it possible for parents to review their account and item statuses
      • A cloud-based franchise management solution giving both franchisees and franchisors immediate insight into the franchise’s operations.

      "We are excited to be powering the expansion of a local franchise. Boomerang Kids has a solid management team and now has the tools to support its upcoming rapid growth." said Jason Kealey, President of LavaBlast. "This collaboration strengthens our position in the Franchise Management market and has allowed us to bring on new team members and scale up our operations."

      image

      About Boomerang Kids:

      At Boomerang Kids, families can help the planet and their wallet through reuse and recycling of kids clothing and equipment. Parents bring the items into the store and Boomerang Kids will take care of verifying quality, selling and, best of all, sharing profits. The concept is extremely popular and independent of the economic climate. From their four initial locations in the Ottawa region, Boomerang Kids is now expanding Canada-wide via franchising.

      image

      About LavaBlast Software Inc.:

      LavaBlast produces state of the art software solutions for the franchise industry and has played an integral part in the growth of numerous franchises, both in Canada and globally. By migrating to FranchiseBlast, franchisors reap the benefits of a turn-key software solution for their franchisees and LavaBlast’s deep software engineering skills to adapt their franchise in a rapidly changing technological environment.

      image

      About our flagship product, FranchiseBlast:

      FranchiseBlast empowers you to run a successful franchise business with easy-to-use operational software. Manage day-to-day issues with franchisees, see everything happening in real-time and increase the level of control you have over your franchise business.

      Download this press release (PDF format).



      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?


      Disclaimer

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

      © Copyright 2013

      Sign in