Gang of Four (GOF) Design Patterns in .NET

source article: http://www.dotnet-tricks.com/Tutorial/designpatterns/NTEH250513-Gang-of-Four-(GOF)-Design-Patterns-in-.Net-.html

  1. Creational Design Patterns

    1. Factory Method : Create instances of derived classes
    2. Abstract Factory : Create instances of several classes belonging to different families
    3. Builder : Separates an object construction from its representation
    4. Prototype : Create a duplicate object or clone of the object
    5. Singleton : Ensures that a class can has only one instance
  2. Structural Design Patterns

    1. Adapter : Match interfaces of different classes
    2. Bridge : Separates an object’s abstraction from its implementation
    3. Composite : A tree structure of simple and composite objects
    4. Decorator : Add responsibilities to objects dynamically
    5. Façade : A single class that represents an entire complex system
    6. Flyweight : Minimize memory usage by sharing as much data as possible with similar objects
    7. Proxy : Provides a surrogate object, which references to other object
  3. Behavioral Design Patterns

    1. Chain of Responsibility
    2. Command
    3. Interpreter
    4. Iterator
    5. Mediator
    6. Memento
    7. Observer
    8. State
    9. Strategy
    10. Visitor
    11. Template Method

Singleton Design Pattern – C#

source article: http://www.dotnet-tricks.com/Tutorial/designpatterns/L2KL080613-Singleton-Design-Pattern—C#.html

 

  1. //eager initialization of singleton
  2. public class Singleton
  3. {
  4.   private static Singleton instance =  new Singleton();
  5.   private Singleton() { }
  6.   public static Singleton GetInstance
  7.   {
  8.      get { return instance; }
  9.    }
  10.  }
  11. }
  12. //lazy initialization of singleton
  13. public class Singleton
  14. {
  15.   private static Singleton instance = null;
  16.   private Singleton() { }
  17.   public static Singleton GetInstance
  18.   {
  19.      get
  20.      {
  21.          if (instance == null)
  22.              instance = new Singleton();
  23.          return instance;
  24.        }
  25.    }
  26. }
  27.  
  28. //Thread-safe (Double-checked Locking) initialization of singleton
  29. public class Singleton
  30. {
  31.    private static Singleton instance = null;
  32.    private Singleton() { }
  33.    private static object lockThis = new object();
  34.    public static Singleton GetInstance
  35.   {
  36.     get
  37.     {
  38.         lock (lockThis)
  39.         {
  40.             if (instance == null)
  41.                 instance = new Singleton();
  42.             return instance;
  43.         }
  44.     }
  45.   }
  46. }

How to put Multiple Markers in Google Map in MVC 4

source article: http://blog.myitside.com/post/2012/01/20/How-to-use-Google-Maps-with-multiple-markers-in-ASPNET-MVC-3.aspx

* In my Controller, 
  public ActionResult Map()
  {
    IEnumerable<Place> places = getAllPlaces();
    return View(places);
  }  

* In Map.cshtml razor view, 

@model IEnumerable<Place>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/src/markermanager.js"></script>

<script language="javascript" type="text/javascript">
   var map;    
   var mgr;    
   function initialize() {
        var myOptions = {
            zoom: 2,
            center: new google.maps.LatLng(0, 0),
            mapTypeId: google.maps.MapTypeId.HYBRID
        };
        map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
        mgr = new MarkerManager(map);
        var infoWindow = new google.maps.InfoWindow({ content: "contents" });
        google.maps.event.addListener(mgr, 'loaded', function () {
            @foreach (var place in Model) {
                <text>
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(@place.Latitude, @place.Longitude),
                    html: "@place.Link"
                });

                google.maps.event.addListener(marker, "click", function () {
				    infoWindow.setContent(this.html);
				    infoWindow.open(map, this);
			    });

                mgr.addMarker(marker, 0);
                </text>
            }
            mgr.refresh();
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="googleMap"></div>

Memory Management in .NET

(1) source article from MSDN : Garbage Collector Basics and Performance Hints

Conclusion

“The .NET garbage collector provides a high-speed allocation service with good use of memory and no long-term fragmentation problems, however it is possible to do things that will give you much less than optimal performance.

To get the best out of the allocator you should consider practices such as the following:

  • Allocate all of the memory (or as much as possible) to be used with a given data structure at the same time.
  • Remove temporary allocations that can be avoided with little penalty in complexity.
  • Minimize the number of times object pointers get written, especially those writes made to older objects.
  • Reduce the density of pointers in your data structures.
  • Make limited use of finalizers, and then only on “leaf” objects, as much as possible. Break objects if necessary to help with this.”

(2) source article : Memory Management Misconceptions

1. A garbage collector collects garbage
2. Doing lots of gen0 collections is bad
3. Performance counters are great for understanding what is happening
4. .NET doesn’t leak memory
5. All objects are treated the same

I believe they are highly recommended well-written articles. Enjoy! 🙂

dynamic variable in C#

from MSDN page- Using Type dynamic (C# Programming Guide),

” a new type, dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation. Therefore, you do not have to be concerned about whether the object gets its value from a COM API, from a dynamic language such as IronPython, from the HTML Document Object Model (DOM), from reflection, or from somewhere else in the program. However, if the code is not valid, errors are caught at run time.”

examples – dynamic (C# Reference)

DynamicObject – Walkthrough: Creating and Using Dynamic Objects (C# and Visual Basic)

Hope this helps! 🙂

Covariance and Contravariance in Generics

source: Covariance and Contravariance in Generics

Covariant type parameters

The following example illustrates covariant type parameters. The example defines two types: Base has a static method named PrintBases that takes anIEnumerable<Base> (IEnumerable(Of Base) in Visual Basic) and prints the elements. Derived inherits from Base. The example creates an emptyList<Derived> (List(Of Derived) in Visual Basic) and demonstrates that this type can be passed to PrintBases and assigned to a variable of typeIEnumerable<Base> without casting. List implements IEnumerable, which has a single covariant type parameter. The covariant type parameter is the reason why an instance of IEnumerable<Derived> can be used instead of IEnumerable<Base>.

using System;
using System.Collections.Generic;

class Base
{
    public static void PrintBases(IEnumerable<Base> bases)
    {
        foreach(Base b in bases)
        {
            Console.WriteLine(b);
        }
    }
}

class Derived : Base
{
    public static void Main()
    {
        List<Derived> dlist = new List<Derived>();

        Derived.PrintBases(dlist);
        IEnumerable<Base> bIEnum = dlist;
    }
}

Contravariant type parameters

The following example illustrates contravariant type parameters. The example defines an abstract (MustInherit in Visual Basic) Shape class with an Areaproperty. The example also defines a ShapeAreaComparer class that implements IComparer<Shape> (IComparer(Of Shape) in Visual Basic). The implementation of the IComparerCompare method is based on the value of the Area property, so ShapeAreaComparer can be used to sort Shapeobjects by area.

The Circle class inherits Shape and overrides Area. The example creates a SortedSet of Circle objects, using a constructor that takes anIComparer<Circle> (IComparer(Of Circle) in Visual Basic). However, instead of passing an IComparer<Circle>, the example passes aShapeAreaComparer object, which implements IComparer<Shape>. The example can pass a comparer of a less derived type (Shape) when the code calls for a comparer of a more derived type (Circle), because the type parameter of the IComparer generic interface is contravariant.

When a new Circle object is added to the SortedSet<Circle>, the IComparer<Shape>.Compare method (IComparer(Of Shape).Comparemethod in Visual Basic) of the ShapeAreaComparer object is called each time the new element is compared to an existing element. The parameter type of the method (Shape) is less derived than the type that is being passed (Circle), so the call is type safe. Contravariance enables ShapeAreaComparerto sort a collection of any single type, as well as a mixed collection of types, that derive from Shape.

using System;
using System.Collections.Generic;

abstract class Shape
{
    public virtual double Area { get { return 0; }}
}

class Circle : Shape
{
    private double r;
    public Circle(double radius) { r = radius; }
    public double Radius { get { return r; }}
    public override double Area { get { return Math.PI * r * r; }}
}

class ShapeAreaComparer : System.Collections.Generic.IComparer<Shape>
{
    int IComparer<Shape>.Compare(Shape a, Shape b) 
    { 
        if (a == null) return b == null ? 0 : -1;
        return b == null ? 1 : a.Area.CompareTo(b.Area);
    }
}

class Program
{
    static void Main()
    {
        // You can pass ShapeAreaComparer, which implements IComparer<Shape>, 
        // even though the constructor for SortedSet<Circle> expects  
        // IComparer<Circle>, because type parameter T of IComparer<T> is 
        // contravariant.
        SortedSet<Circle> circlesByArea = 
            new SortedSet<Circle>(new ShapeAreaComparer()) 
                { new Circle(7.2), new Circle(100), null, new Circle(.01) };

        foreach (Circle c in circlesByArea)
        {
            Console.WriteLine(c == null ? "null" : "Circle with area " + c.Area);
        }
    }
}

/* This code example produces the following output:

null
Circle with area 0.000314159265358979
Circle with area 162.860163162095
Circle with area 31415.9265358979
 */