Posted on

Sharing a Class In ASP.NET Pages

It’s easy enough to create additional classes that can be used in the code behind files of an ASP.NET page, but what if you want to share a class among the ASP pages themselves? It’s quite common and easy to develop generic methods and event handlers that can reduce repetition of code and simplify the process of creating the different parts of your UI. In a recent project, I needed to create such a class and make it available to all my ASP pages. The class contained two methods that were meant to be called by the DataBind event of a GridView or DetailView in order to assign Javascript confirmations to all the Delete Commands and looked something like this…

namespace ProjectNameSpace {

 public class AdminUI {

 public void add_delete_confirmations_to_grid_view(object sender, EventArgs e)
 {
 // Do stuff
 }

 public void add_delete_confirmations_to_detail_view(object sender, EventArgs e)
 {
 // Do stuff
 }
 }
}

Now that we have the class, we need to find the way to make it available to our ASP pages. The usual way to do this is via an entry in the web.config that makes the namespace available like this….


 
 
 

…which works fine if you intend on calling the method using ASP tags…

<% AdminUI.add_delete_confirmations_to_grid_view(); %>

…but the methods above aren’t mean to be used in ASP tags. They are meant to be assigned directly to events of ASP Controls like so…

<ASP:GridView OnDataBoundEvent="AdminUI.add_delete_confirmations_to_grid_view">

…which sadly, does not work. This seems to be something that was overlooked in ASP.NET. The former compiles, but the latter generates a “AdminUI namespace not found” type of error.

So in order to get around that, we are going to have to make use of inheritance.

Normally, the code behind classes for an ASP page are children of the System.Web.UI.Page like this….

public partial class Users : System.Web.UI.Page { }

Therefore, I can construct my AdminUI class as a middle layer between my ASP classes and System.Web.UI.Page by changing AdminUI to…

public class AdminUI : System.Web.UI.Page {}

… and all of my ASP classes to something like this…

public partial class Users : AdminUI { }

… and the assignment of the methods to their corresponding events becomes this…

<ASP:GridView OnDataBoundEvent="add_delete_confirmations_to_grid_view">

…and it works perfectly. All the methods that normally would have to be duplicated in multiple code behind files are in a centralized location and inherited by all of the classes so they can be used directly in the ASP pages without triggering a compiler error.

Posted on

Detecting USB Insertion/Removal in C# .Net 4.0

We need your help!


Cyber Sprocket is looking to qualify for a small business grant so we can continue our development efforts. We are working on a custom application builder platform so you can build custom mobile apps for your business. If we reach our 250-person goal have a better chance of being selected.

It is free and takes less than 2 minutes!

Go to www.missionsmallbusiness.com.
Click on the “Login and Vote” button.
Put “Cyber Sprocket” in the search box and click search.
When our name comes up click on the vote button.

 

And now on to our article…

C# Programming

Introduction

While coding a new Windows desktop app for a client we ran into something that we thought we be fairly simple.  It has turned out to be a rather complex task. The goal: detect when a SmartDongle USB key was being inserted or removed & update our application interface at that time.

Our assumption was that a few minutes of searching the Internet and we’d find a dozen examples of people that have done it already or we’d just use the .Net 4.0 classes for device detection. Wrong on both counts. As ubiquitous as USB devices are these days, it appears that .Net 4.0 still does not have direct support via easy-to-use classes that you can just hook into. Searches of the Internet turned up a lot more people asking questions than viable answers. The few answers we found were outdated or half-answers.

Now that we’ve got basic USB insertion/removal detection working we decided we’d share that part of the solution. Our next challenge is to determine that we’ve inserted the SmartDongle and not some other USB device such as a keyboard, mouse, flash drive, or other USB item. Unfortunately the message handler we’ve got thus far only tells us that a device has changed (windows message WM_DEVICECHANGED), but does not hand off the parameters that would let us query the message stack to find out WHICH device changed. That will be a solution for another post I guess.

Our Environment

We are coding in C# using Visual Studio 2010 (VS2010) with the .Net 4.0 framework helping us along. We are coding a WPF main window, not a form, which can make a difference.

Our Solution

Here is the simplified way to detect that a USB device was inserted or removed from the system, and our call to a ReadDongle method that we wrote to get information from the dongle header (or not, if it was removed). You can call whatever function you’d like, or put your processing loop right inside the windows process handler.

using System.Windows.Interop;
...
public partial class MainWindow : Window
 {
    ...
    public MainWindow()
    {
    ...
    }

    //============================================================
    // WINDOWS MESSAGE HANDLERS
    // 

    private const int WM_DEVICECHANGE = 0x0219;  // int = 537
    private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x00000004; 

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
        source.AddHook(WndProc);
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_DEVICECHANGE)
        {
            ReadDongleHeader();
        }
        return IntPtr.Zero;
    }

}

Summary

That’s it, now we know when a device is inserted or removed. We are overriding the OnSourceInitialized method for our main window, which basically is saying “hey, when the window is initialized and ready to accept external messages from the operating system, add a hook that latches onto the window’s message processing method (WndProc). We can then perform operations by sniffing out specific types of messages like “device changed” (WM_DEVICECHANGE) and doing our thing. When the WndProc override is done it drops back to the default method for further processing. We could override that by setting handled to true, but we don’t want to do that in our app… not yet anyway.

Hope our article helps provide a quick shortcut for someone that is googling stuff like “C# wpf usb insertion/removal”.

Posted on

Configuring log4net with VS2010 and .Net 4.0

We need your help!


Cyber Sprocket is looking to qualify for a small business grant so we can continue our development efforts. We are working on a custom application builder platform so you can build custom mobile apps for your business. If we reach our 250-person goal have a better chance of being selected.

It is free and takes less than 2 minutes!

Go to www.missionsmallbusiness.com.
Click on the “Login and Vote” button.
Put “Cyber Sprocket” in the search box and click search.
When our name comes up click on the vote button.

 

And now on to our article…

After spending a few hours this morning trying to get log4net working with a project, I decided to share my findings.   I chased a lot of dead-ends for what wound up being a fairly simple solution.  Here is a quick article to save both myself, and maybe you, some time in the future.

Get Log4Net

Go to http://logging.apache.org/log4net/ and get the latest version.    Add the project file to your solution.   Then right-click that project, choose the build tab and…

Step 1: Set the log4net conditional compilation symbols replacing NET_1_0 with NET_4_0.

Log4Net Requires Full .Net Access

That means you cannot use “client profile”.  log4net was originally written to log web services.  As such it expects to have a lot of server-side classes available, even though most of those classes are never instantiated.

Step 2: Build  Your Application & The Log4Net component under .Net 4.0, not .Net 4.0 Client Profile

Make Log4Net Less Secure

The .Net 4.0 assemblies are more secure by default.  You need to override this.   As I’m not a .Net development guru I’m not really certain what the differences mean, but Google is your friend (and mine) here, so if you are concerned (and you should be before launching a public app) then search the Internet to find out what this mean. In the meantime…

Step 3: Make log4net assembly less secure, add
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
to the log4net AssemblyInfo.cs file.

Done.

That’s it, the first steps for getting a log4net component into your application.   Now you can follow some of the development & deployment document on the Apache site:

http://logging.apache.org/log4net/release/manual/configuration.html

Posted on

Starburn SDK and .Net 4.0

Introduction

We have been trying to get StarBurn to play well with others for a client project we have been working on lately. The problem is that StarBurn is very particular about the Windows environment, and though the support guys mean well the communication is sometimes hard to decipher. I don’t think English is their primary language, but can’t fault them there… they communicate much better in English than we speak French, or any other language for that matter.

Anyway, we deciphered some of their clues, experimented a bit, and finally came up with a step-by-step guide for getting the latest StarBurn SDK working well with our .Net 4.0 project. If you don’t get the right DLLs activated it will wreak havoc on your Visual Studio debug sessions and will not play well on most final release installs.

Step-By-Step

The first step is to make sure you have registered the StarBurn.X12.dll in your system registry via regsvr32:

1) Download & install latest StarBurn version. Make sure you have a January 2011 or later copy of StarBurn installed.

2) Run CMD as administrator. Search for “cmd” from the windows start menu, then right-click and “run as administrator”. If you do not run as admin you will get a cryptic error from Windows when using regsvr32.

3) CD to the StarBurn install directory. From the command prompt cd “…path-to-starburn-install”.

4) CD to the \Bin\Core\StarBurnX\x86 subdirectory.. Yes you could have done this all in one step, but I like to have the subdirectory spelled out so it is easier to find next itme around.

5) Register the DLL. Enter the command “regsvr32 StarBurnX12.dll”. You should get a message back with no errors saying the DLL was registered.

6) Remove any references to blah-interop-blah if you have them in your project. These references are wrong. Remove them. If you copied the setup from the sample solutions, they reference the Interop files, which is typically all you have to start with if you try registering anything StarBurn in your project prior to doing the regsvr32 trick noted above.

7) Add the corrrect StarBurnX 12.0 Type Library COM reference. Go to your project and add references. Click the COM tab. Look for the newly available “StarBurnX 12.0 Type Library” reference. This is what you want to add for .Net 4.0 Client Profile projects.

StarBurn COM Install
StarBurn COM Install

 

Manifestations

Here are some of the things you’ll see if this is not done correctly.

  • Application crashes immediately on boot.
  • Error code 8007007e simply means that a DLL that the application needs is not registered with the system.
  • A common error when you have problems with StarBurn is “Retrieving the COM class factory for component with CLSID
    {B756C224-A1EA-44F8-95C1-9F726040C800}
    failed…”. You can look for the CLSID by using regedit and searching for that string. This particular Class ID is registered to StarBurnX.StarBurnX, you can find it under HKCR/StarBurnX.StarBurnX/CLSID

 

Hope that helps some of you StarBurn developers out there.   It sure took us a while to figure out the best way to do this, maybe this will save you a few hours.

 

 

 

 

Posted on

Device Interfaces with Simma Software

Simma Software needed solutions QUICK and Cyber Sprocket rose to the occasion.   In one of our fastest turnarounds from new-client to completed solution, Cyber Sprocket was able to work with an expert in the field of CAN and J1939 software.  If you are unfamiliar with those terms from a technical standpoint, we are certain you are familiar with the devices that run on those standards – vehicles of all shapes and sizes.

While Cyber Sprocket Labs had a small role, it was a great experience for us.   We learned a lot of new things in just 48 hours and even got to play with some new toys that Simma Software sent us while working on their software updates.   Our C# experts go to work and knocked out some system upgrades with time to spare.  Quite a feat considering the 48 hour turnaround that was required.

It is always a pleasure working with an experienced client such as JR at Simma Software.  We look forward to doing business with them again whenever they need a helping hand.  Thanks JR!

Technical Overview

Services Provided

  • Desktop application programming
  • Rapid response & turnaround time

Platform Details

  • C#
  • USB device control interface