This blog post is an update to an introduction to the data binding capabilities we first added in Data Services v1.5 CTP1. In CTP2 we have taken the feedback we received from CTP1 and made some updates to the data binding feature. Since this is a CTP release of this feature we eagerly look forward to hearing more of your feedback. Introduction to Data Binding A new collection type, DataServiceCollection, has been added to the client library which extends ObservableCollection and supports two way binding for client code. It is now possible to auto generate client side types that implement the INotifyPropertyChanged and INotifyCollectionChanged interfaces using the add service reference gesture. This means that, when data binding has been enabled, any changes made to contents of a DataServiceCollection or the entities in the collection will be reflected on the client context; any subsequent calls to SaveChanges() on that context will then persist those changes on the service. As well, any changes made to the entities in the context, through a subsequent query to the data service, will automatically be reflected on the items in the DataServiceCollection. This also means that the DataServiceCollection, because it implements the standard binding interfaces, can be bound as the DataSource to most WPF and Silverlight controls. Here are some examples of different ways to create a DataServiceCollection using the ADO.NET Data Services client library. In all of these examples, the queries are being executed against a service named “nwsvc” that exposes two types: products and suppliers that have a one-to-many relationship. Example 1: Creating a DataServiceCollection of all products. DataServiceCollection<Products> products = Example 2: Creating a DataServiceCollection of all products and their associated suppliers. DataServiceCollection<Products> products = DataServiceCollection<Products> products = The following is a walkthrough of using data binding in a WPF application. The walkthrough is a basic introduction to binding in ADO.NET Data Services, if you are already familiar with binding in WPF and Data Services you may want to wait for the next blog post on data binding that will cover more advanced concepts. To get started, you'll want to download all of the required software I use in the walkthrough: Step 1: Create an ADO.NET Data Service v1.5 Service Create a new Web Application (named DatabindingDemo): Our first data access related task is to generate the Entity Framework-based data access layer to the Northwind database. Right click the ASP.NET project and select 'Add New Item', then select 'ADO.NET Entity Data Model'. Name the new item nw.edmx: After clicking ‘Add’ on the screen above, a wizard will open to walk you through creating the Entity Data Model for the Northwind database. Use the default settings until you get to the point where you choose the database objects to include in the model. For this demo, choose only the Products and Suppliers tables. Once you reach the ‘Choose Your Database Objects’ screen, select the two tables and click ‘Finish’. This will open the Entity Data Model designer view. This view allows you to customize the auto-generated conceptual data model. To learn more about the mapping capabilities of the Entity Framework, see the MSDN page here. Create a v1.5 CTP2-based ADO.NET Data Service over this model. To create the data service, right click the ASP.NET project and select 'Add New Item'. Add an 'ADO.NET Data Service v1.5 CTP2' item called nw.svc This will generate a file (nw.svc.cs) which represents the skeleton of a v1.5 data service. All we need to do now is point the data service at the data model to be exposed as a REST-service and we’ll be set. The snippet below shows the 2 or so lines of code you need to write to do this. One thing to note is that a data service is locked down by default, so we need to take explicit steps to open access to it. For this simple application we’ll enable read and write access to the entire model quickly using the call to ‘SetEntitySetAccessRule’ shown below. public static void InitializeService(DataServiceConfiguration config) The data service is now created. To test this, run the project and navigate to the nw.svc file. You should see a listing as shown below that outlines all the entry points to the data service. If you don’t, tweak your IE settings and reload. Step 2: Enable data binding on the client. By default, the client side types generated by ADO.NET Data Services v1.5 CTP2 do not implement binding interfaces. To get client side types that do implement the binding interfaces, you have to tell the code generation library that you want client code that has binding enabled. To do this, set an environment variable before starting Visual Studio and then use Add Service Reference (ASR) to generate client proxy code. The environment variables to set are: set dscodegen_usedsc=1 set dscodegen_version=2.0 Note: The use of this environment variable is further explained by the video embedded in this blog post. Note: It is also possible to generate proxy code that have binding enabled using DataSvcUtil.exe with the /DataServiceCollection and /Version flag. Step 3: Create client proxy code with binding enabled. After setting the environment variable in step 2, open the solution you created in step 1 and create a new WPF project. Once you have created a WPF client project, the next step is to generate client side types. To do this, find the DatabindingClient project in the solution explorer, right-click the project and selectAdd Service Reference... In the Add Service Reference dialog, click the Discover button. The Northwind.svc service will show up in the Service window. Enter NorthwindService as the Namespace value and select OK. This wizard will generate a set of client side types that can be used to interact with the service created in step 1. You will now see a new NorthwindService node under the Service References Node in the solution explorer. As well, you will see a reference to Microsoft.Data.Services.Client in the references node; if you do not see the reference to Microsoft.Data.Services.Client or you see a reference to System.Data.Services.Client go to the ADO.NET Data Services blog and read thispost about enabling ADO.NET Data Services v1.5 features in Visual Studio and then repeat the Add Service Reference Step. The next part of this step is to create a new instance of the ADO.NET Data Services client context and connect to the service created in step 1. To do this, add the following code to the Window1.xaml.cs file to create a connection to the service; making sure to replace the host and port number with the values for your service. public partial class Window1 : Window The next step is to create an interface that you can bind the result of a query to. The service you created in step 1 exposes a set of Suppliers and a set of Products from the Northwind database with a one-to-many relationship between them. The XAML code below will create two listviews, one to display the suppliers and another to display the products associated with the current supplier selected in the first view. This type of binding is called master-detail binding. The code below uses standard WPF binding semantics. The ItemsSource of the supplierView is set to “{Binding}”, this will cause the listview to bind to the collection of items that are supplied as the data context of the supplierView; in this case the collection of items will be a collection of supplier objects. The columns of the supplierView are each bound to a property of the supplier object through the DisplayMemberBinding="{Binding Path=SupplierID}"/> tag. The second listview, productsView, is bound to the Products property of the supplier objects by the ItemsSource="{Binding Products}" tag. By supplying the IsSynchronizedWithCurrentItem="True" tag on the listview, you are taking advantage of the feature WPF has to automatically display the items in the second list view (products) that are associated with the currently selected item in the first list view (suppliers). Paste the following code snippet into the window1.xaml file: <Grid Name="productViewGrid"> This will create a WPF interface that looks like this: The final step to enable binding to these WPF controls is to set the DataContext of the grid in the window you just created to the result of a query for suppliers from the service created in step 1. This is done by executing a standard ADO.NET Data Services query on the context for the set of suppliers and then loading the result of the query into a DataServiceCollection. To do this, add the following code to the constructor for the window: public Window1() Once this is complete, compile the project and run it. The result should be: Step 4: Two-way Binding Up to this point in the walkthrough, you have set up a service, created a WPF client and bound the result of a query to the service to a pair of listview controls in the client. This type of binding you have done so far has all been one-way binding. The DataServiceCollection you used at the end of step 3 also supports two-way binding. This means that any changes made to the collection or items in the collection will propagate to the service when a call to SaveChanges() is made on the context. This final step will walk you through adding buttons that will add items to the collection of products and take advantage of two-way binding to have those changes propagate to the service and the backing northwind database. To start, add the following XAML code to the window1.xaml file to create buttons to that will add a product from the list of products and save the changes to the service. <Button Height="24" HorizontalAlignment="Right" Margin="0,0,89,4" Name="addButton" VerticalAlignment="Bottom" Width="28" Click="addButton_Click">+Button> The next step is to handle the click events on the new buttons and add the currently select product in the list. The first thing we will need is a new product window to input the property values of a new product when one is created. To do this, create a new WPF window in your client project called ProductWindow. After creating the window, we need to set up the product window to bind to a single instance of the product class. To configure binding in the product window, you will use the same WPF binding method you used for the supplier window, except this window will bind to a single object and not a collection of objects. Add the following XAML code into the ProductWindow.xaml: <Grid x:Name="productGrid"> Set the height of the product window to 206 and the width to 296. Next add the following code to the ProductWindow.xaml.cs file to set the data context to a single product and handle the ok button click event. The click event will add the newly created product to the current suppliers list of products. public partial class ProductWindow : Window The final step is to handle the add and save button click events in the supplier window. Add the following code to the Window1.xaml.cs file. Add the following code to the addButton_Click event to create a new product when the add button is selected. The code creates a new Product and creates a new product window for the user to input the property values for the new product . private void addButton_Click(object sender, RoutedEventArgs e) Add the following code to handle the save button click. This button calls SaveChanges on the context which will cause any operations that have been performed on the context to be sent to the service. private void saveButton_Click(object sender, RoutedEventArgs e) Your project is now complete. You can run the form and use the buttons to add items from the collection of products. When you make a change you then click the save button to persist the changes to the service.Introduction to Data Binding in CTP2
DataServiceCollection.CreateTracked<Products>(
nwsvc,
from p in nwsvc.Products
select p
);
DataServiceCollection.CreateTracked<Products>(
nwsvc,
from p in nwsvc.Products.Expand("Suppliers")
select p
);
Example 3: Creating a new DataServiceCollection of products. This creates a new empty collection of products without issuing a query against the service. New product objects can be created and added to this collection.
DataServiceCollection.CreateTracked<Products>(
nwsvc);
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
// TODO: set service behavior configuration options
// Examples:
// config.DataServiceBehavior.AcceptCountRequests = true;
// config.DataServiceBehavior.AcceptProjectionRequests = true;
config.DataServiceBehavior.MaxProtocolVersion = System.Data.Services.Common.DataServiceProtocolVersion.V2;
}
{
NorthwindEntities nwsvc = new NorthwindEntities(new Uri("http://localhost:52002/Northwind.svc/"));
public Window1()
{
InitializeComponent();
}
}
<ListView ItemsSource="{Binding}" Margin="25,11,33,145" Name="supplierView" IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=SupplierID}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=CompanyName}"/>
<GridViewColumn Header="Address" DisplayMemberBinding="{Binding Path=Address}"/>
<GridViewColumn Header="City" DisplayMemberBinding="{Binding Path=City}"/>
<GridViewColumn Header="Region" DisplayMemberBinding="{Binding Path=Region}"/>
GridView>
ListView.View>
ListView>
<ListView Margin="25,0,33,12" Name="productsView" ItemsSource="{Binding Products}" IsSynchronizedWithCurrentItem="True" Height="117" VerticalAlignment="Bottom" >
<ListView.View>
<GridView>
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding ProductID}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding ProductName}"/>
<GridViewColumn Header="QuantityPerUnit" DisplayMemberBinding="{Binding QuantityPerUnit}"/>
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding UnitPrice}"/>
<GridViewColumn Header="InStock" DisplayMemberBinding="{Binding UnitsInStock}"/>
GridView>
ListView.View>
ListView>
Grid>
Edit the following attributes of your window: Height="382" Width="584" to properly display the controls.
{
InitializeComponent();
this.productViewGrid.DataContext =
DataServiceCollection.CreateTracked<Suppliers>(nwsvc,
nwsvc.Suppliers.Expand("Products")
);
}
<Button Height="24" HorizontalAlignment="Right" Margin="0,0,33,4" Name="saveButton" VerticalAlignment="Bottom" Width="50" Click="saveButton_Click">SaveButton>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="171*" />
<ColumnDefinition Width="159*" />
Grid.ColumnDefinitions>
<Label Height="26" Margin="12,17,68,0" Name="nameLabel" VerticalAlignment="Top">Name:Label>
<Label Margin="12,49,6,0" Name="quantityLabel" Height="26" VerticalAlignment="Top">Quantity Per Unit:Label>
<Label Margin="12,78,68,64" Name="priceLabel">Price:Label>
<Label Height="26" Margin="12,0,68,35" Name="inStockLabel" VerticalAlignment="Bottom">InStock:Label>
<TextBox Height="23" Margin="0,23,28.018,0" Name="nameTextBox" VerticalAlignment="Top" Text="{Binding ProductName}" Grid.Column="1" />
<TextBox Margin="0,52,28.018,0" Name="quantityTextBox" Text="{Binding QuantityPerUnit}" Height="23" VerticalAlignment="Top" Grid.Column="1" />
<TextBox Margin="0,81,28.018,64" Name="priceTextBox" Text="{Binding UnitPrice}" Grid.Column="1" />
<TextBox Height="23" Margin="0,0,28.018,35" Name="inStockTextBox" VerticalAlignment="Bottom" Text="{Binding UnitsInStock}" Grid.Column="1" />
<Button Height="23" Margin="19.018,0,61,6" Name="okButton" VerticalAlignment="Bottom" Grid.Column="1" Click="okButton_Click">OKButton>
Grid>
{
Suppliers curSupplier;
Products newProduct;
public ProductWindow(Products p, Suppliers s)
{
InitializeComponent();
this.productGrid.DataContext = p;
curSupplier = s;
newProduct = p;
}
private void okButton_Click(object sender, RoutedEventArgs e)
{
curSupplier.Products.Add(newProduct);
this.Close();
}
}
{
Suppliers supplier = this.supplierView.SelectedItem as Suppliers;
Products product = new Products();
ProductWindow win = new ProductWindow(product, supplier);
win.Show();
}
{
nwsvc.SaveChanges();
}
Introduction to Data Binding With EntityFramework
Monday, September 14, 2009
Posted by Usama Wahab Khan at 11:07 PM 0 comments
Labels: C#, entityframework, wcf, wpf
Asp.net Databind With Linq & linq to Sql
Sunday, September 6, 2009
LINQ: .NET Language-Integrated Query 3 set there id girdView to Gvlinq and Button1 to btnbinding
After two decades, the industry has reached a stable point in the evolution of object-oriented (OO) programming technologies. Programmers now take for granted features like classes, objects, and methods. In looking at the current and next generation of technologies, it has become apparent that the next big challenge in programming technology is to reduce the complexity of accessing and integrating information that is not natively defined using OO technology. The two most common sources of non-OO information are relational databases and XML.
Rather than add relational or XML-specific features to our programming languages and runtime, with the LINQ project we have taken a more general approach and are adding general-purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data. This facility is called .NET Language-Integrated Query (LINQ).
We use the term language-integrated query to indicate that query is an integrated feature of the developer's primary programming languages (for example, Visual C#, Visual Basic). Language-integrated query allows query expressions to benefit from the rich metadata, compile-time syntax checking, static typing and IntelliSense that was previously available only to imperative code. Language-integrated query also allows a single general purpose declarative query facility to be applied to all in-memory information, not just information from external sources.
.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable
The extensibility of the query architecture is used in the LINQ project itself to provide implementations that work over both XML and SQL data. The query operators over XML (LINQ to XML) use an efficient, easy-to-use, in-memory XML facility to provide XPath/XQuery functionality in the host programming language. The query operators over relational data (LINQ to SQL) build on the integration of SQL-based schema definitions into the common language runtime (CLR) type system. This integration provides strong typing over relational data while retaining the expressive power of the relational model and the performance of query evaluation directly in the underlying store.
Object Relational Designer (O/R Designer)
The Object Relational Designer (O/R Designer) provides a visual design surface for creating LINQ to SQL entity classes and associations (relationships) that are based on objects in a database. In other words, the O/R Designer is used to create an object model in an application that maps to objects in a database. It also generates a strongly-typed DataContext that is used to send and receive data between the entity classes and the database. The O/R Designer also provides functionality to map stored procedures and functions to DataContext methods for returning data and populating entity classes. Finally, the O/R Designer provides the ability to design inheritance relationships between entity classes.
Tutorial
1 open Vs 2008 and Create new website
2 Drag n Drop on Form Button and GridView Control From ToolBar
4 Right Click on Solution Explorer click on Add newitem and Select linq to sql
5 Open Server Explorer and Drag and drop any table form Database if u did`nt Created at yat so Sample database is available in Sorcecode copy from there
6 goback to default.aspx and double Click on button
and write code blow
Posted by Usama Wahab Khan at 10:07 PM 0 comments
Labels: Asp.net, Databinding, linq
Asp.net Questions
Monday, August 31, 2009
Que:- What is the sequence in which ASP.NET events are processed ?
Ans:- Following is the sequence in which the events occur :-
* Page_Init.
* Page_Load.
* Control events.
* Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.
Que:- In which event are the controls fully loaded ?
Ans:- Page_load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event.
Que:- How can we identify that the Page is PostBack ?
Ans:- Page object has a “IsPostBack” property which can be checked to know that is the page posted back.
Que:-What is event bubbling ?
Ans:- Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event. As the child control send there events to parent this is termed as event bubbling.
Que:- If we want to make sure that no one has tampered with ViewState, how do we ensure it?
Ans:- Using the @Page directive EnableViewStateMac to True.
Que:- What is AppSetting Section in “Web.Config” file?
Ans:- Web.config file defines configuration for a webproject. Using “AppSetting” section we can define user defined values. Example below defined is ConnectionString” section which will be used through out the project for database connection.
Que:- Where is ViewState information stored ?
Ans:- In HTML Hidden Fields.
Que:- How can we create custom controls in ASP.NET ?
Ans:- User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:
* Register the ASCX control in page using the <%@ Register directive>.
Example:-
<%@ Register tagprefix="Accounting" Tagname="footer" Src="Footer.ascx" %>
* Now to use the above accounting footer in page you can use the below directive.
Que:- How many types of validation controls are provided by ASP.NET ?
Ans:- There are six main types of validation controls :-
1). RequiredFieldValidator :-
It checks whether the control have any value. It's used when you want the control should not be empty.
2). RangeValidator :-
It checks if the value in validated control is in that specific range. Example
TxtCustomerCode should not be more than eight length.
3). CompareValidator:-
It checks that the value in controls should match the value in other control. Example
Textbox TxtPie should be equal to 3.14.
4). RegularExpressionValidator:-
When we want the control value should match with a specific regular expression.
5). CustomValidator:-
It is used to define UserDefined validation.
6). ValidationSummary:-
It displays summary of all current validation errors.
Que:- Can you explain what is “AutoPostBack” feature in ASP.NET ?
Ans:- If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.
Que:- How can you enable automatic paging in DataGrid ?
Ans:- Following are the points to be done in order to enable paging in Datagrid :-
* Set the “AllowPaging” to true.
* In PageIndexChanged event set the current pageindex clicked.
Que:-What is the difference between “Web.config” and “Machine.Config” ?
Ans:- “Web.config” files apply settings to each web application, while Machine.config” file apply settings to all ASP.NET applications.
Que:- What is the difference between Server.Transfer and response.Redirect ?
Ans:- Following are the major differences between them:-
* Response.Redirect sends message to the browser saying it to move to some
different page, while server.transfer does not send any message to the browser
but rather redirects the user directly from the server itself. So in server.transfer
there is no round trip while response.redirect has a round trip and hence puts
a load on server.
* Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is www.yahoo.com you can use server.transfer to move
to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e.
within websites. This cross server redirect is possible only using
Response.redirect.
* With server.transfer you can preserve your information. It has a parameter
called as “preserveForm”. So the existing query string etc. will be able in the
calling page. In response.redirect you can maintain the state, but has
lot of drawbacks.
Que:- What is the difference between Authentication and authorization?
Ans:- This can be a tricky question. These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceed to Authorization; even if your application lets anonymous users connect and use
the application, it still authenticates them as being anonymous.
Que:- What are the various ways of authentication techniques in ASP.NET?
Ans:- Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:
* authentication mode=”windows”
* authentication mode=”passport”
* authentication mode=”forms”
* Custom authentication where you might install an ISAPI filter in IIS that
compares incoming requests to list of source IP addresses, and considers
requests to be authenticated if they come from an acceptable address. In that
case, you would set the authentication mode to none to prevent any of the
.net authentication providers from being triggered.
Que:- How does authorization work in ASP.NET?
Ans:- ASP.NET impersonation is controlled by entries in the applications web.config file. The default setting is “no impersonation”. You can explicitly specify that ASP.NET shouldn’t use impersonation by including the following code in the file
It means that ASP.NET will not perform any authentication and runs with its own
privileges. By default ASP.NET runs as an unprivileged account named ASPNET. You
can change this by making a setting in the processModel section of the machine.config
file. When you make this setting, it automatically applies to every site on the server. To user a high-privileged system account instead of a low-privileged set the userNameattribute of the processModel element to SYSTEM. Using this setting is a definite security risk, as it elevates the privileges of the ASP.NET process to a point where it can do bad things to the operating system.
Que:- What’s difference between Datagrid, Datalist and repeater ?
Ans:- A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.
They have many things in common like DataSource Property, DataBind Method
ItemDataBound and ItemCreated.
When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow
present in the DataRow Collection of DataTable is assigned to a corresponding
DataGridItem and this is same for the rest of the two controls also. But The HTML code generated for a Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows.
For a Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records should
appear per HTML table row. In short in datagrid we have one record per row, but in
datalist we can have five or six rows per row.
For a Repeater Control, the Datarecords to be displayed depends upon the Templates
specified and the only HTML generated is the due to the Templates.
In addition to these, Datagrid has a in-built support for Sort, Filter and paging the Data,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.
Que:- From performance point of view how do they rate ?
Ans:- Repeater is fastest followed by Datalist and finally datagrid.
Que:- What is the method to customize columns in DataGrid?
Ans:- Use the template column.
Que:- How can we format data inside DataGrid?
Ans:- Use the DataFormatString property.
Que:- How to decide on the design consideration to take a Datagrid, datalist or repeater ?
Ans:- Many make a blind choice of choosing datagrid directly, but that's not the right way.
Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it comes at a cost of speed. Second the display format is simple that is in row and columns.
Real life scenarios can be more demanding that With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. It offers better performance than datagrid Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. But repeater does not provide editing features like datagrid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls.
Repeater is fastest followed by Datalist and finally datagrid.
Que:- Difference between ASP and ASP.NET?
Ans:- ASP.NET new feature supports are as follows :-
Better Language Support
* New ADO.NET Concepts have been implemented.
ASP.NET supports full language (C#, VB.NET, C++) and not simple scripting
like VBSCRIPT..
Better controls than ASP
* ASP.NET covers large set’s of HTML controls..
* Better Display grid like Datagrid, Repeater and datalist.Many of the display
grids have paging support.
Controls have events support
* All ASP.NET controls support events.
* Load, Click and Change events handled by code makes coding much simpler and much better organized.
Compiled Code
The first request for an ASP.NET page on the server will compile the ASP.NET code and
keep a cached copy in memory. The result of this is greatly increased performance.
Better Authentication Support
ASP.NET supports forms-based user authentication, including cookie management and
automatic redirecting of unauthorized logins. (You can still do your custom login page and custom user checking).
User Accounts and Roles
ASP.NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.
High Scalability
* Much has been done with ASP.NET to provide greater scalability.
* Server to server communication has been greatly enhanced, making it possible
to scale an application over several servers. One example of this is the ability
to run XML parsers, XSL transformations and even resource hungry session objects on other servers.
Easy Configuration
Configuration of ASP.NET is done with plain text files.
* Configuration files can be uploaded or changed while the application is running.
No need to restart the server. No more metabase or registry puzzle.
Easy Deployment
No more server restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.
Que:- What are major events in GLOBAL.ASAX file ?
Ans:- The Global.asax file, which is derived from the HttpApplication class, maintains a pool
of HttpApplication objects, and assigns them to applications as needed. The Global.asax
file contains the following events:
Application_Init: Fired when an application initializes or is first called. It is invoked for
all HttpApplication object instances.
Application_Disposed: Fired just before an application is destroyed. This is the ideal
location for cleaning up previously used resources.
Application_Error: Fired when an unhandled exception is encountered within the
application.
Application_Start: Fired when the first instance of the HttpApplication class is created.
It allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed.
It is fired only once during an application's lifetime.
Application_BeginRequest: Fired when an application request is received. It is the first
event fired for a request, which is often a page request (URL) that a user enters.
Application_EndRequest: The last event fired for an application request.
Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework
begins executing an event handler like a page or Web service.
Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has finished executing an event handler
Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends
HTTP headers to a requesting client (browser).
Application_UpdateRequestCache: Fired when the ASP.NET page framework completes
handler execution to allow caching modules to store responses to be used to handle
subsequent requests.
Application_AuthenticateRequest: Fired when the security module has established the
current user's identity as valid. At this point, the user's credentials have been validated.
Application_AuthorizeRequest: Fired when the security module has verified that a user
can access resources.
Session_Start: Fired when a new user visits the application Web site.
Session_End: Fired when a user's session times out, ends, or they leave the application
Web site.
Que:- What order they are triggered ?
Ans:- They're triggered in the following order:
* Application_BeginRequest
* Application_AuthenticateRequest
* Application_AuthorizeRequest
* Application_ResolveRequestCache
* Application_AcquireRequestState
* Application_PreRequestHandlerExecute
* Application_PreSendRequestHeaders
* Application_PreSendRequestContent
<>
* Application_PostRequestHandlerExecute
* Application_ReleaseRequestState
* Application_UpdateRequestCache
* Application_EndRequest.
Que:- How can we force all the validation control to run ?
Ans:- Page.Validate
Que:- How can we check if all the validation control are valid and proper ?
Ans:- Using the Page.IsValid() property you can check whether all the validation are done.
Que:- Which JavaScript file is referenced for validating the validators at the client side ?
Ans:- WebUIValidation.js javascript file installed at “aspnet_client” root IIS directory is used
to validate the validation controls at the client side
Que:- What is Tracing in ASP.NET ?
Ans:- Tracing allows us to view how the code was executed in detail.
Que:- How do we enable tracing ?
Ans:- <%@ Page Trace="true" %>
Que:- How can we kill a user session ?
Ans:- Session.abandon
Que:- How do I send email message from ASP.NET ?
ANs:- ASP.NET provides two namespaces System.WEB.mailmessage classand
System.Web.Mail.Smtpmail class. Just a small homework create a Asp.NET project and
send a email at "Email Adress". Do not Spam.
Que:- Explain the differences between Server-side and Client-side code?
Ans:- Server side code is executed at the server side on IIS in ASP.NET framework, while
client side code is executed on the browser.
Posted by Usama Wahab Khan at 10:21 PM 0 comments
Labels: Asp.net
Silverlight Baskit Ball
Saturday, August 29, 2009
Posted by Usama Wahab Khan at 3:40 AM 0 comments
Labels: Silverlight
What’s new in ASP.NET 4.0
Sunday, August 16, 2009
With Visual Studio 2010 Beta 1 and .NET Framework Beta 1 out for some time, this post is due from me for a long time. ASP.NET 4.0 has many improvements for different set of scenarios such as Webforms, Dynamic Data & AJAX based web development. There are also a lot of enhancements to the core runtime that powers ASP.NET such as Caching, Session & Request/Response objects.
For this post, we will examine some of the web form enhancements. There are sure a lot of them and we will examine some of them in the future posts.
Controlling View State using the ViewStateMode Property – Performance Enhancement
One of the most complained thing in ASP.NET Webform is the growing viewstate which becomes a concern for performance. While earlier you can set the EnableViewState property to true or false, post that, all the controls, by default inherit and even if you set it to enabled at control level, the behaviour was inconsistent.
With ASP.NET 4.0, the ViewStateMode property helps to determine for every control, whether the ViewState should be enabled, disabled or inherited accordingly. Ex.-
When you run the above page, you can find that the intial value for both the labels is set to “Value set in code behind” whereas after clicking on the button (postback), the value of label1 changes to “Value set in markup” whereas the value of label2 remains unchanged. As you can see, the Panel which holds both these lables has ViewStateMode set to Disabled and label1 is inherting the mode (this is the default if not specified) and label2 has it enabled. That is the reason label2 maintains viewstate while label1 loses it.
While it is arguably possible using the simple EnableViewState property earlier, it was never consistent. Considering the fact that in most of our performance sessions, we talk about disabling viewstate and then enabling it at control level while it doesnt work, this ViewStateMode is a welcome architectural change to improve performance.
Page Meta Keyword & Description – Search Engine Optimization feature
Upto Visual Studio 2008, one can set the Title of the page declaratively or through program using Page.Title. However, as more and more web traffic is happening through search engines, Page’s Title, Keyword and description become more important. Although the Keyword feature was exploited and hence many search engines today ignore it, Page Description is something still major search engines such as Google, Bing use for identifying and indexing pages based on content.
The new feature in ASP.NET 4.0 allows users to programmatically set the Page Description and Keywords as follows:-
The above code appends the following markup
And the way it works is that, if the meta tags are already present in the HTML markup, whatever is set in the code behind will fill up the “content” part alone if the “name” tag is matching.
Although this looks simple, it is very useful in cases where you want to set these dynamically based on a condition / criteria. So far, these were set statically in the HTML. Now with Page Class level access, these can be set dynamically.
There are many more enhancements to Webforms such as Routing improvements, setting ClientID etc., which we will examine in the future posts.
Cheers !!!


