Showing posts with label MCTS: 70-536. Show all posts
Showing posts with label MCTS: 70-536. Show all posts

Tuesday, May 15, 2012

Reference Types and Value Types

Reference Types (String + Object): String and Objects are reference Types.



When we create an Object of a class it gets stored on Heap and a pointer/reference is set on STACK which points to object.


E.g. Class A =new Class ();


In above example Object A is created in 2 steps


1. Class A; //Reference of Object A. At this time its value is set to null


2. A=new Class (); //Now Object A is created and at the same time reference A is pointing to created Object A.


From the above example we can say when we create an object of a class then the created object get stored on HEAP and at the same time reference of that object get stored on STACK.


Value Types: All types are value types except String and Objects.


Please follow below link for detail:

http://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types


Thursday, March 3, 2011

App Domain Logic

//1. What is application domain.?
//Ans: An application domain is a logical container that allows multiple assemblies to run
//e.g If 10 persons browse same website at a time than the worker process will create 10 app
//domain for individual user,they will be isolated from each other.
//Note: This could be also performed if 10 process will be start for execution of individual user
//but switching between the processes would consume processor time, thus decreasing performance.

//2. Show Logical diagram.
//!!Operating System---(Worker)Process-->.Net framework Runtime---1.App Domain----Assembly
//2.App Domain----Assembly

//3. Why use of application domain?
//Ans:Reliability--> Use application domains to isolate tasks that might cause a process to terminate.
//If the state of the application domain that’s executing a task becomes unstable, the application domain can be unloaded without affectingthe process.
//This technique is important when a process must run for long periods without restarting. You can also use application domains to isolate tasks that should not share data.
// Efficiency--> If an assembly is loaded into the default application domain, the
//assembly cannot be unloaded from memory while the process is running. However,if you open a second application domain to load and execute the assembly,
//the assembly is unloaded when that application domain is unloaded. Use this technique to minimize the working set of long-running processes that occasionally
//use large dynamic-link libraries (DLLs).

//Creating a new Application domain
AppDomain d = AppDomain.CreateDomain("Loader");

//Below is the example of creating application domain inside a assembly and running a different assembly in that app domain
//In that manner increasing the security.
MessageBox.Show("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
MessageBox.Show("Child domain: " + d.FriendlyName);
//1. Executing an assembly in seperate application domain by path
d.ExecuteAssembly(@"C:\Documents and Settings\BS26691\Desktop\SampleEXE\SampleEXE\bin\Debug\SampleEXE.exe");
//Executing the assembly by name.
//d.ExecuteAssemblyByName("SampleEXE");
//Unloading the created one Application domain
AppDomain.Unload(d);

//============================Theory OF securing an Assembly via access rights===============================
//1. Define "EVIDENCE" & "CODEGROUP".
//Ans 1:EVIDENCE: It says about the code group.
//Ans 2:CODEGROUP: It tells about the access rights (privelages)of assembly i.e it requires admin right or something else?
//Note: Providing evidence to an assembly means talking about access rights of that assembly.

//2. How to provide an evidence to a assembly?

//Note : The simplest way to control the permissions assigned to an assembly in an application
//domain is to pass Zone evidence by using a System.Security.Policy.Zone object
//and the System.Security.SecurityZone enumeration. The following code demonstrates
//using the Evidence constructor that requires two object arrays by creating a Zone
//object, adding it to an object array named hostEvidence, and then using the object
//array to create an Evidence object named internetEvidence. Finally, that Evidence object
//is passed to the application domain’s ExecuteAssembly method

object[] hostEvidence = { new Zone(System.Security.SecurityZone.Internet) };
// { new Zone(System.Security.SecurityZone.Intranet)};
// { new Zone(System.Security.SecurityZone.MyComputer )};
// { new Zone(System.Security.SecurityZone.Trusted )};
// { new Zone(System.Security.SecurityZone.Untrusted)};
Evidence evd = new Evidence(hostEvidence, null);
//Creating a new Application domain
AppDomain d1 = AppDomain.CreateDomain("Loader");

d1.ExecuteAssembly(@"C:\Documents and Settings\BS26691\Desktop\SampleEXE\SampleEXE\bin\Debug\SampleEXE.exe",evd );
//It will prompt a simple warning message , if we say untrusted instead of Internet zone than we will get access right issue.

AppDomain.Unload(d1);

Tuesday, October 19, 2010

Generics : Part 1

/*
* Note: Please replace "<" with ! and ">" with *
* Generics are Type safe means it gives warning at compile time only not at RunTime
*/
/*
* ================
* List!* generics
* ===============
*/
List !int* lstintCg = new List!int*();
lstintCg.Add(1);
List !string* lststrCg = new List!string*();
lststrCg.Add("1");
/*
* ================
* SortedList!* generics
* ===============
*/
SortedList !int, string* slst = new SortedList !int, string* ();
slst.Add(1, "Value_1");
/*
* ================
* Dictionary!* generics
* ===============
*/
Dictionary !int, string* dict = new Dictionary!int, string*();
dict.Add(26691, "bimlesh.singh@aexp.com");
foreach (KeyValuePair !int,string* kvp in dict)
{
Console.WriteLine("Key : {0}\n value :{1}",kvp.Key,kvp.Value );
}
Console.Read();

Monday, October 18, 2010

Collections:Part 3

/*
* BitArray Class is derived from the System.Collections.generics
* it supports AND,OR ,XOR Opertaions
* It is used for storing just boolean value.
* It doesn't have Add or remove method like any another Collections.
*/
BitArray btArray1 = new BitArray(3);
btArray1[0] = true;
btArray1[1] = false;
btArray1[2] = true;
BitArray btArray2 = new BitArray(3);
btArray2[0] = true;
btArray2[1] = false;
btArray2[2] = true;
/*
* Note : if you want to change the length of the Array just set its length propery.
* =========================
* Conditions 1
* ==============================
BitArray bitXOR = btArray1.Xor(btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: False,false,false
==============================
* Condition 2
======================================
BitArray bitXOR = btArray1.And (btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
*o/p: True,false,True
*

BitArray bitXOR = btArray1.Or(btArray2);
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: True,false,True
==============================
* Condition 3
======================================

BitArray bitXOR = btArray1.Not();
foreach (object bit in bitXOR)
{
Console.WriteLine(bit.ToString());
}
* o/p: false,true,false
*/
Console.Read();

Collections: Part 2

/*Note:
* For small Collection we generaly use ListDictionary
* For Large Collections we use HashTable
* The Best Part is to use HybridCollections it is the remedy of the above issues
*/

Hashtable hTable = new Hashtable();
hTable.Add("a",1);
hTable.Add("b", 2);
hTable.Add("c", 3);
/*
* In the above there will be no Ordering of Sequence.
* foreach (object hs in hTable.Values )
{
Console.WriteLine("Key Values are : {0}",hs.ToString());
* o/p=1,3,2
}
*/
SortedList slist = new SortedList();
slist.Add("a", 1);
slist.Add("c", 2);
slist.Add("b", 3);
/*
* Bydefault ordering is ascending
* you Can Sort by Key and Value both.
* foreach (object sls in slist.Values )
{
Console.WriteLine("Key Values are : {0}",sls.ToString());
* o/p=1,2,3
}
*/
/*==============================================================
*Note:CommonUtilClass and StringComparer Class
*==============================================================
*/
/*
* Hashtable and Sorted List are CaseInsensitive
* To make it Case Sensitive Use CollectionsUtil CollectionsUtil.CreateCaseInsensitiveHashtable();
* Use NameSpace :using System.Collections.Specialized;
* Note : In The below Case It will through an error.
* Since it is having Same Ket a & A.
*/

Hashtable hTable = CollectionsUtil.CreateCaseInsensitiveHashtable();

hTable.Add("a", 1);
hTable.Add("A", 2);
hTable.Add("c", 3);

/*
* For Making HashTable Invariant Culture u Should use below code.
*/
Hashtable hash = new Hashtable(StringComparer.InvariantCulture);
SortedList list = new SortedList(StringComparer.InvariantCulture);


Queue q = new Queue();
q.Enqueue("First");
q.Enqueue("Last");
//Console.WriteLine(q.Dequeue());
//O/p : First

Stack st = new Stack();
st.Push("1");
st.Push("6");
st.Push("2");
//Console.WriteLine(st.Peek());
//Console.WriteLine(st.Pop());
//O/p: 2
//O/p: 2

/*
* With NameValue Collection we can use same key Name for using multiple values.
*/
NameValueCollection nvc = new NameValueCollection();
nvc.Add("Same_key","Value_1");
nvc.Add("Same_key", "Value_2");

foreach (object obj in nvc.GetValues("Same_key"))
{
Console.WriteLine(obj);
//o/p: Value_1,Value_2
}
Console.Read();

Thursday, October 14, 2010

Collections: Part 1

/*
*Name Space Required using System.Collections;
*This is an example of Arraylist
*/
ArrayList objArrlst = new ArrayList();
string[] arr = { "ID: 1","Domain: BNFS"};
objArrlst.Add("Name: Bimlesh Singh");
objArrlst.AddRange(arr);
objArrlst.Insert(0, "EMP Detail");
/*method 1.
* This is a way of Iterating through a Arraylist.
* With the help of IEnumerator Interface's GetEnumerator method which returns a Interface IEnumerator.
*/

objArrlst.Add(1);

IEnumerator Ienum = objArrlst.GetEnumerator();
while (Ienum.MoveNext())
{
Console.WriteLine(Ienum.Current );
}
/*method 1.
* This is a way of Iterating through a Arraylist with the help of Foreach loop.
* if we use foreach (String objstr in objArrlst)below it will through a casting error.
*/

foreach (Object objstr in objArrlst)
{
Console.WriteLine(objstr);
}

objArrlst.Remove(1);
/*
* Comparer Class is used for in the ArrayList.Sort method to do the default sorting.
* It is the default implementation of the IComparer implementation
*/
objArrlst.Sort();
Console.Read();

Friday, October 8, 2010

Type of GLOBALIZATION CultureInfo Class & enum CultureTypes


Culture can be classified in 3 groups
1. Invariant Culture
2. Neutral Culture
3. Specific Culture


NEUTRAL vs. SPECIFIC:
Neutral Culture contains only Language not region or Country
e.g English (en), French (fr), and Spanish (sp).

Specific Culture contains detail of both Language and region.
e.g en-US(English in United States),es-US etc.

Note : For getting the Current Culture
CultureInfo cInfo = Thread.CurrentThread.CurrentCulture;
Console.WriteLine("Name {0}",cInfo.Name);

//O/P->en-US
Console.WriteLine("Display Name {0}", cInfo.DisplayName);
//O/P->English
Console.WriteLine("Native Name {0}", cInfo.NativeName);
//O/P->English
Console.WriteLine("TwoLetterISOLanguageName {0}", cInfo.TwoLetterISOLanguageName);
//O/P->en
Console.Read();

NOTE : CurrentUICulture must be set at the application’s startup

CultureInfo cInfo = Thread.CurrentThread.CurrentUICulture;
Result will be same like above.

The CurrentCulture can be manipulated at any time during execution. However, this is not the case
With the CurrentUICulture. To be used correctly, the CurrentUICulture must be set at the onset of the
application (ideally in the Main method) or in a form’s constructor. Failure to do so can result in unexpected behavior.


CultureTypes is a enumType & it is Used with the GetCultures() function.
e.g
CultureTypes.AllCultures;
CultureTypes.FrameworkCultures;
CultureTypes.NeutralCultures ;
CultureTypes.SpecificCultures;


Sample Code

foreach (CultureInfo UsersCulture in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
{
Console.WriteLine("Culture: " + UsersCulture.Name);
}
Console.Read();

Sample Example :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Windows.Forms;
using System.Threading;
namespace Globalization_Part1
{
/*
* Step 1. create a window applicatio.
* Add a comboBox and set its ID =cbCulture
* Add three labels set the ID and text of all the labels.
*/

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*
* Fill the comboBox at Form intialization
*/

foreach (CultureInfo UsersCulture in CultureInfo.GetCultures(CultureTypes.SpecificCultures ))
{
cbCulture.Items.Add(UsersCulture);
}
Console.Read();
}

private void button1_Click(object sender, EventArgs e)
{
if (txtCurrency.Text == "")
{
MessageBox.Show("Please supply a numeric value to currency e.g 1000"); }
else
{
//select the comboBox selected value
object val = cbCulture.SelectedItem;
CultureInfo cinfo = new CultureInfo(val.ToString());
Thread.CurrentThread.CurrentCulture = cinfo;
double cuurency = Convert.ToDouble(txtCurrency.Text);
//Set the currecy and dateTime with CultureInfo class setting.
lblCurrency.Text=cuurency.ToString("C", cinfo);
lbldate.Text = DateTime.Now.ToString(cinfo);
txtCurrency.Text="";
}
}
}
}


Points to be Remembered.
1. For creating a custom culture you should have to use CultureAndInfoBuilder Class.

2. Different Culture has different sorting and comparision rules.
to make a consistent sorting and comparision u should have to use CultureInfo.InvariantCulture.

3. In Formatting o/p ToString() and dateTime() helps.

Thursday, October 7, 2010

Explicit Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interface_Example
{
public interface IEditPicture
{
void Paint();

}
public interface IEditImage:IEditPicture
{
//This will hide the method of IEditPicture's
new void Paint();
}
public interface IDrawing : IEditPicture
{
//Bydefault this will hide the IEditPicture's Method
void Paint();
}

public class Studio : IEditImage,IDrawing
{
/*
* For Explicit declaration of Interface don't use any access modifier
* InterfaceName.methodName() will be written instead of writting direct method name
*/

//This is IEditImage Method
void IEditImage.Paint()
{
Console.WriteLine("Paint Method of {IEditImage}");
}

//This is IDrawing Method
void IDrawing.Paint()
{
Console.WriteLine("Paint Method of {IDrawing}");
}


//This is IEditPicture Method
void IEditPicture.Paint()
{
Console.WriteLine("Paint Method of {IEditPicture}");
}

//This is Class Method
public void Paint()
{
Console.WriteLine("Paint Method of Studio Class" );
}

}


class Program
{
static void Main(string[] args)
{
Studio sd = new Studio();
((IEditImage)sd).Paint();
((IDrawing)sd).Paint();
((IEditPicture)sd).Paint();
//This will call method of Studio Class
sd.Paint();
Console.Read();
}
}
}

Implicit Interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Interface_Example
{
public interface IEditPicture
{
void Paint(string ID);

}
public interface IEditImage:IEditPicture
{
//This will hide the method of IEditPicture's
new void Paint(string ID);
}
public interface IDrawing : IEditPicture
{
//Bydefault this will hide the IEditPicture's Method
void Paint(string ID);
}

public class Studio : IEditImage,IDrawing
{

public void Paint(string ID)
{
Console.WriteLine("Paint Method of {0}",ID );
}

}

public class Bollywod :Studio
{
//This will use internally New keyword and hide the method of Studio Class.
public void Paint(string ID)
{
Console.WriteLine("Paint Method of {0}", ID);
}

}
class Program
{
static void Main(string[] args)
{
Studio sd = new Studio();

((IEditImage)sd).Paint("IEditImage");
((IDrawing)sd).Paint("IDrawing");
((IEditPicture)sd).Paint("IEditPicture");
//This will call method of Studio Class
sd.Paint("Class Studio");
Bollywod bd = new Bollywod();
//This will call method of Bollywod Class
bd.Paint("Bollywod");
Console.Read();
}
}
}

Wednesday, October 6, 2010

Reference Type Example

Notes on Refernce Type.
e.g Class, String, Array,Exception etc.
1. Conventionally, the term object refers to an instance of a reference type, whereas the term value refers to
an instance of a value type, but all instances of any type (reference type or value type) are also derived from type
object.

2. Reference of a object stores in Stack but Actual object stores on Heap
//Both the below references 'a' & 'b' will be stored on Stack
CLassA a;
ClassA b;

//Both the below object 'aa' & 'bb' will be stored on Heap.

ClassA aa=new ClassA();
ClassA bb=new ClassA();


IMMUTABLE vs MUTTABLE:
string name = "Bimlesh";
name += "Kumar";
name += "singh";
//In this scenerio 3 copy of name will be created and last one will be latest one.
//name="Bimlesh";
//name="Bimlesh Kumar";
//name="Bimlesh Kumar Singh";

//To avoid this use either StringBuiler or join/Concat/FormatString
Console.WriteLine(name);

StringBuilder sb = new StringBuilder("Bimlesh");
sb.Append("Singh");
Console.WriteLine(sb.ToString());
Console.Read();

Value Type Example

enum Tasks
{
Mr, Mrs, Miss
// Mr=5, Mrs, Miss=2
};
//IN the above case int value will be 0,1,2
//And in commented peace of code value will be 5,6,2

/*The enum type must be byte, sbyte, short,ushort, int, uint, long, or ulong.
**********
* if we will not give the type it will take bydefault as Int
* e.g
enum Tasks:long
{
Mr=500,
Mrs,
Miss

};
**********
*/


class Program
{
static void Main(string[] args)
{
//============================Value Type Classification================================
//1. Built in Type: e.g int16,int32,decimal,system.char,double,boolean,datetime etc.
//2. User Defined Types: Structure
//3. Enums
//Note: 1> All value type stores in stack it takes small memory
// 2> Uint32 for all positive whole numbers
// 3> String() is a method derived from Syste.object all value types are derived from the same base class.

//============example on built in Value Types===========================
// Nullable b ;
//OR
bool? b;
b = true;
//Has value checks for nullability
if (b.HasValue)
{
Console.WriteLine("B has Proper Value i.e {0} ", b);
}
else
{
Console.WriteLine("B is having Null Value");
}

//=========================Enumerations Example===================
Tasks tsk = Task.Mr;

Console.WriteLine("B has Proper Value i.e {0} ", tsk.ToString());
//O/p: Mr
Console.WriteLine("B has Proper Value i.e {0} ", i);
//O/P: 1
Console.Read();
}
}