Monday, February 16, 2009
Toll free
Indian Airlines - 1800 180 1407
Jet Airways - 1800 22 5522
SpiceJet - 1800 180 3333
Air India -- 1800 22 7722
KingFisher - 1800 180 0101
Banks
ABN AMRO - 1800 11 2224
Canara Bank - 1800 44 6000
Citibank - 1800 44 2265
Corporatin Bank - 1800 443 555
Development Credit Bank - 1800 22 5769
HDFC Bank - 1800 227 227
ICICI Bank - 1800 333 499
ICICI Bank NRI - 1800 22 4848
IDBI Bank - 1800 11 6999
Indian Bank - 1800 425 1400
ING Vysya - 1800 44 9900
Kotak Mahindra Bank - 1800 22 6022
Lord Krishna Bank - 1800 11 2300
Punjab National Bank - 1800 122 222
State Bank of India - 1800 44 1955
Syndicate Bank - 1800 44 6655
Automobiles
Mahindra Scorpio - 1800 22 6006
Maruti - 1800 111 515
Tata Motors - 1800 22 5552
Windshield Experts - 1800 11 3636
Computers/IT
Adrenalin - 1800 444 445
AMD - 1800 425 6664
Apple Computers - 1800 444 683
Canon - 1800 333 366
Cisco Systems - 1800 221 777
Compaq - HP - 1800 444 999
Data One Broadband - 1800 424 1800
Dell - 1800 444 026
Epson - 1800 44 0011
eSys - 3970 0011
Genesis Tally Academy - 1800 444 888
HCL - 1800 180 8080
IBM - 1800 443 333
Lexmark - 1800 22 4477
Marshal's Point - 1800 33 4488
Microsoft - 1800 111 100
Microsoft Virus Update - 1901 333 334
Seagate - 1800 180 1104
Symantec - 1800 44 5533
TVS Electronics - 1800 444 566
WeP Peripherals - 1800 44 6446
Wipro - 1800 333 312
xerox - 1800 180 1225
Zenith - 1800 222 004
Railways
Indian Railway General Enquiry 131
Indian Railway Central Enquiry 131
Indian Railway Reservation 131
Indian Railway All Enquiry 139
Indian Railway Railway Reservation Enquiry 1345,1335,1330
Indian Railway Centralised Railway Enquiry 1330/1/2/3/4/ 5/6/7/8/9
Couriers/Packers & Movers
ABT Courier - 1800 44 8585
AFL Wizz - 1800 22 9696
Agarwal Packers & Movers - 1800 11 4321
Associated Packers P Ltd - 1800 21 4560
DHL - 1800 111 345
FedEx - 1800 22 6161
Goel Packers & Movers - 1800 11 3456
UPS - 1800 22 7171
Home Appliances
·
· Aiwa/Sony - 1800 11 1188
· Anchor Switches - 1800 22 7979
· Blue Star - 1800 22 2200
· Bose Audio - 1800 11 2673
· Bru Coffee Vending Machines - 1800 44 7171
· Daikin Air Conditioners - 1800 444 222
· DishTV - 1800 12 3474
· Faber Chimneys - 1800 21 4595
· Godrej - 1800 22 5511
· Grundfos Pumps - 1800 33 4555
· LG - 1901 180 9999
· Philips - 1800 22 4422
· Samsung - 1800 113 444
· Sanyo - 1800 11 0101
· Voltas - 1800 33 4546
· WorldSpace Satellite Radio - 1800 44 5432
Investments/ Finance
CAMS - 1800 44 2267
Chola Mutual Fund - 1800 22 2300
Easy IPO's - 3030 5757
Fidelity Investments - 1800 180 8000
Franklin Templeton Fund - 1800 425 4255
J M Morgan Stanley - 1800 22 0004
Kotak Mutual Fund - 1800 222 626
LIC Housing Finance - 1800 44 0005
SBI Mutual Fund - 1800 22 3040
Sharekhan - 1800 22 7500
Tata Mutual Fund - 1800 22 0101
Travel
Club Mahindra Holidays - 1800 33 4539
Cox & Kings - 1800 22 1235
God TV Tours - 1800 442 777
Kerala Tourism - 1800 444 747
Kumarakom Lake Resort - 1800 44 5030
Raj Travels & Tours - 1800 22 9900
Sita Tours - 1800 111 911
SOTC Tours - 1800 22 3344
Healthcare
Best on Health - 1800 11 8899
Dr Batras - 1800 11 6767
GlaxoSmithKline - 1800 22 8797
Johnson & Johnson - 1800 22 8111
Kaya Skin Clinic - 1800 22 5292
LifeCell - 1800 44 5323
Manmar Technologies - 1800 33 4420
Pfizer - 1800 442 442
Roche Accu-Chek - 1800 11 45 46
Rudraksha - 1800 21 4708
Varilux Lenses - 1800 44 8383
VLCC - 1800 33 1262
Insurance
AMP Sanmar - 1800 44 2200
Aviva - 1800 33 2244
Bajaj Allianz - 1800 22 5858
Chola MS General Insurance - 1800 44 5544
HDFC Standard Life - 1800 227 227
LIC - 1800 33 4433
Max New York Life - 1800 33 5577
Royal Sundaram - 1800 33 8899
SBI Life Insurance - 1800 22 9090
Hotel Reservations
GRT Grand - 1800 44 5500
InterContinental Hotels Group - 1800 111 000
Marriott - 1800 22 0044
Sarovar Park Plaza - 1800 111 222
Taj Holidays - 1800 111 825
Teleshopping
Asian Sky Shop - 1800 22 1800
Jaipan Teleshoppe - 1800 11 5225
Tele Brands - 1800 11 8000
VMI Teleshopping - 1800 447 777
WWS Teleshopping - 1800 220 777
Others
Domino's Pizza - 1800 111 123
Cell Phones
·
· BenQ - 1800 22 08 08
· Bird CellPhones - 1800 11 7700
· Motorola MotoAssist - 1800 11 1211
· Nokia - 3030 3838
· Sony Ericsson - 3901 1111
Thursday, February 5, 2009
Script to query LDSI
'On Error Resume Next
Dim fso
Const ForReading = 1, ForWriting = 2 , forAppend = 8
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("Members.txt", forAppend, True)
' Determine DNS domain name.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use ADO to search Active Directory.
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject" objConnection.Open "Active Directory Provider" objCommand.ActiveConnection = objConnection
strBase = "<LDAP://" & strDNSDomain >"
' Filter on all user objects. strFilter = "(&(objectCategory=person)(objectClass=user))"
' Specify attribute values to retrieve.
strAttributes = "cn,distinguishedName,sAMAccountName,description,homeDirectory, mailnickName,mail,EmployeeNumber"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree" objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
Do Until objRecordSet.EOF
strFullName = objRecordSet.Fields("cn")
strDN = objRecordSet.Fields("distinguishedName")
strNTName = objRecordSet.Fields("sAMAccountName")
strAlias = objRecordSet.Fields("mailnickName")
strmail = objRecordSet.Fields("mail")
strId= objRecordSet.Fields("EmployeeNumber")
strHomeDir = objRecordSet.Fields("homeDirectory")
If IsNull(strHomeDir) Then
strHomeDir = "None"
Else
strHomeDir = strHomeDir
End If
f.writeline strFullName & vbtab & strDN & vbtab & strNTName & vbtab & strHomeDir & vbtab & strAlias & vbtab & strmail & vbtab & strID
objRecordSet.MoveNext
Loop
MsgBox "Done"
Work is donee :0)
Acessing Data Using Data Repeater
Data Repeater repeats the specified data-bound templates without applying any sort of additional formatting. For example, the Repeater doesn't create a table or a vertical or horizontal list of data by default. You determine the final layout of the generated markup by creating ASP.NET templates and explicitly adding markup that separates one row from the next.
HTML File
<asp:repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"AssetType")%>
</ItemTemplate>
<SeparatorTemplate>
</br>
</SeparatorTemplate>
</asp:repeater>
DataBinder.Eval method is used to declare which members of the DataItem to use in the output. The Eval method uses reflection to get the second parameter from the first. This approach typically has Container.DataItem as the first parameter, which yields a DataRowView. The second parameter is the name of the data field within the DataRowView
Code behind (Using Data Reader)
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Objconn As New OleDbConnection
Dim objreader As OleDbDataReader
Dim strsql As String
Dim strconnection As String
''Connection String from web.config file
strconnection = ConfigurationSettings.AppSettings("Dbconn")
Objconn = New OleDb.OleDbConnection(strconnection)
Objconn.Open()
Dim ds As DataSet = New DataSet
strsql = " Select distinct AssetType as AssetType from AM_AssetType order by assettype"
Dim objcommand As New OleDbCommand(strsql, Objconn)
objreader = objcommand.ExecuteReader
Repeater1.DataSource = objreader
Repeater1.DataBind()
End Sub
Code behind (Using Data Adapter)
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Objconn As New OleDbConnection
Dim Objadapter As New OleDbDataAdapter
Dim Objds As New DataSet
Dim strsql As String
''Connection String from web.config file
strconnection = ConfigurationSettings.AppSettings("Dbconn")
Objconn = New OleDb.OleDbConnection(strconnection)
Objconn.Open()
Dim ds As DataSet = New DataSet
strsql = " Select distinct AssetType as AssetType from AM_AssetType order by assettype"
Objadapter = New OleDbDataAdapter(strsql, Objconn)
Objadapter.SelectCommand.CommandTimeout = 50000
Objadapter.Fill(ds)
Repeater1.DataSource = objreader
Repeater1.DataBind()
End Sub
Is Data Reader Disconnected ?
DataReader is connected. However, DataTable and DataSet are disconnected (in-memory).you can't have a new DataReader for a connection if there is another one already active.
Monday, January 26, 2009
Windows Presentation Foundation
WPF: Windows Presentation Foundation
Overview :
WPF is a tool comes as a package in Windows Vista and used to develop User interfaces effectively ,it provides several features to developer to develop dynamic data driven applications. It is used in both web based and stand alone applications.But mostly used in Web based application.
Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a common language runtime (CLR) property
Windows Presentation Foundation :
The core of WPF is a resolution-independent and vector-based implementation of graphics .
The extension of this along with Application development features like XAML(Extensible application Markup Language),Controls,databinding,Layout,2-D and 3-D graphics,animations,styles,templates,audio,video,
text, typography is WPF.
WPF reduces the amount of procedural code in application specifications.It provides us
ability to develop an application using both markup and code-behind.
Markup : Extensible Application Markup Language (XAML) markup to implement the appearance of an application
Code-behind : Managed programming languages (code-behind) to implement application behavior
The separation of logic from appearance has many advantages
Development and maintenance costs are reduced because appearance-specific markup is not tightly coupled with behavior-specific code.
Multiple design tools can be used to implement and share XAML markup, to target the requirements of the application development contributors; Microsoft Expression Blend provides an experience that suits designers, while Visual Studio 2005 targets developers
Globalization and localization for WPF applications is greatly simplified
Many application services like User Interface, fixed documents, adaptive documents, 2D and 3D drawings, animation, audio, video etc. work together in unison under WPF. Microsoft Silverlight that is based on XAML and JScript is a web based subset of WPF. Silverlight helps develop web and mobile applications with codes similar to .NET applications and the applications are similar to Flash.
XAML is Extensible Application Markup Language .It simplifies creation of UI for the .NET Framework programming model.I will explain the details of XAML and its implementation in my next Blog.
Features :
--WPF offers all graphics as Direct3D applications,animations,effects,audio and video.
--Interoperability with Win32 is supported by WPF.
--WPF supports all the standard image formats and video formats like WMV, MPEG and AVI. WPF also supports time based animations, Open Type Font features and Text rendering
--WPF supports XML Paper Specification documents. It also supports reading and writing of paginated documents.
--WPF offers many built-in controls like button, list box etc.
Instantiatiation of classes, properties, calling methods, and event handling in WPF is similar to the one we did in Vb.net (as I am familiar only in vb.net I mentioned as vb.net J ,it is as similar as C# or Visual Basic) and windows forms.
WPF includes additional constructs that enhaces properties and events they are
-Routed events
Dependency Properties
Windows Presentation Foundation (WPF) provides a set of services that can be used to extend the functionality of a common language runtime (CLR) property. Collectively, these services are typically referred to as the WPF property system. A property that is supproted by the WPF property system is known as a dependency property.
The purpose of dependency properties is to provide a way to find out the value of a property based on the value of other inputs
Dependency property identifier: A Dependency Property instance, which is obtained as a return value when registering a dependency property, and then stored as a member of a class. This identifier is used as a parameter in many of the APIs that interact with the WPF property system.
CLR "wrapper": The actual get and set implementations incorporate the dependency property identifier, thus providing the backing for the property using the WPF property system.
Routed Events
Routed events can be defined in 2 different perspectives either functionally or Technically
Functional definition: A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.
Implementation definition: A routed event is a CLR event that is backed by an instance of the Routed event class and is processed by the Windows Presentation Foundation (WPF) event system.
Binding and manipulation of application data is supported by WPF through its built-in set of data services. Data templates for controlling data presentation are also provided by WPF.
Friday, January 23, 2009
ADO.Net Overview
ADO.net objects are
Connection Objects
Connection objects are used to connect to databases. They have properties, such as
DataSource, UserID, and Password, which are needed to access a particular DataSource.
There are two kinds of connection objects in ADO.NET: SqlConnection and OleDbConnection.
Command Objects
Command objects contain the information that is submitted to a database. A
command can be a stored procedure call, an update statement, or a statement
that returns results. You can also use input and output parameters and return
values. In ADO.NET, you can use two kinds of command objects:
SqlCommand and OleDbCommand.
DataReader Objects
A DataReader is a read-only/forward-only view on the data. It provides a
simple and lightweight way of traversing through recordsets
A DataReader is returned after executing a command. It works similarly to a
recordset in ADO, allowing you to simply loop through the records.
ADO.NET includes two types of DataReader objects: the SqlDataReader for
Microsoft SQL Server™ version 7.0 (or later) data, and the OleDbDataReader
for ADO data. The DataReader object is database-specific. The behavior for
the SqlDataReader may differ from the behavior for the OleDbDataReader
and additional DataReader objects that are introduced in the future.
You use the OleDbCommand and SqlCommand objects and the
ExecuteReader method to transfer data into a DataReader.
DataSet Objects
The DataSet is designed to handle the actual data from a data store. The
DataSet provides a rich object model to work with when passing data between
various components of an enterprise solution. The DataSet object is generic.
The behavior of a DataSet is completely consistent regardless of the underlying
database, SQL or OLE DB.
The DataSet object represents a cache of data, with database-like behavior. It
contains tables, columns, relationships, constraints, and data. Data coming from
a database, an XML file, code, or user input can be entered into DataSet
objects and converted into files, forms, or databases. As changes are made to
the DataSet, they are tracked in a way similar to the way changes are tracked in
a word processing document.
The DataSet object has a collection of DataTable objects. A DataTable
represents one table of in-memory data. It contains a collection of columns that
represents the table's schema. A DataTable also contains a collection of rows,
representing the data contained in the table.
You use the OleDbDataAdapter and SqlDataAdapter objects and the Fill
method to get data into a DataSet.
DataView Objects
A DataView provides a custom view of a data table. You can think of the
DataView as the equivalent of the ADO disconnected recordset, because it
contains a single view on top of the table data. You can use a DataView to
specify criteria for filtering and sorting a DataSet.
DataAdapter Object
The DataAdapter object allows for the retrieval and saving of data between a DataSet object and the source datastore. It is responsible for pulling out data from the physical store and pushing it
into data tables and relations. The DataAdapter object is also responsible for
transmitting any update, insertion, or deletion to the physical database. You can
use four command objects to make any updates: UpdateCommand,
InsertCommand, DeleteCommand, and SelectCommand.
The DataAdapter object exists in two forms: SqlDataAdapter objects and
OleDbDataAdapter objects. The data source is SQL Server for
SqlDataAdapter objects and any other OLE DB provider for
OleDbDataAdapter objects.
Difference between Recordset and Dataset
Feature----------------- Recordset-------------------------- DataSet
Number of tables-------- One table -------- -------- -------- -- Multiple tables
Relationships-------- ---- Based on join -------- -------- ------- Includes relationships
Moving through data -- Move row-by-row -------- --------Navigate via relationships
Data connections -------- Connected -------- -------- -------Disconnected
Transmitting data ---------COM marshalling -------- ---------- Transmit XML file
NameSpaces required for ADO.Net
Namespace ---------------------------------------Contains
System.Data ---------------------------------------Base objects and types for ADO.NET
System.Data.OleDb-------------------------------Managed OLE DB data store objects
System.Data.SqlClient -------------------------- SQL Server specific implementations of ADO.NET objects
System.Data.XML ------------------------------ XML objects
System.Data.SqlTypes ------------------------- SQL data types
Garbage Collection
The runtime manages application threading, providing application memory isolation. When objects are no longer used by a .NET application, the runtime performs garbage collection, which frees up the memory that was used by those objects. NET uses the information in the metadata to trace the object graph and detect the objects that need to be garbage collected. Objects that are not reachable from the root are referred to as garbage objects and are marked for garbage collection.
It prevents memory leaks caused by the application that do not release all resources.
We should import System.GC Namespace to implement any garbage collector methods manully in the code.
Garbage collector is applicable only for the managed code.
Some of the methods of Garbage Collector.
GC.Collect Method
Used to force a garbage collection .
GC.GetTotalMemory
returns the total number of bytes that is allocated in the managed memory
GC.KeepAlive Extends the life time of an object passed to it as a parameter
GC.ReRegisterForFinalize
re-registers an object for finalization which is sent as parameter
GC.SupressFinalize
Suppress the finalization on an object.
Friday, January 16, 2009
FAQ
String object is read only (immutable) that means string object cannot be modified .Some methods seems to modify the string object but actually they are not modifying the object but creating the new object.
String builder object is mutable ,it can modify the object by appending,removing,replacing etc.
Here when the object is modified it is refering to the same instance where as in string class a new object is creates
Performance:
Concat method of String class and Append Method of StringBuilder class both concatenate 2 strings.But the string class creates new object from existing object which allocates memory where as A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
2.Explain storage and performance in different Session Modes?
Storage location----------------
InProc - session kept as live objects in web server (aspnet_wp.exe)
StateServer - session serialized and stored in memory in a separate process(aspnet_state.exe). State Server can run on another machine
SQLServer - session serialized and stored in SQL server
Performance------------
InProc - Fastest, but the more session data, the more memory is consumed onthe web server, and that can affect performance.
StateServer - When storing data of basic types (e.g. string, integer, etc),in one test environment it's 15% slower than InProc. However, the cost ofserialization/deserialization can affect performance if you're storing lotsof objects.
SQLServer - When storing data of basic types (e.g. string, integer, etc),in one test environment it's 25% slower than InProc. Same warning aboutserialization as in StateServer.
Robustness-----------
InProc - Session state will be lost if the worker process (aspnet_wp.exe)recycles, or if the appdomain restarts. It's because session state isstored in the memory space of an appdomain. Read doc on when such eventswill happen.
StateServer - Solve the session state loss problem in InProc mode. Allowsa webfarm to store session on a central server. Single point of failure atthe State Server
.SQLServer - Similar to StateServer. Moreover, session state data cansurvive a SQL server restart
3. Difference between dataadapter and datareader?
Data Reader will read only one record at a time.So memory consumption will be less,it is purely connection oriented it will use connection exclusively when datareader is closed.the memory will be released on the server machine and connection will be used for any other purpose.Data Adapter acts as a mediator between dataset and database server.it will read data from the database server and places with in datasetthe manipulations on the dataset will be updated with the database server.
4.Difference between dataset and recordset?
1. Table Collection: ADO Recordset provides the ability tonavigate through a single table of information. That tablewould have been formed with a join of multiple tables andreturning columns from multiple tables. ADO.NET DataSet iscapable of holding instances of multiple tables. It has gota Table Collection, which holds multiple tables in it. Ifthe tables are having a relation, then it can be manipulatedon a Parent-Child relationship. It has the ability tosupport multiple tables with keys, constraints andinterconnected relationships. With this ability the DataSetcan be considered as a small, in-memory relational databasecache.
2. Navigation: Navigation in ADO Recordset is based on thecursor mode. Even though it is specified to be a client-sideRecordset, still the navigation pointer will move from onelocation to another on cursor model only. ADO.NET DataSet isan entirely offline, in-memory, and cache of data. All ofits data is available all the time. At any time, we canretrieve any row or column, constraints or relation simplyby accessing it either ordinarily or by retrieving it from aname-based collection.
3. Connectivity Model: The ADO Recordset was originallydesigned without the ability to operate in a disconnectedenvironment. ADO.NET DataSet is specifically designed to bea disconnected in-memory database. ADO.NET DataSet follows apure disconnected connectivity model and this gives it muchmore scalability and versatility in the amount of things itcan do and how easily it can do that.
4. Marshalling and Serialization: In COM, throughMarshalling, we can pass data from 1 COM component toanother component at any time. Marshalling involves copyingand processing data so that a complex type can appear to thereceiving component the same as it appeared to the sendingcomponent. Marshalling is an expensive operation. ADO.NETDataset and DataTable components support Remoting in theform of XML serialization. Rather than doing expensive
Marshalling, it uses XML and sent data across boundaries.
5. What are major events in GLOBAL.ASAX file ?
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_PreSendContent: Fired before the ASP.NET page framework send content to a requesting client (browser).
Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.
Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.
Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.
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.
Session_End: Fired when a user's session times out, ends, or they leave the application Web site.
6.What order they are triggered ?
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.
7.How can we force all the validation control to run ?
Page.Validate
8.How can we check if all the validation control are valid and proper ?
Page.Isvalid()
9. How to disable client side script in validators?
Set EnableLcientsideScript to False
10. What is Tracing in ASP.NET ?
Tracing allows us to view how the code was executed in detail
11. How can we kill a user session ?
Session.abandon()
12. How do I sign out in forms authentication ?
FormsAuthentication.Signout()
13. If cookies are not enabled at browser end does form Authentication work?
No, it does not work.
14. What is the namespace in which .NET has the data functionality classes ?
Following are the namespaces provided by .NET for data management :-
System.data : This contains the basic objects used for accessing and storing relational data, such as DataSet,DataTable, and DataRelation. Each of these is independent of the type of data source and the way we connect to it.
System.Data.OleDB : It contains the objects that we use to connect to a data source via an OLE-DB provider, such as OleDbConnection, OleDbCommand, etc. These objects inherit from the common base classes, and so have the same properties, methods, and events as the SqlClient equivalents.
System.Data.SqlClient:
This contains the objects that we use to connect to a data source via the Tabular Data Stream (TDS) interface of Microsoft SQL Server (only). This can generally provide better performance as it removes some of the intermediate layers required by an OLE-DB connection.
System.XML
This Contains the basic objects required to create, read, store, write, and manipulate XML documents according to W3C recommendations.
15. What is difference between dataset and datareader ?
Following are some major differences between dataset and datareader :-
DataReader provides forward-only and read-only access to data, while the DataSet object can hold more than one table (in other words more than one rowset) from the same data source as well as the relationships between them.
Dataset is a disconnected architecture while datareader is connected architecture.
Dataset can persist contents while datareader can not persist contents, they are forward only.
16.What are major difference between classic ADO and ADO.NET ?
Following are some major differences between both
As in classic ADO we had client and server side cursors they are no more present in ADO.NET. Note it's a disconnected model so they are no more applicable.
Locking is not supported due to disconnected model.
All data persist in XML as compared to classic ADO where data persisted in Binary format also.
.How do you set the url of Hyperlink dynamically?
Using navigateurl property of hyperlink in code behind.
.What is resolveURL used for?
To get the relative path.
How do you get the current page name
Page.Request.Path
Get virtual path of current request from user control?
mybase.request.path
What is the main difference between Gridlayout and FlowLayout ?
GridLayout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, FlowLayout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers. If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in Flow layout you can see more of using HTML table to position elements which is compatible with wide range of browsers.
Can you give a overview of ADO.NET architecture ?
The two central components of ADO.NET are : the DataSet, and the .NET Framework data provider, which is a set of components including the Connection, Command, DataReader, and DataAdapter objects.
The dataset is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. As a result it can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects made up of rows and columns of data, as well as primary key, foreign key, constraint, and relation information about the data in the DataTable objects.
The other important section in ADO.NET architecture is “Data Provider”. Data Provider provides access to datasource (SQL SERVER, ACCESS, ORACLE).In short it provides object to achieve functionalities like opening and closing connection, retrieve data and update data.
Connection object provides connectivity to a data source.
Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information.
The DataReader provides a high-performance stream of data from the data source.
The DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source Dataset object represents disconnected and cached data.
Difference between dataReader and Data Adapter
DataReader : Reads a forward-only, read-only stream of data from a data source.
DataAdapter : Populates a DataSet and resolves updates with the data source.
Explain DataSet?
The DataSet object is central to supporting disconnected, distributed data scenarios with ADO.NET
The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables
The DataTableCollection
An ADO.NET DataSet contains a collection of zero or more tables represented by DataTable objects. The DataTableCollection contains all the DataTable objects in a DataSet.
A DataTable is defined in the System.Data namespace and represents a single table of memory-resident data. It contains a collection of columns represented by a DataColumnCollection, and constraints represented by a ConstraintCollection, which together define the schema of the table. A DataTable also contains a collection of rows represented by the DataRowCollection, which contains the data in the table. Along with its current state, a DataRow retains both its current and original versions to identify changes to the values stored in the row.
The DataRelationCollection
A DataSet contains relationships in its DataRelationCollection object. A relationship, represented by the DataRelation object, associates rows in one DataTable with rows in another DataTable. It is analogous to a join path that might exist between primary and foreign key columns in a relational database. A DataRelation identifies matching columns in two tables of a DataSet.
Relationships enable navigation from one table to another within a DataSet. The essential elements of a DataRelation are the name of the relationship, the name of the tables being related, and the related columns in each table. Relationships can be built with more than one column per table by specifying an array of DataColumn objects as the key columns. When a relationship is added to the DataRelationCollection, it may optionally add a UniqueKeyConstraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to related column values.
ExtendedProperties
The DataSet (as well as the DataTable and DataColumn) has an ExtendedProperties property. ExtendedProperties is a PropertyCollection where you can place customized information, such as the SELECT statement that was used to generate the resultset, or a date/time stamp of when the data was generated. The ExtendedProperties collection is persisted with the schema information for the DataSet (as well as the DataTable and DataColumn).
http://www.blogger.com/””> Check details
What are the different data providers provided by .Net framework?
.NET Framework Data Provider for SQL Server :
For Microsoft® SQL Server™ version 7.0 or later.
.NET Framework Data Provider for OLE DB:
For data sources exposed using OLE DB.
.NET Framework Data Provider for ODBC
.NET Framework Data Provider for Oracle
For Oracle data sources.
What is command builder object?
A helper object that will automatically generate command properties of a DataAdapter or will derive parameter information from a stored procedure and populate the Parameters collection of a Command object
What are the execute methods of command Object?
The Command object exposes several Execute methods you can use to perform the intended action. When returning results as a stream of data, use ExecuteReader to return a DataReader object. Use ExecuteScalar to return a singleton value. Use ExecuteNonQuery to execute commands that do not return rows.
How do you determine whether dataReader has returned rows or not?
The .NET Framework version 1.1 includes an additional property for the DataReader, HasRows, which enables you to determine if the DataReader has returned any results before reading from it.
Can I access the values return by dataReader before it is closed?
NO,You should always call the Close method when you have finished using the DataReader object.
If your Command contains output parameters or return values, they will not be available until the DataReader is closed.
Can we Handle Multiple result sets in datareader?
Yes, the DataReader provides the NextResult method to iterate through the result sets in order
Expalin briefly about DataAdapter Object?
. A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet. Each .NET Framework data provider included with the .NET Framework has a DataAdapter object.
SQL Server includes a SqlDataAdapter object
OLE DB includes an OleDbDataAdapter object
The DataAdapter also resolves changes made to the DataSet back to the data source. The DataAdapter uses the Connection object of the .NET Framework data provider to connect to a data source and Command objects to retrieve data from and resolve changes to the data source.
The InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter are Command objects that manage updates to the data in the data source according to modifications made to the data in the DataSet.
The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand of the DataAdapter. The Fill method uses the DataReader object implicitly to return the column names and types used to create the tables in the DataSet, as well as the data to populate the rows of the tables in the DataSet
Fill method automatically opens the connection the adapter using and also closes it when the job is done,which is entirely different form data reader
DataAdapter exposes 3 different events.
RowUpdating : An UPDATE, INSERT, or DELETE operation on a row (by a call to one of the Update methods) is about to begin.
RowUpdated : An UPDATE, INSERT, or DELETE operation on a row (by a call to one of the Update methods) is complete
FillError : An error has occurred during a Fill operation
The RowUpdatingEventArgs and RowUpdatedEventArgs arguments passed to the RowUpdating and RowUpdated events include: a Command property that references the Command object being used to perform the update; a Row property that references the DataRow object containing the updated information; a StatementType property for what type of update is being performed; the TableMapping, if applicable; and the Status of the operation.
Status property to determine if an error has occurred during the operation
Continue - Continue the update operation
ErrorsOccurred- Abort the update operation and throw an exception
SkipCurrentRow- Ignore the current row and continue the update operation
SkipAllRemainingRows- Abort the update operation but do not throw an exception
We use ContinueUpdateOnError property to handle errors for updated rows
DataAdapter.ContinueUpdateOnError is true, when an update to a row results in an exception being thrown the text of the exception is placed into the RowError information of the particular row and processing continues without throwing an exception. This enables you to respond to errors when the Update is complete, in contrast to the RowUpdated event that enables you to respond to errors when the error is encountered.
Explain FillError event ?
The DataAdapter issues the FillError event when the data in the row being added could not be converted to a .NET Framework type without some loss of precision.
What is the use of command objects and what are the methods provided by the command object ?
They are used to connect connection object to Datareader or dataset. Following are the methods provided by command object :-
ExecuteNonQuery :- Executes the command defined in the CommandText property against the connection defined in the Connection property for a query that does not return any row (an UPDATE, DELETE or INSERT). Returns an Integer indicating the number of rows affected by the query.
ExecuteReader :- Executes the command defined in the CommandText property against the connection defined in the Connection property. Returns a "reader" object that is connected to the resulting rowset within the database, allowing the rows to be retrieved.
ExecuteScalar :- Executes the command defined in the CommandText property against the connection defined in the Connection property. Returns only single value (effectively the first column of the first row of the resulting rowset) any other returned columns and
What are basic methods of DataAdapter ?
Fill :- Executes the SelectCommand to fill the DataSet object with data from the data source. It an also be used to update (refresh) an existing table in a DataSet with changes
made to the data in the original datasource if there is a primary key in the table in the DataSet.
FillSchema :- Uses the SelectCommand to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all the corresponding constraints.
Update:- Calls the respective InsertCommand, UpdateCommand, or DeleteCommand for each inserted, updated,or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. This is a little like the UpdateBatch method provided by the ADO Recordset object, but in the DataSet it can be used to update more than one table.
What are the various objects in Dataset ?
Dataset has a collection of DataTable object within the Tables collection.
Each DataTable object contains a collection of DataRow objects and a collection of DataColumn objects. There are also collections for the primary keys, constraints, and default values used in this table which is called as constraint collection, and the parent and child relationships between the tables(DataRelationship Collection). Finally, there is a DefaultView object for each table. This is used to create a DataView object based on the table, so that the data can be searched, filtered or otherwise manipulated while displaying the data.
How do we Execute stored procedure in ADO.NET?
To execute stored procedures in .Net ,we use the command object and set the commandtype property to Stored procedure.
How to close database connection after datareader is closed ?
Command method Executereader takes a parameter called as CommandBehavior where in we can specify saying close connection automatically after the Datareader is close
objDataReader =objCommand.ExecuteReader(CommandBehavior.CloseConnection)
How do you return schema information form data reader?
Set the Parameter of ExecuteReader method of Command object to SchemaOnly.
objDataReader =objCommand.ExecuteReader(CommandBehavior.Schemaonly)
How to track the changes in dataset?
For tracking down changes Dataset has two methods
“GetChanges “and “HasChanges”.
GetChanges Returns dataset which are changed since it was loaded or since Acceptchanges was executed.
HasChanges This property indicates that dataset has any changes been made since the dataset was loaded or acceptchanges method was executed. If we want to revert or abandon all changes since the dataset was loaded use “RejectChanges”.
What are the new features of ASP.net 2.0 ?
Master Pages:
Lets you easily create pages with consistent elements such as
banners and navigation elements.
Site navigation
Provides controls that make it easy to create site navigation
Themes
Let you easily customize formatting elements like fonts and colors.
New data-access features
New data source controls and data-bound controls drastically
reduce the amount of code required for most database applications
Login
Provides controls that let you manage user logins to your web sites.
Profiles
Uses a database to store data about users between sessions.
Web parts
Lets the user choose which elements to include in a web page.
What are the new features of ASP.net 3.5 ?
Two new data access controls are included with the
ASP.NET 3.5: the ListView and DataPager controls.
The Microsoft AJAX (Asynchronous JavaScript and
XML) extensions are integrated into the ASP.NET 3.5.
AJAX represents a transition from using server-side
technologies to using client-side technologies when
building we applications. By using ASP.NET AJAX, you
can improve the user experience and the efficiency of your
Web applications.
Microsoft LINQ to SQL is a new query language that you
to access a database without writing any SQL.
Maximum Number of Colums allowed in a table
1024
Maximum number of parameters in a stored procedure
2100.
Thursday, January 15, 2009
Sessions in .Net
The ASP.NET framework enables us to store session state either in Web server memory, in a Windows service, or in a SQL Server database
In-Process Session
The default session state setting is InProc. When configured with this setting, the ASP.NET runtime keeps all session information in the Web application's memory. Because the session is stored in the application's memory, it is much faster to get the stored information. On the other hand, if your Web application restarts for any reason, you will lose every object stored in every user's session.
State Server
The ASP.NET framework enables us to store session information by using a Windows service. Because the Windows service runs as an independent process, information stored in the service is not affected when the Web application is restarted. Also, other Web servers in the server farm can communicate with the Windows service to get access to the session information stored in it.
SQL Server Session
In this mode Microsoft SQL Server is employed to maintain session state. Though the overhead for using SQL Server mode is higher than InProc, you can restart the web server all you want and the users session data will persist.
Caching in ASP.NET
Caching is more useful when we want to store large amount of static data.We can also store portions of the page as well.
ASP.NET supports three types of caching for Web-based applications:
Page Level Caching (called Output Caching)
Page Fragment Caching (often called Partial-Page Output Caching)
Programmatic or Data Caching
Page Level Caching:
Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this (roughly) is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.
Output Caching is particularly useful when you have very static pages.
The syntax
<%@OutputCache Duration="60" VaryByParam="none" %>
The Duration parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid
VaryByParam mentions how and when the data to be cached ,if we want to cached the data based on “NAME” in query string we mention as
VarByParam=”Name”
If VaryByParam attribute is None which means the page content to be served is the same regardless of the parameters passed through the querystring
If we want to vary the cached output based on type of browser.
<%@OutputCache Duration="60" VaryByParam="none" VarByCustom="browser" %>
Page Fragment Caching :
Page Fragment Caching allows specific regions of pages to be cached
Sometimes we might want to cache just portions of a page. For example, we might have a header for our page which will have the same content for all users. There might be some text/image in the header which might change everyday. In that case, we will want to cache this header for a duration of a day.
The solution is to put the header contents into a user control and then specify that the user control content should be cached. This technique is called fragment caching.
To specify that a user control should be cached, we use the @OutputCache directive just like we used it for the page.
<%@OutputCache Duration="60" VaryByParam="none" %>
Programtic or Data Caching :
The Cache object in ASP.NET provides the ability to store application data in a manner similar to the storing of data in the Application object. The Cache object, unlike the Application object, lets you specify that the cached data is to be replaced at a specified time or whenever there is a change to the original source of the data.
When the DataTable in the DataSet is stored in the Cache object, three parameters are passed to the Insert method of the Cache object. The first parameter is the "key" value used to access the data in the cache. A constant is used here since the key value is needed in several places in the code. The second parameter is the DataTable containing the book data. The third parameter is the dependency
context.Cache.Insert(Key,Datasetname,dependency) to get data from cache context.Cache.ITem(Key,Datasetname)
When data in the dependency is changed then cache object will also be refreshed.we can also mention duration for which the data is changed in the cache.
.The benefits
A reduced number of round trips to the data source, such as the database server, keeping the server resources more available for other operations.
An increase in the number of users supported, due to a faster response time to each user's request.
.The risks
Easily filling a computer's memory, which is relatively small, if you put a large amount of data in cache. As the memory gets full, the performance starts to decline, eventually leading to an unacceptable response time from the server.
Problems in a server farm environment, when we cache information in the server's memory, where various Web pages for the same user session may be served by different Web servers.
No guarantee of faster performance. It all depends on how effectively you manage objects in memory
Monday, January 12, 2009
Windows Authentication
Windows authentication is a means of authenticating users of web applications that run on an intranet with their ntlogin.
The role placed by IIS in windows authentication differs from Forms authentication,.
In Forms authentication we need to set anonymous authentication where as in windows authentication IIS is configured to block windows authentication.After set the security levels in IIS
-Web.config file need to be set up with Authentication mode set to “Windows”
<authentication mode="Windows" />
Set the <identity> element to
impersonate:
<identity impersonate="true" userName="" password="" />
If you want all requests to use a different account than IIS used for authentication, the userName and password attributes of the <identity> element can be set to the desired username and password.
Configure the <authorization> element to
deny access to all users:
<authorization>
<deny users="*" /> <!-- Deny all users -->
</authorization>
Add location element if you need to restrict access only to certain pages
Date-time format in asp.net
Dim curdte As DateTime
curdte = Now()
Response.Write("dd-MMM-yyyy : " & curdte.ToString("dd-MMM-yyyy"))
Response.write "<br>"
Response.Write("dddd, dd MMMM yyyy :" & curdte.ToString("dddd, dd MMMM yyyy"))
Response.write "<br>"
Response.Write("MM/dd/yyyy HH:mm:" & curdte.ToString("MM/dd/yyyy HH:mm"))
Response.write "<br>"
Response.Write("MM/dd/yyyy hh:mm " & curdte.ToString("MM/dd/yyyy HH:mm"))
Response.write "<br>"
Response.Write("MMMM dd" & curdte.ToString("MMMM dd"))
Response.write "<br>"
Response.write "<br>"
Response.Write("dddd, dd MMMM yyyy HH:mm:ss :" & curdte.ToString("dddd, dd MMMM yyyy HH:mm:ss"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( 'd' ):" & curdte.ToString("d"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( 'D' ):" & curdte.ToString("D"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( f) :" & curdte.ToString("f"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( F) :" & curdte.ToString("F"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( g) :" & curdte.ToString("g"))
Response.write "<BR>"
Response.Write("DateTime.ToString ( G) :" & curdte.ToString("G"))
d :
Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd :
Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd :
Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd :
Represents the full name of the day of the week (Monday, Tuesday etc)
h:
12-hour clock hour
hh:
12-hour clock, with a leading 0
H :
24-hour clock hour
HH :
24-hour clock hour, with a leading 0
m :
Minutes
mm :
Minutes with a leading zero
M :
Month number
MM :
Month number with leading zero
MMM :
Abbreviated Month Name
MMMM :
Full month name (e.g. December)
s :
Seconds :
ss :
Seconds with leading zero :
t :
Abbreviated AM / PM (e.g. A or P)
tt :
AM / PM (e.g. AM or PM
y :
Year, no leading zero
yy :
Year, leadin zero (e.g. 2001 would be 01)
yyy :
Year
yyyy :
Year
Security-Forms authentication
Authentication is the process of obtaining identification credentials from a user such as name and password , and validating those credentials against some authority.
Authorization determines whether an identity should be granted access to a specific resource.
Authentication is enabled by setting the attributes of < authenticationelement &rt of web.config file
We have 3 different kinds of authentications
Forms Authentication
Windows Authentication
Passport Authentication
Forms Authentication
Forms authentication uses login page to gather the username and Password and validate them against the data store to allow only authorized users to the application.
To Enable forms authentication ,follow the steps as mentioned.
1.Set mode attribute of <authentication> element to forms.
2.Add the child element <Forms > to the <authentication> element.set the attribute of child element
<forms name=".MySampleProject"
loginUrl="Login.aspx"
protection="All"
timeout="30"
path="/">
</forms>
The second step is to add a
name
Defines the name of the HTTP cookie used by ASP.NET to maintain the user authentication information. Care should be taken when naming the cookie. If two applications on the same server use the same cookie name, "cross authentication" could occur.
loginUrl
Defines the page to which ASP.NET will redirect users when they attempt to access pages in your application without being logged in. The login page should provide the fields required to authenticate the user, typically a login ID and password or whatever else your application requires.
protection
Defines the protection method used for the cookie. Possible values are All, None, Encryption, and Validation. Validation specifies that the cookie data will be validated to ensure it was not altered in transit. Encryption specifies that the cookie is encrypted. All specifies that data validation and encryption will be used. None specifies no protection will be provided for the cookie information. The default is All and is highly recommended because it offers the highest level of protection for this authentication cookie.
timeout
Defines the amount of time in minutes before the cookie expires. The value provided here should be at least as long at the timeout for the session. Making the value shorter than the session timeout can result in a user being redirected to the page defined by the loginUrl before the session times out.
path
Defines the path of cookies issued by the application. Be aware that most browsers treat the path as case-sensitive and will not return the cookie for a request that does not match the value provided for the path attribute. The result will be having the users redirected as if they were not logged in. Unless your application requires specifying the path leave the path as "/".
Add <deny> and
<allow> child elements to the
<authorization> element to deny access to
anonymous users and allow access to all who have been authenticated:
<authorization>
<deny users="?" /> <!-- Deny anonymous users -->
<allow users="*" /> <!-- Allow all authenticated users -->
</authorization>
In the .aspx file for the login page:
1. Add the fields required to collect the data the application needs to authenticate the user. Most applications require, at a minimum, a user login ID and password, but you can specify whatever your application requires.
2. Add a Login button.
3. (Optional) Include a checkbox for users to indicate that they want to be remembered between sessions. (You will need to add some code to the code-behind class to persist the authentication cookie on the client machine.)
In the code-behind class for the login page, use the .NET language of your choice to:
1. Use the Login button click event to verify the user credentials.
2. If the user credentials are valid, create a Forms authentication cookie and add it to the cookie collection returned to the browser by calling the SetAuthCookie method of the FormsAuthentication class.
FormsAuthentication.SetAuthCookie(“Usernamee”)
Response.redirect(“Requested Page”)
3. (Optional) Set the Forms authentication cookie to be persisted on the client machine.
4. Redirect the user to the appropriate application start page using Response.Redirect.
When application is configured to use Forms authentication, ASP.NET looks for the cookie defined by the name attribute of the < forms > element in web.config for every page requested from your application. If the cookie does not exist, ASP.NET assumes the user is not logged in and redirects the user to the page defined by the loginUrl attribute. If the cookie does exist, ASP.NET assumes the user is authenticated and passes the request on to the requesting page. In addition, when the cookie exists, ASP.NET creates a user principal object with the information found in the authentication cookie. The user principal object represents the security context under which code is running. This information is available to your application by accessing the User object in the current context
If we need to restrict access to selected pages of the application, we need to add < location > element to the configuration level for each application page to specify whether it is available to the public or only to authenticated users
Here we need to modify allow and deny elements of authorization for each page as we needed.
Let us consider “HomePage.aspx” –Pubilc access page
“CustomerPage.aspx” –Only to customers
<location path="HomePage.aspx">
<system.web>
<authorization>
<allow users="*"/>
//allow all users
</authorization>
</system.web>
</location>
<location path="customerPage.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
//allow all authenticated users.
</authorization>
</system.web>
</location>
If we need to restrict acess by roles
<allow roles="User,Admin"/>
<deny users="*"/>
It is important to include the <deny users="*"/> element for all pages after the list of roles allowed to access the page. This informs ASP.NET that if the user is not assigned one of the previously listed roles, they should be denied access to the page.
Friday, January 9, 2009
File handling FAQ
1.What is the Disadvantage of using Filesystem Object for reading files?
Asp.Net imposes performance constraints on application
2.What are different types of classes provided in .net to read Files?
File and FileInfo.
3.What is difference between File and File Info classes?
File Class contain shared methods where as File info doesn’t. Shared methods are methods that can be invoked without requiring an instance of the class to invoke
//Using FilesDim objStreamReader as StreamReader objStreamReader = File.OpenText(FILENAME)
//Using FileInfo Dim fInfo As FileInfo = New FileInfo(path)Dim fstream as FilestreamFstream=finfo.open(filemode.open)
4.What is the enctype to be added to the form element while working with files?
enctype="multipart/form-data"
5. Where do you change the limit of file size to be uploaded?
In maxRequestLength attribute of HTTPRuntime element in Web.config file.
6. How do u handle Multiple files upload?
Using HttpFileCollection class.
Tracing FAQ
1.What is the difference between Tracing and Debugging.
Tracing is the ability of getting the detailed information of execution where as debugging is process of finding and fixing the errors.
2.How do you sort the Trace messages in the output?
Include the tracemode attribute in the Page directive. Set the attribute to SortByTime to sort the messages in the order in which they are processed. Set the attribute to SortByCategory to sort them by the categories.
3. Mention the object Used to write the debug statements?
Trace.
4. What is TraceContext Class?
ASP.NET uses the Trace Context class to store information about a request, its control hierarchy, and trace information.
5. What are the Methods of TraceContext Class?
The TraceContext class provides two methods, Write and Warn,which allow you to write statements to the trace log. Each method is overloaded and allows you to specify a tracing category, a text message, and optional error information. The only difference between these methods is that the Warn method displays its text in red.
6. What are the attributes of Trace Element?
Refer http://harikaworks.blogspot.com/2009/01/tracing-in-net.html
7. Where do you view the Trace log other than page?
Trace.axd file
8. Is Trace.axd is Page?
No,It is a Http Handler.
Thursday, January 8, 2009
Enable Tracing in Shared components Using Listeners (Web and Non Web Application):
Enable Tracing in Shared components (Web and Non Web Application):
To enable tracing in business components which are used by both web and non web application,we need to implement trace without using the HTTPContext.(Components which are outside the application as well)
This can be done using Listeners which are inherited from Trace.Listener class.
A listener is an object that receives the trace output and outputs it somewhere; that somewhere could be a window in your development environment, a file on your hard drive, a Windows Event log, a SQL Server or Oracle database, or any other customized data store
.Net Framework uses the concept of Trace Listener in handling the Trace messages.In this context we need to create a Listener that inherited from trace.Listener class and add this to the Listener collection in the Web.Config File.
When we enable tracing in the application by default Single Listener is added to the Listeners Collection.If we want add more listeners we need to add to the listener collection as well Programatically in web.config file.
<system.diagnostics>
<trace autoflush="true" indentsize="0">
<listeners>
<add name="ComponentListener"
type="Myproject.Examples.compListener, esamples" />
</listeners>
</trace>
</system.diagnostics>
The custom TraceListener in our example overrides the Write and WriteLine methods to write the passed message to the current HTTP context.
Both the Trace and Debug classes share the same TraceListenerCollection object; therefore, if you add a listener to Trace object, it will also be available to Debug object, and vice versa.
Some of the methods of Trace Listeners:
Fail : Outputs the specified text with the Call Stack.
Write :Outputs the specified text.
WriteLine :Outputs the specified text and a carriage return.
Flush :Flushes the output buffer to the target media.
Close :Closes the output stream in order to not receive the tracing/debugging output.
Once the Listeners are added to the web.config file.
In the component created.
Import System.diagnostics and use trace.write methods to write trace to output.
There ENDS Tracing in the components implementing Listeners
Tracing in WebComponents Of Application
To identify the problems within the components of the application we need to refer to the current context of the Http request. This can be accomplished by the System. Web Name space.
Import System.Web Namespace in the component
Refer to the current context of the http request while using trace.write to output the trace information to the page or to the log file.
Trace.Write, as in
HTTPContext.Current.Trace.Write.
HTTPContext provides access to the trace object to write the output information.
Disadvantege of using the HTTPContext is it doenot allow not web applications to use the companent it is referring to.
It is impossible to share the component between Web and Non Web Applications.
To share the Component we need to implement Listener class instead of HTTP context.
Suppose we are using add method in the component.
Imports System.Web
----
----
----
public sub addnumbers(Byval a as integer, Byval b as integer)
int total;
// output trace message indicating the start of the Method execution
HttpContext.Current.Trace.Write("In Component", "Before performing addition");
Total=a+b
// output trace message indicating the end of the concatenations
HttpContext.Current.Trace.Write("In Component", "After performing Addition");
End Sub
In the aspx page in which we are using the component,just create instance and use it
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim webComponent As Testcomponet
webComponent = New Testcomponet
'add a string to the string in the component 1000 times
webComponent.addToString(2000, 1000)
End Sub 'Page_Load
Tuesday, January 6, 2009
Tracing in .Net
Tracing
We use tracing to pinpoint the problems in the code.Tracing allows to get whole host information about the currently executing request and write it in the trace of the page or in the Trace log.
Tracing can be achieved in two different methods.
-Page Level Tracing
-Application Level tracing
We can also dynamically turn Page level tracing on.
To enable page level tracing for the page we need to set the trace attribute to true in the
@page directive and then use trace.write () or Trace.warn() statements to write trace information to trace output.
Trace Context : Trace context is the class where .net stores information about all http requests and trace information. We can access Trace context class by using Page.trace attribute of the page .
Trace context class has 2 methods to write trace output to the page .They are
Trace.Write( )
Trace.Warn( )
The only difference between them is for Trace.Warn the output is ddisplayed in red in color such that it can be easily notified in the Trace log.
Both methods we have 3 versions .
1. If we pass single argument .Net writes it to Message column of the log file
2. If we use two string arguments, the first string appears in the Category column and the second in the Message column
3. If you use a third argument, it must be of type Exception and contain information about an error, which ASP.NET then writes to the trace log.
Trace.Write(“Page Loaded”)
The Trace Information section of 4 sections.
Category :
A custom trace category that you specified as the first argument in a Trace.Write (or Trace.Warn) method call. Message :
A custom trace message that you specified as the second argument in a Trace.Write (or Trace.Warn) method call.
From First (s) :
The time, in seconds, since the request processing was started (a running total).
From Last (s) :
The time, in seconds, since the last message was displayed. This column is especially helpful for seeing how long individual operations are taking.
Application Level Tracing:
If we don’t want to change paging in each and every page and we need to write the trace to entire application we opt for application level tracing.
To accomplish this we need to enable application-level tracing in the web.config file of the application and view the AXD application trace log for trace information.
Enable Application level tracing.
-To enable application tracing ,locate the web.config file in the application
-Add the trace element to System.web section of Web.config file and set the enabled attribute to true
‘<>
‘ <>
web.config:
<configuration>
<system.web>
<httpHandlers>
<remove verb="*" path="trace.axd" />
</httpHandlers>
</system.web>
</configuration>
-View the application trace log by browsing to the trace.axd page from the application root, like this:
http://localhost/
trace.axd is not an page but rather it is a special URL that is intercepted by ASP.NET.
It is an http handler.
Some of the trace Elements are
RequestLimit: Defualt number of Http requests stored in the trace information are 10, if limit is reached tracing will be disabled,requests count can be set using this attribute.
pageOutput :If, in addition to viewing the trace.axd file, you also want to see trace information displayed at the bottom of the page that it is associated with, add pageOutput="true" to the
The trace information you will see is identical to what would appear had you placed Trace="true" in the @ Page directive for the page
localOnly :To show trace information
If we want to identify problems only
· Set Page.Trace.IsEnabled = true in the Catch block of your exception handler.
· Write to the trace log by using a Trace.Write of the form Trace.Write("Exception", "Message", exc).
Error Handing in .Net FAQ
VB.Net offers the Option Strict and Option Explicit statements to prevent errors at design time.
• Option Explicit :
Prevent errors at design time. It forces explicit declaration of all variables at the module level
Syntax Option
Option Explicit On.
By default it is off.
We can set option explicit in .aspx page in the page directive
• Option strict :
Enabling Option Strict causes errors to be raised if you attempt a data type conversion that leads to a loss in data.
2.What Precisely is an Exception?
The Exception Class is a member of System NameSpace and base class for all the exceptions.
2 subclasses of Exception class are System Exception Class and Application Exception class.
Exception Class
System Exception Application Exception
The SystemException class defines the base class for all .NET predefined exceptions
3.What are the properties of Exception Object ?
Source : Gets the naem of the application or the object that causes the error
Message :Gets a message that describes the current exception.
StackTrace : Gets a string representation of the frames on the call stack at the time the current exception was thrown.
InnerException : Gets the Exception instance that caused the current exception
TargetSite : Gets the method that throws the current exception.
HelpLink :Gets or sets a link to the help file associated with this exception.
4.What is Structured and UnStructured Error Handling?
Unstructured Error Handling:
Unstructured error handling is implemented with the On Error statement, which is placed at the beginning of a code block to handle all possible exceptions that occur during the execution of the code. All Visual Basic 6.0 error handlers in .NET are objects that can be accessed by using the Microsoft.VisualBasic.Information.Err namespace. The handler is set to Nothing each time the procedure is called. You should place only one On Error statement in each procedure, because additional statements disable all previous handlers that are defined in that procedure.
On Error { GoTo [ line 0 -1 ] Resume Next }
Structured Error Handling :
With structured error handling, Visual Basic now has an effective way to prevent unexpected errors from terminating the execution of the application. Structured error handling also provides the programmers with a simpler way to create robust applications that are easier to maintain. Structured error handling is implemented in Visual Basic. NET or Visual Basic 2005 with a Try...Catch...Finally block of statements. The Try...Catch...Finally block provides, for the first time to Visual Basic, the capability of nested error handling.
5. Mention Predefined exceptions provided by .net run time?
Exception --Object--Base class for all exceptions.
SystemException--Exception--Base class for all runtime-generated errors.
IndexOutOfRangeException--SystemException--Thrown by the runtime only when an array indexed improperly.
NullReferenceException--SystemException--Thrown by the runtime only when a null object
referenced.
InvalidOperationException--SystemException--Thrown by methods when in an invalid state.
ArgumentException --SystemException--Base class for all argument exceptions.
ArgumentNullException --ArgumentException--Thrown by methods that do not allow
an argument to be null.
ArgumentOutOfRangeException --ArgumentException --Thrown by methods that verify
that arguments are in a given range.
ExternalException--SystemException--Base class for exceptions that occur or are targeted
at environments outside the runtime.
ComException--ExternalException--Exception encapsulating COM HRESULT information.
SEHException --ExternalException--Exception encapsulating Win32 structured exception handling information
6.What class we need to inherit to create custom Excepton class.
To create a custom exception we must inherit from the ApplicationException class
7.How to redirect the user to the friendly error-handler page when an Application error occurs?
Modify web.config as
customErrors mode="On" defaultRedirect="errorpage.aspx"
The
--< mode="On" defaultredirect="genericerror.htm">
-- < statuscode="404" redirect="pagenotfound.aspx">
--< statuscode="403" redirect="noaccess.aspx">
--< /customerrors>