Friday 18 September 2009

.NET Remoting - Singleton SAO and CAO

Build a Remotable Type:

To build a remotable type, you just need to create a class which inherits from MarshalByRefObject.

SAO vs CAO:
  1. Client of SAO can call only the default constructor, whereas the client of CAO can call any custom constructor

...

Lease Time:

Lease time is the duration unto which object should remain in memory, preventing it from automatic garbage collection.

Singleton SAO would be garbage collected at the server if it remains inactive up to its default LEASE-BASE LIFETIME. Default time is 5 minutes for the first time and 2 minutes for the rest.

To change the default leave time:

public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
}
return lease;
}

Infinite Timeout:

leave.InitialLeaseTime = TimeSpan.Zero;

Sinlgeton SAO

Singleton SAO remotable type - Config file - HTTP channel:

Hosting in a console app:

public class Listener{
public static void Main(){
RemotingConfiguration.Configure("Listener.exe.config");
}
}

app.config settings:

mode="Singleton"
type="RemotableType, RemotableType"
objectUri="RemotableType.rem"
Console Client:

public class Client{

public static void Main(){
RemotingConfiguration.Configure("Client.exe.config");
RemotableType remoteObject = new RemotableType();
}
}

"new" keyword creates a proxy on the client and client will work with that proxy to call the server remotable type.

App.config file:

type="RemotableType, RemotableType"
 
Singleton SAO - Using code - TCP channel:

Server:

TcpChannel channel = New TcpChannel(8080);
ChannelServices.RegisterChannel(channel, False);
RemotingConfiguration.RegisterWellKnownServiceType(RemotableType, "RemotableTypeUri", WellKnownObjectMode.Singleton);

Client:

RemotableType remotableType= (RemotableType) Activator.GetObject (typeof(RemotableType), "tcp://computername:8080/RemotableTypeUri");


CAO

Client Application - CAO - Using code - TCP channel:

RemotableType remotableType= (RemotableType)Activator.CreateInstance (typeof(RemotableType), null, "tcp://computername:8080/RemotableTypeUri")

The second argument is null which means no parameter is passed to create the instance.

CAO - Using Code - TCP channel:

Server:

ChannelServices.RegisterChannel(new TcpChannel(8082));
RemotingConfiguration.RegisterActivatedServiceType(typeof(RemotableType));

Client:

ChannelServices.RegisterChannel(New TcpChannel());
RemotingConfiguration.RegisterActivatedClientType(GetType(RemotableType), "tcp://localhost:8082");

RemotableType remotableType = new RemotableType();


More Info:

Thursday 17 September 2009

.NET Technologies for Enterprise Application Architecture


How to make a decision when using and which technologies for your enterprise application architecture?

.NET 2.0

Web Services
  • Choose for web services if either one of the clients is not a .NET application, or if communication occurs over the internet.

.NET Remoting

  • Choose for .NET remoting if performance is the main issue.

  • When using .NET remoting you are restricted to using it over a LAN or on the same computer.

  • Also, .NET remoting has been superseded by WCF, so if you have any possibility to upgrade the machines to .NET 3.5, that would probably be a better solution.
Service Components
  • Choose for Serviced components if you require very specific functionalities such as object pooling, just-in-time activation, distributed transactions / CRM etc...
.NET 3.0 and above

WCF

WPF

Silverlight

WinForms

To be updated...

Wednesday 16 September 2009

WCF Weakness

WCF doesn't support the following requirement:

Bidirectional (Server <--> Client) + Stateful + .NET 2.0 Client App

Statefulness:
Whichever binding you use, you can achieve this by enabling the session for your WCF service.

Bidirectional:
Only when you use wsDualHttpBinding WCF supports Duplex Message Exchange Pattern. For this to work
  • Your client must use .NET 3.0 and above
  • You must enable Session so it's stateful as well
.NET 2.0 Client:
  • When you use basicHttpBinding, your client can be in .NET 2.0.
  • When you use webHttpBinding, your client can be in .NET 2.0 and call the WCF services using HttpWebRequest.

Alternative Option:
.NET Remoting supports all the above requirements.

My comments:

If you disagree with my conclusion, I would be happy to hear your thoughts about this.

Tuesday 15 September 2009

Martin Fowler Speak about Design Patterns


From my understanding, the main messages about his speak were:

  • First thing to say is that I loved his presentation for many good reasons such as sense of humor, etc.
  • He is currently writing a book about “Domain Specific Languages (DSL)”
  • He said: What I am good at is to discuss and explore ideas and solutions with others...I am not expert in everything...I gather ideas/solutions from my colleagues too...

Domain Specific Languages:

The main idea is:

Domain Representation (e.g. XML) –> Structural Display Representation –> Final Display Representation (e.g. HTML)

(When I get access to the pictures I will post here)

Learning Process:

  1. Novice

  2. Advanced Beginner

  3. Competent: A stage where you ask why and you understand whys. starting to understand patterns target this area.

  4. Proficient: A stage where you understand the principles behind things

  5. Expert: A stage where you start innovating

Pattern Definition:

A pattern is a solution to a problem in a context.

A pattern is not a Recipe, is not a Library and is not a Language.

Learning About Patterns:

  • Learn from experienced developers; those who have done it before. It saves time.

  • Learn from books such as Enterprise Application Architecture.

  • Patterns are cross platform; java, c#, etc

  • Know that each pattern can have many different variations depending on the context.

  • Some people learn from Concrete (code example) to Abstract (design pattern) and some from Abstract to Concrete.

Pattern Parts:

Each pattern has 3 main parts:

  1. Name: it's very important; it should be relevant, short and meaningful

  2. How: how to implement this pattern

  3. When/Why: understanding when and why you can use a particular pattern and when you shouldn't use them.

Support Understanding Patterns:

To support understanding each pattern:

  • Prompt: the picture + description + UML model

  • Example: to see examples how we can implement a pattern. Be variation-wise when looking at examples

Implementation of each pattern could have many variations depending on the context in which you would like to apply a certain pattern, so don’t rely on examples.

Avoid Unnecessary Complexity:

  • Projects fail despite the latest technology for lack of ordinary solutions.

  • Overusing patterns could be disastrous; unnecessary complexity

  • Know when + why + how

Don't be Perfectionist:

Know that what you do today is always inadequate to your knowledge in the future.

Continuous Refactoring:

It's a matter of paying the Interest (when you just develop, debug or maintain) or paying the Capital (when developing and refactoring).

Chunking System/Focus:

You can't spend all your life learning about all the books and patterns. Often the best approach is to chunk the knowledge; focus on the solution to your specific problem and quickly find the pattern you need.

Pioneer in Design Patterns

Christopher Alexander is thought to be pioneer in design patterns.


One of his books is The Timeless Way of Building.
"Each pattern is a three part rule, whih expresses a relationship between a certain context, a problem, and a solution."

Entity Framework - How to Insert a New Row Into a Table With/Without Loading Foreign Key Objects

Approach1: Retrieve foreign key objects from database

var newAudit = new Audit_UserReport();
newAudit.AccessedDate = DateTime.Now;
newAudit.Report = contextHelper.MIPortal.Report.First(report => report.ReportId == reportId);
newAudit.User = contextHelper.MIPortal.User.First(user => user.UserId == currentUserId);
contextHelper.MIPortal.AddToAudit_UserReport(newAudit);
contextHelper.MIPortal.SaveChanges();

Comments:
  • This approach makes extra calls to the database

Approach2: Use stored procedure

Create an insert stored procedure and just call that.

Comments:

  • In this way, you have to make changes to the stored procedure whenever you make any changes to the database table.

Approach3: Attach the foreign key objects

var role = new MIPortalModel.Role();
var defaultReport = new Report(){ReportId = 7, EntityKey = new EntityKey("MIPortalEntities.Report", "ReportId", 7)};
context.Attach(defaultReport);
role.DefaultReport = defaultReport;
context.AddToRole(role);
context.SaveChanges();

Comments

  • The silly thing is that you must attach to the context first before setting the DefaultReport in this case, otherwise it will throw an exception at run time

Approach4: Use EntityReference

var role = new MIPortalModel.Role();
role.DefaultReportReference = new EntityReference()
{EntityKey = new EntityKey("MIPortalEntities.Report", "ReportId", 7)};
context.AddToRole(role);
context.SaveChanges();

Comments:

  • This is the simplest and most efficient way maybe

Thursday 10 September 2009

Principles of Acheiving Testable Software Design

Goal: Testable Software Design

Challenge 1: Unit testing a method which is using a static method or property of another class

Problem example:
public class Utils
{
public static int Add(int a, int b)
{
return a + b;
}
}

public int UnitTestMe(int a, int b)
{
return UnitTestMe(Utils.Add(a, b));
}

Solution 1: Overload your system under test method

Add this:

public int UnitTestMe(int r)
{
return r;
}


Challenge 2: Unit testing a method which is using an instance method or property of another class

Problem example:

public class Utils
{
public int Add(int a, int b)
{
return a + b;
}
}

public int UnitTestMe(int a, int b)
{
var utils = new Utils();
return utils.Add(a, b);
}

Solution 1: Inject the dependency

1. Create an interface of your dependent class:

public interface IUtils
{
int Add(int a, int b);
}

2. Let your dependent class implement the new interface:

public class Utils: IUtils
{
public int Add(int a, int b)
{
return a + b;
}
}

3. Inject the dependency to the class that the UnitTestMe method exists

IUtils utils = new Utils();
public MyClass(IUtils utils)
{
this.utils = utils;
}

4. Change the UnitTestMe method to use the injected dependency

public int UnitTestMe(int a, int b)
{
return utils.Add(a,b);
}

Challenge 3: How to unit test a method that uses ConfigurationManager

Solution:
Wrap the ConfigurationManager; see this.


More:

Tuesday 8 September 2009

Design for Testability



      Challenges:
      • An object uses a static class e.g. using Util.GetProduct(id) inside Product class! - use instance class only.
      • An object uses (HAS) other objects; e.g. an Order object uses one or more OrderItem objects - use dependency injection.
      • Global state e.g. Singleton classes - use an IoC container.
      • An object uses a class from a third-party or another assembly to whose implementation we don't have access such as Order object uses ConfigurationManager - Use Adapter pattern.
      Design tips:
      • Avoid static classes. Create instance classes instead and use an IoC container, such as Unity, to access to that singleton instance.
      • Don't instantiate dependent classes inside another class; instead use constructor injection always.
      • Make sure that you have an interface for each class of your application to enable dependency injection using either constructor or property injection
      • If ClassA uses ClassB, who should instantiate ClassB? Allow ClassB instance to be injectable using the constructor using constructor injection.
      • Let your constructors do only assigning fields; don't call any methods in the constructor, etc.
      • Use an IoC container to manage how your objects and dependencies are instantiated.
      • If your class depends on runtime-determined parameters, use Abstract Factory pattern to create that class. Simply use an IoC container to instantiate that Factory class. Avoid using Initialize() methods in the class which has dependencies for 2 reasons: 1) developer can call it twice or not calling it. Using Abstract Factory makes sure that your class is initialized always properly.
      • If ClassA is using ClassB and ClassB is a singleton class, again you can still create an interface of ClassB and inject it to ClassA.
      • Avoid manual singleton classes. If you’d need a singleton, use the IoC Container and let it control the lifetime
      Questions:
      Should I be writing unit tests for Private Methods?
      There are 3 approaches you can take with private methods:
      1. No unit tests for private methods. Instead leaving them be tested when other public methods that use them are tested.
      2. Use Internal: write unit tests by making those members "internal" rather than "private". Configure the app so that the "InternalsVisibleTo" allows the unit testing project to access the internal members.
      3. Use reflection to write unit tests for the private members
      I'd use the combination of the above approaches usually depending on the scenario and whether I'd really want to test a private method or not.

      Resources:

      Friday 4 September 2009

      Understanding Performance Testing and Memory Profiling

      Most common types of Performance Testing are:
      • Performance Test
      • Load Test
      • Stress Test
      • Capacity Test
      Here, you can find a very rich pdf about Performance Testing on CodePlex.

      Tools:

      Performance/Memory Profilers:
      Monitoring Tools:

      Thursday 3 September 2009

      Understanding RhinoMocks better



      RhinoMocks is a unit testing tool and:

      • Introduction to RhinoMocks by StephenWalther here.
      • Official Site here.
      • RhinoMocks documentation here.
      • RhinoMocks on WikiBooks here.

      Features:

      • You can create a mock object from an interface or a non-static class
      • Set expectations on the called methods by using strongly typed mocks instead of strings unlike NMock

      Limitations:

      • RhinoMocks can't mock static and sealed methods and classes (If you have a static class, you must change it; an example is here.)
      • You can't mock a private interface.
      • You need to use Dependency Injection for all the dependencies of your class otherwise you can't mock the dependencies and you can't test your class. What this means is that you have to create an interface for every dependency of a class which you need to test.

      Tuesday 1 September 2009

      Learning F#

      Statements and Expressions in F# vs C#:

      Keywords and Constructors in F#:

      Learning the basics:

      Tuples and Currying in F#:

      Discriminated Unions in F#

      Pipelining in F#

      F# at Microsoft Research

      Learn F# from MSDN:

      Videos:

      Understanding Managed Extensibility Framework