Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Friday, June 22, 2012

How will another unit test framework cause me to write better tests than using MSTest ?

 I started out with an idea of writing down some of the things I discovered while writing unit tests on both MSTest and the popular NUnit unit testing frameworks and for the most part I wasn't impressed with MSTest. The article developed on how MSTest sucks (the one fore Visual Studio 2010) and how NUnit rules (ok its a bit biased and exaggerating but get this...) but I got hit with one fundamental question...

How will another unit test framework cause me to write better tests than using MSTest?

You see you can have all the "nice features" in the world but if you still write unit tests against a system that isn't well designed or broken up in testable pieces, you will have a hard time writing maintainable unit tests. The other thing is that even if you have the most wonderful designed system and unit-test friendly classes to test against, you still sit with the problem of writing maintainable unit tests.
So I thought of rewriting the post and taking on this discussion from a different perspective. Instead of blabbering on about how this framework rocks and the other one doesn't let's ask the question above. Why against MSTest? Because it seems to be the underdog at the moment. Look at what some of the other bloggers have to say:
I also have a couple of things to say about it which I just quickly want to add before I ask the big quesiton.
  • Firstly it seems to be another monolithic solution from Microsoft. Why not have a .NET testing solution which can be broken down in different testing modules so that you can use the best tool for the job? So then you can use the other testing tools from Microsoft but for Developer unit testing you use something like NUnit or something. But I know why this is the case because again Microsoft wants you to use their products. Now it wouldn't have been a problem if they have taken certain things into account like some of the bloggers up there have stated like extensibility, etc.
  • Startup time is SLOW! And then it's only basic logic tests!
  • There are plugins in Visual Studio to run NUnit tests that are free! (Not a MSTest gripe but many people stick to MSTest because its integrated. Speaking of which there are ways apparently, which I haven't tested myself, to run NUnit on a TFS build server. Check this link: "NUnit for Team Build").
So now I want to start this question objectively and look at how using the best features of unit tests allow me to write more maintainable unit tests. But in instead of taking every unit testing framework I will settle with NUnit and MSTest because I am familiar with NUnit and it seems to be the most popular one out there, and MSTest because everyone is slashing this one to bits so it should provide a nice view if they really make a difference.
Now you might say "I've done this and that with MSTest and it took me hours while I could have done the same in NUnit in minutes". Let's find out shall we?

I'm not going into UI tests and Web tests. Firstly I don't think something like NUnit should be brought anywhere near UI testing! MSTest might have a nice UI tester but you might need to purchase Visual Studio Ultimate or something to get hold of it. Neither am I going to do web tests which involve HTML and JavaScript! That's just a maintenance nightmare waiting to happen!
No I will solely stick to logic tests and maybe even integration tests. Let Developer unit testing BE developer unit testing, anything else, use some of the other tools that are more suited for the job!

Writing tests for small methods are fine because your tests are inherently small to test the small amount of work it needs to do. Stuff like math functions, you give it an input and it spits out an output, very simple and quick. You do the MATH! LOL!
Some of you may say "Well NUnit will simplify your life there, you can have 1 test method with a few value attributes". That's true so NUnit can give you some simplified and good test coverage there. MSTest will require the code duplicate approach or you have to write the plumbing (again it might not be what developers would like as MSTest is not as extensible as NUnit) to get to the same kind of ease-of-effort that NUnit guys are enjoying.

But let's make it more interresting!

How about writing tests against a WCF service where you need to stub out some calls to other services and have to validate that the correct logic is being followed?

So let's say I have a WCF service class:

public class TimeSheetService : ITimeSheetServiceContract
{
       public PersonDetails GetPersonDetails(string id)
       {
            ... some code here ...
       }
}

Ok seems easy to test:

NUnit

[Test]
public void Get_user_details_from_timesheetservice_that_is_existing()
{
     TimeSheetService service = new TimeSheetService();
     var person = service.GetPersonDetails("12345");
     Assert.That(person, Is.Not.Null);
     Assert.That(person.Name, Is.EqualTo("James"));
}

MSTest

[TestMethod]
public void Get_user_details_from_timesheetservice_that_is_existing()
{
     TimeSheetService service = new TimeSheetService();
     var person = service.GetPersonDetails("12345");
     Assert.IsNotNull(person);
     Assert.AreEqual("James", person.Name);  
}

Not much of a difference, right? But hang on a moment! Where do I stub the person with the name "James"?
Big deal, I'll just use my favorite mocking framework to do that.
I currently use Rhino Mocks as my mocking framework and I am open for discussion, so if you see me doing something wrong or you want to notify me on something else that Rhino Mocks users will like to move across to please let me know. Assume I have a preconfigured 'mock' object (will get to that later) and I have noticed that the service needs an IPersonRepository object.

NUnit

[Test]
public void Get_user_details_from_timesheetservice_that_is_existing()
{
     IPersonRepository personRepository = mock.StrictMock<IPersonRepository>();
     personRepository.Expect(x => x.GetPersonDetailsFromRepository("12345")).Return("James");
     mock.ReplayAll();

     TimeSheetService service = new TimeSheetService(personRepository);
     var person = service.GetPersonDetails("12345");
     Assert.That(person, Is.Not.Null);
     Assert.That(person.Name, Is.EqualTo("James"));

}

MSTest


[TestMethod]
public void Get_user_details_from_timesheetservice_that_is_existing()
{
     IPersonRepository personRepository = mock.StrictMock<IPersonRepository>();
     personRepository.Expect(x => x.GetPersonDetailsFromRepository("12345")).Return("James");
     mock.ReplayAll();

     TimeSheetService service = new TimeSheetService(personRepository);
     var person = service.GetPersonDetails("12345");
     Assert.IsNotNull(person);
     Assert.AreEqual("James", person.Name);  
}

See how much it grew? Both are still the same length. The problem is that this is how we generally run into these things. If we don't take care, we usually end up with bloated unit test methods!
Now's the question is how can the unit testing framework make my life simpler?
Now let's forget using other libraries (AutoFixture as example) and let's forget writing helper methods (unless it's part of getting the framework to help deal with this). Let's get the unit testing framework to do most of the work for us. See what I mean with this? I know that there are stuff out there that can help deal with this but that's not the point. Can my unit testing framework help take care of this without me having to write helper methods/classes or rely on external solutions? If it cannot, then why? Those are the things I want to point out.

And so I present this as a question to you the reader. I know MSTest and I know NUnit but I don't know all the integral details that each offer to leverage it to my advantage. So if you look at the above and see some area where MSTest or NUnit can make my life easier please comment below. If you are experienced in another unit testing framework, please give your input as well! You don't necessarily have to give big code replies, just mentioning a feature and how it can be applied should help get a picture.

Just to finalize this let me give a broader picture of the problem and then hopefully people can start sharing their input so that we can really see how much of a difference a unit testing framework makes.

First there is the Rhino Mocks problem. How can I create a new MockRepository for each test and provide it in such a way that when I call the field (or property) "mock" that I have a ready to be used mock. Also don't forget that Rhino Mocks expect the "ReplayAll" to be called before you call your SUT (System Under Test) code and after the test is completed it need to "VerifyAll" against the mock repository object.

Secondly I want to test something else. I want to test the SubmitTime method.
Let me write out the code (only the relevant stuff) so that you can have a clearer picture of what needs to be tested:

public class TimeSheetService : ITimeSheetServiceContract
{
      private readonly IPersonRepository _person;
      private readonly ITimeCaptureRepository _timeCapture;

      public  TimeSheetService(IPersonRepository person, ITimeCaptureRepository timeCapture)
      {
             _person = person;
             _timeCapture = timeCapture;
      }

      public PersonDetails GetPersonDetails(string id)
      {
              var result = _person.GetPersonDetailsFromRepository(id);
              return new PersonDetails { Name = result.Name, Categories = result.Categories };
      }

      public bool SubmitTime(TimeSubmitRequest request)
      {
             PersonDetails personDetails = GetPersonDetails(request.PersonId);
             bool added = _timeCapture.SubmitTimeCapture(request.PersonId, personDetails.Categories, request.TimeSlots);
             return added;

      }
}

Now the Id or PersonId is a string, Categories are IList<string> and TimeSlots are IList<TimeSlot> and TimeSlot is of class of properties { DateTime StartTime, int Minutes, string Category }

If there are somethings that are not clear let me know.

    Wednesday, November 09, 2011

    Renewal Project's WCF Extensions Library

    Hi all

    Just wanted to announce that I've released a beta-version of my WCF Extensions Library on my CodePlex project called Renewal Projects. Check out the documentation section for more info. I think WCF users in the .NET space may want to have a look at this as it might prove useful in the long run as it contains a Channel Repository, Channel Pool and the possibility to have WCF channels hosted in a IOC container.
    Its in BETA at the moment but testers are welcome to try it out.

    http://renewalprojects.codeplex.com/

    Wednesday, November 02, 2011

    MVC 2 Hidden Helper Extension

    I don't know if you've ever needed to store an entire entity object inside a html page using the hidden form fields but for some reason the standard ASP.NET MVC HiddenFor() method doesn't do that. It only seems to work for simple data types such as ints and strings, etc.
    So I wrote a little helper method to do just that.
    It takes all the entity that you wish to store in your HTML page and iterates over each property and performs a Hidden() method call on them to ensure that all its properties are encoded as hidden fields so that it gets passed back to the Controller Action via the POST method.

    public static MvcHtmlString HiddenEntirelyFor<TModel, TResult> (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression)
    {
       ModelMetadata modelMetadata =
          ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
       List<string> htmlEntries =
          modelMetadata.Properties
             .Select(property => htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression) + "." + property.PropertyName, property.Model, null))
             .Select(mvcHtmlString => mvcHtmlString.ToHtmlString())
             .ToList();
       return MvcHtmlString.Create(String.Join(Environment.NewLine, htmlEntries.ToArray()));
    }

    Monday, September 05, 2011

    Moles with Mocking capability

    Myself and a colleague of mine made a discovery when we started to do some unit test coding with moles that it doesn't have any expectation-functionality like Rhino mocks where you can specify what the incoming parameter values should be for a mocked-class.

    That's when I did some searching on the web for mocking frameworks which might complement the Moles tool-set. I came across this library: http://simpledotnet.codeplex.com

    It's not the best out there but it does feature one thing that other mocking frameworks (and correct me if I'm wrong) doesn't have and that is delegate mocking. I told my colleague about it and he tried it out... and it worked! It makes coding less and improves readability.

    Now suppose you have a class ClassX that you want to mock.
    Now with Moles you can only stub the target type by substituting the behavior with delegates.
    With Simple.Net, you first create the expectation scope:

    var expectationScope = new ExpectationScope();

    Then you can create the mock-delegate:

    var getNameMock = Mock.Delegate<MolesDelegates.Func<ClassX, string>>();

    Now we stub the target class with the mock:

    MClassX.AllInstances.GetName = getNameMock;

    Now you set some expectations:

    Expect.Exaclty(1).MethodCall(() => getNameMock(Any<ClassX>.Value)).Returns("Fred");

    Run your system under test code:

    ClassX x = new ClassX();
    Assert.AreEqual("Fred",x.GetName());


    Verify expectations are met:

    AssertExpectations.IsMetFor(expectationScope); 

    And now your test should succeed. Please check out the Simple.NET website to see how this mocking framework works.

    Hope this helped someone.

    Wednesday, August 17, 2011

    Moles, WCF and IDisposable

    We all have heard of the Moles tool which Microsoft released some time ago which allows one to stub any Type with a custom one (which substitutes the behavior of the original one) for the purpose of writing unit tests a bit easier. I did wonder some time ago if one could use this to stub WCF proxies so that you don't have to create a stubbed service hosts and make changes in your App.config, etc.
    Initially it seemed like a dud but when I left it for a while and came back to it later I discovered that the solution is simple but not so obvious. I am not going to cover the basics of Moles, you can google that for yourself, I'm going to cover the necessary steps to get your WCF proxies (or whatever similar case) stubbed for unit testing purposes.

    The problem that I had with Moles and WCF was that the proxy classes inherited from ClientBase (which wasn't the problem) which in turn inherited from IDisposable. Now since a proxy's constructor tries to check the configuration file for proxy configuration, I had to sub the constructor of that proxy with an empty delegate. I managed to stub the proxy call with something that returned a dummy value and running through the tests, it actually stubbed that proxy call which is what I wanted.
    This was fine but I had a couple of proxies wrapped around a 'using' statement and at the end of a using statement the proxy's Dispose() method gets called and I got greeted with a nice NullReferenceException. I realised it was because I stubbed the constructor but when I checked for the Dispose method to stub, I couldn't find it anywhere in the generated Moled-Proxy class. That's the part that messed me around.

    After some thinking and some Googling I started to think that I might have to "mole" the System.ServiceModel assembly in order to stub the Disposable method found in the ClientBase<> class. This also had a minor problem. It caused a compiler error but after some Googling someone recommended that I amend the 'System.ServiceModel.moles' file with the following:
    Beneath the <Assembly> tag just add the following:

    <StubGeneration>
        <Types>
            <Clear/>
            <Add Namespace="System.ServiceModel.Description!"/>
        </Types>
    </StubGeneration>


    When you compile the unit test project it should finally generate the moled System.ServiceModel assembly and now we can finally stub that method! Now suppose you had a proxy which had the contract of IGeneral, you would stub its Disposable method like so:

    MClientBase<IGeneral>.AllInstances.SystemIDisposableDispose = (c) => { };


    Unfortunately you cannot just specify the MClientBase<> without specifying a Type. It will give a compiler error.

    So by using an example unit test:

    [TestMethod]
    [HostType("Moles")]
    public void TestMethod1()
    {
       MGeneralProxy.AllInstances.GetName = (p) => "Stubbed Name";
       MGeneralProxy.Constructor = (p) => { };
       MClientBase<IGeneral>.AllInstances.SystemIDisposableDispose = (c) => { };

       using (GeneralProxy p = new GeneralProxy())
       {
           Assert.AreEqual("Stubbed Name", p.GetName());
       }
    }


    You should be able to successfully run it and stubbing the proxy call for your unit test to work.
    the 'using' block should actually be the part where the production code gets executed but for demonstration purposes, I left it as is so that you can get the idea that the proxy gets stubbed as it should.
    Here is the rest of the code for some clarity:

    public interface IGeneral
    {
       string GetName();
    }

    public class GeneralService : IGeneral
    {
       public string GetName()
       {
           return "General Name";
       }
    }

    public class GeneralProxy : ClientBase<IGeneral>, IGeneral
    {
       public string GetName()
       {
           return Channel.GetName();
       }
    }

    Wednesday, June 22, 2011

    Configuring Proxy settings in .NET config file

    Hi all

    Usually at work when I wanted to test something that requires to make a call over the web, I had to code two lines into my C# app to allow my application to work over our proxy:


    WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy();
    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;


    Now, I found that you can actually configure your App.config or Web.config to do this for you.


    <configuration>
      <system.net>
        <defaultProxy enabled="true" useDefaultCredentials="true">
        </defaultProxy
    >
      </system.net>
    </configuration>


    This would set the proxy to be used to the one currently configured in Internet Explorer and uses your currently logged in credentials to access the web through the proxy.

    If you need to specify a different proxy, you could specify it like this:


    <defaultProxy enabled="true">

      <proxy proxyaddress="some new proxy" />
    </defaultProxy>


    There is just one issue with this, you cannot specify credentials explicitly to use in the configuration file that needs to be used for proxy access. If you have to make use of a proxy and the account you use to log into windows doesn't have access to that proxy, you would have to specify a different set of credentials to be used.
    Yes you can code this in C# by specifying Credentials in your Default proxy.
    But this is not always desirable.
    I did find a post on Stack Overflow where someone suggested that you create a Proxy class and inject it as a Module, which is what I'm going to demonstrate here:

    public class MyProxy : IWebProxy
    {
        public Uri GetProxy(Uri destination)
        {
            string proxy = ConfigurationManager.AppSettings ["proxyaddress"];
            return new Uri(proxy);
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }

        public ICredentials Credentials
        {
            get
            {
                string username = ConfigurationManager.AppSettings ["username"];
                string password = ConfigurationManager.AppSettings ["password"];
                return new NetworkCredential(username, password);
            }
            set {  }
        }
    }


    And in the config file:


    <configuration>
        <appSettings>
            <add key="proxyaddress" value="http://proxyaddress"/>
            <add key="username" value="my user"/>
            <add key="password" value="my password"/>
        </appSettings>
        <system.net>
            <defaultProxy enabled="true" useDefaultCredentials="false">
                <module type="MyAssembly.MyProxy,
    MyAssembly"/>
            </defaultProxy>
        </system.net>
    </configuration> 


    This would make use of the proxy we coded to specify which proxy to use and with which credentials. You might want to cache those settings, etc. but this is just a simple example of how to do this. This way you don't have to touch your production code at all and still configure it to be proxy-aware.

    I hope this would be useful to some one as it has been for me.

    Sunday, June 27, 2010

    TFS Builds

    Some interesting things to note when doing TFS Builds. (I've written this article a few months ago before Visual Studio 2010, just to bear in mind)

    Being exposed to the .NET world for too long, I actually became acquainted with Team Foundation Server for Version Control, Continuous Integration Builds and Release Builds. I'm not going to comment on the system at the moment. I just want to write something that is for me for future reference and maybe that can help someone else.

    I've been struggling a bit on configuring the TFS Build server to not output all the project files to a single Binary folder but to keep it in its projects' configured output folders, i.e. \bin\Release, etc.

    Also, I spent some time trying to get the solution's directory that's being built.

    To get TFS's Build not to override the output directory, add the following in your TFSBuild.proj in the first PropertyGroup section:
    <CustomizableOutDir>true</CustomizableOutDir>

    Here are a few things you can do when writing your own custom MSBuild project file:
    <PropertyGroup>
        <SolutionDir condition=" '$(IsDesktopBuild)' == 'false' ">$(MSBuildProjectDirectory)\..\</SolutionDir>
        <MSBuildCommunityTasksPath>$(SolutionDir)\Third Party Extensions\MSBuildCommunityTasks\</MSBuildCommunityTasksPath>
      </PropertyGroup>

    The SolutionDir is only set if this is a TFS Build (hence the '$(IsDesktopBuild)' == 'false' part). TFS doesn't set this variable. TFS does have a MSBuildProjectDirectory. This has worked for me so far.
    If you need to reference some custom task file like MSBuildCommunityTasks, you can then make use of the $(SolutionDir) variable, as shown above.

    Now that the projects are being built in their respective folders, you might want certain output to be generated so that you can do a release. You might for instance want all the installers to be copied to the Results path so that you can install it on the relevant test or distributed environments. So in each project that you want output from, insert this as AfterBuild Tasks:

    <Target Name="AfterBuild" Condition=" '$(IsDesktopBuild)' == 'false' ">
      <Message Text="Copying output files from $(OutDir) to $(TeamBuildOutDir)" />
        <ItemGroup>
          <FilesToCopy Include="$(OutDir)\*.msi" />
        </ItemGroup>
        <Copy SourceFiles="@(FilesToCopy)" DestinationFiles="@(FilesToCopy ->'$(TeamBuildOutDir)\$(AssemblyName)\%(RecursiveDir)%(Filename)%(Extension)')" />
    </Target>

    Another nice feature that I discovered while browsing through the MSBuildCommunityTasks collection is the ability to set a version number automatically. There are various provided options but the one with the least configuration and storage of info is this one that I'm using:

    <Target Name="UpdateBuildVersion" Condition=" '$(IsDesktopBuild)' == 'false' ">
      <Version BuildType="Automatic"
       StartDate="$(BuildStartDate)"
       Major="1"
       Minor="1">
        <Output TaskParameter="Major" PropertyName="Major" />
        <Output TaskParameter="Minor" PropertyName="Minor" />
        <Output TaskParameter="Build" PropertyName="Build" />
        <Output TaskParameter="Revision" PropertyName="Revision" />
      </Version>
      <Attrib Files="Properties\AssemblyInfo.cs" Normal="true" />
      <FileUpdate Files="Properties\AssemblyInfo.cs"
       Regex="(\d+)\.(\d+)\.(\d+)\.(\d+)"
       ReplacementText="$(Major).$(Minor).$(Build).$(Revision)" />
    </Target>

    Calling this from your built project's BeforeBuild task, will let TFS Build (only) to overwrite your Assembly Info and set the new version number and then do a build. Now you don't have to clutter your check-ins and you don't have to remember to set your version numbers anymore. By using a value from $(BuildStartDate) of the format YYYY/MM/DD, you can have a number increment on every build which equates to the amount of days since the $(BuildStartDate). You'll also note the 'Attrib' task. This is to set the file's attribute to normal because TFS checkouts usually sets the file's read-only flag to true and then all your apps will throw an exception because they "can't" write to a read-only file. Same with TFS Build.

    Config Encryption for .Net

    I know there are many examples of configuration file encryption on the net but I needed some place where I can go to remind myself how it works again without having to Google for long periods again in the future to figure stuff out.

    I want to write about Executable configuration encryption and Web configuration encryption. It is actually simple but there are a few things you need to know before diving in. Executable and Web encryption (through the standard way) cannot be mixed, you can't for instance point to a web project in order to open with the ConfigurationManager and vice versa with the WebConfigurationManager. This is pretty obvious but sometimes when you're working with deployment code, you are sometimes tempted to try one with the other.

    Secondly, when using the ConfigurationManager.OpenExeConfiguration() you have to give the full path to the EXE file. This EXE file must be found along with the configuration file.
    With the WebConfigurationManager.OpenWebConfiguration() you have to give a full or relative path to an IIS Virtual Directory. If you just want to reference the Virtual Directory in the root path from DefaultWebsite, just add the '/' before the Virtual Directory name. This Virtual Directory needs to point to a directory with the web.config file.

    Now once you have an instance of a Configuration (via ConfigurationManager or WebConfigurationManager) you can now finally decide which section you want to encrypt and encrypt it.

    Configuration config = GetConfgiruation(); // Do as explained above
    ConfigurationSection section = config.GetSection("appSettings"); // Example
    SectionInformation sectionInfo = section.SectionInformation;
    if(!sectionInfo.IsProtected)
    {
      sectionInfo.ProtectSection("DataProtectionConfigurationProvider");
      sectionInfo.ForceSave = true;
      config.Save(ConfigurationSaveMode.Full);
    }

    There you have it. Just one thing though. You can't copy this file to another machine and attempt to decrypt it because .Net uses a generated token on your Machine to encrypt/decrypt.

    Thursday, May 01, 2008

    Ruby and Win32 API

    If you are using Ruby as an automation process rather than a development tool, you sometimes might want to use some of Windows' GUI controls, such as a message box or folder browser box. In those cases, you might want to try the DL library.

    Some of you have read this post about OLE Automation and DL. In a way it is quite simple but it can take a while to get right, especially if you're a beginner like me. However, after some time I have managed to get my folder browser to work and I haven't found Ruby code on the web that does this yet.
    However, I feel like it is rather simple to do and to find out how to make your own version, all you need to do is to see how people who wrote VB code do it.
    Why? Because it is that straight forward, in fact, Ruby reduces the amount of lines of code to do it.

    I must warn and say that doing this kind of programming requires excessive use of the Win32API docs (one form or another) and some skilled programming, especially in the C-language area, because you are interfacing to the actual C-functions from Ruby.

    Many VB code snippets that does this, have referenced these 2 c-functions (from the shell32 DLL):
    • SHGetPathFromIDListA

    • SHBrowseForFolderA

    They also require a structure to send data to the BrowseForFolder function.
    Here is a site to get you started.

    Why don't I just paste the code? Well, actually the method I wrote to bring up the dialog box, requires a whole Module and I would like to write my own Ruby module before I publish anything.
    Yeah, I might sound like a bugger but hey, I have posted lots of lines of code on this site before so... take it like a man! ;)
    The hardest part is creating a Ruby C-like structure from the VB structure, so I think I'll help you out on that one:

    ptr = DL.malloc(DL.sizeof('LLSSLLLL'))
    ptr.struct!('LLSSLLLL', :br_hOwner, :br_pidRoot, :br_displayName, :br_title,
    :br_flags, :br_fn, :br_lparam, :br_iImage)

    Now don't say I didn't give you anything! :D

    For those who still don't know what all those L's and S's are for, it is basically saying "This is a Long integer type" or "This is a string type". Its to determine the size of the structure, but you know that there are other data-types so you need to dig in on your own regarding that.

    Now there is one thing I'm having trouble with and it is the Open/Save File Dialog box. Aparently if you take the exact same data-types as the prescribed docs say, Ruby fails to bring it up. After hours of struggling, I decided to skip the VB code and look on the web if someone already did this, and to my "surprise", nobody has posted any code on this. Bummer! So I decided to have a look on the MSDN site, and BAM! I found my answer. The reason why Ruby didn't bring up my dialog box was due to the fact that Ruby created a structure that had a different size than what the function was expecting! So now I am trying to find out where, how and why.

    I might post my code and findings at a later stage, for this is a necessary thing for Windows Ruby Automation Programmers, like me! ;)

    Wednesday, April 30, 2008

    Netbeans 6.1

    As if Netbeans 6.0 wasn't enough to patiently wait for (not in a bad way), the new 6.1 is ready for download/order!
    Check this link out to find out more of what they did in this version.

    Monday, March 31, 2008

    Ruby, ruby, ruby ...

    Yeah it's been a while since the last posting. I was lacking some inspiration on what to blog on or I was just too lazy or too busy to actually log in and blog on something that I wanted to, that is until now...

    You might ask, whats up with the title? Well I remember the song written by a band called Keizer Chiefs (spelling) named: Ruby. Now that reminds me of the Ruby scripting language which lots of people on the web is going on about. A dynamic typed language with multiple ways of saying one thing.

    I was among those who agreed that Ruby was stupid, until I wanted to do a few things in Windows which Python nor other scripting languages could offer (or easily accomplish), except Ruby. Some of us would mock the guy who presented a brief crash course in Ruby, saying that it is too dynamic for our taste and it would make debugging a nightmare, etc. but doing some code delving and with the latest Netbeans language addition, which is Ruby and Ruby on Rails of course, I started to see how cool Ruby actually is.
    Usually I despised dynamic typed languages until I saw how it can increase productivity and coding speed for smallish scripts, which is what I wanted for automation.

    "What kind of automation?" you may ask. Well ordinary and OLE automation. Sure AutoIT is great for GUI and other windows automation but the scripting language is very BASIC (pun intended) lacking structure and (as in, I need structures as in C or C++'s structures or atleast...) object orientation. With Ruby we have good OO support and with the 'win32ole' lib, you can kick VBA and do MS Office automation via Ruby instead. A good starting site is Ruby on Windows which covers Ruby automation in MS Office. I managed to convert Powerpoint slides to somewhat formatted Word docs via Ruby, just to give you an idea.

    I think I'll post a couple of script snippets later on, on what I worked on with Ruby and AutoIT for others to see and for future reference.

    Just to go back to Python, some of you might say that Python does have OLE automation... I had a look at it and it looked very nasty! I wouldn't touch it, unless I looked at the wrong files, and you need to download a library for Python to have OLE automation ability. With Ruby you use the OLE objects exactly as in VBA but within your Ruby context.

    Currently I am trying to implement a few operations in Ruby to have Browse-For-Folder ability, Open-Dialog, and so on functionality by doing Windows API calls via the DL lib in Ruby. You can catch a quick course on DL here.

    I hope this will help you as much as it helped me.
    God Bless!

    Saturday, March 01, 2008

    Code::Blocks is released!

    At last! An official release of Code::Blocks and look'in good!

    I have downloaded the latest release of the Code::Blocks IDE from the site and so far I am pretty impressed by the features and speed of the application. It now features lots of parsers for script editing and compiler languages.
    I wouldn't know about all the other languages and compile projects but I would mainly use C::B for C++ programming.

    The Code Completion is much more responsive than before (you might see it from the second time and onward when opening C::B) and rich in data types (the list box that pops up displays everything from #DEFINEs (except their params) to variables and functions (obviously). Unfortunately it doesn't seem to handle templates. Bummer!

    The wxSmith GUI Editor seems nice enough to use, haven't tried it out completely but it should be sufficient for moderate wxWidgets projects.

    Well thats all that I have seen for now, haven't went through everything but it seems good enough to use though. I have worked with the nightly versions before and even they were pretty good so now I can only image how much better this version is (and how much more stabler).

    Unfortunately I don't know how this IDE compares with others (except VisualStudio but I won't go there) but with those that I have seen so far, it is far better than them (also except Eclipse and Netbeans but they aren't native to C++ development, like you can only do C++ and nothing else, no Gui editors for wxWidgets, no library support, etc. but I could be wrong!), however if I were to compare to wxDevC++, I would say that wxDevC++ has a better Gui editor (but then again I only used C::B's editor for a few seconds, not a few days) but C::B has better coding facilities!

    Cheers and God Bless!

    Tuesday, February 19, 2008

    Code::Blocks comming soon

    The long anticipated IDE for C/C++ and other development tools, is just around the corner...

    On the Code::Blocks home page (it even runs on a new server with a new web page design), it is mentioned that the long awaited RC 3 will be released shortly, officially!
    I have been waiting on this for a long time now, and can't wait to be able to have a stable and installable version of Code::Blocks.

    Code::Blocks is a multi-purpose (GPL 3) IDE for compiler-driven languages and frameworks. It is backed by wxWidgets as its core GUI library, and is also available for c++ development with a built in GUI Editor for wxWidgets projects. It runs on Windows and Linux (probably MacOS as well), gives you the ability to choose which compiler you want to use, has excellent GDB debugging features and the long awaited full implementation of the c/c++ code completion in the editor. Well, unfortunately I can't say how well any of the above will work or perform until a test-run is made on the official release, but I am sure it won't be disappointing.

    You can look at this page to see more features that Code::Blocks brings.

    We just need to be patient for a few more days!

    Tuesday, October 09, 2007

    Java String Switch

    The thing I miss about Java is that it doesn't have string switch functionality like C#. The only way to get close to achieving this in Java is through enums.

    A lot of people wonder how that can be done but when I read on a forum post about it I decided to do it myself.
    Firstly you'll need the strings you want to look out for. Create an enum containing them, just know that it can only be 1 word strings, don't even try multiple words!

    enum StrList
    {
    car,
    dog,
    human
    }

    Now we can take a whole string and pass it through the switch statement.

    switch(StrList.valueOf(incommingStr.toLowerCase()))
    {
    case car:
    //Do what you want with the 'car'
    break;
    case dog:
    //Do what you want with the 'dog'
    break;
    case human:
    //Do what you want with the 'human'
    break;
    }

    Voila! Ok not the best way of doing it but atleast you would have string switching! ;-)
    I would like to look into HashMaps to do this, since Enums perform mappings from string to the actual enum element.
    Hope this was interresting or helpful to you. The only reason why you'd want to do this instead of a list of if/else if statements is performance (it is also a bit more readable).

    Friday, September 14, 2007

    Java Downloader Code + Proxy

    For those that read the previous post Java Downloader Code, would maybe like to read this post as I have smoothed it out a bit and found out how to have Proxy support.

    I have now shaped the code to be more like a Java commandline application downloader. For the proxy settings, you can go to the Windows Control Panel and look for the Java icon, and once opening that control panel app, you can specify the Proxy settings for Java to use and based on that, this downloader will load that settings and use it to navigate through a proxy server. I don't know how this will work on other operating systems other than Windows but I would appreciate it if someone can do a test with this through an authenticated proxy connection.

    Now for the code:

    package javadownload;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;

    interface DowloadEvent
    {
    int getUpdateInterval();
    void update(int received, int total);
    }

    class Report implements DowloadEvent
    {
    public int getUpdateInterval()
    {
    return 1000;
    }

    public void update(int received, int total)
    {
    System.out.println((int)(received / (float)total * 100) + " % completed");
    }
    }

    class DownloadHandler
    {
    public static URLConnection getConnection(String url) throws MalformedURLException, IOException
    {
    return new URL(url).openConnection();
    }

    public static void downloadData(URLConnection from, OutputStream output, DowloadEvent downloadEvent) throws IOException
    {
    InputStream input = from.getInputStream();
    byte[] data = new byte[1024];
    long time;
    int received = 0;
    int rec;
    int total = from.getContentLength();

    time = System.currentTimeMillis();

    while((rec = input.read(data)) > -1)
    {
    output.write(data, 0, rec);
    received += rec;

    if(System.currentTimeMillis() - time >= downloadEvent.getUpdateInterval())
    {
    time = System.currentTimeMillis();
    downloadEvent.update(received, total);
    }
    }

    input.close();
    }
    }

    public class Main
    {
    private static String getFilenameFromUrl(String url)
    {
    int index = url.lastIndexOf("/");
    return url.substring(index + 1);
    }

    public static void main(String[] args)
    {
    PrintStream p = System.out;

    if(args.length != 1)
    {
    p.println("Specify the url to download from.");
    return;
    }

    //Use the system's proxy settings specified in the Java control panel.
    System.setProperty("java.net.useSystemProxies", "true");

    String url = args[0];
    String filename = getFilenameFromUrl(url);
    URLConnection con;
    FileOutputStream fout;
    int length;

    try
    {
    p.println("Connecting to: " + url);

    con = DownloadHandler.getConnection(url);
    con.setUseCaches(false);

    length = con.getContentLength();

    fout = new FileOutputStream(filename);

    p.println("File size: " + (int)(length / 1024.0f) + " Kbytes");
    p.println("Downloading...");

    DownloadHandler.downloadData(con, fout, new Report());

    p.println("Done.");
    fout.close();
    }
    catch (MalformedURLException ex)
    {
    ex.printStackTrace();
    }
    catch (IOException ex)
    {
    ex.printStackTrace();
    }
    }
    }


    Wednesday, September 12, 2007

    Java Downloader Code

    I knew how to make C# download something from the internet via the WebClient class but how on earth does Java do it?

    Today I tried looking on the web but using search strings such as "Java", "Download", "Web" just doesn't cut it. :D
    So I figured that something had to sit in the java.net package.
    Instead of having a WebClient like C#, you use the URL class.
    One would ask why do you download from the URL class? Well like Java is, you don't make use of the URL class itself but it is just another "factory" to obtain the connection to that desired url. From the connection you obtain the input stream and thats how you download.

    Here is a sample code I've written which downloads a file and reports the progress to you every second:


    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;


    interface DowloadEvent
    {
    int getUpdateInterval();
    void update(int received, int total);
    }

    class Report implements DowloadEvent
    {
    public int getUpdateInterval()
    {
    return 1000;
    }

    public void update(int received, int total)
    {
    System.out.println((int)(received / (float)total * 100) + " % completed");
    }
    }

    class DownloadHandler
    {
    public static URLConnection getConnection(String url) throws MalformedURLException, IOException
    {
    return new URL(url).openConnection();
    }

    public static void downloadData(URLConnection from, OutputStream output, DowloadEvent downloadEvent) throws IOException
    {
    InputStream input = from.getInputStream();
    byte[] data = new byte[1024];
    long time;
    int received = 0;
    int rec;
    int total = from.getContentLength();

    time = System.currentTimeMillis();

    while((rec = input.read(data)) > -1)
    {
    output.write(data, 0, rec);
    received += rec;

    if(System.currentTimeMillis() - time >= downloadEvent.getUpdateInterval())
    {
    time = System.currentTimeMillis();
    downloadEvent.update(received, total);
    }
    }

    input.close();
    }
    }

    public class Main
    {
    public static void main(String[] args)
    {
    try
    {
    String urlStr = "http://heanet.dl.sourceforge.net/sourceforge/sevenzip/7z455.msi";
    PrintStream p = System.out;
    long length;

    p.println("Connecting to: " + urlStr);

    URLConnection con = DownloadHandler.getConnection(urlStr);
    con.setUseCaches(false);

    length = con.getContentLength();

    FileOutputStream output = new FileOutputStream("7z455.msi");

    p.println("File size: " + (int)(length / 1024.0f) + " Kbytes");
    p.println("Downloading...");

    DownloadHandler.downloadData(con, output, new Report());

    p.println("Done.");

    output.close();
    }
    catch (MalformedURLException ex)
    {
    ex.printStackTrace();
    }
    catch (IOException ex)
    {
    ex.printStackTrace();
    }
    }
    }


    Hope you like it, or find it useful. Enjoy and may the Lord Jesus Bless you!

    Saturday, July 28, 2007

    Java Look&Feel and Access

    I have recently done a little searching on how to do a few things in Java. I also would like to know Java as well as I would know C++ & C#. On the net I have discovered how to change your look and feel to your native operating system's skin and how to connect to an Access Database using your ordinary JDBC ODBC connection driver...

    It was pretty interesting and not so hard at all. I'll give the basics but if you would like to know more about the Java LookAndFeels (the Java term for skin) you can have a look at this site: How to Set the Look and Feel.

    Basically to let Java inherit your Windows skin, just add the following before your form component creation code:

    try
    {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(UnsupportedLookAndFeelException ex) {}
    catch(ClassNotFoundException ex) {}
    catch(Exception ex) {}


    Yeah and just as I have remembered Java, you must specify the exception handling, unlike C# where you don't have to. Each has it's + and - but anyway, it doesn't matter in this case. Now you can see that when you run your application, it will have your Windows skin. If you are in Linux or whatever, I guess it would take your WindowManager's skin (i.e. KDE, Gnome, etc.)

    Now for something that I would find useful also is to connect with an MS Access DB via Java. Now I believe you have to have MS Access installed since it should install it's ODBC driver so that Java can use that driver to connect with. All you need is the following connection string and you are set to modify your Access DB.

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=YourAccessDb.mdb;DriverID=22;READONLY=true;";
    Connection con = DriverManager.getConnection(database ,"","");


    Now the reason I would rather use Java than Access is mainly because I'm am very tired of VBA! I have an existing Access Database and Java is such a more flexible, structured and more preferred language + it is free! Here (if you'd like) you can maybe use Hibernate (haven't tried it myself) for easier SQL queries. Also to migrate from Access to something else like HyperSQL or something is also easier via Java.

    I hope you found this useful as I have!

    God Bless till next time!

    Tuesday, June 12, 2007

    Pretty good C# string concatenation

    I have discovered a pretty cool way of concatenating strings in C#.

    Here is the code snippet:

    List<string> list = new List<string>();
    list.Add("Some ");
    list.Add("string ");
    list.Add("to be concatenated");

    string res = String.Join(String.Empty, list.ToArray());

    And here you have an equivalent of StringBuilder, except, you are not working with a character buffer, but with an array of strings. This is more efficient than StringBuilder, if you don't know how many concatenations will be done or how big the resulting string is going to be.
    The ToArray is not going to linearly create and copy elements to a string[] array, apparently C# is doing it directly behind the scenes.

    You can do the same with an ArrayList and cast the result of it's ToArray() to (string[]). I tried both. If you do know how big the string is going to be, then the StringBuilder is going to be more efficient (just remember to specify the initial capacity, he he ;) otherwise it won't be!)

    Hope you might find it useful.

    Friday, May 25, 2007

    A few months of C#

    Working on a system for over 2 months now, I think the C# bug has bitten me ;)

    What do I mean? Well, in the beginning I was like: "Ahh C#! How stupid!". Typically I was biased, but now thanks to that system I am working on (seeing how the previous programmer wrote it) and the nice concepts of C#, I have totally developed a new thinking paradigm.

    When I've learned C++, I was mainly performance driven and I worked as low level as I could. Seeing now how foolish I was, I realized that it wasn't all a waste. Having a performance-driven background and now adopting a design way of thinking, I believe, can be a very good combination. Yes I do still have a lot to learn about system design but I'm getting there!

    I'm also doing some training courses which our company is offering on some Wednesday mornings which I believe I can benefit from. They're teaching design patterns which could benefit a OO programmer. Singletons, Observer Pattern, Factory Pattern, etc. Interesting stuff which could benefit your development now or later (especially when you have to expand with more functionality or re-use to make something new).

    Now having explored this new OO world, I see a lot of things which C++ lacks, however one must consider what programs you would write with C++ and whether those new C# and Java quirks could benefit you at all. Man, I haven't touched C++ in a while, I have to think of something to write so that I can see how this new knowledge that I've adopted would make my C++ life easier. I like C++, not just for speed but it is something I have grown accustomed to. However, I wouldn't criticize stuff like C# and so on before venturing into it, again.
    Learn from my mistakes! ;)

    Have a nice week and God Bless to all!

    Thursday, January 04, 2007

    Netbeans offers free CDs

    Those of you who have worked with the new Netbeans might be pleased to hear that Netbeans.org is allowing you to order a free CD containing: NetBeans IDE 5.5, NetBeans Mobility Pack 5.5, NetBeans Profiler 5.5 and Sun Java System Application Server 9.0_1 Platform Edition.

    I'm not sure how long it takes to ship but it saves you some downloading and it comes all on 1 CD. Another great thing is, it also contains Windows, Linux, Solaris x86, Solaris SPARC and Mac OS X versions of Netbeans too.

    They also say that before shipping, they will publish the latest version of Netbeans which is also a good thing and I'm pretty sure that it will also contain the latest JDK.

    Just drop over to http://www.netbeans.org for a free Netbeans CD.
    I also saw a C/C++ Pack addon for it to develop in C/C++.
    EDIT: The C/C++ addon for Windows requires Cygwin. Thanks to rustypup from PCFormat.co.za (who dug a bit deeper than I) LOL!