Thursday, December 17, 2009

Interfaces and Abstract Classes

nterfaces

An interface is a reference type containing only abstract members. These can be events, indexers, methods or properties, but only the member declarations. A class implementing an interface must provide the implementation of the interface members. An interface cannot contain constants, constructors, data fields, destructors, static members or other interfaces. Interface member declarations are implicitly public.


[edit]
Declaration

[attributes] [modifiers]
interface identifier [:base-type[,]]
{
body [;]
}

The attributes is optional and is used to hold additional declarative information.

The modifier is optional. The allowed modifiers are public and internal, unless nested inside a class, then the allowed modifiers are public, protected, private and internal. If no modifier is supplied then a default of internal is used.

The keyword interface must be followed by an identifier that names the interface.

The base-type of an interface can be zero or more interfaces. When more than one base-type is used, then this is a comma-separated list of base-types.

The body contains the member declarations.
[edit]
Implementation

An interface is defined using the keyword interface. It is common practice to start all interface names with a capital I. For example:

public interface IVehicle
{
void Start();
void Drive();
void Park();
void ChangeGear(int gear);
void SwitchOff();
}

In order to implement the interface, every method must be implemented in the class, else a compiler error will ensue.
public class Vehicle : IVehicle
{
public void Start()
{
Console.WriteLine("The vehicle has been started");
}

public void Drive()
{
Console.WriteLine("The vehicle is being driven");
}

public void Park()
{
Console.WriteLine("The vehicle is being parked");
}

public void ChangeGear(int gear)
{
Console.WriteLine("Gear changed to " + gear.ToString());
}

public void SwitchOff()
{
Console.WriteLine("The vehicle has been switched off");
}
}

If a class implements more that one interface and the two interfaces have methods named the same, then each method must be implemented unless they have the same definition in which case only one implementation is needed to implement the methods

Abstract classes

Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.

For example, we could create an abstract class for all vehicle to inherit from:

public abstract class Vehicle
{
public void Start()
{
Console.WriteLine("The vehicle has been started");
}

public abstract void Drive();
public abstract void Park();
public abstract void ChangeGear(int gear);

public void SwitchOff()
{
Console.WriteLine("The vehicle has been switched off");
}
public virtual void Operation1()
{
}
}

So each class that inherits from Vehicle will already be able to use the methods Start and SwitchOff, but they must implement Drive, Park and ChangeGear.

So if we were to implement a Car class, it may look something like this.

public class Car : Vehicle
{
public Car()
{
}

public override void Drive()
{
Console.WriteLine("The car is being driven");
}

public override void Park()
{
Console.WriteLine("The car is being parked");
}

public override void ChangeGear(int gear)
{
Console.WriteLine("The car changed gear changed to " + gear.ToString());
}
public new void Operation1() { }
}

The override keyword tells the compiler that this method was defined in the base class.

Summary

* An Interface cannot implement methods.
* An abstract class can implement methods.


* An Interface can only inherit from another Interface.
* An abstract class can inherit from a class and one or more interfaces.


* An Interface cannot contain fields.
* An abstract class can contain fields.


* An Interface can contain property definitions.
* An abstract class can implement a property.


* An Interface cannot contain constructors or destructors.
* An abstract class can contain constructors or destructors.


* An Interface can be inherited from by structures.
* An abstract class cannot be inherited from by structures.


* An Interface can support multiple inheritance.
* An abstract class cannot support multiple inheritance.

C# – Static Members

A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declared as static.

Static Fields

Static fields can be declared as follows by using the keyword static.

class MyClass
{
public static int x;
public static int y = 20;
}

When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

For example



// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
MyClass mc = new MyClass(25);

Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
}
}

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.

The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.

// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.

Static Member Functions

Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static members only through an instance of the class.

We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();

}
}

Static Properties

The properties also in C# can be declared as static. The static properties are accessing using the class name. A concrete example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
public static int X
{
get
{
Console.Write("GET");
return 10;
}
set
{
Console.Write("SET");
}
}

}
class MyClient
{
public static void Main()
{
MyClass.X = 20; // calls setter displays SET
int val = MyClass.X;// calls getter displays GET
}
}

Static Indexers

In C# there is no concept of static indexers, even though static properties are there.

Static Members & Inheritance

A derived class can inherit a static member. The example is shown below.

// C#:static
// Author: rajeshvs@msn.com
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Base static method'
Console.WriteLine(MyClass.x);// Displays 25
}
}

But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.

An example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
public new static int x = 50;
public new static void Method()
{
Console.WriteLine("Derived static method");
}
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Derived static method'
Console.WriteLine(MyClass.x);// Displays 50
}
}

Finally remember that it is not possible to use this to reference static methods.

Tuesday, November 24, 2009

Cascading Referential Integrity Constraints

By using cascading referential integrity constraints, you can define the actions that the SQL Server takes when a user tries to delete or update a key to which existing foreign keys point.

The REFERENCES clauses of the CREATE TABLE and ALTER TABLE statements support the ON DELETE and ON UPDATE clauses. Cascading actions can also be defined by using the Foreign Key Relationships dialog box:

* [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
* [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]

NO ACTION is the default if ON DELETE or ON UPDATE is not specified.

ON DELETE NO ACTION

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE statement is rolled back.

ON UPDATE NO ACTION

Specifies that if an attempt is made to update a key value in a row whose key is referenced by foreign keys in existing rows in other tables, an error is raised and the UPDATE statement is rolled back.

CASCADE, SET NULL and SET DEFAULT allow for deletions or updates of key values to affect the tables defined to have foreign key relationships that can be traced back to the table on which the modification is performed. If cascading referential actions have also been defined on the target tables, the specified cascading actions also apply for those rows deleted or updated. CASCADE cannot be specified for any foreign keys or primary keys that have a timestamp column.

ON DELETE CASCADE

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all rows that contain those foreign keys are also deleted.

ON UPDATE CASCADE

Specifies that if an attempt is made to update a key value in a row, where the key value is referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key are also updated to the new value specified for the key.
ms186973.note(en-us,SQL.100).gifNote:
CASCADE cannot be specified if a timestamp column is part of either the foreign key or the referenced key.

ON DELETE SET NULL

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute.

ON UPDATE SET NULL

Specifies that if an attempt is made to update a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute.

ON DELETE SET DEFAULT

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Any nonnull values that are set because of ON DELETE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the foreign key constraint.

ON UPDATE SET DEFAULT

Specifies that if an attempt is made to update a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Any non-null values that are set because of ON UPDATE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the foreign key constraint.

Consider the FK_ProductVendor_Vendor_VendorID constraint on the Purchasing.ProductVendor table in AdventureWorks. This constraint establishes a foreign key relationship from the VendorID column in the ProductVendor table to the VendorID primary key column in the Purchasing.Vendor table. If ON DELETE CASCADE is specified for the constraint, deleting the row in Vendor where VendorID equals 100 also deletes the three rows in ProductVendor where VendorID equals 100. If ON UPDATE CASCADE is specified for the constraint, updating the VendorID value in the Vendor table from 100 to 155 also updates the VendorID values in the three rows in ProductVendor whose VendorID values currently equal 100.

ON DELETE CASCADE cannot be specified for a table that has an INSTEAD OF DELETE trigger. For tables that have INSTEAD OF UPDATE triggers, the following cannot be specified: ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE CASCADE, ON UPDATE SET NULL, and ON UDATE SET DEFAULT.
Multiple Cascading Actions

Individual DELETE or UPDATE statements can start a series of cascading referential actions. For example, a database contains three tables: TableA, TableB, and TableC. A foreign key in TableB is defined with ON DELETE CASCADE against the primary key in TableA. A foreign key in TableC is defined with ON DELETE CASCADE against the primary key in TableB. If a DELETE statement deletes rows in TableA, the operation also deletes any rows in TableB that have foreign keys matching the deleted primary keys in TableA, and then deletes any rows in TableC that have foreign keys that match the deleted primary keys in TableB.

The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references. No table can appear more than one time in the list of all cascading referential actions that result from the DELETE or UPDATE. Also, the tree of cascading referential actions must not have more than one path to any specified table. Any branch of the tree is ended when it encounters a table for which NO ACTION has been specified or is the default.
Triggers and Cascading Referential Actions

Cascading referential actions fire the AFTER UPDATE or AFTER DELETE triggers in the following manner:

All the cascading referential actions directly caused by the original DELETE or UPDATE are performed first.

If there are any AFTER triggers defined on the affected tables, these triggers fire after all cascading actions are performed. These triggers fire in opposite order of the cascading action. If there are multiple triggers on a single table, they fire in random order, unless there is a dedicated first or last trigger for the table. This order is as specified by using sp_settriggerorder.

If multiple cascading chains originate from the table that was the direct target of an UPDATE or DELETE action, the order in which these chains fire their respective triggers is unspecified. However, one chain always fires all its triggers before another chain starts firing.

An AFTER trigger on the table that is the direct target of an UPDATE or DELETE action fires regardless of whether any rows are affected. There are no other tables affected by cascading in this case.

If any one of the previous triggers perform UPDATE or DELETE operations on other tables, these actions can start secondary cascading chains. These secondary chains are processed for each UPDATE or DELETE operation at a time after all triggers on all primary chains fire. This process may be recursively repeated for subsequent UPDATE or DELETE operations.

Performing CREATE, ALTER, DELETE, or other data definition language (DDL) operations inside the triggers may cause DDL triggers to fire. This may subsequently perform DELETE or UPDATE operations that start additional cascading chains and triggers.

If an error is generated inside any particular cascading referential action chain, an error is raised, no AFTER triggers are fired in that chain, and the DELETE or UPDATE operation that created the chain is rolled back.

A table that has an INSTEAD OF trigger cannot also have a REFERENCES clause that specifies a cascading action. However, an AFTER trigger on a table targeted by a cascading action can execute an INSERT, UPDATE, or DELETE statement on another table or view that fires an INSTEAD OF trigger defined on that object.
Cascading Referential Constraints Catalog Information

Querying the sys.foreign_keys catalog view returns the following values that indicate the cascading referential constraint specified for a foreign key.
Value Description

0 NO ACTION
1 CASCADE
2 SET NULL
3SET DEFAULT

The UPDATE_RULE and DELETE_RULE columns returned by sp_fkeys and sp_foreignkeys return 0 when CASCADE, SET NULL, or SET DEFAULT is specified; and return 1 when NO ACTION is specified or is the default.

When a foreign key is specified as the object of sp_help, the output result set contains the following columns.

Column name Data type Description
delete_action nvarchar(9) Indicates whether the delete action is CASCADE,
SET NULL, SET DEFAULT, NO ACTION, or N/A
(not applicable).
update_action nvarchar(9) Indicates whether the update action is CASCADE,
SET NULL, SET DEFAULT, NO ACTION, or N/A
(not applicable).

Referential integrity constraints in SQL Server

Cascading referential integrity constraints are foreign key constraints that tell SQL Server to perform certain actions when a primary key field in a primary key-foreign key relationship is updated or deleted. By using cascading referential integrity constraints, you can define the actions that SQL Server 2005 takes when a user tries to delete or update a key to which existing foreign keys point.

SQL Server allows you to define cascading referential integrity constraints. These actions have a trickle-down or cascading effect, sometimes affecting several tables that were related to the primary key table. Let’s look at how these constraints are defined, and some situations where you can use them.

The following script sets up the tables that I will use to look at cascading referential constraints:

IF OBJECT_ID('SalesHistory') > 0
DROP TABLE SalesHistory
GO
CREATE TABLE SalesHistory
(
SaleID int IDENTITY(1,1) NOT NULL,
ProductID TINYINT,
CustomerID INT,
SaleDate datetime NULL,
SalePrice money NULL,
CONSTRAINT pk_SaleID PRIMARY KEY (SaleID)
)
GO
IF OBJECT_ID('Customers') > 0
DROP TABLE Customers
GO
CREATE TABLE Customers
(
CustomerID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
CONSTRAINT pk_CustomerID PRIMARY KEY (CustomerID)
)
GO
IF OBJECT_ID('Products') > 0
DROP TABLE Products
GO
CREATE TABLE Products
(
ProductID TINYINT,
ProductDescription VARCHAR(100),
CONSTRAINT pk_ProductID PRIMARY KEY (ProductID)
)
GO

Relationships between tables are required for cascading updates or delete statements; these relationships are defined through FOREIGN KEY constraints. (Here’s more information on defining SQL Server constraints.) The code below defines a relationship between the SalesHistory and the Customers tables and a relationship between the SalesHistory and the Products tables.

ALTER TABLE SalesHistory
ADD CONSTRAINT fk_SalesHistoryCustomerID FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE SET NULL ON UPDATE SET NULL
ALTER TABLE SalesHistory
ADD CONSTRAINT fk_SalesHistoryProductID FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE CASCADE ON UPDATE CASCASE
GO

The previous script introduces the cascading referential integrity options. In the first statement, I use the ON UPDATE SET NULL option; in the second statement, I use the ON DELETE CASCADE ON UPDATE CASCADE option. Here’s an overview of what these constraints mean.

SET NULL
If a delete statement affects rows in a foreign key table, those values will be set to NULL when the primary key record is deleted. If an update statement affects rows in the foreign key table, those rows will be updated with the value NULL after the primary key record has been updated. The foreign key columns affected must allow NULL values.

CASCADE
If a delete statement affects one or more rows in a foreign key table, those rows will be deleted when the primary key record is deleted. If an update statement affects rows in the foreign key table, those rows will be updated with the value from the primary key record after it has been updated.

SET DEFAULT
All the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns in the related table must have default constraints defined on them.

NO ACTION
This is the default action. This specifies that if an update or delete statement affects rows in foreign key tables, the action will be denied and rolled back. An error message will be raised.

To see how these constraints work, I’ll add some data to my tables.

INSERT INTO Products
(
ProductID, ProductDescription
)
SELECT 1, 'BigScreen'
UNION ALL
SELECT 2, 'Computer'
UNION ALL
SELECT 3, 'PoolTable'
GOINSERT INTO Customers(CustomerID , FirstName , LastName )
SELECT 1, 'Jason', 'Tomes'
UNION ALL
SELECT 2, 'Chris', 'Robards'
UNION ALL
SELECT 3, 'Megan', 'Hill'
UNION ALL
SELECT 4, 'Wanda', 'Guthrie'
UNION ALL
SELECT 5, 'Lilly', 'Cunningham'
UNION ALL
SELECT 6, 'Amanda', 'Travis'
UNION ALL
SELECT 7, 'Willy', 'Grant'
UNION ALL
SELECT 8, 'Zach', 'Tacoma'
UNION ALL
SELECT 9, 'Marty', 'Smith'
UNION ALL
SELECT 10, 'Wendi', 'Jones'
UNION ALL
SELECT 11, 'Angie' , 'Corolla'
UNION ALL
SELECT 12, 'Shelly', 'Hartson'
GO

I can load sample data into the SalesHistory table. Because I am using a numeric value to represent the customers, I can generate the CustomerID number with relative ease with the use of the modulus operator.

DECLARE @i SMALLINT
SET @i = 1
WHILE (@i <=100)
BEGIN
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(1, DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i + 57), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(2, DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i + 13), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(3, DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i + 29), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
SET @i = @i + 1
END

Now let’s see if the constraints I set up work. The script below deletes a customer record from my Customers table. Because the cascading constraint indicates ON DELETE SET NULL, the associated records in the SalesHistory table will have the value NULL for the CustomerID column where that column had the value of 6 before the update.

DELETE FROM Customers
WHERE CustomerID = 6

This script invokes the ON DELETE CASCADE constraint defined on the SalesHistory table. This means that when a record is deleted from the Products table, and it is related to a record in the SalesHistory table, those SalesHistory records will be deleted from the table.

DELETE FROM Products
WHERE ProductID = 1
Cascade with care

You can use cascading constraints in SQL Server to set related values to NULL, to set affected values to original default values, or to delete columns. While it’s great to have these capabilities in a testing or quality assurance environment (where data is not production data and consistently reused), I don’t recommend allowing these types of constraints in a production environment. The reason for this is that these constraints may lead to results that you or other programmers on your team are not aware of, and so their code may not be able to handle the actions from the cascading constraint.

If you are in a situation where you need to delete related data from different tables, it has been my experience to have defined procedures in place to do so, rather than to rely on the database to do this for you.

Thursday, November 19, 2009

Whidbey ASP.NET V2.0 New Features

In this article, we are going to see the new features of Whidbey ASP.NET V2.0. This is just the tip of the ice berg. Whidbey ASP.NET V2.0 comes with whole lot of new features. I will keep updating this article, as and when I find any new features in ASP.NET V2.0. Here is the some of the new features which i found interesting.

Cross-page posting

In Whidbey, you will be able to post Web Forms to pages other than the page on which the input is entered. Postback target is chosen based on the PostTargetUrl attribute of a control that causes a postback. On the target page, you will be able to access all of the controls, viewstate, etc. of the page that caused the web form post. Whidbey passes a page object called PreviousPage to the current page for accessing controls,viewstate and all others contents of previous page. For example consider you are filling your personal details in one page and then you need to post this details to next page for processing. In ASP.NET v1.0 you need to post this values to that same page and then you need to redirect to the next page. But in Whidbey you can directly post this values to the next page.

Page1.aspx


Name




Page2.aspx.vb
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = DirectCast(PreviousPage.FindControl("TextBox1"), System.Web.UI.WebControls.TextBox).Text
End Sub
ValidationGroups

You can now have validator controls optionally validate depending on which button on the page is pushed. You can group validation rules into “groups“ so that all controls within that group fire or don't fire.The new feature validation groups allows you to logically group a set of validation controls, and only validate the fields that are in the group to which belongs the postback control that the user clicks. Uses the ValidationGroup attribute to implement in declarative tags. The key here is that you can have two sets of form fields that aren't typically used together, and implement validation on both sets of fields, without the non-used fields causing the page to fail validation. This feature is very useful in the page where you are having two sets of forms for example you might have a page which has search pane in the top and the registration details at the bottom. when find button is clicked you need to validate only the search page controls and similarly when you press create login, you need to validate the controls in registration form. For this type of requirement, this validation groups is very useful. In our example, we have two textbox and two buttons. When one button is pressed we need to validate only one textbox and similarly for other button. Each button has validationgroup attribute set to particular groups which will validate only one textbox.


Name
Address




*
*

Wizard UI

New control that enables step-by-step wizard UI, for example for gathering multiple pages of input for a single purpose before saving or processing the input. The Wizard control defaults to a Next/Previous UI, but is also templated, so you can customize the UI to your needs. In ASP.NET v1.1, if you want to fill lots of details either you need to place all the controls in one page or create multiple pages for groups of controls for providing wizard kind of approach. But in whidbey you have a new control called Wizard control which will do this type of work with one page but providing wizard kind of approach. Check out the following code and find out how easy to create wizard in ASP.NET V2.o








Step 1 : Fill your Name


Step 2 : Fill your Address




You can find new tags like ,,,. Using stepnavigationtemplate you can define the controls that needs to be placed in the navigation template. For example you need to place two button controls and then set id for the controls as stepnextbutton and steppreviousbutton. Then automatically navigation feature will be there for you wizards. For putting controls in each step you can use wizardsteps tag.
ASP.NET Themes

A theme is a collection of property settings that allow you to define the look of pages and controls and then apply the look consistently across pages. You can apply theme settings to an entire application (Web site), to a page and its controls, or to an individual control. If you take popular websites like yahoo they have implemented theme in their site, for example you need to have theme of yellow color. Then you will view that website in yellow color if you want to change to red, then all the controls will change to red. ASP.NET makes available some predefined themes (global themes) that can be applied to any ASP.NET Web application. For example, ASP.NET includes a theme called BasicBlue that defines a common style for most ASP.NET Web server controls.You can create your own themes, called page themes, to apply to your site or to individual pages.
ASP.NET Site Navigation

When you create Web applications that consist of anything more than a few pages, you will find it useful to provide a consistent way for users to navigate around the site. One solution is to include hyperlinks within pages that allow users to jump to other pages. However, if your site becomes large and as you move pages in the site, it quickly becomes difficult to manage all the links. To create consistent, easily managed navigation for your site, you can use ASP.NET site navigation. If you take this website you can see site navigation bar at the left side. This site navigation can be created with very minimal code using following two new controls ,

SiteMapPath control: This control displays a navigation path (also known as a breadcrumb or eyebrow) that shows the user the current page location and displays links as a path back to the home page. The control provides many options for customizing the appearance of the links.

TreeView controls: This control displays a tree structure, or menu, that users can traverse to get to different pages in your site.

URL Rewriting/Mapping

New built-in module for rewriting paths. With this new feature you can map url's to aspx pages in web.config file. This feature can be used to hide the url from the user. If you need to change the location of your aspx page, then you no need to worry. Just change your url mappings in web.config. Since user is exposed to a url which doesnt change you wont get 404 error. Web.config setting for urlmapping is as follows.




If you are requesting for UrlMappings.aspx, then actually you will get the response of Crosspage.aspx. But the user will think that he is getting UrlMappings.aspx only. If you change the Crosspage.aspx location also, you only need to change this setting in web.config.

Site Counters

This feature can be used to montior a web site. For example if you want to know during certain time if you want to know how many hits is made to a particular virutal folder or file. Then you can use this feature. This services exposes many API's like GetTotalCount,GetRows,GetTotalNavigateUrlCount,etc for monitoring a website. Can also be accessed through attributes (CountClicks, CounterGroup, etc.) on declarative tags, as well as through web.config. Using this feature you can efficiently log or report page hits,button click in a page or any other events. For enabling Site counters, you need to place following code in web.config







Client Script Goodies

Server buttons now have an OnClientClick attribute for client-side handling. Focus mechanisms are now built into the page and controls. A page can also have a default button and a default focused control. All these features emit the appropriate client-side script. There will also be automatic scroll position maintenance in the beta release of Whidbey. Here are few examples


No-compile Pages

In web.config, you can configure at the page and folder level whether pages can be compiled after they've been deployed. You can set the compilation option even at page directive. If compilation is disabled, any change to the page after the page or directory has been locked down will throw an exception.





Various options for Compilation mode are Never,Auto and Always.
Image Generation

New feature for generating images in Whidbey. Includes an HttpHandler (.asix) providing a custom handler and base class for image generation, including support for downlevel rendering. Also includes a new DynamicImage control that uses callbacks with the image generation handler to pull down dynamically generated files. .asix files use the @ Image directive and inherit from System.Web.UI.Image.ImageGenerator. Does not require registering your own custom HttpHandler for image generation. Just write the code.

The control supports databinding. You can bind its imagebytes property to a data column that contains binary image data. Using the new Image Generation Service and asp:DynamicImage server control. Show databinding a photo-album where all images are stored in the database, and bound to the asp:DynamicImage control within a asp:DataList template.

File System Provider

It allows Web content (both compiled and non-compiled) to be stored in non-filesystem locations such as databases or CMS, and even use Sql Cache invalidation to output cache stored content, while always getting the updated content if it changes. Pretends to be the filesystem and provides an interface into whatever storage location the content is actually stored in. Cannot store assemblies, but can store just about any other content.


Note :- More information about it from the given link
http://weblogs.asp.net/scottgu/archive/2003/10/22/32965.aspx

Wednesday, October 7, 2009

String Manipulation in C#

Trim Function

The trim function has three variations Trim, TrimStart and TrimEnd. The first example show how to use the Trim(). It strips all white spaces from both the start and end of the string.

//STRIPS WHITE SPACES FROM BOTH START + FINSIHE
string Name = " String Manipulation " ;
string NewName = Name.Trim();
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");
TrimEnd

TrimEnd works in much the same way but u are stripping characters which you specify from the end of the string, the below example first strips the space then the n so the output is String Manipulatio.

//STRIPS CHRS FROM THE END OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','n'};
string NewName = Name.TrimEnd(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");
TrimStart

TrimStart is the same as TrimEnd apart from it does it to the start of the string.

//STRIPS CHRS FROM THE START OF THE STRING
string Name = " String Manipulation " ;
//SET OUT CHRS TO STRIP FROM END
char[] MyChar = {' ','S'};
string NewName = Name.TrimStart(MyChar);
//ADD BRACKET SO YOU CAN SEE TRIM HAS WORKED
MessageBox.Show("["+ NewName + "]");
Find String within string

This code shows how to search within a string for a sub string and either returns an index position of the start or a -1 which indicates the string has not been found.

string MainString = "String Manipulation";
string SearchString = "pul";
int FirstChr = MainString.IndexOf(SearchString);
//SHOWS START POSITION OF STRING
MessageBox.Show("Found at : " + FirstChr );
Replace string in string

Below is an example of replace a string within a string. It replaces the word Manipulatin with the correct spelling of Manipulation.

string MainString "String Manipulatin";
string CorrectString = MainString.Replace("Manipulatin", "Manipulation");
//SHOW CORRECT STRING
MessageBox.Show("Correct string is : " + CorrectString);
Strip specified number of characters from string

This example show how you can strip a number of characters from a specified starting point within the string. The first number is the starting point in the string and the second is the amount of chrs to strip.

string MainString = "S1111tring Manipulation";
string NewString = MainString.Remove(1,4);

//SHOW OUTPUT
MessageBox.Show(NewSring);
Split string with dilemeter

The example below shows how to split the string into seperate parts via a specified dilemeter. The results get put into the Split array and called back via Split[0].

string MainString = "String Manipulation";
string [] Split = MainString.Split(new Char [] {' '});
//SHOW RESULT
MessageBox.Show(Convert.ToString(Split[0]));
MessageBox.Show(Convert.ToString(Split[1]));

Sunday, August 2, 2009

Web 2.0

Key concepts for web 2.0 is

1)interpersonal computing
ie community site ,facebook, youtube

2) Web service
3)Software as a service(Saas)


Cloud Computing

Cloud Computing is a concept by which we can use software as a service (Saas) as well as hardware as services ie utility services.
An Example for

Saas is salsforce.com(CRM) and

Haas is Amazon EC2 (Elastic Compute Cloud) is a computing service. One allocates a set of hosts, and runs one's application on them, then, when done, de-allocates the hosts. Billing is hourly per host. Thus EC2 permits one to deploy Hadoop on a cluster without having to own and operate that cluster, but rather renting it on an hourly basis.


Monday, May 25, 2009

Creatwe Xml To CSV

private string _Name = "export";
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/xmls/Indiatimes-46000.xml"));
ds.WriteXmlSchema(Server.MapPath("~/xmls/IndiaTimes.xsd"));
ExportCSV(ds.Tables[2]);
}

#region CSV

private void ExportCSV(DataTable _product)
{
DataTable dt = _product;
StringBuilder sb = new StringBuilder();

foreach (DataColumn col in dt.Columns)
{
sb.Append(col.ColumnName + ",");
}

sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);

foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(row[i].ToString() + ",");
}

sb.Append(Environment.NewLine);
}

Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + _Name + ".csv");
Response.AppendHeader("Content-Length", sb.Length.ToString());
Response.ContentType = "text/csv";
Response.Write(sb.ToString());
Response.End();
}

#endregion

Thursday, February 19, 2009

Capture Imgae from Url and Resize it

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;

public partial class CaptureImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int Height, Width;
string strImage = "";
Height = 200;
Width = 200;
Image imgPhotoVert = null;

strImage = http://images.play.com/covers/3472012x.jpg.Replace("../", "").Replace("~/", "");
Stream str = null;
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(strImage);
HttpWebResponse wRes = (HttpWebResponse)(wReq).GetResponse();
str = wRes.GetResponseStream();
imgPhotoVert = Image.FromStream(str);
str.Dispose();

Image imgPhoto = null;
imgPhoto = FixedSize(imgPhotoVert, Width, Height);
imgPhoto.Save(Response.OutputStream, ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhotoVert.Dispose();
}
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);

//if we have to pad the height pad both the top and the bottom
//with the difference between the scaled height and the desired height
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((Width - (sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = (int)((Height - (sourceHeight * nPercent)) / 2);
}

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

Graphics grPhoto = Graphics.FromImage(bmPhoto);
//------- Experimenting -------------

//-----------------------------------
grPhoto.Clear(Color.White);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);

grPhoto.Dispose();
return bmPhoto;
}
}

Websitescreenshot

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Reflection;
using mshtml;

///
/// Summary description for Websitescreenshot
///

///
namespace GetSiteThumpnail
{
public class Websitescreenshot
{

private int S_Height;
private int S_Width;
private int F_Height;
private int F_Width;
private string MyURL;
private WebBrowser MyBrowser;
private string URL;
private int Height;
private int Width;
private System.Drawing.Bitmap oThumbNail;

public int ScreenHeight
{
get { return S_Height; }
set { S_Height = value; }
}
public int ScreenWidth
{
get { return S_Width; }
set { S_Width = value; }
}
public int ImageHeight
{
get { return F_Height; }
set { F_Height = value; }
}
public int ImageWidth
{
get { return F_Width; }
set { F_Width = value; }
}
public string WebSite
{
get { return MyURL; }
set { MyURL = value; }
}
public Websitescreenshot(string WebSite, int ScreenWidth, int ScreenHeight, int ImageHeight, int ImageWidth)
{
this.WebSite = WebSite;
this.ScreenWidth = ScreenWidth;
this.ScreenHeight = ScreenHeight;
this.ImageHeight = ImageHeight;
this.ImageWidth = ImageWidth;
}
public Bitmap GetBitmap()
{
//WebPageBitmap Shot = new WebPageBitmap(this.WebSite, this.ScreenWidth, this.ScreenHeight);
WebPageBitmap(this.WebSite, this.ScreenWidth, this.ScreenHeight);
Thread m_thread = new Thread(new ThreadStart(GetIt));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
//Shot.GetIt();
Bitmap Pic = (Bitmap)oThumbNail; //DrawBitmap(this.ImageHeight, this.ImageWidth);
return Pic;
}

public void WebPageBitmap(string url, int width, int height)
{
this.Height = height;
this.Width = width;
this.URL = url;
}

public void GetIt()
{
MyBrowser = new WebBrowser();
MyBrowser.ScrollBarsEnabled = false;
//MyBrowser.Size = new Size(this.Width, this.Height);
MyBrowser.ClientSize = new Size(this.Width, this.Height);
MyBrowser.Navigate(this.URL);
MyBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while (MyBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
MyBrowser.Dispose();
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser MyBrowser = (WebBrowser)sender;
Bitmap myBitmap = new Bitmap(Width, Height);
Rectangle DrawRect = new Rectangle(0, 0, Width, Height);
MyBrowser.DrawToBitmap(myBitmap, DrawRect);
System.Drawing.Image imgOutput = myBitmap;
oThumbNail = new Bitmap(this.ImageWidth, this.ImageHeight, imgOutput.PixelFormat);
oThumbNail.SetResolution(imgOutput.HorizontalResolution, imgOutput.VerticalResolution);
Graphics g = Graphics.FromImage(oThumbNail);
g.Clear(Color.White);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
Rectangle oRectangle = new Rectangle(0, 0, this.ImageWidth, this.ImageHeight);
g.DrawImage(imgOutput, oRectangle);
//try
//{
// return oThumbNail;
//}
//catch
//{
// throw;
//}
//finally
//{
imgOutput.Dispose();
//MyBrowser.Dispose();
//}

}


private void GetHtml()
{
WebBrowser web = new WebBrowser();
web.Navigate(this.URL);
IHTMLDocument2 doc = web.Document.DomDocument as IHTMLDocument2;
IHTMLElement2 img = doc.images;

}

}

}

Calling this class function in the given format:-
private void CaptureScreen(string url)
{
try
{
string path = null;
path = Server.MapPath("~/images/orderdeals/");
string picName = null;
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
picName = "order-" + Request.QueryString["id"].ToString() + "-" + RandomNumber + ".jpg"; //Format order-dealid-RandomNumber;
//int width = Int32.Parse(txtWidth.Text);
//int height = Int32.Parse(txtHeight.Text);
Websitescreenshot screenshot = new Websitescreenshot(url, 1024, 800, 800, 1024);
//Bitmap bmp = screenshot.GetBitmap();
System.Drawing.Image img = screenshot.GetBitmap();
img.Save(path + picName, ImageFormat.Jpeg);
//bmp.Save(path + "google.jpg");
//imgDeal.ImageUrl = Page.ResolveUrl("~/processimage.aspx?FilePath=../images/orderdeals/" + picName + "&height=464&width=933");
Response.Write(picName);
}
catch (Exception ex)
{

}
}