Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Monday, March 8, 2010

How to expose internal members of a class to Unit Test cases

Going by the convention of design patterns, it is always safe to have the members of a class as private or internal, In order to clearly abstract away the implementation details from the external world. The Classical example of this being Domain Model (Repository Pattern) where all the methods including constructors are made protected internal.

Example:

clip_image001

But there is a bottle neck in doing this. For maintainability purposes SUT (System under Test) (the internal method GetTime()in our case) and Unit test cases for testing the GetTime()) are placed in separate assemblies . Hence from the Unit Test cases, it is not possible to instantiate Class2 and test the GetTime() method .

This can be overcome by the InternalsVisibleTo attribute located in System.Runtime.CompilerServices namespace. The attribute takes the friend assembly’s name (the assembly to which the SUT has to be exposed) as an argument. The attribute when placed upon the namespace of the current assembly, is safely exposed to the target assembly (friend assembly).

Example:

clip_image002

clip_image003

This workaround is similar to the concept of Friend functions in C++, which is the only way by which a Class can access the private members of another Class(of course sparing pointers).

Thursday, February 25, 2010

Accessing live cricket score from C# Win Forms Application - Using Screen Scrapping technique.

Quite often during the crucial stages of a cricket match, we might want to refresh the browser frequently, in order to get the latest score. And more importantly we need to stay in the browser window.

This can be done programmatically, through the following steps.

1. Launch an embedded web browser in a C# win forms application.

2. Supply the URL of the page which publishes the latest cricket score.

3. Capture the entire HTMLDOM of that page.

4. Identify the HTML element which displays the score (that is changing) and save the index of that HTML element (the index is unique for all the HTML elements).

5. Load the entire HTMLDOM once again and Get the element by index (already saved).

6. Querying for the text at that element gives you the latest score.

7. Run the steps 5, 6 on a timer (say 7 seconds to keep refreshing the page.)

Note: The HTML markup of the page should not change while scrapping.

Code Snippets:

Steps -1, 2

image

Steps -3, 4

 image

Steps 5,6,7

image

This technique can be ideally used to ‘scrape’ weather updates, Stock rates etc, which keeps changing frequently.