Friday, January 29, 2010

OOPS

COMPOSITION
-----------------------------
Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. This is COMPOSITION. (ie the firm is COMPOSED OF business units)

Mentioned by HAS-A relationship. It describes the member field or an object.
The part(s) are usually expected to “live” and “die” with the whole



AGGREGATION
-----------------------------
Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance. Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled.


Mentioned by HAS-A relationship. It describes the member field or an object.


ASSOCIATION
-----------------------------
The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm. This is typical ASSOCIATION. (This is the simplest relationship between objects)

Composition Vs Aggregation..
-----------------------------
Usually, composition means that the lifetime of the contained object is bounded by that of the container, whereas aggregation is a reference to an object which may exist independently.


Inheritance
------------------------

Inheritance is used to express “is-a” or “kind-of” relationships. A car is a vehicle. A boat is a vehicle. A submarine is a vehicle. In OOP, the Vehicle base class would provide the common behaviors of all types of vehicles and perhaps delineate behaviors all vehicles must support. The particular subclasses (i.e., derived classes) of vehicles would implement behaviors specific to that type of vehicle. The main concepts behind inheritance are extensibility and code reuse.

Composition
-----------------------------

In contrast to inheritance, there is also the notion of a “has-a” relationship. This relationship is created by using composition. Composition, which is sometimes referred to as aggregation, means that one object contains another object, rather than inheriting an object’s attributes and behaviors. Naturally, a car has an engine, but it is not a kind of engine.

Wednesday, October 14, 2009

Create collection of Anonymous Types and also call Extension Methods.



var StudentDetail = new {ID=0, FirstName="", MiddleName="", LastName="", Age=1, Sex=''};




var StudentRecords = TypeGenerator.MakeList(StudentDetail)


StudentRecords.Add(new
{
ID = 1,
FirstName = "Sankar",
LastName = "Manickam",
MiddleName = "P",
Age = 25,
Sex = "M"

});


public static class TypeGenerator
{
public static List <T> MakeList <T>(this T t)
{
return new List <T>();
}
}

Friday, June 05, 2009

Filter one list using another list in LINQ

public class Country
{
public string CountryID { get; set; }
public string CountryVal { get; set; }
public string CountryDesc { get; set; }


}



List<Country> sourceCountry = new List<Country>
{
new Country{ CountryID="1" , CountryVal="IND", CountryDesc="India"},
new Country{ CountryID="2" , CountryVal="USA", CountryDesc="America"},
new Country{ CountryID="3" , CountryVal="UK", CountryDesc="London"},
new Country{ CountryID="4" , CountryVal="PAR", CountryDesc="Paris"}
};

List<Country> filterCountry = new List<Country>
{
new Country{ CountryDesc="India"},
new Country{ CountryDesc="London"}

};


var finalcountry = from item in sourceCountry
from some in filterCountry
where item.CountryDesc == some.CountryDesc
select item;

List<Country> fin = finalcountry.ToList<Country>();

Let Keyword in C#

Let’s see how the “let” keyword works.

I will start from a list of numbers stored as strings.
I would like to get only numbers greater than 10 and order them by their value but keeping the result as an enumeration of string.

We can write it quickly this way:

var values = new string[] { "12", "4", "7", "18", "32" };
var q =
from s in values
where Convert.ToInt32(s) > 10
orderby Convert.ToInt32(s)
select s;
This works fine but we all notice the ugly “Convert.ToInt32(s)” used twice on the same value. Thanks to the “let” keyword we can create a new parameter that will be accessible in all the query.

var values = new string[] { "12", "4", "7", "18", "32" };
var q =
from s in values
let i = Convert.ToInt32(s)
where i > 10
orderby i
select s;

Monday, March 16, 2009

Design Pattern

What is a Design Pattern?

Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how to solve a problem.

In 1994, the release of the book Design Patterns, Elements of Reusable Object Oriented Software made design patterns popular.

Because design patterns consist of proven reusable architectural concepts, they are reliable and they speed up software development process.

Design Patterns are in a continious phase of evolution, which means that they keep on getting better & better as they are tested against time, reliability and subjected to continious improvements. Further, design patterns have evolved towards targeting specific domains. For example, windows-based banking applications are usually based on singleton patterns, e-commerce web applications are based on the MVC (Model-View-Controller) pattern.


Design Patterns are categorized into 3 types:
Creational Patterns
Structural Patterns
Behavioral Patterns


What are Creational Design Patterns?

The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of when and how objects are created, keeping in mind whats the best way these objects should be created.

Listed below are some of the commonly known Creational Design Patterns:
>>> Abstract Factory Pattern
>>> Factory Pattern
>>> Builder Pattern
>>> Lazy Pattern
>>> Prototype Pattern
>>> Singleton Pattern


Whats the difference between Abstract Factory Pattern and Factory Pattern?

In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component. In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface comprises of the generic method declarations that are passed on to the sub-components. TNote that not just interfaces, but even abstract classes can provide the platform of creating an application based on the abstract factory pattern.
Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like ShouldHavePolice() and ShouldHaveCourts(). There may be several sub-classes like State1Rules, State2Rules etc. created that inheriting the class CentralGovernmentRules, and thus deriving its methods as well.

Note that the term "Factory" refers to the location in the code where the code is created.

A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object. Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's constructor. So basically the Factory Pattern is used wherever sub classes are given the priviledge of instantiating a method that can create an object.

Describe the Builder Design Pattern

In a builder design pattern, an object creation process is separated from the object design construct. This is useful becuase the same method that deals with construction of the object, can be used to construct different design constructs.

What is the Lazy Design Pattern?

The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches, object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?

A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent overheads.

What is the Singleton Design Pattern?

The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object needs to perform the role of a coordinator between various instances of the application that depend on a common object, we may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial and Travel based applications where the singleton object consists of the network related information.

A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists, a reference to the existing object is given. A singleton object has one global point of access to it.

An ASP.NET Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web servers. The session state is handled by a Singleton object in the form of the aspnet_state.exe, that interacts with the ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine one of the web servers shutting down, the singleton object aspnet_state.exe still maintains the session state information across all web servers in the web farm.

In .NET, in order to create a singleton, a class is created with a private constructor, and a "static readonly" variable as the member that behaves as the instance.

What are Structural Design Patterns?

A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an application to interact with each other. Following are some of the commonly known structural patterns:

>>> Adapter Pattern - Interfaces of classes vary depending on the requirement.
>>> Bridge Pattern - Class level abstraction is separated from its implementation.
>>> Composite Pattern - Individual objects & a group of objects are treated similarly in this approach.
>>> Decorator Pattern - Functionality is assigned to an object.
>>> Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
>>> Flyweight Pattern - The concept of sharing a group of small sized objects.
>>> Proxy Pattern - When an object is complex and needs to be shared, its copies are made. These copies are called the proxy objects.


What are the different types of Proxy Patterns?

1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a same machine.
2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.
3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example, in ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the ASP.NET web server.

What is a behavioral design pattern?

Behaviorial design patterns focus on improving the communication between different objects. Following are different types of behavioral patterns:
>>> Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions made by a class.
>>> Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.
>>> Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.


What is the MVC Pattern (Model View Controller Pattern)?

The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set of re-usable classes like classes pertaining to data access, custom control classes, application configuration classes etc. The Controller component interacts with the Model whenever required. The control contains events and methods inside it, which are raised from the UI which is the View component.

Consider an ASP.NET web application. Here, all aspx, ascx, master pages represent the View.

The code behind files (like aspx.cs, master.cs, ascx.cs) represent the Controller.

The classes contained in the App_Code folder, or rather any other class project being referenced from this application represent the Model component.

Advantages: * Business logic can be easily modified, without affecting or any need to make changes in the UI.
* Any cosmetic change in the UI does not affect any other component.

What is the Gang of Four Design Pattern?

The history of all design patterns used in modern day applications derive from the Gang of Four (GoF) Pattern. Gang of Four patterns are categorized into 3 types:
1 - Creational
2 - Structural
3 - Behavioral

The term "Gang of Four" (or "GoF" in acronym) is used to refer to the four authors of the book Design Patterns: Elements of Reusable Object-Oriented Software. The authors are Erich Gamma, Ralph Johnson, Richard Helm and John Vlissides.

When should design patterns be used?

While developing software applications, sound knowledge of industry proven design patterns make the development journey easy and successful. Whenever a requirement is recurring, a suitable design pattern should be identified. Usage of optimal design patterns enhance performance of the application. Though there are some caveats. Make sure that there are no overheads imposed on a simple requirement, which means that design patterns should not be unnecessarily be used.

How many design patterns can be created in .NET?

As many as one can think. Design patterns are not technology specific, rather their foundation relies on the concept of reusability, object creation and communication. Design patterns can be created in any language.

Describe the Ajax Design Pattern.

In an Ajax Design Pattern, partial postbacks are triggered asyncronously to a web server for getting live data. A web application would not flicker here, and the web site user would not even come to know that a request is being sent to the web server for live data.

Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Websites for live news, Sports websites for live scores etc.

Wednesday, February 04, 2009

Instance Management in WCF

By and large, the service instance mode is strictly a service-side implementation detail that should not manifest itself on the client side in any way. To support that and a few other local service-side aspects, WCF defines the notion of behaviors. A behavior is a local attribute of a service that does not affect its communication patterns.

Three Instance Management mode is available.

1.Per-Call
2.Per-Session
3.Single

Other Instance Management techniques are

1.Demarcating Operations
2.Instance Deactivation
3.Throtlling


-------------------------
Per-Call
-------------------------
When the service type is configured for per-call activation, a service instance (the CLR object) exists only while a client call is in progress. Every client request
(that is, a method call on the WCF contract) gets a new dedicated service instance

Per-call services are the Windows Communication Foundation default instantiation mode

-------------------------
Benefits
-------------------------
Creating and destroying a service instance repeatedly on the service side without tearing down the connection to the client (with its client-side proxy) is a lot cheaper than creating an instance and a connection.

The second benefit is that forcing the service instance to reallocate or connect to its resources on every call caters very well to transactional resources and transactional programming, because it eases the task of enforcing consistency with the instance state.


The third benefit of per-call services is that they can be used in conjunction with queued disconnected calls because they allow easy mapping of service instances to
discrete queued messages.



[ServiceContract]
interface IMyContract {...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract {...}



If a per-call service must be state-aware, meaning that state from one call must persist to a future call, the implementation itself must proactively manage the state,giving the client the illusion of a continuous session.

An instance of a per-call service is created just before every method call and destroyed immediately after each call. Therefore, at the beginning of each call, the

object should initialize its state from values saved in some storage, and at the end of the call it should return its state to the storage. Such storage is typically
either a database or the file system, but it can also be volatile storage like static variables. However, not all of the object's state can be saved as-is.

For example, if the state contains a database connection, the object must reacquire the connection at construction or at the beginning of every call and dispose of the
connection at the end of the call or in its implementation of IDisposable.Dispose.

Using per-call instance mode has one important implication for operation design: every operation must include a parameter to identify the service instance whose state needs to be retrieved.

-------------------------
Per-Session
-------------------------


WCF can maintain a session between a client and a particular service instance. When the client creates a new proxy to a service configured as a sessionful service, the
client gets a new dedicated service instance that is independent of all other instances of the same service. That instance will remain in service usually until the client no longer needs it. This activation mode is very much like the classic client-server model. This mode is also sometimes referred to as private sessions. Each private session uniquely binds a proxy and its set of client- and service-side channels to a particular service instance.

Because the service instance remains in memory throughout the session, it can maintain state in memory, and the programming model is very much like that of the classic client/server. Consequently, it also suffers from the same scalability and transaction issues as the classic client/server model. A service configured for private sessions cannot typically support more than a few dozen (or perhaps up to a hundred or two) outstanding clients due to the cost associated with each such dedicated service instance.


The client session is per service endpoint per proxy. If the client creates another proxy to the same or a different endpoint, that second proxy will be associated
with a new instance and session.


[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyContract {...}


The session typically terminates when the client closes the proxy. This causes the proxy to notify the service that the session has ended.


In order to correlate all messages from a particular client to a particular instance, WCF needs to be able to identify the client. One way of doing that is to rely on a transport-level session; that is, a continuous connection at the transport level, such as the one maintained by the TCP and IPC protocols.

public enum SessionMode
{
Allowed,
Required,
NotAllowed
}

[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
[OperationContract]
void MyMethod( );
}



SessionMode.Allowed is the default value of the property.

The SessionMode.Required value mandates the use of a transport-level session, but not necessarily an application-level session. You cannot have a contract configured with SessionMode.Required with a service's endpoint whose binding does not maintain a transport-level session, and this constraint is verified at the service load
time.

SessionMode.NotAllowed disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, it always behaves as a per-call service.


If a per-call service without a transport session (such as with the BasicHttpBinding or with SessionMode.NotAllowed) accesses the SessionId property, it will return
null, since there is no session and therefore no ID.


Typically, the session will end once the client closes the proxy. However, in case the client fails to terminate gracefully or encounters a communication problem, each
session also has an idle time timeout that defaults to 10 minutes—the session will automatically terminate after 10 minutes of inactivity from the client, even if the
client still intends to use the session. Once the session has terminated due to the idle timeout, if the client tries to use its proxy, the client will get a
CommunicationObjectFaultedException.


Both the client and the service can configure a different timeout by setting a different value in the binding. The bindings that support reliable transport-level session provide the ReliableSession property with the InactivityTimeout property used for configuring the idle timeout.


For example, the following shows the code that is required to programmatically configure an idle timeout of 25 minutes for the TCP binding:

NetTcpBinding tcpSessionBinding = new NetTcpBinding();
tcpSessionBinding.ReliableSession.Enabled = true;
tcpSessionBinding.ReliableSession.InactivityTimeout =
TimeSpan.FromMinutes(25);


Here is the equivalent configuration setting using a config file:

<netTcpBinding>
<binding name="TCPSession">
<reliableSession enabled="true" inactivityTimeout="00:25:00"/>
</binding>
</netTcpBinding>

If both the client and the service configure timeouts, then the shorter timeout prevails.

There is another esoteric service-side configuration for session termination. The ServiceBehavior attribute offers an advanced option for managing the session shutdown via the AutomaticSessionShutdown property. This property is intended for optimizing certain callback scenarios, and can be safely ignored in most cases. In a nutshell,AutomaticSessionShutdown defaults to TRue so that when the client closes the proxy, the session is terminated. Setting it to false causes the session to continue until the service explicitly closes its sending channel. When set to false, the client of a duplex session must manually close the output session on the duplex client channel, otherwise the client will hang waiting for the session to terminate.

-------------------------
Singleton Service
-------------------------

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class MyService : IMyContract {...}


The singleton service is the ultimate sharable service.

When a service is configured as a singleton, all clients independently get connected to the same single well-known instance, regardless of which endpoint of the
service they connect to.

The singleton service lives forever and is only disposed of once the host shuts down.

The singleton is created exactly once, when the host is created.

Using a singleton does not require the clients to maintain a session with the singleton instance, or to use a binding that supports a transport-level session.


Closing the client proxy will only terminate the session, not the singleton instance. In addition, the session will never expire. If the singleton service supports contracts without a session, those contracts will not be per-call: they too will be connected to the same instance. By its very nature, the singleton is shared, and each client should simply create its own proxies to it.



-------------------------
Demarcating Operations
-------------------------
Sometimes, a sessionful contract has an implied order to operation invocations. Some operations cannot be called first, while other operations must be called last. For
example, consider this contract used to manage customer orders:

[ServiceContract(SessionMode = SessionMode.Required)]
interface IOrderManager
{
[OperationContract]
void SetCustomerId(int customerId);

[OperationContract]
void AddItem(int itemId);

[OperationContract]
decimal GetTotal( );

[OperationContract]
bool ProcessOrders( );
}



The contract has the following constraints: the client must provide the customer ID as the first operation in the session, or else no other operations can take place;
items may be added, and the total calculated, in any order, and as often as the client wishes; processing the order terminates the session, and therefore must come
last.

WCF allows contract designers to designate contract operations as operations that can or cannot start or terminate the session using the IsInitiating and IsTerminating properties of the OperationContract attribute.



Going back to the order management contract, you can use demarcating operations to enforce the interaction constraints:

[ServiceContract(SessionMode = SessionMode.Required)]
interface IOrderManager
{
[OperationContract]
void SetCustomerId(int customerId);

[OperationContract(IsInitiating = false)]
void AddItem(int itemId);

[OperationContract(IsInitiating = false)]
decimal GetTotal( );

[OperationContract(IsInitiating = false,IsTerminating = true)]
bool ProcessOrders( );
}
//Client code
OrderManagerClient proxy = new OrderManagerClient( );

proxy.SetCustomerId(123);
proxy.AddItem(4);
proxy.AddItem(5);
proxy.AddItem(6);
proxy.ProcessOrders( );

proxy.Close( );


-------------------------
Instance Deactivation
-------------------------

The common way of controlling context deactivation is via the ReleaseInstanceMode property of the OperationBehavior attribute:

public enum ReleaseInstanceMode
{
None,
BeforeCall,
AfterCall,
BeforeAndAfterCall,
}



You typically apply instance deactivation only on some service methods, but not all of them, or with different values on different methods:

[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
[OperationContract]
void MyMethod( );

[OperationContract]
void MyOtherMethod( );
}
class MyService : IMyContract,IDisposable
{
[OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.AfterCall)]
public void MyMethod( )
{...}
public void MyOtherMethod( )
{...}
public void Dispose( )
{...}
}



The reason you typically apply it sporadically is that if you were to apply it uniformly you would have ended up with a per-call-like service, so you might as well
have configured the service as per-call. If relying on instance deactivation assumes a certain call order, you can try and enforce that order using demarcating
operations.


[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
[OperationContract]
void MyMethod( );
}
class MyService : IMyContract,IDisposable
{
public void MyMethod( )
{
//Do some work then
OperationContext.Current.InstanceContext.ReleaseServiceInstance( );
}
public void Dispose( )
{...}
}



Calling ReleaseServiceInstance( ) has a similar effect to using ReleaseInstanceMode.AfterCall. When used in a method decorated with ReleaseInstanceMode.BeforeCall it has a similar effect to using ReleaseInstanceMode.BeforeAndAfterCall.


-------------------------
Throttling
-------------------------



While it is not a direct instance management technique, throttling enables you to restrain client connections and the load they place on your service.

Throttling enables you to avoid maxing out your service and the underlying resources it allocates and uses. When throttling is engaged, if the settings you configure are exceeded, WCF will automatically place the pending callers in a queue and serve them out of the queue in order.

If the client's call timeout expires while pending in the queue, the client will get a TimeoutException. Throttling is done per service type; that is, it affects all instances of the service and all its endpoints. This is done by associating the throttle with every channel dispatcher the service uses.


Throttle Default Values

ConcurrentCalls = "16"
ConcurrentSessions = "10"
ConcurrentInstances = unlimited


Throttled Connections in the Binding
--------------------------------------
When you use the TCP and named-pipe bindings, you can also configure the maximum connection number for a particular endpoint in the binding itself. Both the

NetTcpBinding and the NetNamedPipeBinding offer the MaxConnections property:



On the host side, you can set that property either programmatically or by using a config file:

<bindings>
<netTcpBinding>
<binding name = "TCPThrottle" maxConnections = "25"/>
</netTcpBinding>
</bindings>



MaxConnections defaults to 10. When both a binding-level throttle and a service-behavior throttle sets the max connection value, WCF chooses the lesser of the two.

Monday, December 01, 2008

How to view the buffered output using oracle stored procedure

CREATE OR REPLACE procedure ExtractEmpInfo
(
EmpName in varchar2,
cv_results in out sys_refcursor
)
IS

begin
open cv_results for
Select * from Employee where EmplyoeeName=EmpName;
End;

If you want to see the output.

Go To -> TOAD --> Stored Procedure --> Right Click Execute Procedure
->Now Parameters window will open
->Enter the Arguments except Cursor
->click Options Button
->Now Output Options window will open
->Select Load into grid from memory option.
->Now Click OK..You can view the results in the grid.

Monday, November 24, 2008

Create and fill recordset using VB 6.0

The below example explains how to create the recordset and fill our own values using VB 6.0


If you want to run the below code, you need to add a reference of Microsoft Activex Data Objects 2.8 Library using References under Project.


Dim SpecailizedFunds As String
Dim fields() As String



SpecailizedFunds = "123456,456789"
fields() = Split(SpecailizedFunds, ",")


Dim rsTemp As ADODB.Recordset
Set rsTemp = New ADODB.Recordset
rsTemp.ActiveConnection = Nothing
rsTemp.CursorLocation = adUseClient
rsTemp.LockType = adLockBatchOptimistic


'create fields
rsTemp.fields.Append "Account", adChar, 6
rsTemp.Open


For i = 0 To UBound(fields)
rsTemp.AddNew
rsTemp.fields(0) = fields(i)
If Not rsTemp.EOF Then rsTemp.MoveNext
Next



If rsTemp.RecordCount > 1 Then
rsTemp.MoveFirst
Do Until rsTemp.EOF
MsgBox rsTemp.fields("Account").Value
rsTemp.MoveNext
Loop
End If


rsTemp.Close
Set rsTemp = Nothing