Encapsulation

When designing a class, it is generally a good practice to only reveal the necessary interfaces needed to interact with the object, and hide the implementation details that are not precisely relevant. This hiding of details is known as encapsulation.

The concept of encapsulation is better enforced with the definitions of interfaces and implementations. An interface is defined by the services of communication between objects. Classes declare some methods and properties as visible to outside objects, and hide the other details. The visible, or public, methods and properties become the interface to the object. Interfaces typically only include methods, since any need to access an attribute should be made available through a public method.

public class ClsEncapsulation
{
int SqrOutput;
public ClsEncapsulation()
{
}
//Visible method
public void AssignNumber(int GivenNumber)
{
CalculateSqluare(GivenNumber);
}
public void Display()
{
Console.WriteLine("Square of given number is " + SqrOutput.ToString());
}
//Hiding Method
private void CalculateSqluare(int GnNumber)
{
SqrOutput = System.Math.Pow(GnNumber,2);
}

}

Process Vs Thread

Process:
  • Process is a heavy weight running instance of a program.
  • A Process has its own memory space, runtime enivorment and process ID. One process can have multiple threads(It has atleast one main thread).
  • Processes must use interprocess communication to communicate with silbing processes.
  • Process is an architectural construct.

Thread:
  • A thread is the smallest schedulable unit of execution in aWindows application.
  • A thread always is associated with a particular process.Threads runs the code inside the process and share the address space with other threads inside the process i.e share process handles.
  • Threads can directly communicate with other threads of its process.
  • Thread is coding construct.

Assembly Vs Namespace

Assembly:
  • An assembly is the primary building block of a .NET Framework application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). It's a managed dll or exe (built by .NET).Assemblies are Self-Describing. [e.g. metadata,manifest]
  • One assembly can contain several namespaces.
Namespace:
  • A group of managed types (classes, enums, structs, etc). It form the logical boundary for a Group of classes.
  • One namespace can contain types(Objects) from different assemblies.
  • The name of the namespace is not necessarily the name of the assembly.

Basics of .NET Namespace

Namespace are logical grouping of classes and other types such as unions, structures, interfaces and enumerators.

In Microsoft .Net, every program is created with a default namespace. This default namespace is called as global namespace. But the program itself can declare any number of namespaces, each of them with a unique name. The advantage is that every namespace can contain any number of classes, functions, variables and also namespaces etc., whose names are unique only inside the namespace. The members with the same name can be created in some other namespace without any compiler complaints from Microsoft .Net.

If a new project is created in Visual Studio .NET it automatically adds some global namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace System.

namespace Books
{
class Authors
{
public void Display()
{
Console.WriteLine("Auther name is Dynamic-Coding");
}
}
This is simple namespace example. We can also build hierarchy of namespace. Here is an example for this.

namespace Books
{
namespace Inventory
{
using System;
class AddInventory
{
public void MyMethod()
{
Console.WriteLine("Adding Inventory via MyMethod!");
}
}
}
}

Let's look how we can use the namespaces in our code

using Books;
class HelloWorld
{
public static void Main()
{
Inventory.AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

OR

using Books.Inventory;
class HelloWorld
{
public static void Main()
{
AddInventory AddInv = new AddInventory();
AddInv.MyMethod();
}
}

Note:
The namespaces wide opens the doors for 3rd party and project specific custom components and class libraries.

Object filtering using LINQ

LINQ:
Query is an integrated feature of programming language(like C# and VB.NET).LINQ(Language Integrated query), a set of language extension that allows you to perform queries without leaving the comfort of programming language. It has set of keyword to build a query expression.These query expression can select,filter,sort,group and transform data.


LINQ to Objects:
It is Simplest form of LINQ, allow you to query collection of memory objects. It replace the iteration logic(such as foreach block) with declarative LINQ expression.LINQ using the new set of keywords, including from,in,where and select.


public class Car
{

public Car(string m_Make,string m_Color,int m_Price)
{
Make = m_Make;
Color = m_Color;
Price = m_Price;
}

public string Make { get; set; }
public string Color { get; set; }
public int Price { get; set; }

}



public class LinQApp
{

static void Main(string[] args)
{
ListFiltering();
Console.ReadLine();
}

private static void ListFiltering()
{
List Cars = new List();
Cars.Add(new Car("TATA","Red",100000));
Cars.Add(new Car("TATA", "Yellow", 100000));
Cars.Add(new Car("TATA", "White", 100000));
Cars.Add(new Car("Maruti", "Red", 300000));
Cars.Add(new Car("Maruti", "Yellow", 300000));
//Logic: Show All cars with Red Color
Console.WriteLine("");
//Iterative Method
Console.WriteLine("List Filter Normal Way:");
foreach (Car C in Cars)
{
if (C.Color == "Red")
Console.WriteLine(C.Make + " Price " + C.Price);
}
//LINQ Query Method
Console.WriteLine("");
Console.WriteLine("List Filter LINQ Way:");
IEnumerable MatchCars;


MatchCars = from C in Cars
where C.Color == "Red"
select C; //here C is the object with type of Car

//After the filtering condition all the attributes of car is selected.


foreach (Car MatCar in MatchCars)
{
Console.WriteLine(MatCar.Make + " Price " + MatCar.Price);
}

}

}


Output:

List Filter Normal way:
TATA Price 100000
Maruti Price 300000



List Filter LINQ way:
TATA Price 100000
Maruti Price 300000

PRAGMA AUTONOMOUS_TRANSACTION:To Commit a part of Tranasaction in PL/SQL

There would be business requirement to just commit or rollback part of the transaction regardless of the actual transactions success or failure.We can handle this using PRAGMA AUTONOMOUS_TRANSACTION, if we create a block as PRAGMA AUTONOMOUS_TRANSACTION then this will be independent of thecalling block so if we Commit or rollback a transaction in this PRAGMA AUTONOMOUS_TRANSACTION block will have no commit/rollback impact on the called block.

Example:
create table pragma_table (ename varchar2(32), e_id number);
insert into pragma_table values ('','1');
insert into pragma_table values ('','2');

CREATE OR REPLACE PROCEDURE Sample_AUTONOMOUS_TRANSACTION(emp_id number)
AS PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
UPDATE pragma_table SET ename = 'TWO' Where e_id = 2;
dbms_output.put_line('Iyen going to Commit');
COMMIT;
EXCEPTiON WHEN OTHERS THEN
dbms_output.put_line('Iyen in Pragma Exception so rollback' sqlerrm);
ROLLBACK;
END;


BEGIN
UPDATE pragma_table SET ename = 'ONE' Where e_id = 1; Sample_AUTONOMOUS_TRANSACTION(2);exception when others then dbms_output.put_line('Iyen Example in exception' sqlerrm);
end;

Execute the below select once with Commit and once with rollback; You can find the difference.
select * from pragma_table;

RoT: As a Rule of Thumb , always make sure that your Autonomous transaction block is either getting rollback or commit.

Do send your comments.

--Iyen

Overriding Vs Hiding/Shadowing

Overriding:
  • An override method provides a new implementation of a member inherited from a base class. The overridden base method must have the same signature as the override method.You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
  • Only a procedure (Function or Sub) or property
  • Overriding the accessibility is not possible(Base and child class having same access specifiers).
  • Overriding element inherited by further derived classes; overridden element still overridden.
Hiding(C#)/Shadowing(VB.NET):
  • When two programming elements share the same name, one of them can hide, or shadow, the other one. In such a situation, the shadowed element is not available for reference.
  • It applied to any declared element type(procedure (Function or Sub) or property and fields).
  • Any accessibility is possible.
  • Shadowing element inherited by further derived classes; shadowed element still hidden.


class BaseClass
{
public int X = 10;
public virtual string overridingMethod()
{
return "BaseClass overridingMethod \n";
}
public string hidingMethod()
{
return "BaseClass hidingMethod \n";
}
public void ParentDisplay()
{
Console.WriteLine("Paerent " + X);
}
}

class DerivedClass : BaseClass
{
public new string X = "Hai";
//Hiding applied even field also(new keyword used for hiding)

public override string overridingMethod()
{
return "DerivedClass overridingMethod \n";
}
internal new string hidingMethod()
//Change of accessibility possible in hiding
{
return "DerivedClass hidingMethod \n";
}
public void childDisplay()
{
Console.WriteLine("Child " + X);
}
}

class MainClass
{
static void Main()
{
BaseClass bc = new BaseClass();
Console.WriteLine("Base class ref assigned to Base class object");
bc.ParentDisplay();
Console.Write(bc.overridingMethod());
Console.Write(bc.hidingMethod());
DerivedClass dc = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Derived class ref assigned to Derived class object");
dc.ParentDisplay();
dc.childDisplay();
Console.Write(dc.overridingMethod());
Console.Write(dc.hidingMethod());
BaseClass bc2 = new DerivedClass();
Console.WriteLine("");
Console.WriteLine("Base class ref assigned to Derived class object");
bc2.ParentDisplay();
Console.Write(bc2.overridingMethod());
//It will return overrided method(not relavent to it's reference)
Console.Write(bc2.hidingMethod()); //It will return method which is relavent to it's reference
}
}

Output :

Base class ref assigned to Base class object
Parent 10
BaseClass overridingMethod
BaseClass hidingMethod

Derived class ref assigned to Derived class object
Parent 10
Child Hai
DerivedClass overridingMethod
DerivedClass hidingMethod

Base class ref assigned to Derived class object
Parent 10
DerivedClass overridingMethod
BaseClass hidingMethod

Reflection in .NET Framework

Reflection is the feature in .Net, which enables us to get some information about object in runtime. That information contains data of the class. System.Reflection namespace contains all the Reflection related classes. These classes are used to get information from any of the class under .NET framework.

The Type class is the root of all reflection operations. Type is an abstract base class that acts as means to access metadata though the reflection classes. Using Type object, any information related to methods, implementation details and manipulating information can be obtained. The types include the constructors, methods, fields, properties, and events of a class, along with this the module and the assembly in which these information are present can be accessed and manipulated easily.

public class TestDataType
{
public delegate void DelMaxCounterAttained(int Counter);
public event DelMaxCounterAttained MaxCounterAttained;
public TestDataType()
{
counter = 1;
}
public TestDataType(int c)
{
counter = c;
}
public int counter;
public int Inc()
{
if (counter++ >= 10)
MaxCounterAttained(counter);
return counter;
}
public int Dec()
{
return counter--;
}
}


public class ReflectionSample
{
public static void Main()
{
//At first we should get type of object that was created.
TestDataType testObject = new TestDataType(15);
Type objectType = testObject.GetType();


//Using objectType we can able to extract constructor, method and events information
ConstructorInfo[] info = objectType.GetConstructors();
FieldInfo[] fields = objectType.GetFields();
MethodInfo[] methods = objectType.GetMethods();
EventInfo[] events = objectType.GetEvents();

// get all the constructors
Console.WriteLine("Constructors:");
foreach (ConstructorInfo cf in info)
{
Console.WriteLine(cf);
}
Console.WriteLine();

//get all the fields
Console.WriteLine("Fileds:");
foreach (FieldInfo ff in fields)
{
Console.WriteLine(ff);
}


// get all the methods
Console.WriteLine("Methods and handles:");
foreach (MethodInfo mf in methods)
{
Console.WriteLine(mf);
}

//get all the events
Console.WriteLine("Events:");
foreach (EventInfo ef in events)
{
Console.WriteLine(ef);
}

}
}

Output:

Constructors:
Void .ctor()
Void .ctor(Int32)

Fields:
Int32 counter

Methods and hanles:
void add_MaxCounterAttained(DelMaxCounterAttained)
void remove_MaxCounterAttained(DelMaxCounterAttained)
Int32 Inc()
Int32 Dec()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()

Events:
DelMaxCounterAttained MaxCounterAttained

Abstract Class Vs Interface

Abstract Class :

We can not make instance of Abstract Class as well as Interface. It cannot be a sealed class. It can contain abstract methods, abstract property as well as other members (just like normal class).

Interface:

Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. Interface are useful to achieve Multiple inheritence.

abstact class is a abstract view of any realword entity and interface is more abstract one


//Abstract class
public abstract class Calculate
{
public abstract int Result
{
get;
set;
}
public abstract void Summation(int First, int Second);
}


//Interface
public interface ICalculate
{
int Result
{
get;
set;
}
void Summation(int First, int Second);
}


//Abstract class inherited class
public class ClsAbstraction : Calculate
{
private int m_Result;
public override void Summation(int First, int Second)
{
m_Result = First + Second;
}
public override int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Interface implemented class
public class ClsInterface : ICalculate
{
private int m_Result;
public void Summation(int First, int Second)
{
m_Result = First + Second;
}
public int Result
{
get { return m_Result; }
set { m_Result = value; }
}
}


//Main class
public class ClsMain
{
public static void Main()
{
//Using abstarct class
ClsAbstraction objClsAbstarction = new ClsAbstraction();
objClsAbstarction.Summation(4, 5);
Console.WriteLine("Abs class result " + objClsAbstarction.Result);
//Using Interface
ClsInterface ObjClsInterface = new ClsInterface();
ObjClsInterface.Summation(5, 5);
Console.WriteLine("Interface result " + ObjClsInterface.Result);
}
}


Conclusion:

Abstract class having upper-hand in compare to interface. Using interface having only advantage of multiple inheritance.

Difference between String and string data types

There is no difference between string and String data type. string is C# based keyword and it is alaises for CLR Type(String).

C# defines a number of aliases for CLR types. It have the keywords because they are easier to remember and programmers coming from other languages like c/c++ would also be familiar with these types. They may be used interchangably, and even mixed together,
e.g : string x = new System.String(' ', 5);

These are the aliases defined:

string->System.Strings
byte->System.SByte
byte->System.Byte
short->System.Int16
ushort->System.UInt16
int->System.Int32
uint->System.UInt32
long->System.Int64
ulong->System.UInt64
char->System.Char
float->System.Single
double->System.Double
bool->System.Boolean
decimal->System.Decimal

Boxing and Unboxing in .NET

Boxing:
Converting a value type to reference type is called Boxing.

Unboxing:
Unboxing is an explicit operation. You have to tell which value type you want to extract from the object.

Int32 vt= 10; //value type variable
object rt= vt; /*memory is allocated on the heap of size equal to size of vt,the value type bits are copied to the newly allocated memory and the address of the object is returned and stored in rt.This is basically called Boxing.*/

Int32 vt2=(Int32)rt;//Unboxing

Purpose of Boxing and UnBoxing :

.NET provides a unified type system. All types including value types derive from the type object. It is possible to call object methods on any value, even values of primitive types such as int.

private void display()
{
Console.WriteLine(3.ToString());
}

calls the object-defined ToString method on an integer value.In programs that need int values to behave like objects, this capability is available on demand. This ability to treat value types as objects bridges the gap between value types and reference types that exists in most languages.

Destructor,Finalizer and Dispose Method in .NET Framework

Destructor and Finalizer:

Destructor are called by the CLR when the Garbage Collector destroys an object. In VB.NET it is called the Finalize() method. In C# it is declared by putting a tilda '~' in front of the class name (~MyClass() {}). Destructors aren't the best place to put clean up code. This is because it is only called by the GC and you can't determine when it will be called (you can force it to be called, but that's not recommended).

Dispose:

The Dispose() method is simply a method you call manually to clean up yourobject. For this explicit clean up, .NET provides the dispose design pattern. Objects which need explicit clean up of unmanaged resources(connection object,File objects, etc..) implement the IDisposable interface. The IDisposable interface consists of the Dispose method, which unlike the Finalize method is under the control of the developer.

The recommended practice is to implement both Finalize as well as Dispose methods on an object which needs to clean up unmanaged resources. The Finalize method would serve as a backup mechanism in the event that the Dispose is never called. The garbage collector would perform the object finalization and prevent a permanent leak of the unmanaged resource.

Destructor and Forced Garbage Collection in .NET Framework

Destructor :

In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system. Destructor method is called only by .Net frameworks Garbage Collector (GC).

Forced Garbage Collection :

Foced Garbage collection is executed by means of calling System.GC.Collect() method. The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application(checking the references exist for an object).

class Person
{
public Person() //Constructor
{
Console.WriteLine("Person {0} constructor", GetHashCode());
}
~Person() //Destructor
{
Console.WriteLine("Person {0} finalizer", GetHashCode());
}
}



class GCDemo
{
static void Main(string[] args)
{
Person p = new Person(); // The constructor is invoked here.
p = null;
Console.WriteLine("The object p will not be used anymore ");
Person pc = new Person(); // The constructor is invoked here.
pc = null;
Console.WriteLine("The object pc will not be used anymore ");
GC.Collect(); // Force to collect.
Console.WriteLine("Now the carbage collection is called forcefully...");
GC.WaitForPendingFinalizers(); // Wait until it finish
}
}


Output:

Person 33156464 constructor
The object p will not be used anymore
Person 15645912 constructor
The object pc will not be used anymore
Now the carbage collection is called forcefully...
Person 33156464 finalizer
Person 15645912 finalizer

Conclusion:

  • Destructor methods are called after the garbage collection method executed.
  • Garbage collector destroys both person objects because reference "p" and "pc" is null.

Step by step process of getting connection string from web.config

Getting Connection string from web.config
In web.config file you find tag like this

<connectionStrings/>

We have to write a connection in connectionstring tag so that we can use in our application.

Steps are

1.replace <connectionStrings/> by

<connectionStrings>
</connectionStrings>

2.add connection string to this tag
Sql Authentication Connection,you have the user name and passwords of ur database

<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;User ID=databaseuserid;Password=databasepassword" providerName="System.Data.SqlClient"/>

Windows Authentication Connection default settings of Sqlserver2005

<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;integrated security=SSPI" providerName="System.Data.SqlClient"/>

Just u have to replace User ID=databaseuserid;Password=databasepassword to
integrated security=SSPI that’s all for Sql Authentication to Windows Authentication

It look like this

<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;User ID=databaseuserid;Password=databasepassword" providerName="System.Data.SqlClient"/>
</connectionStrings>

or

<connectionStrings>
<add name="ConnectionStringName" connectionString="Data Source=.\Sqlexpress;Initial Catalog=databasename;integrated security=SSPI" providerName="System.Data.SqlClient"/>
</connectionStrings>

3. Getting Connection from web.config using c#

Add fallowing Namespace to your application

using System.Web.Configuration;
using System.Data.SqlClient;

Code for getting connection

SqlConnection sqlConn = null;

String str=
WebConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString();

// Note:Ensure ConnectionStringName is same we mentioned in web.config file that all

sqlConn = new SqlConnection(str);
sqlConn.Open();

// do operation

sqlConn.Close();

Enjoy this coding…