0 Comments

Well, maybe not the best, but it comes very close to it.  For sure, it's the FUNNEST time you can have while trying to understand jQuery internal and at the same time learn about some exotic things about JavaScript and browser DOM.

What I am talking about is the More Things I Learned from the jQuery Source videos by Paul Irish.

Trust me... If you are a JavaScript / jQuery geek, it is definitely worth the time to look at them.

Paul is quite a fun guy to watch and his explanation style kind of remind me of how Head First book series are written.

Fun, Fun, Fun.

http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/

0 Comments

A client of mine was having a problem trying to automate Excel to print to a specific (non default) printer.  They know which printer they want to use, but are having trouble trying to get Excel to understand it.

Excel’s Application.ActivePrinter property is quite picky about what it will accept.  The right pattern to feed to the property is something like PrinterName on PortName:.

For example, if you want to print to Microsoft XPS Document Writer, you need to do something like this:

var excel = new Excel.Application();
var workbook = excel.Workbooks.Open("....");
var worksheet = workbook.ActiveSheet;

excel.ActivePrinter = “Microsoft XPS Document Writer on ne01:”;
worksheet.PrintOut();

excel.Quit();

And this of course assuming that the selected printer (Microsoft XPS Document Writer) is on port ne01.

Getting the right name for the printer is somewhat trivial.  You can poke around the Devices and Printers control panel item on Windows and see their name.

The problem is… the port name information is not so obvious to find.

So, how would you know where to get the port name?

Trying to enumerate the attached printers as described by this StackOverflow question does not gives you the right port name… See the sample code and output below…

The Code:

using System;
using System.Management;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var oquery = new ObjectQuery("SELECT * FROM Win32_Printer");
            var mosearcher = new ManagementObjectSearcher(oquery);
            var moc = mosearcher.Get();            

            foreach (var o in moc)
            {
                var pdc = o.Properties;

                foreach (var p in pdc)
                {
                    if (p.Name == "Name" || p.Name == "PortName")
                    {

                        Console.WriteLine("{0}: {1}", p.Name, o[p.Name]);
                    }
                }
            }
        }
    }
}

The result:

Name: Xerox WorkCentre 3119 Series
PortName: USB001
Name: Send To OneNote 2010
PortName: nul:
Name: Microsoft XPS Document Writer
PortName: XPSPort:
Name: CAMPUS-R101-DC236
PortName: 192.168.100.21
Name: CAMPUS-R217-DC236
PortName: 192.168.100.22
Name: Fax
PortName: SHRFAX:
Name: \\TIGER\Canon Inkjet MP140 series
PortName: USB001

You just have to trust me the port name here is not the port name that Excel wants to use.

So, where else can you get this particular information?

After looking around the web, I found this post that gives some clues on how to do this from VBA that can easily be adapted for .NET.

It turns out that the key to this is to poke around in the registry. in particular HKCU\Software\Microsoft\Windows NT\CurrentVersion\Devices.

So I came up with the code below to test it and lo and behold.  It works perfectly.  Basically I enumerate through all the devices in that particular registry location, did some string manipulation on the port (remove the winspool, prefix from the port name) and concatenate the stripped version of the port name with the printer / device name to form the PrinterName on PortName: combination that is required by Excel.

using System;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var excelApp = new Excel.Application();
            excelApp.Visible = true;

            var workbook = excelApp.Workbooks.Add();
            var worksheet = workbook.ActiveSheet;

            var key = Registry.CurrentUser;
            var subkey = key.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Devices");

            var printerNames = subkey.GetValueNames();

            //Should be able to complete this loop without throwing an exception
            //if all the names matches to what Excel is expecting.
            foreach (var printerName in printerNames)
            {
                var excelPrinterName = ConvertToExcelPrinterFriendlyName(printerName);
                Console.WriteLine(excelPrinterName);

                excelApp.ActivePrinter = excelPrinterName;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();

            Marshal.FinalReleaseComObject(worksheet);

            workbook.Close(false);
            Marshal.FinalReleaseComObject(workbook);

            excelApp.Quit();
            Marshal.FinalReleaseComObject(excelApp);
        }

        public static string ConvertToExcelPrinterFriendlyName(string printerName)
        {
            var key = Registry.CurrentUser;
            var subkey = key.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion\Devices");

            var value = subkey.GetValue(printerName);
            if (value == null) throw new Exception(string.Format("Device not found: {0}", printerName));

            var portName = value.ToString().Substring(9);  //strip away the winspool, 
 
            return string.Format("{0} on {1}", printerName, portName);;
        }
    }
}

Hope this is useful for those who need it… Enjoy.

0 Comments

I was perusing stackoverflow.com questions and came upon a question regarding JavaScriptSerializer that I found quite interesting.  I decided to do a quick spike in Visual Studio to find out if I can get answer for the question.  Fired up Visual Studio 2010, created a new Console Application and tried to instantiate a JavaScriptSerializer in my code, but of course, the IDE did not recognize JavaScriptSerializer since I haven't added a reference to the necessary assembly.  In trying to fix that, I launched the Add Reference dialog and chose the .NET tab and scrolled down... and guess what.... no System.Web.Extensions... hmmm...

Thinking the problem through I know System.Web.Extensions is part of .NET 4 (which was installed when I installed VS 2010), so how come it is not available in the Add Reference dialog?

After a bit more thinking I came to realize that it's probably because Console Application is targeting the .NET Framework 4 Client Profile which does not include all the web stuffs in it.  Switching the Target framework to .NET Framework 4 (Full profile) from the Project Property, Application tab, solved the problem.

0 Comments

Ran into this problem with a client of mine.

Symptom:

Platform:

  • server: SQL Server 2008 Service Pack 2
  • client: Windows XP x86

Causes:

  • Insufficient user permission 
  • Potential bug introduced in SQL Server 2008 SP 2?

Working Remedy:

  • Deploying the RSClientPrint-x86.cab from SQL Server 2008 R2 to the client machine fixed the problem.

References:

0 Comments

As a general rule, when creating unit test, you should NOT have the test code communicate directly across the network, to the database, the file system, etc.  This is a good thing since it will allow the unit test to be fast and remove the headache of doing test data management, etc.  For more details on what a unit test should not do, see here. To achieve this goal, mocking and stubbing were introduced into the unit testing world.

Stubbing

Stubbing will allow you to create fake dependency objects that you can use to give the class that you are unit testing constant / static values, something that will not change across tests.  An example of this is when you want to create a fake data repository from a data repository interface that will return you a set of pre-canned (always the same) values when queried.

var warehouse = new Mock<IWarehouse>();
warehouse.SetupGet(w => w.HasInventory).Returns(false);

Fig 1. Example of a warehouse stub using Moq (warehouse stub will return false when it’s HasInventory property is invoked).

Mocking

Mocking will allow you to create fake dependency objects that contain expectations that you can validate as part of your unit test (and also can provide what stub can provide).  An example of this is when you want to determine if a particular branch or path is taken when a certain parameter is passed to your method.

 [TestMethod]
        public void Should_SendMail_If_Unfilled() {
            //Assign
            var warehouse = new Mock<IWarehouse>();
            var mailer = new Mock<IMailService>();
            warehouse.SetupGet(w => w.HasInventory).Returns(false);
            var order = new Order
                            {
                                ItemName = "Boo", 
                                Amount = 51, 
                                Mailer = mailer.Object
                            };

            //Act
            order.Fill(warehouse.Object);

            //Assert
            mailer.Verify(m => m.Send(It.IsAny<Message>()), Times.Once());

Fig 2. Example of using mock to verify mailer Send method was called once when trying to fullfill an order using Moq.

For more information on the difference between mock and stub, see this.

Perhaps this is old news, but like there are a lot of unit testing frameworks out there, i.e. NUnit, xUnit, MSTest, etc., there are also a bunch of mocking frameworks out there, like RhinoMock, Moq, TypeMock Isolator, and recently JustMock from Telerik.

To do proper mocking or stubbing, and by extension, unit testing, you usually need the following things: interface and dependency injection.

Interface

Interface will allow you to switch one implementation of it with a different implementation.  I.e. SqlRepository, that derives from an IRepository, will actually talk to a SQL database backend, while a FakeRepository that derives from the same IRepository might actually fake the database call and instead returns an in memory list of data when asked.  The ability to switch between a real implementation and a fake implementation is a crucial thing if you want to make your unit test fast.

Dependency Injection

Image courtesy of Derick Bailey

Before we go too far into the topic of dependency injection, let’s take a quick detour.  The Dependency Inversion Principle stated that higher level object should not depend on the lower level objects, instead, have all of them depend on a contract or interface / abstraction. 

Think about how a desk lamp and electric socket interact.  The electric socket can provide electricity to any devices (not just the lamp) that can connect to it.  As long as the specific device that wants to get electricity implement the right plug, then it’s no problem for the socket to provide it with electricity.  Compare this design versus lamps that are built into the wall and wired directly to the electrical wiring.  If you want to switch the lamp, you have to tear down your wall, rip out the old lamp, install a new lamp, wire it up to the electrical wiring in the wall and redo your wall.  What a pain… With electrical socket, I can just unplug the lamp and replace it with a TV for example, and it still work.  The electrical socket can still provide electricity with very minimum interruption.

Again, this will allow you to easily swap one implementation with another for the same contract / interface.  See here to see more detail on this topic.

public interface IElectricalDevice
{
    void SwitchOff();
}

public class Lamp : IElectricalDevice
{    
    public void SwitchOff()
    {
        //It's dark!
    }
}

public class Refridgerator : IElectricalDevice
{
    public void SwitchOff()
    {
       //Wow it's getting warm in here...
    }
}

public class ElectricalOutlet
{
    private IElectricalDevice _pluggedInDevice;
    public ElectricalOutlet(IElectricalDevice pluggedInDevice)
    {
        _pluggedInDevice = pluggedInDevice;
    }

    public void PowerOff()
    {
        _pluggedInDevice.SwitchOff();
    }
}

Fig 3. Example of electric socket and devices as code

Now that we see why DIP is important, comes the question of how can we “inverse” the dependency to make our solution more loosely coupled?  That’s where injection comes in.  You need to provide points in your object where you can inject other objects that it need to do its work.

Most common points are the class constructor and public properties.  In Fig. 3 code above, I was using constructor injection in the ElectricalOutlet class (the constructor takes an IElectricalDevice object, thus injecting it into the ElectricalOutlet class).  Property is self explanatory.  Since you can inject different instance of object of its type during the application runtime.

Moles

image

Now, let’s talk about moles.

What a tunneling blind rodent has to do with this, you ask…

Well, not that kind of mole. 

Not the other mole either (WPF debugger).  I am talking about a unit testing kind of moles.  Moles is a mocking framework from Microsoft Research group with similar ability that TypeMock Isolator or JustMock offered.  Just like the other products, it will allow you mock stuffs that previously unmockable if you are using mocking frameworks like RhinoMock or Moq.  Unlike TypeMock and JustMock, Moles is a free product.  I supposed the name was chosen due to the ability of the framework to dig deep into a class and replace whatever you wish to replace with your own implementation that you can use during unit testing.

Moles provides 2 types of capabilities: stubs and moles. 

Stub is a very fast compared to moles but has certain limitation, mostly you can only stub things that has interfaces and class instances with virtual methods, similar to RhinoMock and Moq.

Mole is not as fast as stub since it injects instrumentation code into your actual classes and redirect control to itself when called.  The benefit of this method is that now it can totally take control of any sealed class, static methods, etc. that are usually not mockable / stubable without a proper interface or virtual methods.

// let's detour DateTime.Now (Mole into DateTime.Now property, which usually not mockable w/ other framework)
MDateTime.Now = () => new DateTime(2000, 1, 1);

if (DateTime.Now == new DateTime(2000, 1, 1))
  throw new Y2KBugException(); // take cover!

Fig 4. Using Moles to return 1 Jan 2000 everytime DateTime.Now is called.

Having said that, currently Moles does not have internal mocking support like RhinoMock and Moq.  To do mocking with Moles, you will have to implement them yourself.

[TestMethod]
        [HostType("Moles")]
        public void Should_SendMessage_Once_When_Not_Filled() 
        {
            //Assign
            var mailSendCallCount = 0;

            //Create stubs (S prefix = stub)
            var warehouse = new SIWarehouse();
            var mailer = new SIMailService();
            
            //Setup warehouse stub to return false 
            //when its HasInventory property is called
            warehouse.HasInventoryGet = () => false;

            //Setup mailer stub to increase the mailSendCallCount 
            //everytime SendMessage is called
            mailer.SendMessage = (m) => { mailSendCallCount++; };

            var order = new Order
            {
                ItemName = "Boo",
                Amount = 51,
                Mailer = mailer
            };

            //Act
            order.Fill(warehouse);

            //Assert
            Assert.AreEqual(1, mailSendCallCount);
        }

Fig 5. Example of mocking with Moles

Resources

To learn more detail on Moles, I suggest you check the following resources:

http://www.dimecasts.net/Casts/CastDetails/170 (good short video on introduction to Moles)

http://research.microsoft.com/en-us/projects/pex/molesmanual.pdf

Happy Unit Testing & Moling?  Is that a verb?