Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
.NET Design Patterns

You're reading from   .NET Design Patterns Learn to Apply Patterns in daily development tasks under .NET Platform to take your productivity to new heights.

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781786466150
Length 314 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Praseed Pai Praseed Pai
Author Profile Icon Praseed Pai
Praseed Pai
Shine Xavier Shine Xavier
Author Profile Icon Shine Xavier
Shine Xavier
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. An Introduction to Patterns and Pattern Catalogs FREE CHAPTER 2. Why We Need Design Patterns? 3. A Logging Library 4. Targeting Multiple Databases 5. Producing Tabular Reports 6. Plotting Mathematical Expressions 7. Patterns in the .NET Base Class Library 8. Concurrent and Parallel Programming under .NET 9. Functional Programming Techniques for Better State Management 10. Pattern Implementation Using Object/Functional Programming 11. What is Reactive Programming? 12. Reactive Programming Using .NET Rx Extensions 13. Reactive Programming Using RxJS 14. A Road Ahead

The C# language and the .NET platform

Microsoft (MS) initially placed their bets on an enterprise architecture strategy called Windows DNA, centered on the Distributed Component Object Model (DCOM). The advent and traction of the Java programming model forced Microsoft to rework their strategy, so they decided to create a virtual machine platform called .NET. The .NET platform was released in 2002, and it was monikered Microsoft's Java. The old adage imitation is the sincerest form of flattery was echoed by industry pundits. Web development is done using the ASP.Net Web Forms programming model, and desktop development is based on Windows forms. They also created a new language for the new platform, named C#. For platform interoperability, they created .NET remoting architecture, which became the gateway for communication between homogeneous systems (including CLR-managed and unmanaged) via TCP and DCOM protocols. For communication with heterogeneous systems, open standards such as SOAP and WSDL were leveraged by remoting objects, either self-hosted or hosted, within an IIS context.

In 2003, Microsoft released .NET v1.1, which fixed many of the bugs in .NET v1.0. The release of Microsoft .NET 1.1 encouraged people to bet their future on this platform. There was no application server in its offering. This led to some delay in the adoption of the platform. A code snippet in C#, which computes the average of a series of numbers through the command line, is shown as follows:

    // Chap1_01.cs 
    using System; 
    using System.Collections; 
    class Temp 
    { 
      public static void Main(String [] args) { 
      //---- accumulate command line arguments to  
      //---- to a list 
      ArrayList a = new ArrayList(); 
      for(int i=0; i< args.Length; ++i) 
        a.Add(Convert.ToDouble(args[i])); 
      //----- aggregate value to a variable (sum) 
      double sum = 0.0; 
      foreach(double at in a) 
        sum = sum + at; 
      //------------ Compute the Average 
      double ar = sum/a.Count; 
      //------------ Spit value to the console 
      //------------ Wait for a Key  
      Console.WriteLine(ar); 
      Console.Read(); 
    } 
  } 

In 2005, Microsoft added a lot of features to their platform, which included generics and anonymous delegates. With C# 2.0, we can rewrite the average computation program by using generics and anonymous delegates as follows:

    // -- Chap1_02.cs 
    using System; 
    using System.Collections; 
    using System.Collections.Generic;public delegate double    
    Del(List<double> pa); 
    class Temp 
    { 
      public static void Main(String [] args) { 
      //----- Use a Generic List (List<T> ) 
      //----- to accumulate command line arguemnts 
      List<double> a = new List<double>(); 
      for(int i=0; i< args.Length ; ++ i ) 
      a.Add(Convert.ToDouble(args[i])); 
      //--- Define a anonymous delegate and assign 
      //--- to the variable temp 
      //--- The delegate aggregates value and  
      //--- compute average 
      Del temp = delegate(List<double> pa ) { 
        double sum = 0.0; 
        foreach( double at in pa ) 
          sum = sum + at; 
        return sum/pa.Count; 
      }; 
      //---- invoke the delegate 
      //---- and wait for the key 
      Console.WriteLine(temp(a)); 
      Console.Read(); 
     } 
   } 

The release of .NET platform 3.0 overcame the shortcomings of the previous releases by introducing WCF, WPF, and Windows Workflow Foundation (WF), which coincided with the release of the Vista platform.

Microsoft released version 3.5 of the platform with some key features including LINQ, lambda, and anonymous types. They also released the C# 3.0 programming language. Using type inference and lambda expressions, the average computation program is rewritten as follows:

    //--- Chap1_03.cs 
    using System; 
    using System.Collections; 
    using System.Collections.Generic; 
    using System.Linq; 
    class Temp { 
      public static void Main(String [] args) { 
      //---- leverage type inference feature to assign 
      //---- a List<T> and accumulate values to that list 
      var a = new List<double>(); 
      for(int i=0; i< args.Length ; ++ i ) 
        a.Add(Convert.ToDouble(args[i])); 
      //----- Define a Lambda function which passes 
      //----- through the value.  
      Func<double,double> ar2 = (x => x );

      //------ use the Sum function available with List<T> 
 
      //------ to compute the average 
      var ar = a.Sum(ar2 )/a.Count; 
      //------ Spit the value to the console 
      Console.WriteLine(ar); 
      Console.Read(); 
    } 
  } 

With Visual Studio 2010, Microsoft released C# 4.0 with support for dynamic programming. The following code snippet demonstrates dynamic typing (based on DynamicObject) and ExpandoObjects. The following code snippet shows how one can create a custom object that can add arbitrary properties and methods:

    // Chap1_04.cs 
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Dynamic; 
 
    namespace TestVS 
    { 
      class DynamicClass : DynamicObject 
    { 
      //---- underlying container for storing  
      //---- Ibject memebers 
      private Dictionary<string, Object> props = 
      new Dictionary<string, object>(); 
 
      public DynamicClass() { } 
 
      //------- Retrieve value from a member 
      public override bool TryGetMember(GetMemberBinder binder,  
      out object result){ 
        string name = binder.Name.ToLower(); 
        return props.TryGetValue(name, out result); 
      } 
      public override bool TrySetMember(SetMemberBinder binder, 
      object value){ 
        props[binder.Name.ToLower()] = value; 
        return true; 
      } 
    } 
 
    class Program{ 
      static void Main(string[] args){ 
        dynamic dc = new DynamicClass(); 
        //--------- Adding a property 
        dc.hell = 10; 
        //--------read back the property... 
        Console.WriteLine(dc.hell); 
        //------- Creating an Action delegate... 
        Action<int> ts = new Action<int>( delegate(int i ) { 
          Console.WriteLine(i.ToString()); 
        }); 
        //------------Adding a method.... 
        dc.rs = ts; 
        //----------- invoking a method.... 
        dc.rs(100); 
        Console.Read(); 
      } 
    } 
  } 

The following code snippet shows how one can use ExpandoObject to add a property to a type we created. We will be leveraging the dynamic feature of C# 4.0:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Dynamic;  
 
    namespace TestVS 
    { 
      class Program 
    { 
      static void Main(string[] args){ 
        dynamic ds = new ExpandoObject();
      //---- Adding a property 
        ds.val = 20; 
        Console.WriteLine(ds.val); 
        //---- Assign a new value to the "val" property 
        //-----This is possible because of dynamic typing  
        ds.val = "Hello World..."; 
        Console.WriteLine(ds.val); 
        //---------------- Wait for the Keyboard input 
        Console.Read(); 
      } 
    } 
  } 

In 2012, Microsoft released version 5.0 of the C# programming language, which incorporated a declarative concurrency model based on the async/await paradigm. The following C# code demonstrates the usage of async/await:

    //-- Chap1_05.cs 
    using System; 
    using System.IO; 
    using System.Threading.Tasks; 
 
    class Program 
    { 
      static void Main() { 
        //--- Create a Task to Start processing 
        Task task = new Task(ProcessCountAsync); 
        task.Start();
    task.Wait(); 
        Console.ReadLine(); 
      } 
 
    static async void ProcessCountAsync() 
    { 
      // Start the HandleFile method. 
      Task<int> task = HandleFileAsync(@".\WordCount.txt"); 
      // 
      // -------- One can do some lengthy processing here 
      //  
      int x = await task; 
      Console.WriteLine("Count: " + x); 
    } 
 
    static async Task<int> HandleFileAsync(string file) 
    { 
      int count = 0; 
      using (StreamReader reader = new StreamReader(file)) 
      { 
        string v = await reader.ReadToEndAsync(); 
        count += v.Length; 
      } 
      return count; 
    } 
  } 

With Visual Studio 2015, Microsoft released C# 6.0, which mostly contains cosmetic changes to the language. Additionally, C# 7.0 does not add many features to the language. The .NET Core released by Microsoft runs on Windows GNU Linux and MAC OS X, promises to make C# a multiplatform/cross platform language. The acquisition of Xamarin has helped Microsoft to foray into cross-platform, native code-based mobile development.

You have been reading a chapter from
.NET Design Patterns
Published in: Jan 2017
Publisher: Packt
ISBN-13: 9781786466150
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image