Wednesday, December 23, 2009

Necessity for Object Oriented Programming Language.

In simple terms, why we have moved from C(Procedural Language) to C++(Object Oriented Language) ?

In C we use user defined data types like Structure, Union etc, where as in C++ we use classes, here I will try to answer the above question in terms of using these different language elements:

1. The variables we use in a structure or union can be accessed any where in the program, this means, that there is no proper security for data in C i.e. Procedural Langauage. Where as in c++ we have access specifiers like public, private, protected etc, which allows us to restrict the access to a particular variable. So unlike C, C++ has some control over the access to the data.

2. The variables/ elements of one structure are cannot be accessed in an other structure unless they are nested, so there is some access limitations for data in C. Where as in C++ the variables declared and used in one class are allowed/ restricted to get accessed by other classes throught the same access specifiers public, private, protected etc.

3. Function concepts is not supported by structures in C i.e, we cant declare a function as a structure member, where classes can have functions as their members.

These are a few reasons, where there is a necessity to move from a structure oriented language to a object oriented language.

Monday, December 21, 2009

Interfaces

* Interface is the collection of all public members of the class.
* Interface,like classes,defines a set of properties,methods and events.But unlike classes ,interfaces do not provide implementation.
* This is a powerful programming tool because they allow you to separate the definition of objects from their implementation.
* All the members of the interface are by default public and abstract.we need not specify.
* An interface body is limited to declaration for methods,property,indexer.
* Fields,constructor,constants etc cannot be included in an interface.
* Interface members are implicitly public and it is a compiler error to specify the access level explicitly.
* No implementations are allowed in an interface.
* Methods are specified by giving only the return type,name and parameters list followed by a semicolon.


Syntax with example:
interface IFigure
{
int Dimension
{set;get}
double Area();
double Perimeter();
}




Where do we use interface:
* Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation multiple interfaces.



using System;
namespace InterfaceTest1
{
interface CA{
void Foo(); }
interface CB{
void Foo(); }
public class CC:CA,CB
{
//CA members
public void Foo(){
Console.WriteLine("From CA");
}

//CB members
void CB.Foo(){
Console.WriteLine("From CB");
}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ CC c = new CC();
CA ca; //Interface variable
CB cb; //Interface variable
ca=c; // Explicit implementation
ca.Foo();
cb=c; // Explicit implementation
cb.Foo();
}}}

The output is CA

CB


* Interfaces are better in situations in which you do not need to inherit implementation from a base class.
* Interfaces are useful in cases where you cannot use class inheritance.For example ,structures cannot inherit from classes,
but they can implement interfaces.
An interface represents a contract, in that a class that implements an interace must implement every aspect of that interface exactly as it is defined.



Example:
using System;
namespace InterfaceTEST
{
interface IFigure //INTERFACE
{
int Dimension
set;get}
double Area();
double Perimeter();
}
class Circle:IFigure //CLASS
{
private int mRadius;
public int Dimension{
get{return mRadius;}
set { mradius = value;}}
public double Area(){
return Math.PI*Dimension*Dimension;
}
public double Perimeter(){
return 2* Math.PI*mradius;
}
}
class Square :IFigure //CLASS
{
private int mSide;
public int Dimension{
get{return mside;}
set { mside = value;}}
public double Area()
{return mside * mside;}
public double Perimeter()
{return 4*mside;}
}
class Class1
{

[STAThread]
static void Main(string[]args)
{ //Circle
Circle C = new Circle();
C.Dimension = 10;
Console.WriteLine("Area of circle=" + C.Area());
Console.WriteLine("Perimeter of circle=" + C.Perimeter());
//Square
Square S = new Square();
S.Dimension =5;
Console.WriteLine("Area of square=" + S.Area());
Console.WriteLine("Perimeter of square=" + S.Perimeter());
}
}
}

Inheritance

Inheritance is a process to create new class from an exiting class.

Or

Inheritance is the process that allows the reuse of an exiting class to build a new class.

Mainly,Inheritance is based on the principal of code reuse.Instead of creating a class from scratch,it is possible to add new methods,properties and events (events are responce to user actions.)to exiting classes,thus saving time and efforts.The class on which the new class is created is called Base class or Parent class and the class that is created is called Derived, Sub or Child class.

Example:

using System;

namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
public void GetInfo()
{
Console.WriteLine("Enter your name = ");
_name = Console.ReadLine();
Console.WriteLine("Enter your age = ");
_age = int.Parse(Console.ReadLine());
}
public void DispInfo()
{
Console.WriteLine("Dear {0},Your age is {1}",_name,_age) ;
}
}

//Derived class
public class Student:Person
{
private string_school;
private int_english;
private int_math;
private int_science;
public void GetMarks()
{
Console.WriteLine("Enter school names = ");
_school = Console.ReadLine();
Console.WriteLine("Enter marks for English,Maths,Science");
_english = int.Parse(Console.ReadLine());
_math = int.Parse(Console.ReadLine());
_science = int.Parse(Console.ReadLine());
Console.WriteLine("Total Marks obtained : {0}",_english+_math+_science);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student();
objstudent.GetInfo(); //Accessing base member
objstudent.DispInfo(); //Accessing base member
objstudent.GetMarks();
}
}
}

Base Keyword
The keyword base is used to access members of the base class from inside a derived class.To call a method of the base class is possible even if it has been overridden in the derived class by using the keyword base.Also,creating an instance of a derived class
The constructor of the base classes can be called using base keyword
Constructor, an instance method of an instance property accessory only of the base class can be accessed using the keyword base.

Example:

using System;

namespace InheritanceDemo1
{
public class CA
{
private int priA;
public CA()
{ priA =100;
}
protected void fun(){
Console.WriteLine("From CA"); }
}
public class CB:CA {
private int priB;
public CB(){
priB = 200; }
public void foo(){
base.fun();
Console.WriteLine("From CB");
}
public class UsingBaseKeyword
{
statci void Main(string[] args) {
CB b = new CB();
b.foo(); }}}

* Calling base class constructor by using derived class using base keyword.

Example:

using System;
namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
//base supplies constructor to perform initialization
public Person(string name,int age)
{
this._name = name;
this._age = age;
Console.WriteLine("Name = {0} ",name);
Console.WriteLine("Age = {0} ",age);
}
}


//Derived class
public class Student:Person
{
private int _id;
public Student(String name,int age,int id):base (name,age)
{
this._id=id;
Console.WriteLine("Id = {0} ",id);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student("Raj",24,4);
}
}
}


Method Overriding in C#

Overriding :- Overriding a method of base class means changing its implementation or overwriting it in the derived class.
*Override keyword:
The override keyword is used to modify a method.An override method provides a new implementation of the base method.For this the base class method has to be declared virtual.Adding virtual to a base class method marks it to for overriding its implementation in the derived class.By default, methods are non-virtual in C# and hence they cannot be overridden.

Note:-
1. The overridden method in a derived class should have the same signature as the base class method it is overriding.
2. The keywords new,static,virtual cannot be used along wirg the override modifier.

*Virtual keyword :
C# provides a keyword virtual that is used the definition of a method to support polymorphism.The virtual keyword is used to modify a method declaration in a class.Such method is called a virtual method.The child classes are now free to implement their own versions of thr virtual method

using override keyword.
The Syntax:-
[Access modifier]virtual[return tyoe]name([parameter list])
{
//Virtual method implementation.
}

Note: The virtual modifier cannot be used with modifier like static and override.
Ex:-
Public virual void function_name()
{
Console.WriteLine("This is a virtual method and can be overridden");
}


* When a virtual method is called ,a runtime check is made to identify the object and the appropriate method is invoked.In case of non-virtual methods,this information is available at compile time,so no runtime check to identify the object is done.
* "new" keyword:- The new keywordmis used as an operator or as a modifier,This section is discussingthe new modifier.The new modifier is used to explicitly hide a member that is inherited from the base class.This means in case if the derived class has a member with the same name as a member in the parent class,then new distinguishes the derived class member as a completely new member.

* Note:- It is an error to use both new an override on the same method.
* Note:- To conclude ,the real benefit of "new modifier" is to be sure that the intention is to hide the base method and this did not happen by accident or misspelling
* Conversely,if a method is declared as new and it does not really hide a base method ,the compiler will also issue a warning that can be suppressed by removing the new modifier.

Constructors

Constructor is a method in a classs which is automatically invoked as soon as object is created.In C#.Net it is invoked by class name.

Syntax:
Classname referencename;
Reference = new classname();
Example:
Account a;
a=new Account();


Constructor may be of default type.copy type or parameterized.

Default Constructor:No parameters will be sent to this constrcutor .Intially the properties of the class are assigned default values(0's).
The syntax of the default constructor is as shown above.

Copy Constructor:This constructor create a clone of another object.

Syntax with example:
public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}


Constructor with parameters:This typeof constructors takes the values to the members of the class.

Syntax with example:
public Account(string n ,balance b,int i)
{

this.Id = i;
this.Name = n;
this.Balance = b;
}


Example:
Class:
Public Account
{
private int Id;
private string Name;
private decimal Balance;
//Default Constructor
Public Account()
{
Id =101;
Name="E101";
Balance=101.11;
}
//Constructor with parameter
Public Account(int Id,string Name,decimal Balance)
{
this.Id = id;
this.Name = name;
this.Balance = balance;
}
//Copy Constructor
Public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}
Public void Display()
{
Console.WriteLine("Id="+id.ToString());
Console.WriteLine("Name="+Name);
Console.WriteLine("Balance="+Balance.ToString());
}
}
Public static void(string []args)
{
//Accessing Default Constructor
Account a=new Account();
//Accessing Constructor with parameter
Account a1=new Account(1,"E1",11);
a1.Display();
//Accessing Copy Constructor
Account a2=new Account(2,"E2",22);
Account a2=new Account(a2);//Passing parameter as object
}


//Note:If all constructors are used together in program,then it is called Constructor overloading.

Concept Of Property

C# provides the facility to protect a field in a class by reading and writing to it through a feature called properties.C# properties enable this type of protection while at the same time letting one access the property like a field.Thus properties can be used to encapsulate data within a field.
Property allows fields like access to data members,while still providing data encapsulation and security.
Type of Properties
Properties are categorized into four different types which are as follows:-
>Read/Write Properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
>Read only properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
}
>Write only properties
Syntax:
[Access_modifier]datatype PropertyName
{
set();
}
>Static properties
Syntax:
[Access_modifier]datatype PropertyName
{
get();
set();
}
Example:-
using System;
using System.Collections.Generic;
using System.Text;
namespace PropertyDemo{
//Class fields to store account number,balance and interest earned.
class SavingsAccount
{
private int_accountNumber;
private double_balance;
private double_interestEarned;
//Rate of interest is static because all accounts earn the same interest
private static double_interestRate;
//Constructor initializes the class members.
public SavingsAccount(int accountNumber,double balance){
this.accountNumber=accountNumber;
this.balance=balance;
//Read only AccountNumber property
public int AccountNumber{
get{
return_accountNumber;
} }
//Read only balance property
public double Balance {
get {
if (_balance<0)
Console.WriteLine("No balance available");
return _balance; }
}
//Read/Write InterestEarned property
public double InterestEarned {
get {
return _interestEarned; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestEarned cannot be negative");
return ; }
_interestEarned =value; }
}
//Read/Write interestrate static property since all accounts of a particular type have the same interest //rate
public static double InterestRate {
get {
return _interestRate; }
set {
//validating data
if (value<0.0)
Console.WriteLine("InterestRate cannot be negative");
return ; }
_interestRate =value / 100;
} } }
}
class Program {
static void Main(string[] args) {
//Creating an object of SavingsAccount
SavingsAccount objSavingsAccount= new SavingsAccount(12345,5000);
//User interaction
Console.WriteLine(" Enter Interest Earned till now and rate of interest");
objSavingsAccount.InterestEarned=Convert.ToDouble(Console.ReadLine());
SavingsAccount.InterestRate=Convert.ToDouble(Console.ReadLine());
//Saving property is accessed using class name
objSavingsAccount.InterestEarned+= objSavingsAccount.Balance * SavingsAccount.InterestRate;
Console.WriteLine(" Total Interest Earned is :{0}",objSavingsAccount.InterestEarned);
} } }

Difference between encapsulation and abstraction

Encapsulation:
----------------------
Encapsualation is basically, wrapping up of data memebers and methods.
As you said, You hide the data for security such as making the variables as private, and expose the property to access the private data which would be public. So, when you access the property you can validate the data and set it.

Example:

Class Demo
{
private int _mark;

public int Mark
{
get { return _mark; }
set { if (_mark > 0) _mark = value; else _mark = 0; }
}
}

Abstraction:-
------------------
Abstraction have the methods which will be common for all the derived class would need. It contains the skeletion which needs to be implemented by the derived class also, which will be declared as abstract method.

Example:

abstract class CurryBase
{
public abstract void doCurryMasala();
}

public class FishCurry : CurryBase
{
public void doCurryMasala()
{
// Add Fish Curry specific contents also.
}
}

Encapsulation is the concept of binding data with methods...

Abstraction is nothing but hiding of data...in the sense hiding of complexity and providing functionallity..

Thursday, December 17, 2009

C# Crystal Reports Tutorials

http://csharp.net-informations.com/crystal-reports/csharp-crystal-reports-tutorial.htm
http://dotnetslackers.com/articles/xml/ReportingXMLDataUsingCrystalReportsAndWindowsForms.aspx

How to get URL without querystring?

string url = "http://localhost:4351/WebSite8/Default5.aspx?" + TextBox1.Text;
Uri weburi = new Uri(url);
string query = weburi.Query;
string weburl = url.Substring(0, url.Length - query.Length);
Response.Redirect(weburl);

Tuesday, December 15, 2009

Code Converter

Convert your code from vb to c#/c# to vb

Wednesday, December 9, 2009

How to read .doc document in ASP.NET?

protected void Button1_Click(object sender, EventArgs e)
{
string path="C:\\Documents and Settings\\Administrator\\My Documents\\abcd.txt";
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
TextBox1.Text += "
" + line;

}
}

}

Tuesday, December 8, 2009

How to create dynamic Gridview?

Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.


Details of the Grid






Create a gridview in the page,

Drag and drop the GridView on to the page
Or

Manually type GridView definition in the page.
public partial class _Default : System.Web.UI.Page

{

#region constants

const string NAME = "NAME";

const string ID = "ID";

#endregion



protected void Page_Load(object sender, EventArgs e)

{

loadDynamicGrid();

}



private void loadDynamicGrid()

{

#region Code for preparing the DataTable



//Create an instance of DataTable

DataTable dt = new DataTable();



//Create an ID column for adding to the Datatable

DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

dcol.AutoIncrement = true;

dt.Columns.Add(dcol);



//Create an ID column for adding to the Datatable

dcol = new DataColumn(NAME, typeof(System.String));

dt.Columns.Add(dcol);



//Now add data for dynamic columns

//As the first column is auto-increment, we do not have to add any thing.

//Let's add some data to the second column.

for (int nIndex = 0; nIndex < 10; nIndex++)

{

//Create a new row

DataRow drow = dt.NewRow();



//Initialize the row data.

drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));



//Add the row to the datatable.

dt.Rows.Add(drow);

}

#endregion



//Iterate through the columns of the datatable to set the data bound field dynamically.

foreach (DataColumn col in dt.Columns)

{

//Declare the bound field and allocate memory for the bound field.

BoundField bfield = new BoundField();



//Initalize the DataField value.

bfield.DataField = col.ColumnName;



//Initialize the HeaderText field value.

bfield.HeaderText = col.ColumnName;



//Add the newly created bound field to the GridView.

GrdDynamic.Columns.Add(bfield);

}



//Initialize the DataSource

GrdDynamic.DataSource = dt;



//Bind the datatable with the GridView.

GrdDynamic.DataBind();

}

}


Friday, December 4, 2009

MVC Architecture

MVC or Model View Controller is an architectural style that separates the business from the presentation layer to enable independent development and testing of each. MVC is not a new concept, It has existed right from the nascent days of software development with the first implementation being in SmallTalk in 1979 done by Trygve Reenskaug.

It is relatively new to the Microsoft World though, with the ASP.NET MVC framework being shipped in 2008 compatible with Visual Studio 2008 – .NET Framework 3.5. So what is MVC? MVC divides the application into three parts – The model, View and the controller.

  • Controller:- The controller is the heart of the MVC application. It recieves each and every request that is made by the user and responds to it accordingly. It controls the flow of the application.
  • Views:- This is the actual UI of the application. The controller controls how the view should be rendered to the browser. Views contain markup, scripts just like an .aspx page
  • Model:- Apart from the View and the controller, all the other parts in the application are collective called as the Model. These components are the business and data logic of the application.

A huge advantage of the MVC architecture is that it separates all these three components and makes them completely independent of each other. Hence all of them can be tested separately rather than the case with the webform architecture where testing each component is a pain and mostly we end up doing functional testing for the whole application. This also means modifying one component is far more easy without disturbing the whole application.

Since all the requests are now handled by the controller, we cannot use the postback feature of the web controls like the webform architecture. One of the drawback (or advantage) of MVC is the level of control over HTML rendering that we have. Since we can exactly control how the page will be rendered, we have to write more code to do so. Also you will see more code mixed with Markup, something that ASP.NET eliminated with the help of code behind.

MVC and WebForms are to be seen as two distinct styles which are advantageous to use depending on the scenario, rather than being pitted against each other. If you have a small standalone application to develop with fewer programming resources, a webform based application makes more sense since there is less coding involved. However if you are looking to build an application that would be used and extended by a large number of users, MVC is certainly the way to go.


Reference:http://blog.ganeshzone.net/blog/index.php/tag/mvc/

Difference between http and https

There are some primary differences between http and https, however, beginning with the default port

1) which is 80 for http and 443 for https.
2) Https works by transmitting normal http interactions through an encrypted system,
3) the information cannot be accessed by any party other than the client and end server.
4) There are two common types of encryption layers: Transport Layer Security (TLS) and Secure Sockets Layer (SSL), both of which encode the data records being exchanged.

5)When using an https connection, the server responds to the initial connection by offering a list of encryption methods it supports. In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities. After this is done, both parties exchange the encrypted information after ensuring that both are using the same key, and the connection is closed. In order to host https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity. Most certificates are verified by a third party so that clients are assured that the key is secure.


6)Https is used in many situations, such as log-in pages for banking, forms, corporate log ons, and other applications in which data needs to be secure. However, if not implemented properly, https is not infallible, and therefore it is extremely important for end users to be wary about accepting questionable certificates and cautious with their personal information while using the Internet.


7)http is a system for transmitting and receiving information across the Internet. Http serves as a request and response procedure that all agents on the Internet follow so that information can be rapidly, easily, and accurately disseminated between servers, which hold information, and clients, who are trying to access it. Http is commonly used to access html pages, but other resources can be utilized as well through http. In many cases, clients may be exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access. For this reason, https, or secure http, was developed by Netscape corporation to allow authorization and secured transactions.

8)https is identical to http, because it follows the same basic protocols. The http or https client, such as a Web browser, establishes a connection to a server on a standard port. When a server receives a request, it returns a status and a message, which may contain the requested information or indicate an error if part of the process malfunctioned. Both systems use the same Uniform Resource Identifier (URI) scheme, so that resources can be universally identified. Use of https in a URI scheme rather than http indicates that an encrypted connection is desired.

Bubble Tooltip CSS

http://ajax-matters.blogspot.com/2009/01/css-bubble-tooltip.html