Tuesday, December 15, 2009
Set the DateFormat in Indian Format (dd-MM-yyyy)
To View Date in Indian Format (dd-MM-yyyy)
By Fixing the Date format(Our desired) throughout the Application By doing this in .ASAX File
In Global.asax
using System.Globalization;
using System.Threading;
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo inf = new CultureInfo("en-US");
inf.DateTimeFormat.ShortDatePattern = "dd--MM--yyyy";
inf.DateTimeFormat.DateSeparator = "--";
Thread.CurrentThread.CurrentUICulture = inf;
Thread.CurrentThread.CurrentCulture = inf;
}
In Default.aspx
Label4.Text = DateTime.Now.ToShortDateString();
Monday, December 14, 2009
Constructors and Types of Constructors in C#
* Constructor has same name as class name.
* Constructor is used to initialize an object (instance) of a class.
* Constructor is a like a method without any return type.
* Constructor follows the access scope (Can be private, protected, public, Internal and external).
* Constructor can be overloaded.
Broadly speaking, it is a method in the class which gets executed when its object is created. Usually we put the initialization code in the constructor.
C# supports two types of constructor:
- a class constructor static constructor and an
- instance constructor (non-static constructor).
Non-static constructors are inline and are faster.
Constructors generally following types :
* Default Constructor
* Parametrized constructor
* Private Constructor
* Static Constructor
* Copy Constructor
Default Constructor
A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different data members of the class.
You need not to define default constructor it is implicitly defined.
class Program
{
class c1
{
int
a, b;
public c1()
{
this.a =
10;
this.b = 20;
}
public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}",
b);
}
}
static void
Main(string[] args)
{
// Here when you create instance
of the class default constructor will be called.
c1
ob1 = new c1();
ob1.display();
Console.ReadLine();
}
}
Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.Parameterized constructor
Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.
class Program
{
class c1
{
int
a, b;
public c1(int x, int
y)
{
this.a = x;
this.b =
y;
}
public void
display()
{
Console.WriteLine("Value of a: {0}",
a);
Console.WriteLine("Value of b: {0}",
b);
}
}
static void
Main(string[] args)
{
// Here when you create instance
of the class parameterized constructor will be called.
c1
ob1 = new c1(10,
20);
ob1.display();
Console.ReadLine();
}
}
Private ConstructorPrivate constructors are used to restrict the instantiation of object using 'new' operator. A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
This type of constructors is mainly used for creating singleton object.
If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.
class Program
{
class c1
{
int a, b;
// Private constructor declared
here
private c1(int x, int
y)
{
this.a = x;
this.b =
y;
}
public static c1
create_instance()
{
return new c1(12,
20);
}
public void
display()
{
int z = a +
b;
Console.WriteLine(z);
}
}
static void
Main(string[] args)
{
// Here the class is initiated
using a static method of the class than only you can use private
constructor
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
Static constructors:Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.
Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members.
class Program
{
public class test
{
static string name;
static int age;
static
test()
{
Console.WriteLine("Using static constructor to initialize static
data members");
name = "John Sena";
age
= 23;
}
public static void
display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}
}
static void
Main(string[] args)
{
test.display();
Console.ReadLine();
}
}
Copy ConstructorIf you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied.
class Program
{
class c1
{
int a, b;
public
c1(int x, int y)
{
this.a = x;
this.b = y;
}
// Copy construtor
public c1(c1 a)
{
this.a =
a.a;
this.b = a.b;
}
public void display()
{
int z
= a + b;
Console.WriteLine(z);
}
}
static void
Main(string[] args)
{
c1
ob1 = new c1(10,
20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the
values already defined with ob1
c1 ob2 =
new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
Note: Copy constructor sets behavior during runtime. It is shallow copying.The following are the Access Modifiers for constructors,
Public : A constructor that is defined as public will be called whenever a class is instantiated.
Protected : A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created.
Private : A constructor is defined as private in such cases whenever a class which contains only static members has to be accessed will avoid the creation of the object for the class.
Internal : An internal constructor can be used to limit concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.
External : When a constructor is declared using an extern modifier, the constructor is said to be an external constructor.
General:
1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
FAQs Regd. Constructors :
1. Is the Constructor mandatory for the class ?
Yes, It is mandatory to have the constructor in the class and that too should be accessible for the object i.e., it should have a proper access modifier. Say for example we have the private constructor in the class then it is of no use as it cannot be accessed by the object, so practically it is no available for the object. In such conditions it will raise an error.
2. What if I do not write the constructor ?
In such case the compiler will try to supply the no parameter constructor for your class behind the scene. Compiler will attempt this only if you do not write the constructor for the class. If you provide any constructor ( with or without parameters), then compiler will not make any such attempt.
3. What if I have the constructor public myDerivedClass() but not the public myBaseClass() ?
It will raise an error. If either the no parameter constructor is absent or it is in-accessible ( say it is private ), it will raise an error. You will have to take the precaution here.
4. Can we access static members from the non-static ( normal ) constructors ?
Yes, We can. There is no such restriction on non-static constructors. But there is one on static constructors that it can access only static members.
5. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
7. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
Source:
1: http://www.c-sharpcorner.com/UploadFile/neerajsaluja/ConstructorsInCSharp11152005233222PM/ConstructorsInCSharp.aspx
2: http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx
Reverse String - HTTP to HTTPS - Image Type(without checking extensions)
string str = TextBox1.Text.Trim();
char[] chr = str.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i =0 ; i < chr.Length; i++) { sb.Append(chr[(chr.Length-1)-i].ToString());
}
Label1.Text = sb.ToString();
Change the Current page from HTTP to HTTPS
if (!Request.IsSecureConnection)
{
//to get the current URL
UriBuilder uri = new UriBuilder(Page.Request.Url);
uri.Scheme = Uri.UriSchemeHttps;
// Redirect to https
Response.Redirect(uri.ToString());
}
Find Out the Image Type without Checking its Extension
Image imgUp = Image.FromFile(Server.MapPath("~/images/abc.jpg"));
if (imgUp.RawFormat.Equals(ImageFormat.Jpeg))
Response.Write("JPEG");
else if (imgUp.RawFormat.Equals(ImageFormat.Gif))
Response.Write("GIF");
first Monday of every month in an year
StringBuilder sb = new StringBuilder();
for (int mth = 1; mth <= 12; mth++)
{
DateTime dt = new DateTime(2010, mth, 1);
while (dt.DayOfWeek != DayOfWeek.Monday)
{
dt = dt.AddDays(1);
}
sb.Append(Convert.ToString(dt.ToLongDateString() + " ::: " )); } Label2.Text = sb.ToString();
VB.Net:
For mth As Integer = 1 To 12
Dim dt As New DateTime(2010, mth, 1)
Do While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(1)
Loop
Console.WriteLine(dt.ToLongDateString())
Next mth
Console.ReadLine()
Saturday, December 12, 2009
How to create a secured and locked folder in Windows XP
To secure my "topsecret" folder in D directory.

Create a notepad file with this content:
ren topsecret Fonts.{21EC2020-3AEA-1069-A2DD-08002B30309D}
Save the file as "loc.bat" in D directory itself (Where your folder is located. Ex: "topsecret").

Create another one notepad file with this content:
ren Fonts.{21EC2020-3AEA-1069-A2DD-08002B30309D} topsecret
Save the file as "key.bat" in D directory itself (Where your folder is located. Ex: "topsecret").

click "loc.bat" file to lock our "topsecret" folder.
Now the "topsecret" folder will turn into fonts and clicking on that folder will open the control panel.
To unlock that "topsecret" folder, click the "key.bat" file.
Now it will work fine......
source: http://www.online-tech-tips.com
Friday, December 11, 2009
write and read a cookie from a client's computer ASP.Net C#
FirstName
LastName
LastVisit
2. Create the user interface to enter FirstName and LastName. The HTML for the webform is as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesExample.aspx.cs" Inherits="CookiesExample" % >
<html >
<head runat="server" >
<title >Write a cookie to the client computer </title >
</head >
<body >
<form id="form1" runat="server" >
<table >
<tr >
<td style="width: 100px" >
First Name </td >
<td style="width: 100px" >
<asp:TextBox ID="FirstNameTextBox" runat="server" > </asp:TextBox >
</td >
</tr >
<tr >
<td style="width: 100px" >
Last Name
</td >
<td style="width: 100px" >
<asp:TextBox ID="LastNameTextBox" runat="server" > </asp:TextBox >
</td >
</tr >
<tr >
<td style="width: 100px" >
</td >
<td style="width: 100px" >
<asp:Button ID="WriteCookieButton" runat="server" Text="Write Cookie" OnClick="WriteCookieButton_Click" / >
</td >
</tr >
<tr >
<td style="width: 100px" >
</td >
<td style="width: 100px" >
<asp:Button ID="ReadCookieButton" runat="server" Text="Read Cookie" OnClick="ReadCookieButton_Click" / >
</td >
</tr >
</table >
</form >
</body >
</html >
3. WriteCookieButton_Click event handler in the code behind file, has the code required to write the cookie to the client computer as shown below.
protected void WriteCookieButton_Click(object sender, EventArgs e)
{
// Create an instance of HttpCookie class
HttpCookie UserCookie = new HttpCookie("USER");
// Populate FirstName, LastName and LastVisit fields
UserCookie["FirstName"] = FirstNameTextBox.Text;
UserCookie["LastName"] = LastNameTextBox.Text;
UserCookie["LastVisit"] = DateTime.Now.ToString();
// Set the cookie expiration date
UserCookie.Expires = DateTime.Now.AddDays(3);
// Write the cookie to the client computer
Response.Cookies.Add(UserCookie);
}
4. ReadCookieButton_Click even handler in the code behind file has the code to read the cookie from the client computer as shown below.
protected void ReadCookieButton_Click(object sender, EventArgs e)
{
// Check if the "USER" cookie exists on the client computer
if (Request.Cookies["USER"] != null)
{
//Retrieve the "USER" cookie into a cookie object
HttpCookie UserCookie = Request.Cookies["USER"];
//Write FirstName,LastName and LastVisit values
Response.Write("First Name = " + UserCookie["FirstName"] + "
");
Response.Write("Last Name = " + UserCookie["LastName"] + "
");
Response.Write("Last Visit = " + UserCookie["LastVisit"] + "
");
}
}
5. Finally test. Run the application and enter first name and Last name and click, the write cookie button. This should write the cookie to the client's computer. Now click the read cookie button, which will read the FirstName, LastName and LastVisit information from the cookie and writes on to the webform.
Source:
http://venkataspinterview.blogspot.com/2008/11/write-and-read-cookie-aspnet-interview.html
Bind an XML to DropDownList ASP.Net C#
<Employee >
<Name >David </Name >
<ID >101 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Tom </Name >
<ID >102 </ID >
<IsActive >true </IsActive >
</Employee >
<Employee >
<Name >Rick </Name >
<ID >103 </ID >
<IsActive >false </IsActive >
</Employee >
<Employee >
<Name >Mark </Name >
<ID >104 </ID >
<IsActive >true </IsActive >
</Employee >
</Employees >
--------------------------------------------------------
Code sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet DS = new DataSet();
DS.ReadXml(Server.MapPath("Employees.xml"));
DataView DV = DS.Tables["Employee"].DefaultView;
DV.RowFilter = "IsActive='true'";
DV.Sort = "Name asc";
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
-------------------------------------------------------
Code Explanation:
1. Read the XML data from Employees.xml file into a DataSet. We make use of the ReadXml() method. ReadXml method loads the XML data into the dataset DS. DS.ReadXml(Server.MapPath("Employees.xml"));
2. Now you have the Data in a relational format in the dataset. Create a DataView on the employees table in the DataSet. The DefaultView property of DataTable returns the DataView.
DataView DV = DS.Tables["Employee"].DefaultView;
3. After you have created the DataView, apply the RowFilter, to select only the active employees. You apply the RowFilter as shown below.
DV.RowFilter = "IsActive='true'";
4. Now sort the data in the DataView in ascending order. We sort the data on the Name column. You can apply the sort expression on a dataview as shown below.
DV.Sort = "Name asc";
5. Finally set the DataSource, DataValueField and DataTextField properties of the dropdownlist and call the DataBind() method as shown in the below code.
DropDownList1.DataSource = DV;
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataBind();
Untill now we have seen how to bind an XML file to dropdownlist. We have also seen how to create a DataView on DataTable. DataView is used for sorting and filtering the data. Now we have to get the SelecteValue and SelectedItem Text of a dropdownlist. To achieve this, follow the below steps.
1. Set the autopostback property of the dropdownlist to true. So, when ever a selection in the dropdownlist changes, the webform is posted back to the server automatically.
2. In the DropDownList1_SelectedIndexChanged event handler we can capture the employee name and id using the DropDownList1.SelectedItem.Text and DropDownList1.SelectedItem.Value properties as shown below.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("Name Is : " + DropDownList1.SelectedItem.Text + " and ID is " + DropDownList1.SelectedItem.Value);
}
Source: http://venkataspinterview.blogspot.com/2008/10/bind-xml-file-to-dropdownlist.html
Tuesday, December 1, 2009
C# Tips
Object: In computer science, an object, in the domain of object-oriented programming, usually means a compilation of attributes (object elements) and behaviors (methods) encapsulating an entity.
Classes are reference types; they are allocated on the Managed Heap. The Managed Heap is an area of memory that is managed by the Common Language Runtime, which has the ability to free unused memory blocks (objects) in a process known as Garbage Collection.
Access Modifier keywords: public, private, protected and internal.
Public: no restrictions on accessing public members.
Accessibility: Can be accessed by objects of the class.
Can be accessed by derived classes.
Private: Private members are accessible only within the body of the class or the struct in which they are declared.
Accessibility: Cannot be accessed by object.
Cannot be accessed by derived classes.
Protected: A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Accessibility: Cannot be accessed by object.
By derived classes.
Internal: The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project assembly.
Accessibility: In same assembly (public) can be accessed by objects of the class
Can be accessed by derived classes
In other assembly (internal) cannot be accessed by object
Cannot be accessed by derived classes.
Protected internal: The protected internal accessibility means protected OR internal, not protected AND internal.
In other words, a protected internal member is accessible from any class in the same assembly, including derived classes.
The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:
-Inherited types, even though they belong to a different assembly, have access to the protected internal members.
-Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.
Class members: fields, properties, methods, constructors, destructor, indexers, constants, events, delegates and operators.
Struct: Similar to Class, A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. By default it is sealed. There is no inheritance for structs as there is for classes. The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color.
Class Program
{
Struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
} ;
static void Main ()
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
}
Static class: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Ex: UtilityClass.MethodA ();
- Contains only static members.
- Cannot be instantiated.
- Is sealed.
- Cannot contain Instance Constructors.
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
}
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{ //Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
}
}
Static member: A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter. We can’t use this keyword to access Static Members.
Abstract Class: -cannot be instantiated. - An abstract class is only to be sub-classed (inherited from). - A class may inherit only one abstract class, but may implement multiple numbers of Interfaces. - Abstract class methods may OR may not have an implementation.
Public abstract class Shape
{ //...Class implementation
Public abstract void Draw (int x, int y)
{ //this method mustn't be implemented here.
//If we do implement it, the result is a Syntax Error.
}
}
Public abstract class Shape2D: Shape
{
//...Class implementation //...you do not have to implement the method Draw (int x, int y)
}
Public class Circle: Shape2D
{
//here we should provide an implementation for Draw (int x, int y)
Public override void Draw (int x, int y)
{
//must do some work here
}
}
Abstract and Virtual Method:
When a base class declares a method as virtual, a derived class can override the method with its own implementation.
If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.
An abstract method is a method without any method body. They are implicitly virtual in C#.
Abstract class MyAbs
{
public void NonAbMethod()
{
Console.WriteLine("Non-Abstract Method");
}
public abstract void AbMethod(); // An abstract method
}
class MyClass : MyAbs //must implement base class abstract methods
{
public override void AbMethod()
{
Console.WriteLine("Abstarct method");
}
}
An Interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
Ex:
Interface ISampleInterface
{
Void SampleMethod ();
}
Class ImplementationClass: ISampleInterface
{
// Explicit interface member implementation:
Void ISampleInterface.SampleMethod ()
{
// Method implementation.
}
Static void Main ()
{
ISampleInterface obj = new ImplementationClass ();
Obj. SampleMethod ();
}
}
Sealed class: A sealed class cannot be used as a base class; it cannot also be an abstract class. By creating an instance we can use the methods in the Sealed Class.
class Program
{
public sealed class BaseClass
{
public void Display()
{
Console.WriteLine("This is a sealed class which can’t be further inherited");
}
}
public class Derived : BaseClass
{
// this Derived class can’t inherit BaseClass because it is sealed
}
static void Main(string[] args)
{
BaseClass obj = new BaseClass();
obj.Display();
Console.ReadLine();
}
}
Delegates: Delegates are used to pass methods as arguments to other methods. It allow programmer to encapsulate a reference to a method inside a delegate object. Delegates are type-safe, secure managed objects. This means that the runtime guarantees that a delegate points to a valid method, which further means that you get all the benefits of function pointers without any of the associated dangers, such as an invalid address or a delegate corrupting the memory of other objects.
class clsDelegate
{
public delegate int simpleDelegate (int a, int b);
public int addNumber(int a, int b)
{
return (a+b);
}
public int mulNumber(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate clsDlg = new clsDelegate();
simpleDelegate addDelegate = new simpleDelegate(clsDlg.addNumber);
simpleDelegate mulDelegate = new simpleDelegate(clsDlg.mulNumber);
int addAns = addDelegate(10,12);
int mulAns = mulDelegate(10,10);
Console.WriteLine("Result by calling the addNum method using a delegate: {0}",addAns);
Console.WriteLine("Result by calling the mulNum method using a delegate: {0}",mulAns);
Console.Read();
}
}
Types: Single-Cast delegate and Multicast delegate.
A Single-cast delegate can call only one method at a time, whereas a Multicast delegate can call multiple methods at the same time.
Value type variables directly contain their values, which mean that the memory is allocated inline in whatever context the variable is declared.
There are two categories of value types: struct and enum.
A type that is defined as a class, delegate, array, or interface is a Reference type. At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator.
A Generic type can be declared with one or more type parameters. Generic collection classes are called strongly-typed collections because the compiler knows the specific type of the collection's elements and can raise an error at compile-time if, for example, you try to add an integer to the strings object.
Namespaces: .NET Framework uses namespaces to organize its many classes. Namespaces are used to logically arrange classes, structs, interfaces, enum and delegates. One namespace can contain other namespaces also.
The enum keyword is used to declare an enumeration (a numbered list), a distinct type consisting of a set of named constants called the enumerator list.
enum Days {low, medium, high};
class EnumSwitch
{
Public Static Void Main ()
{
Volume myVolume = Volume. Medium;
Switch (myVolume)
{
Case Volume. Low:
Console.WriteLine("The volume has been turned Down.");
break;
Case Volume. Medium:
Console.WriteLine ("The volume is in the middle.");
break;
Case Volume. High:
Console.WriteLine ("The volume has been turned up.");
break;
}
Console.ReadLine (); .
}
}
Dictionary: A Dictionary (TKey, TValue) contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value.
Dictionary
{
{ 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211 }},
{ 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317 }},
{ 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198 }}
};
Boxing: Conversion of Value Types to Reference Types.
Ex: int32 x=10;
Object obj=x; //Implicit Boxing; No need to tell the compiler about boxing
Object obj= (Object) x; //Explicit Boxing;
Unboxing: Conversion of Reference Types to Value Types.
X= obj; //Implicit Unboxing
Constructors: Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class. They do not have return types, not even void. Constructor is invoked by the new operator immediately after memory is allocated for the new object.
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler.
Note: There is always at least one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor.
Destructor: A destructor is just opposite to constructor. It has same as the class name, but with prefix ~ (tilde). They do not have return types, not even void and therefore they cannot return values. Destructor is invoked whenever an object is about to be garbage collected
Finalize () Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize (). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.
Method Overloading: Method with same name but with different arguments is called method overloading. Method Overloading forms compile-time polymorphism.
Class A1
{
Void hello ()
{
Console.WriteLine (“Hello”) ;
}
Void hello (string s)
{
Console.WriteLine (“Hello {0}”, s) ;
}
}
Method Overriding: Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass. Method overriding forms Run-time polymorphism.
Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
Class parent
{
Virtual void hello ()
{
Console.WriteLine (“Hello from Parent”) ;
}
}
Class child: parent
{
Override void hello ()
{
Console.WriteLine (“Hello from Child”) ;
}
}
Static void main ()
{
Parent objParent = new child ();
objParent.hello ();
}
//Output: Hello from Child.
OOPS:
Polymorphism (Many Shapes): Polymorphism is briefly described as "one interface, many implementations. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts.
There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Function Overloading: In case of compile time it is called function overloading. Two or more functions can have same name: different parameters or their data types. Compiler will select the right function depending on the type of parameters passed.
Operator Overloading: Operators can be overloaded in order to perform special functions with respect to the class. With the help of operator overloading standard operations such as +, - , *, etc can be applied on the objects of the class.
Encapsulation is the procedure of covering up of data and functions into a single unit. Ex: Delegate.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Inheritance is the mechanism which allows a class A to inherit properties of a class B. Note: A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note: Struct is implicitly sealed; so they cannot be inherited.
Partial Class: It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
• when working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
• when working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when creating Windows Forms, Web Service wrapper code, and so on. You can create code that uses these classes without having to edit the file created by Visual Studio.
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
Casting: Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed.
static void TestCasting(){
int i = 10;
float f = 0;
f = i; // An implicit conversion, no data will be lost.
f = 0.5F;
i = (int)f; // An explicit conversion. Information will be lost.
}
Difference between FOR and FOREACH: The FOR LOOP executes a statement or a block of statements repeatedly until a specified expression evaluates to false. There is need to specify the loop bounds (minimum or maximum).
The FOREACH statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum.
string [] n = new string[] {"test1", "test2"}
foreach(string a in n)
....
for(int i=0; i
Is XML case-sensitive? Yes, so
Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
What does Dispose method do with the connection object? Deletes it from the memory.
Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set assessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
How does one compare strings in C#? In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows:
if ((object) str1 == (object) str2) { }
What is the difference between const and static read-only? The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it: -- in the variable declaration (through a variable initializer).
-- in the static constructor (instance constructors if it's not static).
Is there any sample C# code for simple threading?
Some sample code follows: using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
What is the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
What is the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
How can I get the ASCII code for a character in C#? Casting the char to an int will give you the ASCII value: char c = 'f'; System.Console.WriteLine((int)c); or for a character in a string: System.Console.WriteLine((int)s[3]); The base class libraries also offer ways to do this with the Convert class or Encoding classes if you need a particular encoding.
Can you allow a class to be inherited, but prevent the method from being over-ridden? Yes. Just leave the class public and make the method sealed.
What is the smallest unit of execution in .NET? An Assembly.
What is the maximum size of the textbox? 65536.
What does the term immutable mean? The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
What is the difference between Finalize() and Dispose()? Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.
Difference between Debug class and Trace class? Debug class is used for debug builds while Trace class is used for both debug and release builds.
Monday, November 30, 2009
performance improvement
Performance Improving Methods( From YSlow)
1. Make fewer HTTP requests
Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.
2. Content Delivery Network (CDN)
User proximity to web servers impacts response times. Deploying content across multiple geographically dispersed servers helps users perceive that pages are loading faster.
3. Add Expires headers
Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.
4. Compress components with gzip
Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.
5. Grade A on Put CSS at top
Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.
6. Put JavaScript at bottom
JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.
7. Avoid CSS expressions
CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.
8. Make JavaScript and CSS external
Using external JavaScript and CSS files generally produces faster pages because the files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded each time the HTML document is requested. This reduces the number of HTTP requests but increases the HTML document size. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the HTML document size is reduced without increasing the number of HTTP requests.
9. Reduce DNS lookups
The Domain Name System (DNS) maps hostnames to IP addresses, just like phonebooks map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a hostname. The browser cannot download anything from the host until the lookup completes.
10. Minify JavaScript and CSS
Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.
11. Avoid URL redirects
URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.
12.Remove duplicate JavaScript and CSS
Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.
12. Configure entity tags (ETags)
Entity tags (ETags) are a mechanism web servers and the browser use to determine whether a component in the browser's cache matches one on the origin server. Since ETags are typically constructed using attributes that make them unique to a specific server hosting a site, the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.
13. Make AJAX cacheable
One of AJAX's benefits is it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using AJAX does not guarantee the user will not wait for the asynchronous JavaScript and XML responses to return. Optimizing AJAX responses is important to improve performance, and making the responses cacheable is the best way to optimize them.
14. GET for AJAX requests
When using the XMLHttpRequest object, the browser implements POST in two steps: (1) send the headers, and (2) send the data. It is better to use GET instead of POST since GET sends the headers and the data together (unless there are many cookies). IE's maximum URL length is 2 KB, so if you are sending more than this amount of data you may not be able to use GET.
15. Reduce the number of DOM elements
A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.
16. Avoid HTTP 404 (Not Found) error
Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.
17. Reduce cookie size
HTTP cookies are used for authentication, personalization, and other purposes. Cookie information is exchanged in the HTTP headers between web servers and the browser, so keeping the cookie size small minimizes the impact on response time.
18. Use cookie-free domains
When the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic. To workaround this problem, make sure that static components are requested with cookie-free requests by creating a subdomain and hosting them there.
19. Avoid AlphaImageLoader filter
The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.
20. Do not scale images in HTML
Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.
21. Make favicon small and cacheable
A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.
Thursday, November 26, 2009
Tips
C# Classes are reference types; they are allocated on the Managed Heap. The Managed Heap is an area of memory that is managed by the Common Language Runtime, which has the ability to free unused memory blocks (objects) in a process known as Garbage Collection.
Access Modifier keywords: public, private, protected and internal.
Class members: fields, properties, methods, constructors, destructor, indexers, constants, events, delegates and operators.
Struct: Similar to Class, A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. By default it is sealed. There is no inheritance for structs as there is for classes. The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color.
class Program
{
struct Simple
{ public int Position;
public bool Exists;
public double LastValue;
};
static void Main ()
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
}
Static class: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Ex: UtilityClass.MethodA ();
* Contains only static members. * Cannot be instantiated. * Is sealed. * Cannot contain Instance Constructors.
Static member: A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter. We can’t use this keyword to access Static Members.
Abstract Class: -cannot be instantiated. - An abstract class is only to be sub-classedinherit only one abstract class, but may implement multiple numbers of Interfaces. - Abstract class methods may OR may not have an implementation.
An Interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
Ex:
Interface ISampleInterface
{ Void SampleMethod (); }
Class ImplementationClass: ISampleInterface
{ // Explicit interface member implementation:
Void ISampleInterface.SampleMethod ()
{ // Method implementation. }
Static void Main ()
{ ISampleInterface obj = new ImplementationClass ();
Obj. SampleMethod (); }
}
Abstract and Virtual Method:
When a base class declares a method as virtual, a derived class can override the method with its own implementation.
If a base class declares a member as abstract, that method must be overridden in any non-abstract class that directly inherits from that class.
Sealed class: A sealed class cannot be used as a base class; it cannot also be an abstract class. By creating an instance we can use the methods in the Sealed Class.
Delegates: Delegates are used to pass methods as arguments to other methods. It allow programmer to encapsulate a reference to a method inside a delegate object.
public delegate void SimpleDeleg();
class DelegateExample
{
public void SimpMet()
{
string s= "I am From Simple Method.";
}
public static void main()
{
SimpleDeleg del = new SimpleDeleg(SimpMet);
SimpleDeleg();
}
}
Value type variables directly contain their values, which mean that the memory is allocated inline in whatever context the variable is declared.
There are two categories of value types: struct and enum.
A type that is defined as a class, delegate, array, or interface is a Reference type. At run time, when you declare a variable of a reference type, the variable contains the value null until you explicitly create an instance of the object by using the new operator
A Generic type can be declared with one or more type parameters. Generic collection classes are called strongly-typed collections because the compiler knows the specific type of the collection's elements and can raise an error at compile-time if, for example, you try to add an integer to the strings object.
Namespaces: .NET Framework uses namespaces to organize its many classes. Namespaces are used to logically arrange classes, structs, interfaces, enum and delegates. One namespace can contain other namespaces also.
The enum keyword is used to declare an enumeration (a numbered list), a distinct type consisting of a set of named constants called the enumerator list.
enum Days {low, medium, high};
class EnumSwitch
{
Public Static Void Main ()
{
Volume myVolume = Volume. Medium;
switch (myVolume)
{
case Volume. Low:
Console.WriteLine("The volume has been turned Down.");
break;
case Volume. Medium:
Console.WriteLine ("The volume is in the middle.");
break;
Case Volume. High:
Console.WriteLine ("The volume has been turned up.");
break;
}
Console.ReadLine ();
}
}
Dictionary: A Dictionary (TKey, TValue) contains a collection of key/value pairs. Its Add method takes two parameters, one for the key and one for the value.
Dictionary
{
{111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
{112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317}},
{113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198}}
};
Boxing: Conversion of Value Types to Reference Types.
Ex: int32 x=10;
Object obj=x; //Implicit Boxing; No need to tell the compiler about boxing
Object obj= (Object) x; //Explicit Boxing;
Unboxing: Conversion of Reference Types to Value Types.
X= obj; //Implicit Unboxing
Constructors: Constructors are class methods that are executed when an object of a given type is created. Constructors have the same name as the class. They do not have return types, not even void. Constructor is invoked by the new operator immediately after memory is allocated for the new object.
A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler.
Note: There is always at least one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor.
Destructor: A destructor is just opposite to constructor. It has same as the class name, but with prefix ~ (tilde). They do not have return types, not even void and therefore they cannot return values. Destructor is invoked whenever an object is about to be garbage collected
Finalize () Method of Object class
Each class in C# is automatically (implicitly) inherited from the Object class which contains a method Finalize (). This method is guaranteed to be called when your object is garbage collected (removed from memory). You can override this method and put here code for freeing resources that you reserved when using the object.
Method Overloading: Method with same name but with different arguments is called method overloading. Method Overloading forms compile-time polymorphism.
Class A1
{
Void hello ()
{Console.WriteLine (“Hello”) ;}
Void hello (string s)
{Console.WriteLine (“Hello {0}”, s) ;}
}
Method Overriding: Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass. Method overriding forms Run-time polymorphism.
Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
Class parent
{ Virtual void hello ()
{ Console.WriteLine (“Hello from Parent”) ;}
}
Class child: parent
{ Override void hello ()
{ Console.WriteLine (“Hello from Child”) ;}
}
Static void main ()
{ Parent objParent = new child ();
objParent.hello ();
}
//Output
Hello from Child.
OOPS:
Polymorphism (Many Shapes): Polymorphism is briefly described as "one interface, many implementations. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts.
There are two types of polymorphism one is compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is functions and operators overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Function Overloading: In case of compile time it is called function overloading. Two or more functions can have same name: different parameters or their data types. Compiler will select the right function depending on the type of parameters passed.
Operator Overloading: Operators can be overloaded in order to perform special functions with respect to the class. With the help of operator overloading standard operations such as +, - , *, etc can be applied on the objects of the class.
Encapsulation is the procedure of covering up of data and functions into a single unit. Ex: Delegate.
Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Inheritance is the mechanism which allows a class A to inherit properties of a class B.
Note: A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note: Struct is implicitly sealed; so they cannot be inherited.