Friday, July 31, 2009

Web site vs Web Application

visual studio 2003 : Introduced Web Application model .
Note :It has static Compilation

Visual studio 2005 : Introduced WebSite project type was introduced .
Note :
  • It contains both web Application Model and webSite model.
Visual studio 2008 : Supports both types of project

Web Site model and Web Application

  • And is based on folder model .After SP1 project file was introduced in visual studio 2005.
  • WebApplication project is more structured than web site project.
  • Class file shuuld be placed inside the App_Code.
  • Web Application project type is restricted to one language .Where as web site supports multiple languages,Because web site is compiled dynamically.
  • web site supports multiple lanuages files ,but those files need to be in the same folder .So the changes required in the webconfig.
E.g:



  • When deploy web Applicaton you can just copy the compiled elements and visual elements to the iis folder..Where as website we need to copy everything to the iis to work.
  • Code behind pages was introduced in visual studio 2005.Where we can create both the files(with code behind and with out code behind paes)
  • Partial class was also introduced in visual studio 2005
Dynamic compilation in Website

When you sent a request for a ASP.Net page,Frame work checks for the corresponding page and if the class is not exists ,Frame work compiles the page into a new .Net class and the stored the compiled class into the temporary ASP.Net folder located at

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

In future if a request comes to the same page ,the page is not compiled again .The previously compiled class is executed and returns to the browser.This process is called ASP.Net dynamic compilation.
If Asp.Net page is modified corresponding to .Net class is automatically deleted and when a new request comes for that page it compiles the modified page into a new .Net class.

To change compiled in Web site are as follows as

  • change the compilation mode using the page
E.g:




  • To change compilation mode using webconfig
E.g :



Thursday, July 30, 2009

To get the microsecond in C#

"ffffff" format string is to represent microseconds in C#

E.g :DateTime.Now.ToString("HH:mm:ss.ffffff")

To find server address using sql server 2005

@@ServerName :returns the name of the local server that is running in sql server.

more details

Monday, July 27, 2009

Common Table Expression(CTE) and ROW_NUMBER()

can be thought of as a temporary result set that is defined with in the execution of the scope of a single select,insert,update,delete or create view statement.

A CTE can be used to :

  • create a recursive query .
  • substitute for a view when the general use of a view is not required ,that is you dont have to store the definition in metadata
  • enable grouping by a column that is derived from a scalar subset ,or a function that is not deterministic or has extrenal access.
  • reference the resulting table multiple time in the same statement.
Syntax

with expression_name [(column name [,....n])]
AS
(CTE query definition)

E.g :with [EMP_SCHED order by rowid] as
(select row_number() over (order by emp_id asc) as rowid ,* from EMP_SCHED)
select * from [EMP_SCHED order by rowid] where rowid=3

Row_Number()

Returns the sequential number of a row with in a partition of a result set ,starting at 1 for the first in each partition

Syntax
ROW_NUMBER() OVER ([ ] )

E.g :with [EMP_SCHED order by rowid] as
(select row_number() over (order by emp_id asc) as rowid ,* from EMP_SCHED)
select * from [EMP_SCHED order by rowid] where rowid=3

Sunday, July 26, 2009

Collections in C# 2 Part 1

Collections is introduced in C# 2 . To make the strongly typed collections

C#1 : it contains array list not collections class

Disadvantage of Arraylist
  • arraylist has no compile time information.If any mismatch type is there error will throw at runtime only.(It is weekly typed collection)
E.g :public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
}
public class program
{
public static void Main()
{
ArrayList al = new ArrayList();
al.Add(new Employee("Anish", 20000m));
al.Add(new Employee("marokey",30000m));

foreach (Employee emp in al)
{
Console.Write(emp.Name);
Console.Write(emp.Salary);
Console.WriteLine();
}
}
}
Result : Anish20000
marokey30000

Just look the below code produce no error at compile time but throws error at runtime
public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
}
public class program
{
public static void Main()
{
ArrayList al = new ArrayList();
al.Add(new Employee("Anish", 2000m));
al.Add(new Employee("marokey",30000m));
al.Add("Error");

foreach (Employee emp in al)
{
Console.Write(emp.Name);
Console.Write(emp.Salary);
Console.WriteLine();
}
}
}

Error : Unable to cast object of type 'System.String' to type 'dummy.Employee

Array list allows all items .It doesnot consider about the item

To avoid these types of error collection class is introduced .

public class Employee
{
string name;
public string Name
{
get{return name;}

}
decimal salary;
public decimal Salary
{
get{return salary;}
}
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}

public Employee(string name)
{
this.name = name;
}
}
public class program
{
public static void Main()
{
List empList = new List();
empList.Add(new Employee("Anish", 2000m));
empList.Add(new Employee("marokey", 30000m));
empList.Add("Error");
}
}

During compile time itself it throws error
Error 1 :The best overloaded method match for 'System.Collections.Generic.List.Add(dummy.Employee)' has some invalid arguments
Error 2 : cannot convert from 'string' to 'dummy.Employee'

Note : This is known as strongly typed collections


Collection Class

1)ArrayList : A simple resizeable ,indexbased collection of objects
2)SortedList : A sorted Collection of name/value pairs.And accessible by key and by index

E.g : static void Main()
{
SortedList sl = new SortedList();
sl.Add("maorkey",0);
sl.Add("Anish",1);

Console.WriteLine( sl.GetKey(1));
}

Note :When it creates a list it automatically sort the data based on the object key.
It wont allow redundant values.

E.g: static void Main()
{
SortedList sl = new SortedList();
sl.Add("Anish",0);
sl.Add("Anish",1);

Console.WriteLine( sl.GetKey(1));
}

//Error (Item is has already been added)

3)Queue : Represent the first-in-first-out collection of objects

static void Main()
{
Queue myQ = new Queue();
myQ.Enqueue("a");
myQ.Enqueue("n");
myQ.Enqueue("i");

Console.WriteLine(myQ.Dequeue());
Console.WriteLine(myQ.Dequeue());
Console.WriteLine(myQ.Dequeue());
}

Result : ani (FIFO manner)


Better way of using Queue is generic Queue

E.g : static void Main()
{
Queue smyQ = new Queue();
smyQ.Enqueue("a");
smyQ.Enqueue("n");
smyQ.Enqueue("i");

Console.WriteLine(smyQ.Dequeue());
Console.WriteLine(smyQ.Dequeue());
}

Note : This queue allows only sting to iterate.
4)Stack : Last in First out non generic collection of objects

static void Main()
{
Stack sTack = new Stack();
sTack.Push("a");
sTack.Push("n");
sTack.Push("i");

Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
}

Result : ina(LIFO manner)

Generic Stack is the better way of using

static void Main()
{
Stack sTack = new Stack();
sTack.Push("a");
sTack.Push("n");
sTack.Push("i");

Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
Console.WriteLine(sTack.Pop());
}

5)HashTable : A collection of name/value pair of objects that allow retrieval of name or index

E.g: static void Main()
{
Hashtable openWith = new Hashtable();
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");


Console.WriteLine();
foreach (DictionaryEntry de in openWith)
{
Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
}

Generic HashTable is not there .Because it takes Object as value and key.Dictionary class can act as generic hashTable not Exactly.Because there we can set the object key and value.

6)BitArray :compact array of bit values ,Which as represent as Boolean.

static void Main()
{


BitArray myBA1 = new BitArray(5);
Console.WriteLine("myBA1");
Console.WriteLine(" Count: {0}", myBA1.Count);
Console.WriteLine(" Length: {0}", myBA1.Length);
Console.WriteLine(" Values:");
PrintValues(myBA1, 8);
}

public static void PrintValues(IEnumerable myList, int myWidth)
{
int i = myWidth;
foreach (Object obj in myList)
{
if (i <= 0)
{
i = myWidth;
Console.WriteLine();
}
i--;
Console.Write("{0,8}", obj);
}
Console.WriteLine();
}
}

7)Stirng Collection : It allows null and duplicate values


static void Main()
{


StringCollection myCol = new StringCollection();

// Add a range of elements from an array to the end of the StringCollection.
String[] myArr = new String[] { "RED", "orange", "yellow", "RED", "green", "blue", "RED", "indigo", "violet", "RED" };
myCol.AddRange(myArr);
PrintValues1(myCol);
}


public static void PrintValues1(StringCollection myCol)
{
foreach (Object obj in myCol)
Console.WriteLine(" {0}", obj);
Console.WriteLine();
}

8) StringDictionary :collection of name/value pair .It can retrieve by name or index.It is strongly typed .


static void Main()
{


StringDictionary myCol = new StringDictionary();

// Add a range of elements from an array to the end of the StringCollection.
myCol.Add("red", "0");
myCol.Add("blue", "1");
myCol.Add("green", "2");
PrintKeysAndValues1(myCol);
}


public static void PrintKeysAndValues1(StringDictionary myCol)
{
Console.WriteLine(" KEY VALUE");
foreach (DictionaryEntry de in myCol)
Console.WriteLine(" {0,-25} {1}", de.Key, de.Value);
Console.WriteLine();
}
9) List directory :An efficient collection to store small list of objects .
It is smaller and faster than the HashTable .If the number of element is 10 or less.

10)HybridDictionary :Using a ListDictionary while collection is small and it switches to HashTable when he collection is large.

11)NameValueCollection :Collection of name/ value pairs . It is less performance than HashTable.


Saturday, July 25, 2009

Set single user mode in sql server 2oo5

The single user-mode specifies that only one user at a time can access the database and is generally used for maintenance actions

To set by using SQL query
Set single user mode

ALTER DATABASE [DATABASENAME] SET SINGLE_USER WITH NO_WAIT

Set back to multi user

ALTER DATABASE [DATABASENAME] SET MULTI_USER WITH NO_WAIT

Friday, July 24, 2009

Implict vs explict

Implicit : something is being done automatically
Explicit : have to write something in the source code to indicate what to happen


E.g: int i =20;
long y =i // Implicit conversion from int to long
int z = (long)y // Explicit conversion from long to int

Guidelines for Names(taken from MSDN)

Cast Style
Pascal Casting : First letter in the identifier and the first letter of each subsequent concatenated word are capitalize.Use Pascal case for identifiers for three or more characters .

E.g: BlackColor

Camel Casting : first letter of identifier is lowercase and first letter of each subsequent concatenated word is capitalize

E.g: blackColor

UpperCase :All the letters in the identifiers are capitalized.

E.g : IO

For more details MSDN


Thursday, July 23, 2009

Change schema on table and proc in SQL SERVER 2005

To change the schema table from one to another is by executing the query

select 'ALTER SCHEMA dbo TRANSFER ' + s.Name+ '.' + p.Name
FROM sys.tables p
inner join
sys.Schemas s on p.schema_id = s.schema_id


Result :
  • ALTER SCHEMA dbo TRANSFER aniSchema.video_master
  • ALTER SCHEMA dbo TRANSFER aniSchema.enquiry_master
  • ALTER SCHEMA dbo TRANSFER aniSchema.blog_master
Copy the result and execute the result in new query then the schema(aniSchema) is changed to dbo .

OR
For tables and views

SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'aniSchema'

And do the above step after getting the result

Sunday, July 19, 2009

Visual Studio Short Cut Keys

Shortcut keys are easy to navigate,Increase productivity ,etc .... :)

These are the short cut keys i like in visual studio

  • To understanding the code
Class view : [ctrl-w] ,[ctrl -c]
Note : helps to see the class view.
Create Class diagram (by adding .cd file to the project)
Note : This will display the class diagram created.copy and paste the necessary methods ,properties from one class to another class.

  • Navigate through code

F12 : GoTODefinition
shift -F12 : Show all the reference to a symbol
F8:Cycle through list of items in the currently active output window
shift - F8 : same as F8 but opposite in direction

ctrl - m ,ctrl- m: collapses /expand the method the cursor is currently in
ctrl -m,ctrl-o : collapse all methods to the outline view

ctrl - -(minus) : moves to the cursor previous location
ctrl - shift - -(minus) :moves to the cursor last location

ctrl - F :find menu
ctrl - H : find and replace
ctrl - i :incremental search
ctrl - shift - F : find in all files

  • Modify code

ctrl -k, ctrl - c : command out the selected code
ctrl -k ,ctrl - u : uncommand out the selected code
ctrl-k ,ctrl -f :auto format the selected code

ctrl - R ,ctrl - M :extract method
ctrl -R,ctrl - E :encapsulate field
ctrl- R ,ctrl -l :extract interface
F2 :Rename

  • Debugging code

F10 :step over
ctrl - F10 :Run to cursor
F11 :step into
shift - F11 : step out
F9:toggle a break point
F5 :Run with debugging
Shift - F5 :stop debugging
ctrl-F5 :Run without Debugging


Saturday, July 18, 2009

ER Diagram in Sql server 2005

To see the ER diagram for sql server 2005.
  • Right click the Database Diagrams on the particular table and select new database diagram
Error i Got

Database diagram support objects cannot be installed because this database does not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or the ALTER AUTHORIZATION statement to set the database owner to a valid login, then add the database diagram support objects.

How i Solved

  • Right on database ,Choose properties
  • Go to options menu
  • check whether the compatibility level :SQL Server 2005(90)
  • Click ok
Still i got the same error . After that i executed
ALTER AUTHORIZATION ON DATABASE::DatabaseName TO sa

Every thing working fine and i got ER diagram




Joining two tables Using UNION

two tables
//No Error
select Fname,Lname from tbl_Master
union
select Fname,Lname from tbl_Master



Two proc
//Error
exec SPtbl_Master1
union
exec SPtbl_Master2



Two Table-valued Functions
//No Error
select * from Fntbl_Master1('p')
union
select * from Fntbl_Master2('p')


charindex Vs patindex

charindex : Returns the starting position of the first occurrence of a pattern in a specified expression ,or zero if the pattern is not matched

E.g: select charindex('+','anish+varghese')
Result : 6

patindex:Returns the starting position if found.And it can use wildcard characters

E.g: select patindex('%+%','anish+varghese')
Result : 6

Where is the difference ?
Actually patindex act as a like operator .

% : any string of zero or more characters
E.g : select charindex('%+%','anish+varghese')
Result : 0
E.g: select patindex('%+%','anish+varghese')
Result : 6
E.g :select patindex('%+','anishvarghese+')
Result :14
E.g:select patindex('+%','+anishvarghese')
Result :1

_(underScore) :any single character

E.g:select patindex('%_r%','anishvarghese')
Result :7

[ ] : Any single character with in the specified range [a-z] or ser [abcd]

E.g:select patindex('%[0-9]%','anish4varghese')
Result:6
[^] :Any sigle character not with in the specified range [^a-z] or set [^abcd]
E.g:select patindex('%h%','anish4varghese')
Result :5
E.g:select patindex('%h[^4]%','anish4varghese')
Result :11


Monday, July 13, 2009

Implicitly Type local variable

The Implicitly Type local variable being declared is inferred from the expression used to initialize variable.

E.g : var i =10;
var s="anish";

Note : it can be a anonymous type ,user defined type or FCL(frame work class library) type etc.But the compiler determines the type.

E.g: var i =10//implicitly typed
int i=10//Explicitly typed

collection Initializers in .Net 3.0

.Net offers a new features of initializing objects.

class people
{
public string FirstName { get; set; }
public string LastName { get; set; }
}



class main
{
static void Main()
{
//Method 1:Adding people to List
people People = new people();
List Names = new List();
People.FirstName = "Anish";
People.LastName = "Varghese";
Names.Add(People);
People.FirstName = "ani";
People.LastName = "marokey";
Names.Add(People);

//Method 2:Adding people to List
List Names1 = new List();
Names1.Add(new people { FirstName = "Anish", LastName = "Varghese" });
Names1.Add(new people { FirstName = "ani", LastName = "marokey" });

//Method 3:Adding people to List
List Names2 = new List()
{
new people{FirstName="Anish",LastName="Varghese"},
new people{FirstName="ani",LastName="marokey"}
};
//Method 4 :Adding people to List

List Names3 = new List { new people { FirstName = "Anish", LastName = "Varghese" }, new people { FirstName = "ani", LastName = "marokey" } };
}

Note :where we can use is a class has no default constructor and initialization is required.



Type Safe in C#

When casting from one type to another.C# compiler will check whether the casting wont cause any problem .Then only the casting will happen other wise it throw error "InvalidCastExpression" . This is why .Net is type safe.

We can freely cast form a derived class to a base class .But we cannot blindly convert a base class to a derived class.

E.g1 :
object obj = new object();
string s = (string)obj;
//Error "Unable to cast object of type 'System.Object' to type 'System.String' "

Note : Because system.String is derived from system.Object(base class of .NET ).i.e we are converting from a base class to derived class.

Object obj = "foo";
string str = (string)obj;
//No error

Note : we are converting derived class to a base class.

E.g2:
class classA
{

}

class classB:classA
{
}

class main
{
public static void Main()
{
classA a = new classA();
classB b = (classB)a;
//Error " Unable to cast object of type 'Console_Anisj.classA' to type 'Console_Anisj.classB' "

}
}

Note : Because classB is derived from ClassA.i.e we are converting from a base class to derived class.

class classA
{

}

class classB:classA
{
}

class main
{
public static void Main()
{
classB b = new classB();
classA a = (classA)b;
}
}

Note : we are converting derived class to a base class.

Why this is compailing ?
During compile time compiler checks whether the classA and classB is derived from System.Object class.So it wont throw any error.During run time it will check the base class and derived class.This is the reason the error is throwing in the runtime.

Best way to check the casting by using is and as operator in C#

object obj = new object();
System.Boolean b1 = (obj is System.Object);
System.Boolean b2 = (obj is System.String);

Note : here b1 is true and b2 is false.


classA a = new classA();
classB b = new classB();
System.Boolean b1 = (a is classB);
System.Boolean b2 = (b is classA);

if(b2)
{
classB b = new classB();
classA a = (classA)b;
}

Note : here the b1 is false and b2 is true .CLR wants to check the type twice one out side the
if loop and one inside the if loop. so introduced the new concept as "as"operator.

classA a = new classA();
classB b = new classB();
classA a1 = b as classA;
classB b1 = a as classB;
if (a1 != null)
{
classA a2 = (classA)b;
}
if (b1 != null)
{
classB b2 = (classB)a;
}

Note :if the type can be casting then it returns not null pointer and if it returns null it cannot be cast.CLR wants to check the type only once.so it improve the performance.





Friday, July 10, 2009

Deploy Asp.Net application using "compilation debug="false"

If you are deploying using compilation debug="true".The following will happen.
  1. The compilation of ASP.NET pages takes longer
  2. Code executes slower
  3. Memory useage will be high .during run time
  4. Scripts and images download from the webresourcre.axd handler are not catched
Note:the last point is important.If you are using external scripts(javascript ,css etc ). "" webresourcre.axd handler automatically set long cache for on the resources retrieved via it.So that the resource is only downloaded once to the client and catched there forever.

For more details click Here

CLR Profiler

CLR Profiler: this allows developers to see the allocation profile of their managed code

Note :if you love your memory space of your server try this .For more details click here .This link is for .NET Framework 2.0. How to use CLR Profile .See the read me file that is included in the Zip.

Thursday, July 9, 2009

Content delivery Network

Content Delivery Network(CDN) is a collection of web server distributed across multiple location to deliver content more efficiently to users.The server is selected for delivering content to a specific user is typically based on the measure of network work proximity.

E.g:the server with fastest network hops or the server with the quickest response time is chosen.

CDN service provide companies : Akamai Technologies,Mirror Image Internet or limelight networks.

Google Chrome OS is comming

Google is also comming with there latest OS (open source) into the market.
  • It will run with a Linux kernel as its base
  • It will boot directly into the Chrome Web browser
  • It will be aimed primarily at netbooks
  • It will run on both x86 and ARM processors
  • It will not be designed to have local storage; all data will be stored in the cloud
  • Google will not entice developers to build software to run on the Chrome OS; instead, they want them to build Web apps that will run on any standards-based browser
  • The three most important features will be “speed, simplicity and security,” according to Google
  • Google will release the software to the open source community before the end of 2009
  • Announced Chrome OS hardware partners: Acer, Adobe, ASUS, Freescale, Hewlett-Packard, Lenovo, Qualcomm, Texas Instruments, and Toshiba.
  • Netbooks running Chrome OS will be available in the second half of 2010
For more details Read

Wednesday, July 8, 2009

sp_spaceused system procedure

This will tells whatt is the physical space used by the system and the objects

exec sp_spaceused 'databasename'

for more details Click Here

Cryptographic Serivce Providers

It is a software library that implements the cryptographic serverce Programming interface .CSPs are responsible for encryption and decryption .

CSP : Are independent modules that can be used by different algorithms .A user wants to call the CSP .CSP are responsible for implementing cryptographic alrorithms.

Note:some of the special types of DLL are implemented by CSP.In delay sigining Microsoft uses CSP ,siginal varifies when windows load the CSP.
: CSP are the "containers" that abstract the location of these keys.When it loads the key grabed from the CSP container.
:If private/Public key pairs in a CSP container donot use the AssemblyKeyFileAttribute or AL.EXEs /Keyf[ile].Insted it uses the system.Reflection.AssemblyKeyNameAttribute or AL.EXEs /keyn[ame](takes the name of the key container in CSP)

C# allows Passing Parameters by reference

By default CLR assumes that all the parameters to a method are value type.
C# allows pass parameter by reference type in two ways
  1. Ref :The caller must initialized the parameter's value to the method
E.g: Public static void RefAni(ref int iVal)
{
iVal+=2;
}
public static void Main()
{
int i=3; //i must be intialized
RefAni(ref i);
Console.Writeline(i);
}
Note : The i value is declared on the thread stack and initialized to 3.Address location of i is passed to RefAni method. RefAni iVal takes the value and new value is returned to the caller.
2.Out: The caller must not have to be initalized the parameter's value to the method
E.g:
Public static void OutAni(out int iVal)
{
iVal+=2;
}
public static void Main()
{
int i; //doesnot have to be intialized
OutAni(out i);
Console.Writeline(i);
}

Note : the i is declared on the thread stack .The address is then passed to the OutAni(here no values are comming).Inside the OutAni iVal is initailized to 2 and new value is returned to the caller.

Why ref and out is required ?
This is that the compailer want to do the right thing automatically.

Note : overloading is possiblie in this

E.g : Public static void OutAni(out int iVal)
Public static void OutAni(int iVal)
This will compile properly.

Tuesday, July 7, 2009

Command Line Tips

open command prompt and type the following ,Makes your work easy

enable firewall: netsh firewall set opmode mode = enable
disable firewall : netsh firewall set opmode mode =disable
change command line title :title new_window
computer name :hostname
os version :ver
logoff system :logoff
to see date :date

Windows XP Shortcut Keys

In Run

Devenv : Open visual studio
ssmsee : Open sql server management studio expression edition
Control : Open control panel
services.msc : open windows services
appwiz.cpl : add/Remove programs
mspaint : Open paint
iexplore.exe : open internet explore
safari : open safari browser
firefox : open mizilla browser
chrome : open chrome browser
perfmon.exe : Open performance moniter
shutdown -s -t 01 : Shutdown xp in 01 second
shutdown -s :shutdown
shutdown -r :restart
shutdown -a :abort shutdown
nero : open nero
outlook : open outlook express
winword : open word
assembly : Open GAC
cliconfg : open SQL Server Client Network
cleanmgr:open Cleanup Tool
userinit:open documents




Monday, July 6, 2009

Difference between Primary key and unique key?

Primary Key : Creates uniqueness for the column.And also creates clustered index on the column,by default

Unique Key :Creates uniqueness for the column.By default it creates a Non clustered index

To know more about Clustered index and non Clustered index.

Note : try to avoid using GUID as primaryKey (it will waste of your space (16 bytes)).If the database volume is high it will affect performance.if use int it will take less space(4 bytes).

Union and UnionAll

Union:its Like a join Command.When using the union all the selected columns need to be of the same datatype.Only distinct values are selected.

Union All :it almost like union.There is no distinct operation so it will take all the values.

Rules for Union
a union must be composed of two or more select statement and each is separated by a keyword union
Each union must contain same column,expression or aggregate function.
Column name need not be same ,but they must be the type that the sql can implicitly convert.

Friday, July 3, 2009

Value type can have an implict Constructor?

All the value type is initialized to zero or null.This is because it dont have a implict constructor.

ways you can define a variable

1) variable inside a Reference Type
ie
E.g:
Class c
{
int i;
};

test()
{
c C = new c(); //At this point GC will take care of it
}

Note : GC checks the variable is zero or NULL before releasing the variable from heap.

2) Inside Value type

struct structDemo
{
int i;
};
test()
{
c C = new c(); //At this point JIT will take care of it
}

Note : JIT checks inside the stack.if nothing is defined stack place occupied with zero labeled.
3)If value type has a value ,stack occupied with the that value as labled


Thursday, July 2, 2009

Linq(Language integrated Query) Part 1

LinQ
LinQ is tightly coupled to C# and VB

Imperative Programming language: Programmers want to describe the statement(C# and VB)

Declartive Programming language : In the case of SQL,the engine determines the physical strategy to retrive the logical request made in the form of a query.

Most mordern language supports RDBMS in their code,like Xml .But nothing was type safe.Microsoft solution is LinQ ,a type safe query.
Note : LinQ can be coded in Lambda syntax(Anonymous code blocks from functional programming Community ) and comprehension syntax.

Lambda Syntax : Normally takes => as expression.
How linq makes development Easy

Example 1 : without using LinQ

void NameContainsA()
{
List cell = new List ();

string[] Names = new string[]{
"Anish"
,"Varghese"
,"Linq"
,"Anish Varghese"};

for(int iCount=0; iCount<>
{
if(Names [iCount].StartsWith("A"))
{
cell.Add(Names[i]);
}
}

Example 2 : With LinQ

void NameContainsA()
{
List cell = new List ();

string[] Names = new string[]{
"Anish"
,"Varghese"
,"Linq"
,"Anish Varghese"};

cell = (from n in Names where n.StartsWith("A") select n).ToList();
}

Note : this makes the development very easy.

Example 3 : With Linq (above same example with less number of codes)

void NameContainsA()
{
List cell = new List ();

string[] Names = new string[]{
"Anish"
,"Varghese"
,"Linq"
,"Anish Varghese"};

cell = Names.Where(x => x.StartsWith("A")).ToList();
}


NEWSEQUENTIALID()

Creates a GUID that is greater than any GUID previously generated by this function on a specified computer.

CREATE TABLE myGUIDTable (myCol uniqueidentifier DEFAULT NEWSEQUENTIALID())

this is grate to see the id is created based on the machine id .
E.g: id created for me B0DD13B4-FB66-DE11-A148-001CC031A29A

my Physical address of my machine is 00-1C-C0-31-A2-9A

To know you ip address this will help you click here
to see your machine address type ipconfig/all
you can see physical address : that is same as the last 12 digits of your id

They introduced this to improve the performance of uniqueidentifiers when inserting

to get more information click here


.Net 3.0

New features in .net Framework 3.o?

The .Net framework 3.0 contains the same CLR 2.0 and base class libraries.The three new things in .Net 3.0 are windows persentation fountation(WPF),Windows Communication Fountation(WCF) and Windows work Flow foundation(WWF).


Windows Presentation Foundation : Helps advanced 3D animaitons and graphics.it uses Extesibile Application Mark up language.

Windows Communication Foundation :offers Service oriented message trasaction.It uses soap(Simple object access protocol) ,so it is reliable and secure.

Windows Work Flow Foundation : Offers automated business process.helps to tranfer whole or a part ,during which documentation information or task from one participient to another for action.

Wednesday, July 1, 2009

Properties in C#

Properties in C#

Why property are required?
If you are simply delcaring a variable and you want to do some operation on a variable .
E.g: Class demo1
{
Public string Age;
}
Class Maindemo1
{
demo1 Demo = new demo1();
Demo.Age= -35;
}

This we want to check manually whether the logic is correct or not.Like the below way

class Employee
{
public int Age;

public int GetAge()
{
return (Age);
}

public void SetAge(int value)
{
if(value<0)
throw new ArgumentOutOfRangeException ("Age Must be greater than zero");
Age = value;
}


}

class MainEmployee
{
static void Main()
{
Employee e = new Employee();
e.SetAge(35);
int i = e.GetAge();
}
}

This will solve the above problem.If Age is less than zero it will throw an error.
Disadvantage : want to write long number of codes.and user must call a method rather than a variable.

CLR offers a mechanism to overcome the above disadvantage,ie by using properties.
class Employee
{
private int _Age1;
public int Age1
{
get
{
return _Age1;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Age Must be greater than zero");
_Age1 = value;
}
}
}

class MainEmployee
{
static void Main()
{
Employee e = new Employee();
e.Age1 = 35;
int j = e.Age1;
}
}

The CLR offers get accessor and set accessor.During compile time it will automatically added GetAge() and SetAge(int value).And makes the code easy

Types of Properties

1) Parameterless Property
2) Parameterful property


Parameterless Property

This doesn’t have a parameter
E.g :
public int Age1
{
get
{
return _Age1;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("Age Must be greater than zero");
_Age1 = value;
}
}
}

Parameterful property

C# developer to overload [] operator

private int[] arr=new int[10]
public int this[int i]
{
get
{
return arr[i];
}
set
{
arr[i]=value;
}
}

CLR doesnot differentiate parameterless properties and parameterful proprty.C# team set this[] as syntax for indexer.which this choice means is that C# allows indexer to be defined only instace of the objects.so C# doesnot allow developer to define a static parameterful property.
 
Counter