.NET and me Coding dreams since 1998!

29Aug/072

Slides and examples from my “Design Patterns – real world examples” session

I had a really nice time presenting composite, lazy load, singleton, mono state, service stub and dependency injection design patterns.


I hope that the attendees were satisfied with the things I presented and they would be back on the next part of the patterns saga I plan to run in next month or two  


Here is missing illustration for first composite example


image


You can download slides and source code of all examples from here


 


Filed under: Uncategorized 2 Comments
27Aug/070

Nice blog post: Model view controller,Model view presenter and Presenter Abstraction Control

Derek  Greer did excellent job in wrapping up all the most important flavors of the MVC UI related patterns with a complete history and design overview in a very detail blog post


All of his blog posts are of the same high quality so if you are interested in modern architecture related things, get his feed :)


Article can be found here: Interactive Application Architecture Patterns


 


Technorati tags: , , ,

Filed under: Uncategorized No Comments
16Aug/070

Design patterns in real world use case scenarios – Dependency injection (set type)

To get a detail explanation of what this pattern stands for check out the Dependency injection post where I posted detail article about dependency injection pattern

How injection can be a pleasant thing

A good development practice is to encapsulate page functionality in a set of controls, because it is easier to maintain that code, performances can be tuned on more granular level, multiple developers can work on the functionality of the same page, we can reuse the control on some other page with similar UI. (I'll stop here writing ode to web controls - I'm sure you read this in almost every ASP .NET book you've seen)

But in real world this composite UI implementation usually comes with a cost due to several reasons:

a) Strict control encapsulation creates redundant code among controls and multiplies calls to database because every control has to retrieve it's own piece of data, update it's own piece of data etc. (Btw, this can be handled with a little async programing, but we today speak about cleaner way)

b) To solve redundancy in a) developers pretty often put shared logic on a page level and then do some "blind casting" like
((SomeSpecificPage)this.Page).SomeSharedElement

This is also a bad practice because sooner or later we would want to use this control on another page and then that require "spaghetti" coding such as"

if (this.Page as SomeSpecificPage!=null)

...

elseif (this.Page as SomeSpecificPage2!=null)

This burden can be eased by pages implementing the same interface, but sooner or later we would like to use a control on page X which is not implementing that interface and creating interfaces everywhere so the control could work doesn't sound clean to me.

Also, to me the fact that control is aware of it's surroundings  looks as a bad OOP practice too

c) To solve the hard coupling done in c), developers usually strive to event publishing, observer pattern, registry pattern etc. Problem from b) is solved by that but we also got a page for which maintenance we need a "map".

The solution here which would be presented tries to solve all 3 problems (redundant db calls, control coupled to its surroundings, high complexity) on a very simple and pleasant way - by using dependency injection setter type, where the page would inject itself to controls on highly simple and decoupled way

 

Problem - use case

Make a web page which would be used by user to update their data.

User data are: last name, first name, street, city, yahoo, email.

Page should be made of 3 different controls: one for names, one for address and one for Internet attributes. Desired functionality is that controls should encapsulate and separate concerns between them on class level as they would do on UI level without additional overhead caused

Why dependency injection pattern?

Dependency injection pattern in short is a pattern where some type is having a property  and implementing its own functionality referring to it, but doesn't set that property by himself. Instead, some external type sets the property value either through the type constructor or by using property setter.

So all you need is a class with a property and: either constructor setting the field property wraps or a property has to implement set block.

If we would take a look at our problem we would see that we need that someone somehow inject into the control user data required by control without control knowing who, how and when. Usage of web page constructors is unusual in web development so we would pick the solution of using property set block - dependency injection setter type

Rule of thumb

In a way, DI can be treated as a "Stranger strategy" because that is a strategy variation where the behavior is defined outside of the type implementing strategy

Usage of dependency injection pattern is usually appropriate when we have a situation where one object for its functionality needs information about the state of another object but we don't want to have any kind of coupled relation between the two objects (such as inheritance, composition).

Sound like our case!

Problem - solution example

Class Diagram of the solution

Dependency injection solution diagram

Page level code

Our page would contain those three controls  (ControlA, ControlB and ControlC) which are supposed to handle their own part of editing user data

image

The page would also have a "SaveUser" button which clicking should persist the updates done by page user

User service

Let's imagine that page for loading user data requires to call a UserService component which makes a very expensive call to database (web service etc) and retrieves whole set of user data.

Something like this diagram

image

and this code

    public class UserService

    {

        public static User GetUserFromDatabase()

        {

            // let's imagine there's been a very expensive database call

            //which retreive user data

            return

                new User("Prague", "malovicn at vuscode dot com", "Nikola",

                "Malovic", "Bryksova", "nmalovic_monster at yahoo dot com");

        }

    }

Allowing every control to repeat this call to retrieve their subset of data is not acceptable so we would make that call only once from page level and store the result on page level in a UserData property.

So the class diagram of the page would look like this:

image

(I'll touch later initControl method)

UserAwareControl

Even I like more interfaces, in this use case usage of abstract classes is more appropriate, because there is a common functionality (not only behavior) of the user controls. They all need user data so they could present them.

So the base control class would look like this:

    public abstract class UserAwareControl : UserControl

    {

        private User _userData;

 

        public User UserData

        {

            set

            {

                _userData = value;

                UpdateUIControls();

            }

            get { return _userData; }

        }

 

        public abstract void UpdateUIControls();

    }

 

There is a property UserData of type User which setter would be used for injection and there is an abstract method UpdateUIControls() which all controls have to implement and which enforce the update of controls when the page would set control user data

Control code

Every control would follow the same pattern as the ControlA does. Only difference would be then that the ControlB would have Street and City text boxes and access appropriate properties; ControlC Email and IM text boxes with accessing appropriate user data properties;

They all look like this:

public partial class ControlA : UserAwareControl

{

    protected void Page_Load(object sender, EventArgs e)

    {

        UserData.FirstName = FirstName.Text;

        UserData.LastName = LastName.Text;

    }

 

    public override void UpdateUIControls()

    {

        LastName.Text = UserData.LastName;

        FirstName.Text = UserData.FirstName;

    }

}

As you can see, control overrides abstract method and takes the property value and sets the ui elements with it.

On a page load event, control takes the content of the text boxes and sets the base control property value.

The injection

The injection would occur on a page level, during the Page_Init event. (Page level because page knows about controls; Page_Init - we need it just once). Page would first made expensive call to retrieve user data and then it would recurevly iterate through the control collections checking if the control is of UserAwareControl type. For all the controls found UserData property value would be set to reference to page property containing  user data and by that page would by that inject itself to control

The same thing said through the code could look like this

    private User PageUser;

 

    protected void Page_Init(object sender, EventArgs e)

    {

        // we load this only once

        PageUser = UserService.GetUserFromDatabase();

 

        initControls(Controls);

    }

 

    private void initControls(ControlCollection controls)

    {

        foreach (Control control in controls)

        {

            /// a little bit of composite recursion

            if (control.Controls.Count > 0)

                initControls(control.Controls);

 

            UserAwareControl userAwareControl = control as UserAwareControl;

            if (userAwareControl != null)

            {

                // setting the control to be aware of page user

                userAwareControl.UserData = PageUser;

            }

 

        }

    }

So, when some control sets a UserData property of the base control, the PageUser property is been set by that, because what we inject to control property is the reference to the page property.

That's how control gets the page single loaded data without coupling itself to page and without complex wire ups between them!

Testing the solution

When we start the web page we see that the control ui elements have been populated

image

After that I have updated some of the text boxes values

image

and then I clicked the button and the result showed that the code is working properly

image

Problem solved!

To download source code click here: Example source code

Filed under: Uncategorized No Comments
16Aug/071

Design patterns in real world use case scenarios – Composite (part 2)

To get a detail explanation of what this pattern stands for check out the Armen's blog - Composite where he posted detail article about pattern illustrated with one nice example

How this could get you a job

An usual question on job interviews could be "write a pseudo code for binary tree" (Family tree is the same tree as binary tree but not restricted to two child tree nodes as binary tree is)

I believe this is a very good interview question which would classify a developer knowledge  in next 4 categories:

a) Not able to solve the problem -

b) Able to solve it using plain old recursion structural methods

c) Uses OOP techniques such as defining separate properties for child nodes of the same type

d) Deliberate using of the composite pattern

I wouldn't hire a), would hire b) as junior, c) as senior, d) as possible tech lead

Problem - use case

"Write a code which would in a given binary tree find a desired tree node and write a search traversal path."

Why composite pattern?

If we would take a look at previous composite post Composite pattern - Control tree persistence, rule of thumb there is:

Usage of composite pattern is usually appropriate whenever there are hierarchical tree structures where all the tree nods are of the same type.

Well, sound like our case

Problem - solution example

Class Diagram of the solution

image

Tree node code example

Every node would have a NodeKey and Node Value properties. Every node would also have a collection property which would contain instances of his own type

Something like this:

    public class TreeNode

    {

        private readonly IList<TreeNode> _treeNodes = new List<TreeNode>();

        private string _nodeKey;

        private string _nodeValue;

 

        /// <summary>

        /// Initializes a new instance of the TreeNode class.

        /// </summary>

        /// <param name="nodeKey"></param>

        /// <param name="nodeValue"></param>

        public TreeNode(string nodeKey, string nodeValue)

        {

            _nodeKey = nodeKey;

            _nodeValue = nodeValue;

        }

 

        public IList<TreeNode> TreeNodes

        {

            get { return _treeNodes; }

        }

 

        /// <summary>

        ///

        /// </summary>

        public string NodeKey

        {

            get { return _nodeKey; }

            set { _nodeKey = value; }

        }

 

        public string NodeValue

        {

            get { return _nodeValue; }

            set { _nodeValue = value; }

        }

}

 

Required functionality implementation

Is very simple with the pattern set up like explained: TreeNode would define a method which would call the same method on all the children nodes contained in TreeNodes property.

Something like this:

        public TreeNode FindByKey(string searchNodeKey, ref string resultpath)

        {

            if (NodeKey == searchNodeKey)

                return this;

 

            foreach (TreeNode node in TreeNodes)

            {

                resultpath += " -> " + node._nodeKey;

                TreeNode result = node.FindByKey(searchNodeKey, ref resultpath);

                if (result != null)

                    return result;

            }

            return null;

        }


Testing the solution

Now when our little tree node is been written we have to test the solution.

Setting up the test tree

First we need to build a tree of nodes, something like this:

 

        private static TreeNode buildingTheTree()

        {

            TreeNode rootNode=new TreeNode("rootKey","rootValue");

           

            TreeNode firstlevelNode1 = new TreeNode("key1_1", "value1_1");

            TreeNode firstlevelNode2 = new TreeNode("key1_2", "value1_2");

            TreeNode secondLevellevelNode1 = new TreeNode("key2_1", "value2_1");

            TreeNode thirdLevellevelNode1 = new TreeNode("key3_1", "value3_1");

            TreeNode thirdLevellevelNode2 = new TreeNode("key3_2", "value3_2");

 

            secondLevellevelNode1.TreeNodes.Add(thirdLevellevelNode1);

            secondLevellevelNode1.TreeNodes.Add(thirdLevellevelNode2);

 

            firstlevelNode1.TreeNodes.Add(secondLevellevelNode1);

 

            rootNode.TreeNodes.Add(firstlevelNode1);

            rootNode.TreeNodes.Add(firstlevelNode2);

            return rootNode;

        }

As you can see from the code above we pick a test case where root node, has two child nodes and first child node has his own child which has two child nodes of it's own.

Diagram of the code above result could look like this:

image

Testing tree functionality

Our test would be to find nodes 3_2 and Node 2_1. The code using our tree node class to achieve this could be like this

 

    static void Main(string[] args)

        {

            TreeNode rootNode=buildingTheTree();

            TreeNode node;

            string resultPath;

                                        

            resultPath=String.Empty;

            node = rootNode.FindByKey("key3_2", ref resultPath);

            Console.WriteLine("nFound node key is:{0}, value is:{1}. n SearchPath:{2}",node.NodeKey, node.NodeValue, resultPath);

           

            resultPath=String.Empty;

            node = rootNode.FindByKey("key2_1",ref resultPath);

            Console.WriteLine("nFound node key is:{0}, value is:{1}. n SearchPath:{2}", node.NodeKey, node.NodeValue, resultPath);

 

            Console.WriteLine("nPress enter when you are done.");

            Console.ReadLine();

 

        }

The result

image

Problem solved!

To download source code click here: Example source code

Filed under: Uncategorized 1 Comment
11Aug/072

Try out Commerce Server 2007 for free without installing it

Installing of Commerce Server 2007 can be a painful thing (and it could take a lot of time), which is maybe a turn off thing in case of people wanting only to get a first glimpse of how Commerce Server powerful is or in case that you want to make a presentation about CS etc..


I plan to blog later about the fastest way of installing CS2007 (which would include tools, tips and shortcuts from Max Akbar and Wade Wegner) but for now I'll present you the way to try out the Commerce Server without installing it at all


The process is simple, there's no rocket science there but it works


Steps:


1. Navigate to Commerce Server Virtual Labs


2. Pick some of the labs (I'll pick for this example profile one)


3. Click Register Online


4. Log in with your Windows Live ID


5. Click Confirm


6. Click on "Click here to enter the Virtual Lab"


Lab ready to be started


7. In case you haven't installed before "Virtual Server VRM" ActiveX component you would see this screen


Click on Install


image


8. When ActiveX You would be installed you would see the Lab Loading screen


image


9. When loading would be complete there would be a Start Lab screen


image


10. Click on start Lab and you would have a Fully functional 90 minutes Virtual Machine in your Internet Explorer:


image


Technorati Tags:

Filed under: Uncategorized 2 Comments
11Aug/070

Using design patterns in real world applications | Altairis – kalendář akcí

To register:Using design patterns in real world applications | Altairis - kalendář akcí


August, 28th 18:00, Microsoft, I'll be having presentation on design patterns and their usage in some "real world examples"


Have you ever asking yourselves what really design patterns are, when to use them and when to run away from them? How composition can find you a good job? How stubbing can help you getting promoted? How laziness can save your project? How injection can be pleasant thing?
All those questions and maybe some more Nikola Malovic would try to answer for you on this session, so in case you care for a cup of architectural talk with some pattern biscuits, stop by.

Examples would still be simplified not to distract attention, but the examples wouldn't be the usual (boring) examples we see in the books


I'll be having only two hours so I pick a list of patterns of small complexity:


  • composite

  • service stub and poor man dependency injection

  • lazy load

  • dependency injection and service locator

I think that would fulfill  those two hours and more advanced patterns I plan to cover in some next upcoming sessions

...In case you care for a cup of architectural talk with some pattern biscuits, stop by.... :)

 


Filed under: Uncategorized No Comments
8Aug/070

Visual Studio Team System Code Name “Rosario”

My last blog post (Feature complete development) was about the fact that Microsoft started practicing the Agile methodology in main stream development project such Visual Studio is.


We are still trying out Visual Studio 2008 Beta 2 product and the next Version of Visual Studio code name "Rosario" is already available as an CTP release you can install and try


I dare anyone to tell me now that Agile is "just for teams up to 20 people", "not working in real world" etc


Visual Studio Team System Code Name "Rosario"


Technorati tags: , , ,

Filed under: Uncategorized No Comments
6Aug/070

Feature complete development

In a video cast I was watching today (about new things in VS 2008 Beta 2) I heard an unexpectedly interesting part related to the fact that Microsoft building the Visual Studio 2008 was using Agile methodology: sprints, iterations etc.


Scott Gu was speaking in favor about the experiences Microsoft faced while working on VS2008 comparing with standard waterfall process used in VS2005 development


Soma called that paradigm shift: a shift from "Code Complete" to the "Feature complete", which is really awesome description.


By Code Complete he describes typical waterfall methodology:



  1. developers writes the code and at the end we have code complete ,
  2. testers are testing that code then and at the end we are in test complete phase
  3. then goes test automation phase with the automation test complete

With a feature complete, we have now on place Agile principles where the development phase goes in parallel with strictly defined resulting artifacts and expectations at the end of every small iterations which is been then tested by QA people, while development of another feature starts..


Soma also mentioned an interesting concept of feature based branching model, which is another step away from standard waterfall release oriented branching model 


At the end of "Agile in MS" part of this video Soma spoke about the "Feature Crew", "Feature group" team organization Microsoft used in developing Visual Studio 2008 where for each feature they have 5-10 people consisted of developers, testers and project managers. That team is the smallest organizational unit of people working on one unit of work and they are responsible for the "feature  complete". If a member of feature crew leave the team it is the feature crew responsibility to figure out how to reorganize on micro level to make their "feature complete"


All this changes were causing first 4-6 months an "growing pain", because they had to learn how to work in this small teams but by the time they came to Milestone 3 in Orcas they learn the new way of organization and overall effect of that reorganization was very good and feature teams are now working very well.


 


I was really stunt hearing that the biggest bastion of waterfall methodology felt down and that MS finally realized that it is year 2007 and not 1997 :)


Check the video out at S. Somasegar (Soma) and Scott Guthrie on Orcas Beta 2: What's in it?


 


Filed under: Uncategorized No Comments
5Aug/077

Releasing the build

I've been investigating today different effects of some csc.exe (C# compiler) compiler switches and came up with the really interesting conclusion

CSC.exe

C# compiler compiler has two important switches I pick for my today's investigation:

  • optimize, with values -/ +
  • debug, with values   -/+/full/pdbonly (+ and full are the same setting)

When you create a new C# project in Visual Studio;

  • Debug configuration is set up to use: /optimize- /debug:full
  • Release configuration is set up to use /optimize+ /debug:pdbonly

(To see it for yourself check out Output window after starting the build in release and debug build)

What I tested

I pick four different scenarios for my little experiment:

  • /optimize- /debug:full (debug configuration of visual studio )
  • /optimize+ /debug:full (optimized code with complete debug info setting)
  • /optimize+ /debug:pdbonly (release configuration of visual studio)
  • /optimize+ (typical "release" build setting used while building manually - command prompt, Nant etc)

How did I test it

I was using in my tests very simple console application which only  purpose is to have a property (to check optimization) and to throw an exception (to check stack trace)

using System; 

namespace TestApp

{   

class Program   

{       

     static void Main(string[] args)       

     {           

         int i = 5 / Convert.ToInt32(Test);       

     }        

     private static string _test;        
    
public static string Test
       
    
{
           
       
get { return _test; }
           
       
set { _test = value; }
       
    
}
    

}

}

After every build I was:

  1. Checking out for IL code optimization using ILDASM.exe to check out if the property code has been inlined and that there are no NOP IL statement at the beginning )
  2. Checking if stack trace shows the line number
  3. Checking if debugger can be attached to process

Test 1: /optimize- /debug:full

This one was just done for warming up, because we all know what debug configuration in visual studio does

Command line: csc /t:exe /debug:full /optimize- program.cs

File data

TestApp.exe 4608 bytes

TestApp.pdb 13824 bytes

Optimization check

Test1_IL

As you can see there are 10 lines of code and IL_0000 contains NOP. Clearly, not optimized IL code

Debugger check

I succeed in attaching debugger to cp

Stack trace check

System.DivideByZeroException was unhandled
  Message="Attempted to divide by zero."
  Source="TestApp"
  StackTrace:
       at TestApp.Program.Main(String[] args) in D:DocumentsDocumentsBlog materialCSCTestAppTestAppProgram.cs:line 9
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

There is  line number data in stack trace, which is also expected

Test 2: /optimize+ /debug:full

File data

TestApp.exe 4096 bytes

TestApp.pdb 13824 bytes

Optimization check

Test4_IL

IL code is optimized

Stack Trace

System.DivideByZeroException was unhandled
  Message="Attempted to divide by zero."
  Source="TestApp"
  StackTrace:
       at TestApp.Program.Main(String[] args) in D:DocumentsDocumentsBlog materialCSCTestAppTestAppProgram.cs:line 9
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

So the stack trace shows line number.

Test 3: /optimize+ /debug:pdbonly

Command line: csc /t:exe /debug:pdbonly /optimize+ program.cs

File data

Program.exe  4096 bytes

Program.pdb 11776 bytes

Optimization check

Test2_IL

As we can see on the ILDASM screen shoot code is optimized (property is inlined and no NOP)

Stack trace

System.DivideByZeroException was unhandled
  Message="Attempted to divide by zero."
  Source="TestApp"
  StackTrace:
       at TestApp.Program.Main(String[] args) in D:DocumentsDocumentsBlog materialCSCTestAppTestAppProgram.cs:line 9
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

There is a line number in stack trace. Great!

Test 4: /optimize+ /debug-

Command line: csc /t:exe /debug:pdbonly /optimize+ program.cs

File data

Program.exe  3584 bytes

Program.pdb  N/A

Optimization check

Test3_IL

Results totally expected for the release build - optimized IL code

Stack trace

at TestApp.Program.Main(String[] args)

No stack trace information

Conclusions

Test result analysis

Test case 4 (release build with debug- switch produces the smallest program.exe: 3584 bytes)

Test 2 (debug:full) and Test 3 (debug:pdbobnly) with optimize+ produced optimized code but the assembly file size increased to 4096 bytes

The size increase comes from the additional assembly manifest declaration of the DebuggableAttribute; IL code is exactly the same in test cases cases 2,3,4.

DebuggableAttribute is initialized with OR values of DebuggingModes enumeration

[Flags]

public enum DebuggingModes

{

Default = 1,

DisableOptimizations = 0x100,

EnableEditAndContinue = 4,

IgnoreSymbolStoreSequencePoints = 2,

None = 0

}

If we would take a look at test cases 2 and 3 with ILDASM we would notice that both of them have in their manifests

debug: pdbonly

// --- The following custom attribute is added automatically, do not uncomment -------
//  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 02 00 00 00 00 00 )

debug:full

// --- The following custom attribute is added automatically, do not uncomment -------
//  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 03 00 00 00 00 00 )

Or if we would visualize the same initialized flag values by using Reflector

debug:pdbonly

dbgPdbOnly_Manifest

debug:full

dbgFull_Manifest

The difference between the test case 2 (full) and test case 3 (pdbonly) is that with full debug switch compiler initialize the Debuggable attribute with DebuggingModes.Default value.

 

According to the MSDN: DebuggableAttribute.DebuggingModes Enumeration:

DebuggingModes.Default value

"Instructs the just-in-time (JIT) compiler to use its default behavior, which includes enabling optimizations, disabling Edit and Continue support, and using symbol store sequence points if present."

DebuggingModes.IgnoreSymbolStoreSequencePoints

"Sequence points are used to indicate locations in the Microsoft intermediate language (MSIL) code that a debugger user will expect to be able to refer to uniquely, such as for setting a breakpoint. The JIT compiler ensures it does not compile the MSIL at two different sequence points into a single native instruction. By default, the JIT compiler examines the symbol store in the program database (PDB) file for a list of additional sequence points. However, loading the PDB file requires that the file be available and has a negative performance impact. In version 2.0, compilers can emit "implicit sequence points" in the MSIL code stream through the use of MSIL "nop" instructions. Such compilers should set the IgnoreSymbolStoreSequencePoints flag to notify the common language runtime to not load the PDB file."

According to  Rick Byers - DebuggingModes.IgnoreSymbolStoreSequencePoints this flag setting informs the compiler to use all available space in code (places where IL evaluation stack is empty, or on any "nop" instruction is generated) to store implicit sequence points (internal pointers to PDB locations) into the resulting assembly which results with performance boost of the release build.

Final conclusion on test cases

There is no significant differences between the test cases 2 (full) and 3 (pdbonly) from the performance perspective

How-To:Releasing the builds

Build all of your release builds with /optimize+ /debug:pdbonly switch.

1) Your IL code would be optimized, so no performance hit would occur

2) The stack class would get access to the line information, and make your release builds "debug like"

3) The visual studio IDE release configuration default setting is set to that value

4) I couldn't find any information on net that effects of emitting DebuggableAttributes to assembly manifest causes any significant performance in NET 2.0

Technorati tags: , , , , , , ,


Share this post :

Filed under: Uncategorized 7 Comments
2Aug/070

Design patterns in real world use case scenarios – Service stub

The second pattern I would be presenting in my mini series of the patterns in real world is one of the main patterns used in Test Driven Development (TDD).

Service stub - decoupled business logic

To get a very detail explanation of what this pattern stands for check out the blog post of the person who 'first documented' it, Martin Fofler P of EAA: Service stub .

Problem - use case

Let’s imagine we have:

- a SomeManager class which has a LoadSomething method which reads data from sql server and that

- OtherType class which has a method which uses the LoadSomething method to get data on which he would imply some business process

That example coded could look like this:

using System.Collections.Generic;

 

namespace TestProject1

{

    public class SomeManager

    {

        public static ICollection<string> LoadSomething()

        {

            List<string> result = new List<string>();

            // read data from sql server

            // result.Add(...);

            return result;

        }

    }

 

    public class OtherType

    {

        public void PopulateSomething()

        {

            ICollection<string> collection= SomeManager.LoadSomething();

            foreach (string s in collection)

            {

                // do something with s

            }

        }

    }

}

 

The problems in this approach are:

  • to test OtherType.PopulateSomething() method I would have to create data rows in some SQL database which would be then read in SomeManager.LoadSomething() and then processed in PopulateSomething() method (which is to be tested). Imagine now that test dependency chain couple levels deep and you would come to the testing nightmare scenario where tests are very, very complexed and inter dependable.
  • if SomeManager.LoadSomething() is been developed in paralel with OtherType.PopulateSomething() there is a possibility that SomeManager won't be finished on time when OtherType would need it to work on its functionality (e.g. DBAdmin's a re too busy to create tables and rows needed)

Summarized: very hard dependency between the types is very inflexible design approach.

Why service stub?

Service stub in short is a pattern where we instead talking to the full type instance we talk to the interface representation of the type and that is exactlly what we need: to talk with abstracted form of the DB  dependable type. If we refer the interface, ANY type implementing the interface could be used in our code. (Usually, this pattern goes together with some form of Dependency injection and service locator)

Rule of thumb

Use service stub if you have dependencies in your code to the parts of system which execution is expensive or dependable on some external information sources.

Problem solution example

Class diagram of the solution

SolutionDiagram

Diagram explanation

What are we testing? OtherType.PopulateSomething method. Not the SomeManager behavior (for which we would have have separate test).

Testing of PopulateSomething method means “test me the result of iteration for given set of data”

Knowing that, we could rewrite our starting example to extract the interface of the SomeManager type, like this

public interface ISomeManager

{

ICollection<string> LoadSomething();

}

 

And our manager would now just implement that interface on the same way it is implemented in starting example

 

public class SomeManager : ISomeManager

{

public ICollection<string> LoadSomething()

{

              List<string> result = new List<string>();

              // read data from sql server

              // result.Add(...);

              return result;

        }

}

 

Now when we have this done, we would alter the OtherType to contain the private field  of ISomeManager type , something like

 

public class OtherType

    {

        private readonly ISomeManager _someManager;

 

 

    }

 

Having this in place we can change the OtherType PopulateSomething method implementation to use the _someManager field instead of constructing the SomeManager instance, something like this:

        public void PopulateSomething()

        {

            ICollection<string> collection = _someManager.LoadSomething();

            foreach (string s in collection)

            {

                // do something with s

            }

        }

The code would compile , but we don't have any code which would set that interface field value to a new SomeManager instance. To keep things decoupled we have to keep the instantiation of SomeManager type outside of the OtherType and one of the ways to do that is to use Dependency Injection - constructor type pattern, by defining constructor which accepts argument of ISomeManager type, something like this

        public OtherType (ISomeManager someManager)

        {

            _someManager = someManager;

        }

With this on place, we have now code which does:"Inside of OtherType.PopulateSomething method use a instance field of ISomeManager type which value someone outside of the OtherType would set"

Usage

Now with this approach I can make for my test purposes a mock object (in this example I would use static mock but dynamic is possible (and preferable) too) 

 

    internal class MockSomeManager : ISomeManager

    {

        public ICollection<string> LoadSomething()

        {

            List<string> result = new List<string>();

            result.Add("1");

            result.Add("2");

            result.Add("3");

            return result;

        }

    }

 

So my test method would look something like

 

        [TestMethod]

        public void TestMethod1()

        {

            OtherType other=new OtherType(new MockSomeManager());

            other.PopulateSomething();

        }

 

Notice that I have constructed the type which implements the ISomeManager interface and pass it to the constructor of the OtherType to use.

One small gotcha of the service stub pattern

The possible downside of this approach could be the fact that with original implementation in real world OtherType usage (TestMethod1 in this example) I would encapsulate the internals how PopulateSomething works:

        [TestMethod]

        public void TestMethod1()

        {

            OtherType other=new OtherType();

            other.PopulateSomething();

        }

That is a valid point, we do want to get flexibility, but not to loose encapsulation. 

To override this obstacle we would use "Poor man dependency injection" technique which would in our example add a new default constructor

        public OtherManager():this(new SomeManager())

        {

        }

That's how even if the user would use the default (encapsulated) constructor the component would work on the way how it worked in original starting state and we would still have all the flexibility

Complete refactored code source

The from example now looks like:

public class OtherType

{

    private readonly ISomeManager _someManager;

 

    public OtherType(): this(new SomeManager())

    {

    }

 

    public OtherType(ISomeManager someManager)

    {

        _someManager = someManager;

    }

 

    public void PopulateSomething()

    {

        ICollection<string> collection = _someManager.LoadSomething();

        foreach (string s in collection)

        {

            // do something with s

        }

    }

}

Problem solved!

Filed under: Uncategorized No Comments