I got Windows 8. Goodbye 3rd party virtualization?

Finally, Hyper-V is coming to Windows client and not just server.  For a long time I have to use 3rd party products such as VirtualBox, which is very nice, or VMWare Workstation, etc. to run my 64 bit VMs or dual boot to Windows Server instance to try out Hyper-V.  Guess it's no longer required since Hyper-V will be built-in to Windows client itself.

Mounting VHD is also easier to do in Win8 (at least from what I've seen in the keynote).

Another cool thing is mounting ISO is also easier now and built-in to the OS.

 Awesome!! :)

Share this post: | | | |

How to call SharePoint Web Service with Specific Credential from Silverlight OOB

 

The Problem

While playing around with SharePoint web service from Silverlight out of browser, I bumped into web service proxy limitation where I am forced to authenticate no matter what I pass to the ClientCredential.UserName property of the web service client proxy.

//This does not work... will get authentication prompt
var request = HttpWebRequest.Create(uri);
request.ClientCredential.UserName.UserName = "DOMAIN\\user1";
request.ClientCredential.UserName.Password = "password";
 

The Authentication Problem Workaround

Luckily, starting from Silverlight 3 up, you can use the ClientHttp object that allows passing specific credential for the web request.

//This now work wonderfully from Out of Browser Silverlight 3 or up
var request = WebRequestCreator.ClientHttp.Create(new Uri("http://localhost/_vti_bin/lists.asmx", UriKind.Absolute));

//This is required, or otherwise you will be prompted for authentication
//It basically said, no don't use the current login, I'll tell you what login to use later.
request.UseDefaultCredential = false

//Pass your credential here...
request.Credentials = new NetworkCredential("user1", "password", "DOMAIN");

Ouila! Authentication problem solved.  Bye bye authentication prompt.  See you later... or not.

What About My Web Service?

Now... for the second problem, without the nicely generated web service proxy, how the heck am I going to call my web service method?

Well, luckily, SharePoint and other web service for that matter, give you a neat example of what to pass in a SOAP message like so:

if you put something like http://localhost/_vti_bin/lists.asmx into your browser Address (URL) field, you'll get this:

image

In this case, I am interested in adding a list item to one of my SharePoint list.  The method (SOAP action) for this is UpdateListItems.  If you don't believe me, see this.

So if you click the UpdateListItems from the nice list above, you'll get this:
image

See that SOAP message example (in particular the top one which is a SOAP 1.1 request message)?
Yeah it's a bit ugly, but trust me underneath the nicely generated web service proxy that you usually get when adding a service reference, you'll see this message somewhere in there if you open up the generated proxy client code in one shape or form. 

<digress>Actually if you look inside the generated proxy inside Reflector or similar tool like ILSpy for those who don't want to pay for Reflector, you'll see the serializable form of this as class and class members which later on will be serialized into
the XML format that you see above. </digress>

Well, like it or not, you will need to create your own web service wrapper around the SOAP message.  The good thing is... it's not that hard.

Below is a bit of code that I whipped out and refactored in about 2 hours to do this (for now only the UpdateListItems is implemented plus the rest of SOAP Web Service infrastructure):

using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml.Linq;
using System.Net.Browser;
 
namespace SilverlightApplication9
{
    public class SharePointWebService
    {
        static XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
        static XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
        static XNamespace soap = "http://schemas.xmlsoap.org/soap/envelope/";
        static XNamespace sharepoint = "http://schemas.microsoft.com/sharepoint/soap/";
 
        XElement SoapEnvelopeTemplate;
        Uri WebServiceUri;
        NetworkCredential Credential;
 
        public SharePointWebService(Uri spWebServiceUri, NetworkCredential credential)
        {
            WebServiceUri = spWebServiceUri;
            Credential = credential;
 
            SoapEnvelopeTemplate = new XElement(soap + "Envelope",
            new XAttribute(XNamespace.Xmlns + "xsi", xsi),
            new XAttribute(XNamespace.Xmlns + "xsd", xsd),
            new XAttribute(XNamespace.Xmlns + "soap", soap),
            new XElement(soap + "Body"));
        }
 
        public void UpdateListItemsAsync(string listName, XElement updates, Action<XDocument> callback)
        {
            var message = CreateUpdateListItemsMessage(listName, updates);
 
            SoapActionInvokeAsync(
                "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems",
                message,
                callback);
        }
 
        protected void SoapActionInvokeAsync(string soapAction, XElement soapMessage, Action<XDocument> callback)
        {
            WebRequest request = WebRequestCreator.ClientHttp.Create(WebServiceUri);
 
            if (Credential != null)
            {
                request.UseDefaultCredentials = false;
                request.Credentials = Credential;
            }
 
            request.Headers["SOAPAction"] = "\"" + soapAction + "\"";
            request.ContentType = "text/xml; charset=utf-8";
            request.Method = "POST";
 
            var message = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + soapMessage.ToString();
 
            request.BeginGetRequestStream((ar1) =>
            {
                using (var stream = request.EndGetRequestStream(ar1))
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        writer.Write(message);
                    }
                }
 
                request.BeginGetResponse((ar2) =>
                {
                    XDocument xml = XDocument.Load(
                        request.EndGetResponse(ar2).GetResponseStream());
 
                    callback(xml);
                }, null);
            }, null);
        }
 
        public XElement CreateUpdateListItemsMessage(string listName, XElement updates)
        {
            EnsureSharePointNamespace(updates);
 
            var body = new XElement(sharepoint + "UpdateListItems",
                new XAttribute("xmlns", sharepoint),
                new XElement(sharepoint + "listName", listName),
                new XElement(sharepoint + "updates", updates));
 
            var envelope = XElement.Parse(SoapEnvelopeTemplate.ToString());
            envelope.Descendants(soap + "Body").First().Add(body);
 
            return envelope;
        }
 
        protected XElement EnsureSharePointNamespace(XElement el)
        {
            foreach (var e in el.DescendantsAndSelf())
            {
                e.Name = sharepoint.GetName(e.Name.LocalName);
            }
 
            return el;
        }
    }
}

And here is an example of how to use it from Silverlight:

           var ws = new SharePointWebService(
                new Uri("https://localhost/_vti_bin/lists.asmx", UriKind.Absolute),
                new NetworkCredential("user1", "password", "DOMAIN"));
 
            ws.UpdateListItemsAsync("jtest",
                XElement.Parse(@"<Batch><Method ID=""1"" Cmd=""New""><Field Name=""Title"">New item</Field></Method></Batch>"),
                (doc) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        textBox1.Text = doc.ToString();
                    });
                });

 

This has been a pretty fun exercise... It would be better if the proxy ClientCredential code can do similar thing, but well... live sucks and that's why you are a coder, right?  

<digress>Some of you might be thinking what the hell the relation between live sucks and being a coder.... Don't worry, I don't know either, LOL.  Guess that's why this blog is called Incoherent Rambling... </digress>

Share this post: | | | |

How to Add a link in SharePoint 2010 that will launch InfoPath form template?

While playing around with SharePoint 2010, I want to add a link to my site home page that will do the same thing when I am in a particular document / form library and click the Add Document link. 

In other word, how can I launch Word or Excel or InfoPath from my own link without having to go inside the library and clicking Add Document?

At first, I couldn't figure out how to do this.  Decided to dive into the HTML source of the Form Library AllItems.aspx view and found a CoreInvoke JS method, like:

CoreInvoke('createNewDocumentWithProgIDEx', 'template source URI', event, 'save location URI', 'SharePoint.OpenXMLDocuments', true);

I plop that inside a link tag and it worked. 

After the fact, I look around the web and finally found someone else that has done this already...

See: http://www.sharepointkings.com/2010/02/create-new-document-link-in-listview.html

The syntax is something like: createNewDocumentWithProgID(templateSourceURI, saveLocation, docType, false);  

In my case, I want to launch an InfoPath form template, and I found the following work just fine:

createNewDocumentWithProgID('http://intranet/spike/FormLib1/Forms/template.xml', 'http://intranet/spike/FormLib1', 'SharePoint.OpenXMLDocuments', false);

 

Share this post: | | | |
Posted by Jimmy Chandra | with no comments

Coolest Feature of IE9 in My Opinion

Just want to link to Scott Hanselmann's blog post on Site Pinning and the cool things that you can do with it.  I think it's the coolest feature in IE9... graphic hardware acceleration, canvas support, improved javascript speed... PHHBTTT... seen it too many times, but this... is awesome ... or maybe not?  Well, I think it is anyhow Big Smile.

 http://www.hanselman.com/blog/IE9SiteSpecificBrowsersAndAddingYourOwnJumpListItemsToPinnedTabs.aspx

Check it out. 

Information that you will find:

  • How to add Jump List that is available from Windows 7 Pinned Site
  • Adding notification to the pinned site icon in the taskbar (Push Overlay)
  • Adding task bar buttons to the pinned site
Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under: ,

Oh Nirvana... VirtualBox, Hyper-V VHD and Synergy

In my daily work, I am doing a lot of prototyping, testing, etc.  And for this, I lean heavily on virtualization to isolate my workstation versus the prototyping / testing environment and for its ability to quickly rollback to previous snapshot.

Currently, I configured my laptop to be a dual boot system (Windows 7 and Windows Server 2008 R2 w/ Hyper-V, both implemented as 40GB VHD in the actual harddisk).  I utilized Boot from VHD capability of Windows to do this, which is pretty sweet.

But I am getting tired of having to maintain 2 OS on the same box.  I am trying to get rid of W2K8R2 from my system since 99% of the time I am using Windows 7 anyhow.  But one thing kept preventing me from doing this... call it laziness or whatever you wish, but I use Hyper-V to run some precanned VHDs from Microsoft such as SharePoint 2010 demo which already has everything that I need.  I supposed the other reason for this is just to play around with Hyper-V so I understand the technology and can demonstrate them when needed.

The rest of my virtualized environment actually run in Windows 7 using VirtualBox which support 64-bit guest OS.  I like VirtualBox very much for what it can do; Not to mention it is also free.  So one pet peef that I had previously is I couldn't find a way to boot Hyper-V VHD from inside VirtualBox.  Virtual Server / VPC VHD runs just fine, but not Hyper-V one... weird.

Today, I decided to look around the web again, and finally came across this particular blog post... lo and behold... it is actually possible to do this.  The trick is just to not to use SATA to boot up the VHD, but rather to attach it to the IDE controller instead.  Curious, I tried to quickly create a VM inside VirtualBox and connect it to my existing Hyper-V SP2010-7a.vhd.  Boot it up and guess what... it runs :). YAY!!

So now... I need to decide whether to scrap the 40GB W2K8R2 VHD from my hard drive or not ... Hmmm...

Nothing against Hyper-V, but I just wish Hyper-V can run on top of Win7 so I don't have to do the OS switcheroos.  Most of my tools like Office, Outlook pst and ost, etc. are in my Win7 system.  It is such a hassle to maintain 2 different OS (patches, etc.) and the applications when I only use the other one 1% of the time.  And Virtual Server / VPC are not an option on Win7 since they can't run 64-bit guest OS which is needed for SharePoint 2010.

On a totally different thing, at home I like to use my work laptop as my server environment and actually do the work from my home laptop that is attached to a secondary monitor.  So I was thinking... wouldn't it be neat if I can use my home laptop keyboard and mouse to control my work laptop seamlessly... I am not talking about remoting to it since that will actually waste some screen space on my home laptop.  But rather, emulate a 3 screens environmment where my work laptop is the left most screen and my home laptop is the middle screen and the additional LCD for the right most screen.  One screen to browse, one screen to do some works like coding, and another one for other peripheral stuffs like TweetDeck or email or whatever.  It turns out you can do this... Found this piece of open source software (Synergy) that will allow you to do just that.  Cut and paste work just fine across machines and it work across multiple OS too (Windows, MacOS, and Linux).  Awesome.

So, with the new ability to run Hyper-V VHD inside VirtualBox and lots of screen estate and seamless control over my other computer screen using Synergy... I am a happy camper :).

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under: ,

Finally!! Indonesian Mobile Developers Can Submit WP7 Application to the MarketPlace.

There are/were 2 things that bug me as an Indonesian in regard to Windows Phone 7.

  1.  From Indonesian consumer point of view... The ability to purchase application in Marketplace is basically non existant if you don't have the right credit card.  What I mean by the right credit card is a non Indonesian credit card. (If anyone know different, please let me know.)
  2. From Indonesian mobile developer point of view... The ability to submit WP7 application into the MarketPlace via AppHub was also non existant.  Again... the problem here is related to Indonesian credit card was not supported. (Note that I said... WAS) Big Smile

So, the good news... 

As developer (in Indonesia and other countries), it is now possible to participate in the Marketplace!! Yay!!  A Global Publisher Program was recently announced during TechEd Middle East in Dubai.  So what are you waiting for?  Go to Yalla Apps and register yourself and start making money.  For full news, see this blog post.

But wait... what about if I want to buy from Marketplace as consumer? ... Eh, basically it is still the same situation as before... You need a credit card that is allowed by Marketplace... It's very hard, but it is not entirely impossible.   But hey... at least you can hawk your stuffs online now!  Better 1/2 than nothing, right? Big Smile.

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under: ,

The Best Deep Dive on jQuery Session

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/

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under: ,

Move to the Cloud, Use the Cloud and Be a Cloud

As you might already know, there are 3 general types of cloud offerings out there.

  • Infrastructure as a Service (IaaS)
  • Platform as a Service (PaaS)
  • Software as a Service (SaaS)

Each gives you a different level of control and benefits.  I won't bother you with the detail on each.  It's not what this blog entry is about.  If you like to compare and contrast these offerings, see this.

A different perspective on the cloud offerings has been suggested to me:

  • Move to the cloud
  • Use the cloud
  • Be a cloud

Moving to the Cloud

Moving to the cloud is like outsourcing one more of your services such as e-mail, CRM, portal solution, and even some business productivity tools.  A lot of cloud players are playing in this field including Microsoft Office 365 and other Microsoft Online Services, third party / partner hosted services, Google docs, .and salesforce.com.

The benefits for this is you no longer need to maintain the infrastructure necessary for these "IT commodity" services, instead you can utilize your resources to do more strategic stuffs and let the cloud provider deals with the day-to-day administration.

The disadvantage for this is you might not have the ability to do full customization on top of the solution that you have outsourced since most of the time, the provider will configure the solution to run on multi-tenancy architecture that makes it a bit difficult to customize for a specific tenant.  Maybe, if you are lucky, and depending on your service level with the provider, you might be able to do this, but expect to treat this offerings the same way as shopping for cloths from a department store instead of going to the tailor to make a custom suit / dress.  You have your choices of colors and sizes and that's that.  No addditional pockets, replacing buttons, etc.

Use the Cloud

Think of this as not moving the entire solution to the cloud like in Move to the Cloud above, but rather, you still have something on-premise that is reaching out to the cloud for additional things.  Or your internal solutions are using some cloud services.   Seasonal business activities like internet campaign marketing / promotion can defintely take advantage of the public cloud services such as using Windows Azure or other platform like Google AppEngine as your workhorse during the promotional period by quickly adding the necessary computing power without the need to put down the huge capital cost for hardware up front.  The ability to pay as you go is definitely something to consider when you want to cut down the capital cost.  Once you are done with the seasonal activity, you don't need to worry about what to do with the extra computing capacity that won't be doing anything if you were to implement the solution in house using your own hardware (that you have to purchase up front).

Be a Cloud

A couple of example for this are a hosting business offering elastic computing based on private cloud technology or your company itself decided that you want to keep your data and computing power inside the company but still wants the elasticity that a cloud offering can provide.  A good scenario for considering this kind of solution is when your company or country you operate in has regulation that requires your data to stay within a certain physical boundary or you are considering being a cloud provider for others.  Another good case for this is when you have a cloud solution that you want to sell as a service (SaaS) to others.  With the right VM infrastructure and management solution, it is definitely possible to be a cloud.  An example of this is Microsoft Private Cloud solutions such as Hyper-V Cloud and Windows Azure Platfrom Appliance described here.  Another vendor that is also playing in this area is VMWare.

Things to Consider

Different level of IT maturity is required for operating in the cloud.  Before you can move to the cloud, your IT infrastructure, staff, and procedures must be at a certain level of maturity.  If you are putting out fire most of the time, you are probably not ready to move yet.  How easy you can integrate your internal IT systems such as security & identity with the cloud offering is another thing that you might want to consider before making your move. 

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under:

How to Change the Active Printer to Specific Printer in Excel Using .NET and How the Heck Can I Find the Right Printer Name and Port Combination that Excel Wants?

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.

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under: ,

How come System.Web.Extensions.dll cannot be found in the Add Reference dialog?

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 targetting 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.

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under:

"Unable to load client print control" on SQL Server 2008 SP 2 SSRS

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:

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under:

Certified ScrumMaster training in Jakarta by Bas Vodde

For those who are interested in Scrum and agile development process, this is a good chance to get your ScrumMaster certification.

It's going to be at Gran Melia from 21-22 February 2011.

The detail can be found here.

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under:

SEA SharePoint Conference Announced

So, you are a SharePoint IT Pro / Dev in SEA area... Are you looking for an alternative to US based SharePoint Conference (connotation... far, expensive, not enough training budget to send you halfway across the globe)?  Well, how about a SEA regional SharePoint conference?

Wait no more!! Well, actually, wait a little, but SEA Sharepoint Conference has been announced.  It's scheduled to take place on October 26 - 27, 2010 in Singapore.  The cost is also quite reasonable, which is about SGD 400 per person with additional discounts.

 For detail, visit http://spevents.co.nz/SEA/default.aspx

Register early and go as a group for additional discounts :)

 

Share this post: | | | |
Posted by Jimmy Chandra | 1 comment(s)
Filed under: ,

Unit Testing, Mocking, Stubbing and Moles?

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

dependencyinversionprinciple_0278f9e2

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

moleNow, 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?

Share this post: | | | |
Posted by Jimmy Chandra | 2 comment(s)
Filed under: , , ,

Martial Art Can Improve The Way You Code? For Real? How?

When I was still in elementary school I used to take martial art class, specifically Kyoukushin karate.  And when you get to a certain level, you have to perform some series of karate movements / form called kata, for example this one.  So, why am I talking about martial art in a development related blog?

Apparently some coders like Dave Thomas and Uncle Bob (in this podcast) believe that us coder can learn something from martial art.  Really?

One used of kata in Karate is to build up one's muscle memory.  Once you learn the form, it will come easily to you when you need to perform it.

Dave believe, just as kata in martial art can improve the practioner's skill, by adapting kata in coding (by performing a series of coding exercise repeatedly), can hone your skill as a programmer through a lot practice and repetition.  Thus he coined the term Code Kata.

Actually, I heard about this a while ago, but I never took any real interest in it, until a couple days back when I listed to this particular Herding Code podcast.  In the podcast, they talked about someone doing this String Calculator Kata in Python and Vim.  The actual topic was not even about the kata, but about how awesome this guy in using editor like Vim.  Anyhow... As I said before, it made me interested, so I looked it up on the net and found this.  Which if you are not familiar with the context, you will be scratching your head while watching it... like myself :).  So I go search around a bit more on String Calculator Kata and found out that Roy Osherove was the one who created it and I found out the context that I need to understand just what the heck the previous video is about, here.   So, I decided, what the heck, I'll give it a try in C# and the MS Test framework that comes with Visual Studio.  Doing the usual TDD red green refactor steps, I managed to complete the kata to what I think was satisfactory result.  Roy also posted a bunch of kata-cast on the same page and I decided to give some a look and a glance and stumbled upon this one.  And boy, I was watching it with my mouth half opened on some of the stuffs that they did in that katacast which sort of open my mind and eyes to a whole lot of possibility (on how to use LINQ, lambda & fluent interface programming style.

Not that I'm going to do this daily from now on, but I do think practicing the code kata from time to time will benefit me in the long run, so I'll give it a try, perhaps in multiple different languages, which should also be a good way to learn the language that I want to learn like Ruby for example.

So, what are you waiting for? Learn it, Practice it, Love it... Happy Code-Kata-ing??  Is that even a word?

Share this post: | | | |
Posted by Jimmy Chandra | with no comments
Filed under:
More Posts Next page »