Search This Blog

Saturday, June 29, 2013

Observer Design Pattern

         Definition in Wikipedia:
"The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar Model View Controller (MVC) architectural pattern. In fact the observer pattern was first implemented in Smalltalk's MVC based user interface framework. The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits."
          In www.dofactory.com the Observer Design Pattern is the  this:
          

In terms of the .NET Framework the terminology is a bit difference:
The abstract class Observer is replaced by the IObserver  interface.
The  abstract class Subject is replaced by the IObservable  interface.
The class ConcreteSubject usually is called Observable.
The function Attach is replaced by the function Register.
The function Dettach is replaced by the function Unregister
Also under the term  container we mean some generic type collection in which we can have the observers.

Wednesday, June 26, 2013

Boxing and Unboxing

"Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit."
          During the process of unboxing two types of exception can be  appeared:

  •  NullReferenceException ( if you try to unbox null object)
  • InvalidCastException ( if you try to unbox to to an incompatible value type )

        // Boxing
                     int k = 2;
            // The following line boxes i.  
            object o = k;   
       // Unboxing
                     int j = (int) o; // that creates InvalidCastException: int j = (short) o;

Events

Events is something like to interrupts in hardware design.There is and here -behind of the scenes- the main endless loop(listener) .Generally speaking  many of modern Operating Systems support the event driven programming.
There are two approaches to implement events in .NET. The first one by using delegate keyword and the second by using EventHandler keyword
We will start with the first approach:
This approach is used when we want to pass the event's source object as parameter(sender)..
Example: ((EventDelegate ) sender).Add("one","Greg")
We have three classes.:EventDelegate ,Listener and Test Class.

Tuesday, June 25, 2013

polymorfism in ANSI C

The key point here is to create Virtual Tables (xxx_vtables) in which you can have the chance to use pointer to function 
"const char* (*sound)();"


#include 

struct animal_vtable {
    const char* (*sound)();
};

struct animal {
    struct animal_vtable methods;
    const char* name;
};

const char* cat_sound() {
    return "meow!";
}

const char* dog_sound() {
    return "bark!";
}

void describe(struct animal *a) {
    printf("%s makes \"%s\" sound.\n", a->name, a->methods.sound());
}

struct animal cat = {{&cat_sound}, "cat"};
struct animal dog = {{&dog_sound}, "dog"};

int main() {
    describe(&cat);
    describe(&dog);

    return 0;
}
}

Delegates

Delegates in terms of C language is  pointer to function.
Firstly I will try to explain what does this mean.

Pointer to Function
 In the following example we define one  function pointer named pt2Function.
This point to function, which take three int parameters and return an int
// define a function pointer and initialize to NULL
int (*pt2Function)(int, int, int) = NULL;  
// assign an address to the function pointer
int Fun1  (int a, int b, int c){    return a+b+c; }
int Fun2 (int a, int b, int  c)const{ return a-b+c; }
pt2Function = &Fun1;    // correct assignment using address operator
if(pt2Function >0){                           // check if initialized
   if(pt2Function == &Fun1)
      printf("Pointer points to Fun1\n"); }
else
   printf("Pointer not initialized!!\n");
// calling a function using a function pointer
int result = (*pt2Function) (12, 3, 5);  
Now  we will see :How to Pass a Function Pointer as an Argument
//  How to Pass a Function Pointer
//  is a pointer to a function which returns an int and takes three int
void PassPtr(int (*pt2Func)(int, int, int))
{
   int result = (*pt2Func)(12, 3, 6);     // call using function pointer
  
}
 and in some other point we execute this function
.....
PassPtr(&Fun1);
.....
and at the end we will see:How to Return a Function Pointer as function's return value
//  How to Return a Function Pointer
int (*GetPtr1(int f1))(int, int,int)
{
   if(f1==0)
      return &Fun2;
   else
      return &Fun1;
}
and in some other point inside of some function
// define a function pointer and initialize it to NULL
   int (*pt2Function)(int, int, int) = NULL;
pt2Function=GetPtr1(1);   // get function pointer from function 'GetPtr1'
int result = (*pt2Function) (12, 3, 5);    // call function using the pointer
Now we can go on with delegates.
Delegates
Generally speaking we can divide delegates in two types:Simple and multicast delegate.

Monday, June 24, 2013

Wrapper class




/// Example for Wrapper class
Structural design patterns 
Proxy, Decorator, and Adapter also use thiw approach.
see more...


public class WrapperExample
{
    private int x = 20;
    private int y = 10;

   
    public WrapperExample()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public int mul(int x, int y)
    {
        Wrapper.internalClass obj = new internalClass();
        //core functionality of this method is written in the wrapped class.
        int res = obj.mul(x, y);
        return sum;
    }

    ///
    /// this class is wrapped by the WrapperExample class.
    /// we can access only inside this class.
    /// outside the class, we cant access this class.
    ///
    private class internalClass
    {       

        public int mul(int x, int y)
        {
          
            return x * y;
        }
    }
}
 

IHttpHandlerFactory and Abstarct Factory Design Pattern

http://www.dofactory.com/Patterns/PatternAbstract.aspx


In terms of Abstract Factory design pattern, the IHTTPHandlerFactory forms the abstract factory,
the IHTTPHandler forms the abstract product, the PageHandlerFactory forms the concrete factory and the Page class forms the concrete Product. 

IHTTPHandlerFactory<->Abstract Factory
IHTTPHandler<->abstract produc
pagehandlerfactory<->concrete factory (1 or more)
Page Class<->concrete Product.  (1 or more)

HTTPRuntime,HTTPApplication,HTTPContext.HTTPHandler,HTTPModule....

   I extract from the following exelent article
    http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp
"From Browser to ASP.NET
Let’s start at the beginning of the lifetime of a typical ASP.NET Web Request. A request starts on the browser where the user types in a URL, clicks on a hyperlink or submits an HTML form (a POST request). Or a client application might make call against an ASP.NET based Web Service, which is also serviced by ASP.NET. On the server side the Web Server – Internet Information Server 5 or 6 – picks up the request. At the lowest level ASP.NET interfaces with IIS through an ISAPI extension. With ASP.NET this request usually is routed to a page with an .aspx extension, but how the process works depends entirely on the implementation of the HTTP Handler that is set up to handle the specified extension. In IIS .aspx is mapped through an ‘Application Extension’ (aka. as a script map) that is mapped to the ASP.NET ISAPI dll - aspnet_isapi.dll. Every request that fires ASP.NET must go through an extension that is registered and points at aspnet_isapi.dll.
 Depending on the extension ASP.NET routes the request to an appropriate handler that is responsible for picking up requests. For example, the .asmx extension for Web Services routes requests not to a page on disk but a specially attributed class that identifies it as a Web Service implementation. Many other handlers are installed with ASP.NET and you can also define your own. All of these HttpHandlers are mapped to point at the ASP.NET  ISAPI extension in IIS, and configured in web.config to get routed to a specific HTTP Handler implementation. Each handler, is a .NET class that handles a specific extension which can range from simple Hello World behavior with a couple of lines of code, to very complex handlers like the ASP.NET Page or Web Service implementations. For now, just understand that an extension is the basic mapping mechanism that ASP.NET uses to receive a request from ISAPI and then route it to a specific handler that processes the request.
 
The ISAPI Connection
ISAPI is a low level unmanged Win32 API. The interfaces defined by the ISAPI spec are very simplistic and optimized for performance. They are very low level – dealing with raw pointers and function pointer tables for callbacks - but they provide he lowest and most performance oriented interface that developers and tool vendors can use to hook into IIS. Because ISAPI is very low level it’s not well suited for building application level code, and ISAPI tends to be used primarily as a bridge interface to provide Application Server type functionality to higher level tools. For example, ASP and ASP.NET both are layered on top of ISAPI as is Cold Fusion, most Perl, PHP and JSP implementations running on IIS as well as many third party solutions such as my own Web Connection framework for Visual FoxPro. ISAPI is an excellent tool to provide the high performance plumbing interface to higher level applications, which can then abstract the information that ISAPI provides. In ASP and ASP.NET, the engines abstract the information provided by the ISAPI interface in the form of objects like Request and Response that read their content out of the ISAPI request information. Think of ISAPI as the plumbing. For ASP.NET the ISAPI dllis very lean and acts merely as a routing mechanism to pipe the inbound request into the ASP.NET runtime. All the heavy lifting and processing, and even the request thread management happens inside of the ASP.NET engine and your code.
 
As a protocol ISAPI supports both ISAPI extensions and ISAPI Filters. Extensions are a request handling interface and provide the logic to handle input and output with the Web Server – it’s essentially a transaction interface. ASP and ASP.NET are implemented as ISAPI extensions. ISAPI filters are hook interfaces that allow the ability to look at EVERY request that comes into IIS and to modify the content or change the behavior of functionalities like Authentication. Incidentally ASP.NET maps ISAPI-like functionality via two concepts: Http Handlers (extensions) and Http Modules (filters). "
Aw we can see in the following article Introduction to HTTP Handlers and Modules HTTP handlers and modules can be defined as
"HTTP handlers proces the request and are generally responsible for initiating necessary business logic tied to the request. "
"The following consists of a list of events that should be considered when implementing your HTTPmodule:
  • BeginRequest
  • AuthenticateRequest
  • AuthorizeRequest
  • ResolveRequestCache
  • AcquireRequestState
  • PreRequestHandlerExecute
  • PostRequestHandlerExecute
  • ReleaseRequestState
  • UpdateRequestCache
  • EndRequest
  • PreSendRequestHeaders*
  • PreSendRequestContent*
  • Error*
"

Also

Asynchronous and Synchronous HTTP Handlers

An HTTP handler can be either synchronous or asynchronous. A synchronous handler does not return until it finishes processing the HTTP request for which it is called. An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.
Asynchronous HTTP handlers enable you to start an external process, such as a method call to a remote server. The handler can then continue processing without waiting for the external process to finish. While an asynchronous HTTP handler is processing, ASP.NET puts the thread that would ordinarily be used for the external process back into the thread pool until the handler receives a callback from the external process. This can prevent thread blocking and can improve performance because only a limited number of threads can execute at the same time. If many users request synchronous HTTP handlers that rely on external processes, the operating system can run out of threads, because many threads are blocked and are waiting for an external process.
When you create an asynchronous handler, you must implement the IHttpAsyncHandler interface. You must also implement the BeginProcessRequestmethod in order to initiate an asynchronous call that processes individual HTTP requests. In addition, you must implement the EndProcessRequest method to run cleanup code when the process ends.

Saturday, June 22, 2013

Turing Machine

FSM

File:DFA example multiplies of 3.svg

Turing Machine

addone
TM simulator

Types of JIT Compilers

There are the following three types of JIT Compilers in Microsoft .Net Framework


1) Pre-JIT: Pre-JIT Compiler compiles the whole source code into native code in a single cycle, done at the time of deployment of the application itself.

2) Econo-JIT: Econo-JIT Compiler compiles only specific methods that are called at runtime. These compiled methods are removed once their processing is finished and not required in further execution.

3) Normal-JIT: - Normal-JIT Compiler compiles only specific methods that are called at runtime. These methods are compiled once and are stored in the cache. When the same methods are called again, the compiled code from cache will be used for execution.

See How the CLR Creates Runtime Objects

Before the CLR executes the first line of the managed code, it creates three application domains. Two of these are opaque from within the managed code and are not even visible to CLR hosts. They can only be created through the CLR bootstrapping process facilitated by the shim—mscoree.dll and mscorwks.dll (or mscorsvr.dll for multiprocessor systems). 

See more....

null in C#

From Microsoft MDSN:
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null. However, C# 2.0 introduced nullable value types. See Nullable Types (C# Programming Guide).
.............

There are three things in C# that "null" can be. A reference, a pointer, and a nullable type.

  • The implementation of C# on the CLR represents a null reference by zero bits
  • The a null pointer is represented also by  zero bits
  •  A null nullable value type is also implemented by zeroes, though in a different way. When you say
int? j = null;
what we actually create is the moral equivalent of:
struct NullableInt
{
    int value;
    bool hasValue;
}


The following example demonstrates use of nullable data types:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
      static void Main(string[] args)
      {
         int? num1 = null;
         int? num2 = 45;
         double? num3 = new double?();
         double? num4 = 3.14157;
         
         bool? boolval = new bool?();

         // display the values
         
         Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", 
                            num1, num2, num3, num4);
         Console.WriteLine("A Nullable boolean value: {0}", boolval);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Nullables at Show: , 45,  , 3.14157
A Nullable boolean value:            


The Null Coalescing Operator (??)

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable( or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this:
using System;
namespace CalculatorApplication
{
   class NullablesAtShow
   {
         
      static void Main(string[] args)
      {
         
         double? num1 = null;
         double? num2 = 3.14157;
         double num3;
         num3 = num1 ?? 5.34;      
         Console.WriteLine(" Value of num3: {0}", num3);
         num3 = num2 ?? 5.34;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();

      }
   }
}
When the above code is compiled and executed, it produces following result:
Value of num3: 5.34
Value of num3: 3.14157

DBNull

DBNull.Value is what the .NET Database providers return to represent a null entry in the database. DBNull.Value is not null and comparissons to null for column values retrieved from a database row will not work, you should always compare to DBNull.Value.

DBNull Class

C# bitwise oerators

OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -60 which is 1100 0011
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

example

Try following example to understand all the bitwise operators available in C#:
using System;
namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 60;            /* 60 = 0011 1100 */  
            int b = 13;            /* 13 = 0000 1101 */
            int c = 0;           

             c = a & b;           /* 12 = 0000 1100 */ 
             Console.WriteLine("Line 1 - Value of c is {0}", c );

             c = a | b;           /* 61 = 0011 1101 */
             Console.WriteLine("Line 2 - Value of c is {0}", c);

             c = a ^ b;           /* 49 = 0011 0001 */
             Console.WriteLine("Line 3 - Value of c is {0}", c);

             c = ~a;               /*-61 = 1100 0011 */
             Console.WriteLine("Line 4 - Value of c is {0}", c);

             c = a << 2;     /* 240 = 1111 0000 */
             Console.WriteLine("Line 5 - Value of c is {0}", c);

             c = a >> 2;     /* 15 = 0000 1111 */
             Console.WriteLine("Line 6 - Value of c is {0}", c);
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Friday, June 21, 2013

MVVM,MVP,MVC




ASP.NET MVC

ASP.NET is a development framework for building web pages and web sites with HTML, CSS, JavaScript and server scripting.
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.

Web Forms vs MVC

The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms). It is a lightweight, highly testable framework, integrated with all existing ASP.NET features, such as Master Pages, Security, and Authentication.

Introduction

MVC
....
ASP.NET MVC

Principle Inversion of Control

In software engineeringinversion of control (IoC) is a programming technique, expressed here in terms of object-oriented programming, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection, for example:
    1. a constructor injection
    2. parameter injection
    3. a setter injection
    4. an interface injection
  4. using a contextualized lookup
see more about dependency injection

http://www.c-sharpcorner.com/UploadFile/akkiraju/dependency-injection-techniques-explained-part-1/

Process, AppDomains and Threads

Reviewing Processes and Threads Under Traditional Win32
The concept of processes and threads has existed within Windows-based operating systems well before the release of the .NET platform. Simply put, process is the term used to describe the set of resources (such as external code libraries and the primary thread) as well as the necessary memory allocations used by a running application. For each *.exe loaded into memory, the operating system creates a separate and isolated memory partition (aka process) for use during its lifetime. Using this approach to application isolation, the result is a much more robust and stable runtime environment, given that the failure of one process does not effect the functioning of another.

..........

Understanding the System.AppDomain Type
unlike a traditional (non-.NET) Win32 *.exe application, .NET assemblies are hosted in a logical partition within a process termed an application domain (aka AppDomain) and many application domains can be hosted inside a single OS process. This additional subdivision of a traditional Win32 process offers several benefits, some of which are:

  • AppDomains are a key aspect of the OS-neutral nature of the .NET platform, given that this logical division abstracts away the differences in how an underlying operating system represents a loaded executable.
  • AppDomains are far less expensive in terms of processing power and memory than a full blown process (for example, the CLR is able to load and unload application domains much quicker than a formal process).
  • AppDomains provide a deeper level of isolation for hosting a loaded application. If one AppDomain within a process fails, the remaining AppDomains remain functional.

......
Context
As you have just seen, AppDomains are logical partitions within a process used to host .NET assemblies. A given application domain may be further subdivided into numerous context boundaries. In a nutshell, a .NET context provides a way for a single AppDomain to partition .NET objects that have similar execution requirements. Using context, the CLR is able to ensure that objects that have special runtime requirements are handled appropriately and in a consistent manner by intercepting method invocations into and out of a given context. This layer of interception allows CLR to adjust the current method invocation to conform to the contextual settings of a given type.




......

The Process/AppDomain/Context/Thread Relationship
As mentioned at the opening of this chapter, a thread is a path of execution within a loaded application. While many .NET applications can live happy and productive single-threaded lives, the primary thread may spawn secondary threads of execution to perform additional units of work. In just a moment, you will be introduced to the System.Threading namespace, which defines numerous types used to create multithreaded .NET applications. First however, we need to check out exactly "where" a thread lives within a .NET process.

The first thing you must understand is that under the .NET platform, there is not a direct one-to-one correlation between application domains and threads. In fact, a given AppDomain can have numerous threads executing within it at any given time. Furthermore, a particular thread is not confined to a single application domain during its lifetime. Threads are free to cross application domain boundaries as the thread scheduler and the CLR see fit.

Although active threads can be moved between application boundaries, a given thread can only execute within a single application domain at any point in time (in other words, it is impossible for a single thread to be doing work in more than one AppDomain).
.......
.......
.......
Summary
The point of this chapter was to expose the internal composition of a .NET executable image. As you have seen, the long-standing notion of a Win32 process has been altered under the hood to accommodate the needs of the CLR. A single process (which can be programmatically manipulated via the System.Diagnostics.Process type) is now composed on multiple application domains, which represent isolated and independent boundaries within a process. As you recall, a single process can host multiple application domains, each of which is capable of hosting and executing any number of related assemblies. Furthermore, a single application domain can contain any number of contextual boundaries. Using this additional level of type isolation, the CLR can ensure that special-need objects are handled correctly.

The remainder of this chapter examined the role of the System.Threading namespace. As you have seen, when an application creates additional threads of execution, the result is that the program in question is able to carry out numerous tasks at (what appears to be) the same time. Finally, the chapter examined various manners in which you can mark thread-sensitive blocks of code to ensure that shared resources do not become unusable units of bogus data.

Very good!!



using System;
class Test {
static void Main() {
AppDomain d = AppDomain.CreateDomain("NewDomain");
Console.WriteLine("Host domain:  "  + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("Child domain:  "   + d.FriendlyName);
  }
}

output

c:\Windows\MICROS~1.NET\FRAMEW~1\V20~1.507>ADomain.exe
Host domain:  ADomain.exe
Child domain:  NewDomain

More detailed

  private void button1_Click(object sender, EventArgs e)
        {
            //AppDomain d = AppDomain.CreateDomain("NewDomain");
           // AppDomain.MonitoringIsEnabled = true;
            //int mt = AppDomain.CurrentDomain. MonitoringTotalProcessorTime.Milliseconds;
            //string ms = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize.ToString();
            //string mas = AppDomain.CurrentDomain.MonitoringSurvivedMemorySize.ToString();
            textBox1.Text = AppDomain.CurrentDomain.FriendlyName.ToString();
            List a=AppDomain.CurrentDomain.GetAssemblies().ToList();
           
            Context ctx = Thread.CurrentContext;

            textBox2.Text = a.Count.ToString() + ctx.ContextID.ToString() + Thread.GetDomain();
           
        }

Using Pointers in C#

<<...unsafe keyword:
Typically when we write code in C# by default it is what's known as safe code. Unsafe code allows you to manipulate memory directly, in the normal world of C# and the .NET Framework, this is seen as potentially dangerous, and as such you have to mark your code as unsafe. Using unsafe code, you are loosing garbage collection and whilst directly accessing memory, you have the possibility of accessing memory that you didn't want to and causing untold problems with your application. Unsafe code can only be used within a fully trusted assembly....>>

Pointers in C#

<<..Enter the fixed keyword. When used for a block of statements, it tells the CLR that the object in question cannot be relocated, and thus, it ends up pinning the object. Thus, when pointers are used in C#, the fixed keyword is used pretty often to prevent invalid pointers at runtime.
 ...>>

using System;
class CData
{
    public int x;
}

class CProgram
{
    unsafe static void SetVal(int *pInt)
    {
        *pInt=1979;
    }
    
    public unsafe static void Main()
    {
        CData d = new CData();
        
        Console.WriteLine("Previous value: {0}", d.x);
        
        fixed(int *p=&d.x)
        {
            SetVal(p);
        }
        
        Console.WriteLine("New value: {0}", d.x);
    }
}


Unsafe programming in C#


Blog Archive

About Me

An seasoned developer, architect and with some Team Leading exposure, offering full project life cycle experiences within multi cultural, multi National environments and within differing business streams and all primarily on a .Net platform.