Monitoring Solutions(Monsol) specializes in helping industry and government meet rapidly growing demands for air pollution monitoring and reporting due to changing regulatory requirements. CEMDAS is Web-Based Control and Monitoring Solutions' comprehensive Data Acquisition Software package for use with Continuous Emissions Monitoring (CEM) Systems. CemMaster Ladder Software is another package for PLC, this system used to control valves, pumps, temperatures, flows, and store data temporarily.CEMDAS is collect emissions data extract from PLC, print reports, and provide an operator interface. Database used to store and manage all data in the CEM system. . CEMDAS has been satisfied the environmental monitoring needs of clients throughout the world in the electric utility, ethanol, pharmaceutical, chemical, petroleum, independent power producer, to name a few.
It is Highly Configurable by allowing modifications when user needs and requirements change.Pre-configured reports can be generated automatically or manually, and sent to a printer, the screen, or a disk file. Available reports include minute, hourly, daily, monthly and quarterly reports, along with calibration, availability and exceedance reports. Customized/Dynamic Reports are also available by provide a screen to user which parameters to get report based on aggregate functions and group by conditions.
Friday, March 26, 2010
asp.net
Question:
What is the difference between Server.Transfer and response.Redirect?
Select Answer:
• 1. No difference
• 2. Server.Transfer needs a Round Trip, Response.Rediect not
• 3. Response.Rediect needs Rountrip to bowser Server.Transfer does not need a Round Trip,
• 4. Server.Transfer can transfer user between two applications
Ans: 3
How many types of errors r there in ASP.NET? what r they?
Select Answer:
• 1. 4 types. Configuration,Runtime,compilation and parser errors
• 2. 2 types. Runtime and Compilation errors
• 3. 2 types. Configuration and Parser errrors
• 4. none of the above
Ans:1
What is the default authendication mode in aps.net?
Three are three types of authendication mode available in asp.net . by default windows authendication.
Select Answer:
• 1. Windows
• 2. Passport
• 3. Form
Ans: 1
What happens if we remove session tag from web.cofig file ?
Select Answer:
• 1. sessions will not work
• 2. sessions will work
• 3. cookies will not be created
• 4. none
Ans:2
which class use to delete ,update ,select data in dataset.
Select Answer:
• 1. sqldataAdapter
• 2. sqlDataReader
• 3. SqlCommand
• 4. None
Ans:1
How to set focus in a textbox in asp.net after click on a button ?
Select Answer:
• 1. using Java script code textbox.focus and register it in asp.net by page.registerecript
• 2. can't focus by asp.net coding
• 3. use setfocus method
• 4. use keypress event with keycode property
Ans:1
if you develop a simple web page and use only text box than which one is better way for develop ?
Select Answer:
• 1. use only HTML Textbox control and for code make them runat server
• 2. use asp.net web form textbox
• 3. both
Ans:1
how to open more than one datareader at time ??
Select Answer:
• 1. use different Datareader varibles.
• 2. use different Datareader and connection variable and connection must be connected
• 3. use different datareader with signle connection and connection status must be connected
• 4. can't use more than one datatreader at a time
Ans:2
How to add asp.net 3rd party component ?
Select Answer:
• 1. By Add/Remove Items in PRoject Menu.
• 2. Add Reference of Dll file and palce their code where programmer want to use
• 3. can't add 3rd party component in asp.net
• 4. Require .OCX files of add component in aps.net
Ans:2
which component can be use for reporting in asp.net
Select Answer:
• 1. HTML Table.
• 2. data grid
• 3. Data Reapter
• 4. All of above
Ans:4
Advantage fo Disconneted mode ADO.net in asp.net ?
Select Answer:
• 1. automatically dump data at client pc.
• 2. user data can be update and retrieve in dataset and when connection connted update values with serve
• 3. not neccessary to connect with server
• 4. all of above
Ans: 2
How to execute java script code in asp.net back-end code. ??
Select Answer:
• 1. Page.RegisterScript.
• 2. Page.Language='Java Script'
• 3. To set Defalut Langaue Java Script in Virtual Directory
• 4. asp.net back end automatic provide this facility
Ans:1
How to deploy a ASp.Net Web Application as Web Site on Web Server ?
Select Answer:
• 1. Run Web setup on Web Server.
• 2. Register ASP.net application dll files on web server
• 3. install at locat pc and copy vitural directory on web server
• 4. Copy all project files on web server
Ans:1
Name the tool which converts from resx file to resources file which will be used in building satellite assemblies?
Select Answer:
• 1. SN.exe
• 2. AL.exe
• 3. Ngen.exe
• 4. Resgen.exe
• 5. None
Ans:4
What does WSDL stand for?
Select Answer:
• 1. Web System Description Language
• 2. Web Services Details Language
• 3. Web Services Design Language
• 4. Web Services Description Language
Ans:4
Which one of the following statements indicates ASP.NET’s advantage over ASP?
Select Answer:
• 1. Compiled Code
• 2. Caching
• 3. Web Controls
• 4. All of the above
Ans:4
What is Page Caching
Select Answer:
• 1. Keep the page with u
• 2. Keep a copy of the page anywhere
• 3. Delete the page
• 4. Carry the whole page in the session object
• 5. All of the above
Ans:2
Is there any significant difference between Link Button and Button in ASP.NET?
Select Answer:
• 1. Yes
• 2. No
• 3. Don't know
Ans:2
Can ASP and ASP.Net share session variables?
Select Answer:
• 1. yes
• 2. no
• 3. no, both support session variables but they cannot be shared
Ans:2
What id the default namespace for the web services?
Select Answer:
• 1. System.Web.WebServices
• 2. WebServices
• 3. Service1
• 4. http://tempuri.org
• 5. None
Ans:4
What is a satellite Assembly?
Select Answer:
• 1. A peripheral assembly designed to monitor permissions requests from an application?
• 2. Any DLL file used by an EXE file
• 3. An assembly containing localized resources for another assembly
• 4. An assembly designed to alter the appearance or ‘skin’ of an application
• 5. None of these
Ans:3
How can we fix that if any error will come in my live website, the error should not be displayed to site user. He will get an SORRY MESSAGE and a mail should be sent to Admin of website with following information.
1. Error Type
2. Description of Error
3. Line Number
4. Error source
5. Script Name
Select Answer:
• 1. Can put an Exception Handler
• 2. Can set some settings in IIS
• 3. Can set Some settings in Web.Config
• 4. It is not possible
Ans:1
Which one of the following objects is used to create a foreign key between two DataTables?
Select Answer:
• 1. DataRelation
• 2. DataRelationship
• 3. DataConstraint
• 4. DataKey
• 5. DataForeignKey
Ans:1
Which interface provides a fast, connected, forward-only access to a data source?
Select Answer:
• 1. IDataRecord
• 2. IDatabase
• 3. IDataCursor
• 4. IDataReader
• 5. IdataSet
Ans:4
Which is the best approach to move very large files from a web server to a browser client.
Select Answer:
• 1. Allow direct access to the file.
• 2. Using Response.WriteFile
• 3. Streaming the File using Response.BinaryWrite
• 4. Use an ISAPI Filter or improve by Upgrading to IIS 6.0 and running in Isolation mode
Ans:4
Can we manipulate Sessions thru Classes ( Not Code behind files) in ASP.NET application?
Select Answer:
• 1. Access in Classes
• 2. Set / Update in Classes
• 3. Both of above
• 4. None
Ans: 3
What is the Default ScriptTimeOut for Server Object?
Select Answer:
• 1. 30 Sec
• 2. 20 Sec
• 3. 60 Sec
• 4. 90 Sec
Ans:4
View State Concept based on
Select Answer:
• 1. HiddenField
• 2. PostBack
• 3. EventGeneration
• 4. ServerSide Controls
Ans:1
By default, when does validation automatically occur?
Select Answer:
• 1. After page initialization and before event handling
• 2. After page initialization and event handling
• 3. Before the data is sent to the server
• 4. Before page initialization and event handling
• 5. Any time an input control is changed
Ans:1
Which property of the Session object is used to set the local identifier?
Select Answer:
• 1. SessionID
• 2. LCID
• 3. Item
• 4. Key
Ans:2
What extension does the Web User Control file contain?
Select Answer:
• 1. .asmx
• 2. .ascx
• 3. .aspx
• 4. .awuc
Ans:2
To which namespaces do Trace and Debug belong?
Select Answer:
• 1. System.ComponentModel
• 2. System.Collections
• 3. System.Diagnostics
• 4. System.Trace
Ans: 3
Which control would you use if you needed to make sure the values in two different controls matched?
Select Answer:
• 1. Range Validator Control
• 2. Regular Expression Validator Control
• 3. Match Validator Control
• 4. CompareValidator Control
Ans: 4
What base class do all Web Forms inherit from?
Select Answer:
• 1. The System Class
• 2. The Inherit Class
• 3. The Page Class
• 4. The Global Class
Ans:3
How can you provide an alternating color scheme in a Repeater control?
Select Answer:
• 1. AlternatingItemTemplate
• 2. AlternateItemTemplate
• 3. AlternateTemplate
• 4. AlternatingTemplate
Ans:1
Which template must you provide, in order to display data in a Repeater control?
Select Answer:
• 1. DisplayTemplate
• 2. ShowTemplate
• 3. ItemTemplate
• 4. HeaderTemplate
Ans:3
what is a diffgram?
Select Answer:
• 1. Data Diagram
• 2. Data Dictionary
• 3. XML format
• 4. Diagram file
Ans:3
What type of code (server or client) is found in a Code-Behind class?
Select Answer:
• 1. Client-side code
• 2. Server-side code
• 3. Client-Server Code
• 4. None of the above
Ans:2
Which one of the following is NOT a valid state management tool?
Select Answer:
• 1. Hidden Form Fields
• 2. Cookies
• 3. Query State
• 4. Application State
• 5. Session State
Ans:3
Which DataTable property returns all rows and columns from a DataTable?
Select Answer:
• 1. TableView
• 2. ViewAll
• 3. DefaultView
• 4. ReturnTable
Ans:3
What is the purpose of code-behind?
Select Answer:
• 1. To separate different sections of a page into different files according to function
• 2. To merge layout HTML and the code into one file
• 3. To separate the layout HTML and the code into two different files
• 4. To discard the use of HTML
Ans:3
How to put conditional statement in Data Grid?
Select Answer:
• 1. Using Calling function in data grid only
• 2. Using ItemDataBound event only
• 3. Above both a and b.
• 4. Directly put condition in data grid
Ans:3
What are the default user directory permissions when a Web site is created in IIS?
Select Answer:
• 1. Read and Execute
• 2. Read and Write
• 3. Read/Write and Execute
• 4. Execute Only
Ans:1
An application using cookie authentication was working fine on another server. When moved to a new server, cookie authentication is not working correctly.
Which one of the following is the likely explanation of the above problem?
Select Answer:
• 1. The new IIS server is not configured to allow anonymous access
• 2. SSL is not properly configured.
• 3. The IP address of the new server does not match the prior server IP address
• 4. Passport authentication is not correctly configured.
• 5. The users are not correctly entering their passwords
Ans:1
How we can terminate the current session.
Select Answer:
• 1. Session.End
• 2. Session.Kill
• 3. Session.Abondon
• 4. We Can't Terminate the session
Ans:3
In global.asax file, which event will occur first when an application is invoked?
Select Answer:
• 1. Session_onStart()
• 2. Application_onStart()
• 3. Session_onEnd()
• 4. Application_onEnd()
• 5. None
Ans: 2
Which property indicates whether the control posts back to server each time a user interacts with a control?
Select Answer:
• 1. Post Back
• 2. Auto Post Back
• 3. Auto Event Wire Up
• 4. Trace
Ans:2
What are the minimum changes required for deploying an Asp.net Application using xCopy deployment. where web site name will be change.
Select Answer:
• 1. Changes in web.Config Files
• 2. Changes in All Files and Build Application Again
• 3. Changes in the path of .SLN and webinfo.cs files.
• 4. changes in All configuration files and build Application again on the Destination Server.
• 5. None of Above
Ans:3
Which session state gives fastest application performance when we are maintaining sessions?
Fastest Mode in session states
Select Answer:
• 1. SqlServer
• 2. StateServer
• 3. InProc
• 4. Off
Ans:3
In which session state mode the session state will be disabled ?
Select Answer:
• 1. Inproc
• 2. StateServer
• 3. SqlServer
• 4. None of the Above
Ans:4
Threads are:
Threads are:
Select Answer:
• 1. static methods
• 2. objects
• 3. instance methods
• 4. events
Ans:2
What is the printout of the following?
What is the printout of the following?
byte b1=1;
byte b2=255;
byte total=b1+b2;
Console.WriteLine (total);
Select Answer:
• 1. We will get a runtime error
• 2. We will get a compilation error
• 3. 256
• 4. 1
Ans:2
Which of the following is true ?
Select Answer:
• 1. IsPostBack is a method of System.UI.Web.Page class
• 2. IsPostBack is a method of System.Web.UI.Page class
• 3. IsPostBack is a property of System.UI.Web.Page class
• 4. IsPostBack is a readonly property of System.Web.UI.Page class
• 5. IsPostBack is a static property of System.UI.Web.Page class
Ans:4
How you can dynamically change the background color of Datagrid cells.
Select Answer:
• 1. By Handling OnSelect event
• 2. By Handling Edit event
• 3. By Handling ItemBound event
• 4. By Handling PageChange event
Ans:3
The .NET class Global is derived from which of the following classes ?
Select Answer:
• 1. System.Web.UI.PageParser
• 2. System.Web.HttpApplicationState
• 3. System.Web.UI.Page
• 4. System.Web.HttpApplication
• 5. None of the above.
Ans:4
What is the function of Response.End?
Select Answer:
• 1. it will stop the server process
• 2. it will stop the client process
• 3. or both
• 4. or none
Ans:1
From which one of the following locations does the garbage collector remove objects?
Select Answer:
• 1. The download cache
• 2. The global assembly cache
• 3. The thread stack
• 4. The managed heap
• 5. The system registry
Ans: 4
What is Static and Dynamic Assemblies.?
The Difference between both.
Select Answer:
• 1. Both are same
• 2. There is no Static Assemblies
• 3. Dynamic assemblies have dynamic variable input but static assemblies have no variable input
• 4. Static Assemblies Define metadata and Dynamic assemblies Define Icon,String
• 5. Static Assemblies are created by user before running the application, Dynamic Assemblies are Dynamic
Ans:5
If one web form inherits the another web form, the drived web form able to access base class ....
Select Answer:
• 1. Code.
• 2. Server controls
• 3. HTML's
• 4. 1 and 2
• 5. all of above
Ans: 1
Technically,to whom we bind the any controls?
Select Answer:
• 1. Dataset
• 2. Datareader
• 3. Datatable
• 4. Dataview
Ans: 4
Which of the following controls contribute the highest Requests per second
Select Answer:
• 1. DataGrid
• 2. DataList
• 3. DataRepeater
Ans:3
User Control is nothing but
Select Answer:
• 1. A logical component
• 2. A visual component
• 3. Both of Logical and Visual
• 4. None of the above
Ans:3
What is boxing and unboxing ?
Implicit (manual) conversion of value type to reference type of a variable is known as BOXING, for example integer to object type conversion. Conversion of Boxed type variable back to value type is called as UnBoxing.
what is connected and diconnected database ?
Connected and Disconneted database basicallythe approch that how you handle the database connection, It may be connected that once the application starts you have to open the connection only for a single time and then performs many transactions and close the connection just before exit the application. This approch will be generally used in windows based application. On other hand disconnected architecter refere to open and close the connection for each time while performing a transactio.
What is garbage collection and how it works ?
Garbage Collection is Automatic Memory Manager for the dotnet framework. It manages the momery allocated to the .NET framework. CLR takes cares about .NET framework. When a variable is defined, Its gets a space in the memory and when the program control comes out of that function the scope of variable gets ended, so the garbage collection acts on and memory will releases.
What are the different types of caching ?
Output caching, Fragment Caching and Data caching.
What are different types of directives in .NET ?
Page, Outputcache, Register
1.What is the difference between user controls and custom controls?
CUSTOM CONTROLS are DLL'S.It can be placed in the toolbox.Drag and drop controls.
USER CONTROLS: are pages (.ascx).It can not be placed in the tool box.
2.what are the 3 types of session state modes?
a.Inproc-session kept as live object in the web server(aspnet_wp.exe)
b.Stateserver-Session serialized and stored in memory in a seperate process(aspnet_state.exe),we can use for webform architecture.
c.SQLServer-Session serialized and stored in sql server.
3. what are the 6 types of validation controls in ASP.NET?
1.Required Field validator.2.Range validator.3.Regular Expression validator.4.compare validator.5custom validator.
6.validation summary.
4.What are the 3 types of caching in ASP.NET?
1. Output Caching(Page Caching)- stores the responses from an asp.net page(aspx) or user control(.ascx).
2.Fragment Caching(Partial Caching)- Only stores the portion of a page.
3. Data Caching is the programmatic way to your objects to a managed cache.
//Add item
Cache["TopProducts"] = objTopProductsDataset;
//Retrieve item
objDataset = Cache["TopProducts"];
.5.How to Manage state in ASP.NET?
we can manage the state in two ways
Clent based techniques are
Viewstate, Query strings and Cookies.
Server based techniques are
Application and Session
6.What is the difference between overloading and shadowing?
Overloading ----------- A Member has the name, but something else in the signature is different.
Shadowing --------- A member shadows another member if the derived member replaces the base member
7.what is the difference between overloading and overriding?
Overloading : Method name remains the same with different signatures.
Overriding : Method name and Signatures must be the same.
8.what is the difference between Manifest and Metadata?
Manifest:
Manifest describes assembly itself.
Assembly Name,version number,culture,strongname,listof all all files,Type references,and referenced assemblies.
MetaData:
Metadata describes contents in an assembly
classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type,
its visibility/scope, its base class, the interfaces it implemented, its methods and their scope
, and each method’s parameters, type’s properties, and so on.
9.What is Boxing and Unboxing?
Boxing is an implicit conversion of a value type to the type object
int i = 123; // A value type
Object box = i // Boxing
CASTING : casting is the process of converting a variable from one type to another (from a string to an integer )
Unboxing is an explicit conversion from the type object to a value type
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
10.what are the method parameter in c#?
C# is having 4 parameter types which are
1.Value Parameter. default parameter type. Only Input
2.Reference(ref) Parameter. Input\Output
3.Output(out) Parameter.
4.Parameter(params) Arrays
11.what are value types and reference types?
Value type
bool, byte,chat, decimal,double,enum , float, int, long, sbyte, short, strut, uint, ulong, ushort
Value types are stored in the Stack
Reference type
class, delegate, interface, object, string
Reference types are stored in the Heap
12.what are the two activation modes for .NET Remoting?
1. Singleton 2. Singlecall
13.what's singlecall Activation mode used for ?
The Server Object is instantiated for responding to just one single request
14.what's the singleton Activation mode used for?
The server object is instantiated for responding number of clients
15.what are the channels and Formatters?
Channels
HTTP and TCP
Binay Over TCP is most efficient
SOAP over HTTP is most interoperable
Formatters
Binary and SOAP
16.What are the two Authentication modes for SQL server connection?
1. Trusted Connection - Windows Authentication
2. Non trusted Connection - Sql Server Authentication(its preferable for webservices)
17.What is typed dataset?
Data Access is normally done using indexes on collectionsin object model.
In ADO.NET it is possible to create a variation on a Dataset that does support
such syntax.Such Dataset is called "Typed Dataset".
Errors in the syntax are detected during compile time rather than runtime.
Advantages of Typed Dataset:
1.The data designer tool generates typed Datasets.
2.When we type the name of a dataset while writing a code,
weget a list of all available tables in the dataset.No need to
remember the table names.
For (eg) instead of typing
myDataset.Tables("products")
we can type
myDataset.products.
18.what is DataReader?
DataReader is a read only stream of data returned from
the database as the query executes.
It contains one row of data in memory at a time and is
restricted to navigating forward only in the results one record at a time.
Datareader supports access to multiple result sets but only one at a time and in the order retrieved.
In ADO data is no longer available through the Datareaderoncethe connection to the datasource is closed
which means a Datareader requires a connection to the Database throughout its usage.
o/p parameters or return values are only available thrugh the Datareader once the connection is closed.
19.Difference between Dataset and Recordset?
The Recordset was not XML-based and could not be serialized to XML easily or flexibly.
Finally, a Recordset was not independent of a data store because it tracked a Connection object
and through its methods could send queries to the data source to populate, update,
and refresh its data.
To that end, the Recordset contained functionality found in the ADO.NET DataSet,
data reader, and data adapter objects.
Similar to the DataSet, a Recordset could be disconnected from its data store
and therefore act as an in-memory cache of data.
Of course, it could also be used in a connected model depending on the cursor options that were set.
Although the Recordset object stored multiple versions of each column for each of its rows,
it was not by nature able to represent multiple tables without the use of the Data Shape Provider.
.
21.What isan Assembly, Private Assembly and SharedAssembly,Strong Name?
Assembly: Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.
Private assembly is used inside an application only and does not have to be identified by a strong name
Shared assembly can be used by multiple applications and has to have a strong name.
Strong Name :A strong name includes the name of the assembly, version number, culture identity, and a public key token.
22.what is an Delegate?
A strongly typed function pointer. A delegate object encapsulates a reference to a method.
23.what are webservices?
A Web Service is an application that delivers a service across the Internet using the standards and technologies defined in the Web Services architecture in a platform-independent and language-neutral fashion.
Web Services rely on several XML protocols based on open standards that are collectively known as the Web Services architecture
24.Define Automatic memory Management:
c# Provides Automatic memory Management.
Automatic memory Management increases code quality and enhances developer productivity without negatively impacting
either expressivenessor perfromance.Developers are freed from this burdensome task.
25.Define Threading:
It's a process of creating applications that can perform multiple tasks independently.
26Difference Between XML AND HTML?
XML:
User definable tags.
Content driven
End tags required for well formed documents
Quotes required around attributes values
Slash required in empty tags
HTML :
Defined set of tags designed for web display
Format driven
End tags not required
Quotes not required
Slash not required
27.What is XSLTand what is it's use?
XSL Transformations (XSLT) is yet another popular W3C specification that defines XML-based syntax, used to transform XML documents to any other text format, such as HTML, text, XML, etc. XSLT stylesheets can be applied on the source XML document to transform XML into some other XML, or text, HTML, or any other text format.
28.What is Diffgram?
It's an XML format.
It'sone of the two xml formats that uses to render Dataset object contents to XML.
For reading database data to an XML file to be sent to a webservice.
29.what is the Role of XSL?
Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules
30.What is SAX?
Simple API for XML Processing (SAX) is an alternative to DOM, and can be used to parse XML documents. SAX is based on streaming model. The SAX parser reads input XML stream and generates various parsing events that an application can handle. With each parsing event, the parser sends sufficient information about the node being parsed. Unlike DOM, SAX does not build an in-memory representation of the source XML document, and hence it is an excellent alternative when parsing large XML documents, as SAX does not require that much memory (and resources). Unlike DOM, SAX is not defined/controlled by W3C. See http://www.saxproject.org/ for details.
32.Give a few examples of types of applications that can benefit from using XML.
XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.
33.When constructing an XML DTD, how do you create an external entity reference in an attribute value?
when using SGML, XML DTDs don't support defining external entity references in attribute values.
34.Give some examples of XML DTDs or schemas that you have worked with.
Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology.commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project
35.What is SOAP and how does it relate to XML?
The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.
36.What is WSDL?
Another key standard in the Web Services architecture is the Web Services Description Language, or WSDL for short. Whereas SOAP is responsible for providing a platform-neutral protocol for transporting data types and interapplication messaging, WSDL is an XML grammar responsible for exposing the methods, arguments, and return parameters exposed by a particular Web Service.
37.What’s the difference between authentication and authorization? Authentication happens first. You verify user’s identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for.
38.Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications.
39.Define scalability.
The application meets its requirement for efficiency even if the number of users increases.
40.Define reliability.
The application generates correct and consistent information all the time.
41.Define availability.
Users can depend on using the application when needed.
42.Define security.
The application is never disrupted or compromised by the efforts of malicious or ignorant users
43.Define manageability.
Deployment and maintenance of the application is as efficient and painless as possible
44.Explain durability.
Make sure that the system can return to its original state in case of a failure.
45.Explain integrity.
Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.
46.Explain consistency.
We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.
47.Explain JIT activation.
The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases
48.Define Constructors and destructors
The create and destroy methods - often called constructors and destructors - are usually implemented for any abstract data type. Occasionally, the data type's use or semantics are such that there is only ever one object of that type in a program. In that case, it is possible to hide even the object's `handle' from the user. However, even in these cases, constructor and destructor methods are often provided.
Of course, specific applications may call for additional methods, e.g. we may need to join two collections (form a union in set terminology) - or may not need all of these.
What is the difference between Server.Transfer and response.Redirect?
Select Answer:
• 1. No difference
• 2. Server.Transfer needs a Round Trip, Response.Rediect not
• 3. Response.Rediect needs Rountrip to bowser Server.Transfer does not need a Round Trip,
• 4. Server.Transfer can transfer user between two applications
Ans: 3
How many types of errors r there in ASP.NET? what r they?
Select Answer:
• 1. 4 types. Configuration,Runtime,compilation and parser errors
• 2. 2 types. Runtime and Compilation errors
• 3. 2 types. Configuration and Parser errrors
• 4. none of the above
Ans:1
What is the default authendication mode in aps.net?
Three are three types of authendication mode available in asp.net . by default windows authendication.
Select Answer:
• 1. Windows
• 2. Passport
• 3. Form
Ans: 1
What happens if we remove session tag from web.cofig file ?
Select Answer:
• 1. sessions will not work
• 2. sessions will work
• 3. cookies will not be created
• 4. none
Ans:2
which class use to delete ,update ,select data in dataset.
Select Answer:
• 1. sqldataAdapter
• 2. sqlDataReader
• 3. SqlCommand
• 4. None
Ans:1
How to set focus in a textbox in asp.net after click on a button ?
Select Answer:
• 1. using Java script code textbox.focus and register it in asp.net by page.registerecript
• 2. can't focus by asp.net coding
• 3. use setfocus method
• 4. use keypress event with keycode property
Ans:1
if you develop a simple web page and use only text box than which one is better way for develop ?
Select Answer:
• 1. use only HTML Textbox control and for code make them runat server
• 2. use asp.net web form textbox
• 3. both
Ans:1
how to open more than one datareader at time ??
Select Answer:
• 1. use different Datareader varibles.
• 2. use different Datareader and connection variable and connection must be connected
• 3. use different datareader with signle connection and connection status must be connected
• 4. can't use more than one datatreader at a time
Ans:2
How to add asp.net 3rd party component ?
Select Answer:
• 1. By Add/Remove Items in PRoject Menu.
• 2. Add Reference of Dll file and palce their code where programmer want to use
• 3. can't add 3rd party component in asp.net
• 4. Require .OCX files of add component in aps.net
Ans:2
which component can be use for reporting in asp.net
Select Answer:
• 1. HTML Table.
• 2. data grid
• 3. Data Reapter
• 4. All of above
Ans:4
Advantage fo Disconneted mode ADO.net in asp.net ?
Select Answer:
• 1. automatically dump data at client pc.
• 2. user data can be update and retrieve in dataset and when connection connted update values with serve
• 3. not neccessary to connect with server
• 4. all of above
Ans: 2
How to execute java script code in asp.net back-end code. ??
Select Answer:
• 1. Page.RegisterScript.
• 2. Page.Language='Java Script'
• 3. To set Defalut Langaue Java Script in Virtual Directory
• 4. asp.net back end automatic provide this facility
Ans:1
How to deploy a ASp.Net Web Application as Web Site on Web Server ?
Select Answer:
• 1. Run Web setup on Web Server.
• 2. Register ASP.net application dll files on web server
• 3. install at locat pc and copy vitural directory on web server
• 4. Copy all project files on web server
Ans:1
Name the tool which converts from resx file to resources file which will be used in building satellite assemblies?
Select Answer:
• 1. SN.exe
• 2. AL.exe
• 3. Ngen.exe
• 4. Resgen.exe
• 5. None
Ans:4
What does WSDL stand for?
Select Answer:
• 1. Web System Description Language
• 2. Web Services Details Language
• 3. Web Services Design Language
• 4. Web Services Description Language
Ans:4
Which one of the following statements indicates ASP.NET’s advantage over ASP?
Select Answer:
• 1. Compiled Code
• 2. Caching
• 3. Web Controls
• 4. All of the above
Ans:4
What is Page Caching
Select Answer:
• 1. Keep the page with u
• 2. Keep a copy of the page anywhere
• 3. Delete the page
• 4. Carry the whole page in the session object
• 5. All of the above
Ans:2
Is there any significant difference between Link Button and Button in ASP.NET?
Select Answer:
• 1. Yes
• 2. No
• 3. Don't know
Ans:2
Can ASP and ASP.Net share session variables?
Select Answer:
• 1. yes
• 2. no
• 3. no, both support session variables but they cannot be shared
Ans:2
What id the default namespace for the web services?
Select Answer:
• 1. System.Web.WebServices
• 2. WebServices
• 3. Service1
• 4. http://tempuri.org
• 5. None
Ans:4
What is a satellite Assembly?
Select Answer:
• 1. A peripheral assembly designed to monitor permissions requests from an application?
• 2. Any DLL file used by an EXE file
• 3. An assembly containing localized resources for another assembly
• 4. An assembly designed to alter the appearance or ‘skin’ of an application
• 5. None of these
Ans:3
How can we fix that if any error will come in my live website, the error should not be displayed to site user. He will get an SORRY MESSAGE and a mail should be sent to Admin of website with following information.
1. Error Type
2. Description of Error
3. Line Number
4. Error source
5. Script Name
Select Answer:
• 1. Can put an Exception Handler
• 2. Can set some settings in IIS
• 3. Can set Some settings in Web.Config
• 4. It is not possible
Ans:1
Which one of the following objects is used to create a foreign key between two DataTables?
Select Answer:
• 1. DataRelation
• 2. DataRelationship
• 3. DataConstraint
• 4. DataKey
• 5. DataForeignKey
Ans:1
Which interface provides a fast, connected, forward-only access to a data source?
Select Answer:
• 1. IDataRecord
• 2. IDatabase
• 3. IDataCursor
• 4. IDataReader
• 5. IdataSet
Ans:4
Which is the best approach to move very large files from a web server to a browser client.
Select Answer:
• 1. Allow direct access to the file.
• 2. Using Response.WriteFile
• 3. Streaming the File using Response.BinaryWrite
• 4. Use an ISAPI Filter or improve by Upgrading to IIS 6.0 and running in Isolation mode
Ans:4
Can we manipulate Sessions thru Classes ( Not Code behind files) in ASP.NET application?
Select Answer:
• 1. Access in Classes
• 2. Set / Update in Classes
• 3. Both of above
• 4. None
Ans: 3
What is the Default ScriptTimeOut for Server Object?
Select Answer:
• 1. 30 Sec
• 2. 20 Sec
• 3. 60 Sec
• 4. 90 Sec
Ans:4
View State Concept based on
Select Answer:
• 1. HiddenField
• 2. PostBack
• 3. EventGeneration
• 4. ServerSide Controls
Ans:1
By default, when does validation automatically occur?
Select Answer:
• 1. After page initialization and before event handling
• 2. After page initialization and event handling
• 3. Before the data is sent to the server
• 4. Before page initialization and event handling
• 5. Any time an input control is changed
Ans:1
Which property of the Session object is used to set the local identifier?
Select Answer:
• 1. SessionID
• 2. LCID
• 3. Item
• 4. Key
Ans:2
What extension does the Web User Control file contain?
Select Answer:
• 1. .asmx
• 2. .ascx
• 3. .aspx
• 4. .awuc
Ans:2
To which namespaces do Trace and Debug belong?
Select Answer:
• 1. System.ComponentModel
• 2. System.Collections
• 3. System.Diagnostics
• 4. System.Trace
Ans: 3
Which control would you use if you needed to make sure the values in two different controls matched?
Select Answer:
• 1. Range Validator Control
• 2. Regular Expression Validator Control
• 3. Match Validator Control
• 4. CompareValidator Control
Ans: 4
What base class do all Web Forms inherit from?
Select Answer:
• 1. The System Class
• 2. The Inherit Class
• 3. The Page Class
• 4. The Global Class
Ans:3
How can you provide an alternating color scheme in a Repeater control?
Select Answer:
• 1. AlternatingItemTemplate
• 2. AlternateItemTemplate
• 3. AlternateTemplate
• 4. AlternatingTemplate
Ans:1
Which template must you provide, in order to display data in a Repeater control?
Select Answer:
• 1. DisplayTemplate
• 2. ShowTemplate
• 3. ItemTemplate
• 4. HeaderTemplate
Ans:3
what is a diffgram?
Select Answer:
• 1. Data Diagram
• 2. Data Dictionary
• 3. XML format
• 4. Diagram file
Ans:3
What type of code (server or client) is found in a Code-Behind class?
Select Answer:
• 1. Client-side code
• 2. Server-side code
• 3. Client-Server Code
• 4. None of the above
Ans:2
Which one of the following is NOT a valid state management tool?
Select Answer:
• 1. Hidden Form Fields
• 2. Cookies
• 3. Query State
• 4. Application State
• 5. Session State
Ans:3
Which DataTable property returns all rows and columns from a DataTable?
Select Answer:
• 1. TableView
• 2. ViewAll
• 3. DefaultView
• 4. ReturnTable
Ans:3
What is the purpose of code-behind?
Select Answer:
• 1. To separate different sections of a page into different files according to function
• 2. To merge layout HTML and the code into one file
• 3. To separate the layout HTML and the code into two different files
• 4. To discard the use of HTML
Ans:3
How to put conditional statement in Data Grid?
Select Answer:
• 1. Using Calling function in data grid only
• 2. Using ItemDataBound event only
• 3. Above both a and b.
• 4. Directly put condition in data grid
Ans:3
What are the default user directory permissions when a Web site is created in IIS?
Select Answer:
• 1. Read and Execute
• 2. Read and Write
• 3. Read/Write and Execute
• 4. Execute Only
Ans:1
An application using cookie authentication was working fine on another server. When moved to a new server, cookie authentication is not working correctly.
Which one of the following is the likely explanation of the above problem?
Select Answer:
• 1. The new IIS server is not configured to allow anonymous access
• 2. SSL is not properly configured.
• 3. The IP address of the new server does not match the prior server IP address
• 4. Passport authentication is not correctly configured.
• 5. The users are not correctly entering their passwords
Ans:1
How we can terminate the current session.
Select Answer:
• 1. Session.End
• 2. Session.Kill
• 3. Session.Abondon
• 4. We Can't Terminate the session
Ans:3
In global.asax file, which event will occur first when an application is invoked?
Select Answer:
• 1. Session_onStart()
• 2. Application_onStart()
• 3. Session_onEnd()
• 4. Application_onEnd()
• 5. None
Ans: 2
Which property indicates whether the control posts back to server each time a user interacts with a control?
Select Answer:
• 1. Post Back
• 2. Auto Post Back
• 3. Auto Event Wire Up
• 4. Trace
Ans:2
What are the minimum changes required for deploying an Asp.net Application using xCopy deployment. where web site name will be change.
Select Answer:
• 1. Changes in web.Config Files
• 2. Changes in All Files and Build Application Again
• 3. Changes in the path of .SLN and webinfo.cs files.
• 4. changes in All configuration files and build Application again on the Destination Server.
• 5. None of Above
Ans:3
Which session state gives fastest application performance when we are maintaining sessions?
Fastest Mode in session states
Select Answer:
• 1. SqlServer
• 2. StateServer
• 3. InProc
• 4. Off
Ans:3
In which session state mode the session state will be disabled ?
Select Answer:
• 1. Inproc
• 2. StateServer
• 3. SqlServer
• 4. None of the Above
Ans:4
Threads are:
Threads are:
Select Answer:
• 1. static methods
• 2. objects
• 3. instance methods
• 4. events
Ans:2
What is the printout of the following?
What is the printout of the following?
byte b1=1;
byte b2=255;
byte total=b1+b2;
Console.WriteLine (total);
Select Answer:
• 1. We will get a runtime error
• 2. We will get a compilation error
• 3. 256
• 4. 1
Ans:2
Which of the following is true ?
Select Answer:
• 1. IsPostBack is a method of System.UI.Web.Page class
• 2. IsPostBack is a method of System.Web.UI.Page class
• 3. IsPostBack is a property of System.UI.Web.Page class
• 4. IsPostBack is a readonly property of System.Web.UI.Page class
• 5. IsPostBack is a static property of System.UI.Web.Page class
Ans:4
How you can dynamically change the background color of Datagrid cells.
Select Answer:
• 1. By Handling OnSelect event
• 2. By Handling Edit event
• 3. By Handling ItemBound event
• 4. By Handling PageChange event
Ans:3
The .NET class Global is derived from which of the following classes ?
Select Answer:
• 1. System.Web.UI.PageParser
• 2. System.Web.HttpApplicationState
• 3. System.Web.UI.Page
• 4. System.Web.HttpApplication
• 5. None of the above.
Ans:4
What is the function of Response.End?
Select Answer:
• 1. it will stop the server process
• 2. it will stop the client process
• 3. or both
• 4. or none
Ans:1
From which one of the following locations does the garbage collector remove objects?
Select Answer:
• 1. The download cache
• 2. The global assembly cache
• 3. The thread stack
• 4. The managed heap
• 5. The system registry
Ans: 4
What is Static and Dynamic Assemblies.?
The Difference between both.
Select Answer:
• 1. Both are same
• 2. There is no Static Assemblies
• 3. Dynamic assemblies have dynamic variable input but static assemblies have no variable input
• 4. Static Assemblies Define metadata and Dynamic assemblies Define Icon,String
• 5. Static Assemblies are created by user before running the application, Dynamic Assemblies are Dynamic
Ans:5
If one web form inherits the another web form, the drived web form able to access base class ....
Select Answer:
• 1. Code.
• 2. Server controls
• 3. HTML's
• 4. 1 and 2
• 5. all of above
Ans: 1
Technically,to whom we bind the any controls?
Select Answer:
• 1. Dataset
• 2. Datareader
• 3. Datatable
• 4. Dataview
Ans: 4
Which of the following controls contribute the highest Requests per second
Select Answer:
• 1. DataGrid
• 2. DataList
• 3. DataRepeater
Ans:3
User Control is nothing but
Select Answer:
• 1. A logical component
• 2. A visual component
• 3. Both of Logical and Visual
• 4. None of the above
Ans:3
What is boxing and unboxing ?
Implicit (manual) conversion of value type to reference type of a variable is known as BOXING, for example integer to object type conversion. Conversion of Boxed type variable back to value type is called as UnBoxing.
what is connected and diconnected database ?
Connected and Disconneted database basicallythe approch that how you handle the database connection, It may be connected that once the application starts you have to open the connection only for a single time and then performs many transactions and close the connection just before exit the application. This approch will be generally used in windows based application. On other hand disconnected architecter refere to open and close the connection for each time while performing a transactio.
What is garbage collection and how it works ?
Garbage Collection is Automatic Memory Manager for the dotnet framework. It manages the momery allocated to the .NET framework. CLR takes cares about .NET framework. When a variable is defined, Its gets a space in the memory and when the program control comes out of that function the scope of variable gets ended, so the garbage collection acts on and memory will releases.
What are the different types of caching ?
Output caching, Fragment Caching and Data caching.
What are different types of directives in .NET ?
Page, Outputcache, Register
1.What is the difference between user controls and custom controls?
CUSTOM CONTROLS are DLL'S.It can be placed in the toolbox.Drag and drop controls.
USER CONTROLS: are pages (.ascx).It can not be placed in the tool box.
2.what are the 3 types of session state modes?
a.Inproc-session kept as live object in the web server(aspnet_wp.exe)
b.Stateserver-Session serialized and stored in memory in a seperate process(aspnet_state.exe),we can use for webform architecture.
c.SQLServer-Session serialized and stored in sql server.
3. what are the 6 types of validation controls in ASP.NET?
1.Required Field validator.2.Range validator.3.Regular Expression validator.4.compare validator.5custom validator.
6.validation summary.
4.What are the 3 types of caching in ASP.NET?
1. Output Caching(Page Caching)- stores the responses from an asp.net page(aspx) or user control(.ascx).
2.Fragment Caching(Partial Caching)- Only stores the portion of a page.
3. Data Caching is the programmatic way to your objects to a managed cache.
//Add item
Cache["TopProducts"] = objTopProductsDataset;
//Retrieve item
objDataset = Cache["TopProducts"];
.5.How to Manage state in ASP.NET?
we can manage the state in two ways
Clent based techniques are
Viewstate, Query strings and Cookies.
Server based techniques are
Application and Session
6.What is the difference between overloading and shadowing?
Overloading ----------- A Member has the name, but something else in the signature is different.
Shadowing --------- A member shadows another member if the derived member replaces the base member
7.what is the difference between overloading and overriding?
Overloading : Method name remains the same with different signatures.
Overriding : Method name and Signatures must be the same.
8.what is the difference between Manifest and Metadata?
Manifest:
Manifest describes assembly itself.
Assembly Name,version number,culture,strongname,listof all all files,Type references,and referenced assemblies.
MetaData:
Metadata describes contents in an assembly
classes, interfaces, enums, structs, etc., and their containing namespaces, the name of each type,
its visibility/scope, its base class, the interfaces it implemented, its methods and their scope
, and each method’s parameters, type’s properties, and so on.
9.What is Boxing and Unboxing?
Boxing is an implicit conversion of a value type to the type object
int i = 123; // A value type
Object box = i // Boxing
CASTING : casting is the process of converting a variable from one type to another (from a string to an integer )
Unboxing is an explicit conversion from the type object to a value type
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
10.what are the method parameter in c#?
C# is having 4 parameter types which are
1.Value Parameter. default parameter type. Only Input
2.Reference(ref) Parameter. Input\Output
3.Output(out) Parameter.
4.Parameter(params) Arrays
11.what are value types and reference types?
Value type
bool, byte,chat, decimal,double,enum , float, int, long, sbyte, short, strut, uint, ulong, ushort
Value types are stored in the Stack
Reference type
class, delegate, interface, object, string
Reference types are stored in the Heap
12.what are the two activation modes for .NET Remoting?
1. Singleton 2. Singlecall
13.what's singlecall Activation mode used for ?
The Server Object is instantiated for responding to just one single request
14.what's the singleton Activation mode used for?
The server object is instantiated for responding number of clients
15.what are the channels and Formatters?
Channels
HTTP and TCP
Binay Over TCP is most efficient
SOAP over HTTP is most interoperable
Formatters
Binary and SOAP
16.What are the two Authentication modes for SQL server connection?
1. Trusted Connection - Windows Authentication
2. Non trusted Connection - Sql Server Authentication(its preferable for webservices)
17.What is typed dataset?
Data Access is normally done using indexes on collectionsin object model.
In ADO.NET it is possible to create a variation on a Dataset that does support
such syntax.Such Dataset is called "Typed Dataset".
Errors in the syntax are detected during compile time rather than runtime.
Advantages of Typed Dataset:
1.The data designer tool generates typed Datasets.
2.When we type the name of a dataset while writing a code,
weget a list of all available tables in the dataset.No need to
remember the table names.
For (eg) instead of typing
myDataset.Tables("products")
we can type
myDataset.products.
18.what is DataReader?
DataReader is a read only stream of data returned from
the database as the query executes.
It contains one row of data in memory at a time and is
restricted to navigating forward only in the results one record at a time.
Datareader supports access to multiple result sets but only one at a time and in the order retrieved.
In ADO data is no longer available through the Datareaderoncethe connection to the datasource is closed
which means a Datareader requires a connection to the Database throughout its usage.
o/p parameters or return values are only available thrugh the Datareader once the connection is closed.
19.Difference between Dataset and Recordset?
The Recordset was not XML-based and could not be serialized to XML easily or flexibly.
Finally, a Recordset was not independent of a data store because it tracked a Connection object
and through its methods could send queries to the data source to populate, update,
and refresh its data.
To that end, the Recordset contained functionality found in the ADO.NET DataSet,
data reader, and data adapter objects.
Similar to the DataSet, a Recordset could be disconnected from its data store
and therefore act as an in-memory cache of data.
Of course, it could also be used in a connected model depending on the cursor options that were set.
Although the Recordset object stored multiple versions of each column for each of its rows,
it was not by nature able to represent multiple tables without the use of the Data Shape Provider.
.
21.What isan Assembly, Private Assembly and SharedAssembly,Strong Name?
Assembly: Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.
Private assembly is used inside an application only and does not have to be identified by a strong name
Shared assembly can be used by multiple applications and has to have a strong name.
Strong Name :A strong name includes the name of the assembly, version number, culture identity, and a public key token.
22.what is an Delegate?
A strongly typed function pointer. A delegate object encapsulates a reference to a method.
23.what are webservices?
A Web Service is an application that delivers a service across the Internet using the standards and technologies defined in the Web Services architecture in a platform-independent and language-neutral fashion.
Web Services rely on several XML protocols based on open standards that are collectively known as the Web Services architecture
24.Define Automatic memory Management:
c# Provides Automatic memory Management.
Automatic memory Management increases code quality and enhances developer productivity without negatively impacting
either expressivenessor perfromance.Developers are freed from this burdensome task.
25.Define Threading:
It's a process of creating applications that can perform multiple tasks independently.
26Difference Between XML AND HTML?
XML:
User definable tags.
Content driven
End tags required for well formed documents
Quotes required around attributes values
Slash required in empty tags
HTML :
Defined set of tags designed for web display
Format driven
End tags not required
Quotes not required
Slash not required
27.What is XSLTand what is it's use?
XSL Transformations (XSLT) is yet another popular W3C specification that defines XML-based syntax, used to transform XML documents to any other text format, such as HTML, text, XML, etc. XSLT stylesheets can be applied on the source XML document to transform XML into some other XML, or text, HTML, or any other text format.
28.What is Diffgram?
It's an XML format.
It'sone of the two xml formats that uses to render Dataset object contents to XML.
For reading database data to an XML file to be sent to a webservice.
29.what is the Role of XSL?
Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules
30.What is SAX?
Simple API for XML Processing (SAX) is an alternative to DOM, and can be used to parse XML documents. SAX is based on streaming model. The SAX parser reads input XML stream and generates various parsing events that an application can handle. With each parsing event, the parser sends sufficient information about the node being parsed. Unlike DOM, SAX does not build an in-memory representation of the source XML document, and hence it is an excellent alternative when parsing large XML documents, as SAX does not require that much memory (and resources). Unlike DOM, SAX is not defined/controlled by W3C. See http://www.saxproject.org/ for details.
32.Give a few examples of types of applications that can benefit from using XML.
XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.
33.When constructing an XML DTD, how do you create an external entity reference in an attribute value?
when using SGML, XML DTDs don't support defining external entity references in attribute values.
34.Give some examples of XML DTDs or schemas that you have worked with.
Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology.commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project
35.What is SOAP and how does it relate to XML?
The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.
36.What is WSDL?
Another key standard in the Web Services architecture is the Web Services Description Language, or WSDL for short. Whereas SOAP is responsible for providing a platform-neutral protocol for transporting data types and interapplication messaging, WSDL is an XML grammar responsible for exposing the methods, arguments, and return parameters exposed by a particular Web Service.
37.What’s the difference between authentication and authorization? Authentication happens first. You verify user’s identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for.
38.Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications.
39.Define scalability.
The application meets its requirement for efficiency even if the number of users increases.
40.Define reliability.
The application generates correct and consistent information all the time.
41.Define availability.
Users can depend on using the application when needed.
42.Define security.
The application is never disrupted or compromised by the efforts of malicious or ignorant users
43.Define manageability.
Deployment and maintenance of the application is as efficient and painless as possible
44.Explain durability.
Make sure that the system can return to its original state in case of a failure.
45.Explain integrity.
Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.
46.Explain consistency.
We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.
47.Explain JIT activation.
The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases
48.Define Constructors and destructors
The create and destroy methods - often called constructors and destructors - are usually implemented for any abstract data type. Occasionally, the data type's use or semantics are such that there is only ever one object of that type in a program. In that case, it is possible to hide even the object's `handle' from the user. However, even in these cases, constructor and destructor methods are often provided.
Of course, specific applications may call for additional methods, e.g. we may need to join two collections (form a union in set terminology) - or may not need all of these.
oops
What is static Readonly fields ?
Ans : Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change. Readonly fields can be used to prevent such problems.
Assignments to a readonly field can only occur as part of the declaration,
or in an instance or static constructor in the same class.
A static readonly field can be assigned in a static constructor,
and a non-static readonly field can be assigned in an instance constructor.
Thus, the Color class can be enhanced by adding the readonly modifier to the static fields:
class Color
{
internal ushort redPart;
internal ushort bluePart;
internal ushort greenPart;
public Color(ushort red, ushort blue, ushort green) {
redPart = red;
bluePart = blue;
greenPart = green;
}
public static readonly Color Red = new Color(0xFF, 0, 0);
public static readonly Color Blue = new Color(0, 0xFF, 0);
public static readonly Color Green = new Color(0, 0, 0xFF);
public static readonly Color White = new Color(0xFF, 0xFF, 0xFF);
}
What is a constant?
Ans : A constant is a class member that represents a constant value:
a value that can be computed at compile-time.
Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies.
The rules governing constant expressions are defined in constant expression
The example
class Constants
{
public const int A = 1;
public const int B = A + 1;
}
shows a class named Constants that has two public constants.
Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in
class Test
{
static void Main() {
Console.WriteLine("{0}, {1}", Constants.A, Constants.B);
}
}
which prints out the values of Constants.A and Constants.B.
Q. What is the difference between Value types and Object types?
A. Value types are built-in data types in any .Net compliant language and they are stored on the application stack, whereas the Object types are user-defined types and are by default reference types and will be stored in the managed heap.
Note: A thread of discussion started here to know the depth of my understanding about the stack and heap implementation in .NET. This discussion went on for more than 12 minutes. Basically he wanted to know memory is managed in .NET by the CLR or runtime.
Q. When is a value type used over an object type?
A. Value types are used for temporary storage. They are valid only in the scope of the function or the execution block in which they are declared. Whereas the reference types are used for user-defined types which need to retain the state across function calls and have a lifetime which is defined by the usage.
Note: I also explained him about the Garbage collection mechanism here and how GC works: Application roots, marking for removal, Compaction and Finalization etc.
Q. What are different keywords used related to inheritance in C#?
A. Virtual, override, new, sealed and abstract.
Q. Given an unsigned 16 bit integer, what is the max value it can hold?
A. 65535
Q. What happens if I store more than max value in the previous scenario?
A. In .Net this scenario can be addressed in two ways: If the same is done in a checked context, the runtime will throw an OverflowException, whereas if run in unchecked context, the MSB is truncated and rest of the value is stored in the variable and the execution continues…
Note: He asked whether I was sure about this and I said, yes. But he said “Check this out to-night and you will be surprised to see the result”. Which in fact I did and didn’t find any surprise. May be there’s some undocumented feature of .NET here.
Q. What does the new keyword do w.r.t inheritance?
A. It hides the base class’s implementation.
Q. Rate yourself in OOAD and UML on a scale of 10?
A. 7-8.
Q. What is the difference between Inheritance and Composition?
A. Inheritance is a generalization relationship, used for code reuse. I cited an example of Shape as the base class and Circle, Rectangle as the derived classes. Explained him about generalization to specialization.
Composition is a strong form of containment, where the part’s lifetime is dependent on the whole. Cited and example.
Q. What is polymorphism?
A. Compile time polymorphism (Function/operator overloading examples).
Runtime polymorphism (Late binding, Virtual/Overridden functions examples).
Q. Given a base class reference to a derived class can you access the derived class methods?
A. Object Polymorphism in other words: Cited the same shape Circle example and explained the behavior.
Q. What all database components are available in .NET?
A. ADO.NET components. Connection, Command, DataReader, DataSet and DataView. Explained each.
Q. What is the advantage of using the OLE DB drivers directly?
A. Certainly the performance will improve as the abstraction layers are removed.
Q. What is the difference between a clustered index and non-clustered index?
A. In a clustered-index, the data page and the index page are same whereas in a non-clustered index, the data pages and the index page is separate.
Q. How do you implement an index?
A. I haven’t done in the past.
Q. Explain a Left outer join and a right outer join?
A. Left outer join will also involve the fields of the table on the left of the join query that are not specified in the SQL query.
Right outer join will also involve the fields of the table on the right of the join query that are not specified in the SQL query.
Q. Do you know about execution plan?
A. Execution plans are formed by the database engine to find the optimized way of executing a query. I will use the most appropriate query plan as needed.
What is the diff b/w Abstract method and virtual method?
Ans: Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived Class to override the method.
28. What is the dif b/w Array and Array list?
Ans: major difference in between array and array list is insertion and deletion of
Data, in Array List we can easily insert Data at a particular location while
In array it is not possible
Array is for homogeneous data. I.e data of same data type.
Whereas Array list is for Heterogeneous data. The data in the array list need
Not be of same data type.
29: What is diff b/w Array list and Hash table?
Ans: Array list is a collection of objects (may be of different types).
Array list is very much similar to array but it can take values of different data types.
If you want to find something in an array list you have to go through each value in array list, there’s no faster way out.
Hash table is also collection which takes a key corresponding to each value.
If you want to find something in a hash table you don’t have to go through each value in hashtable, instead search for key values and is faster.
Ex:
Creating Hashtable: Hashtable hash=new Hashtable ();
Adding items to Hashtable: hash.Add ("Author1","Mahesh Chand");
hash.Add ("Author2","James Brand");
Retrieving items value: string name=hash ["Author1"].ToString ();
Removing items: hash.Remove ("Author1");
30. What is Partial class?
31. What is diff b/w a==b and a.equals (b)?
Ans: generally we are using == for comparing with value types where as .equals method for reference types
If A and B are the objects of the class
A.equals (B) is correct method to compare two objects
32. What is Reflection?
Ans: All .Net assemblies have metadata information about the types used in our modules. This metadata information can be accessed by mechanism is called Reflection.
33. What is diff b/w Constant variable and Read-only variables?
Ans: We can’t change Constant variable values.
But we can change Read-only variables at runtime.
17. What is abstract class?
Note: This is must inherit class.
Ans: Abstract class contains General methods and Abstract methods. It contains atleast
One abstract method. The method which contain with out body is called Abstract
Method. We can not create instance for that. But we can create reference
16. What is diff b/w overloading and overriding?
Ans: Overloading is the concept of it contains same method name and diff prototypes.
Ex: Public void AAA (int a, int b);
Public void AAA (int a, int b, int c);
Overriding is the concept of it contains same method name and same prototypes
In base class and derived classes
21. What is the diff b/w string and string Builder class?
Ans: String
.It is immutable (value cannot be changed)
.if the value has to be changed then new instance should be created
Ex: string s1 = "dotnet";
string s2 = "spider";
string s3 = string.concat (s1, s2)
Stringbuilder
.it is mutable (value can be changed)
.no need to create the new instance.becz the append method used to add the new string in the same instance.
Ex:
StringBuilder s1 = new StringBuilder ("dotnet");
s1.append ("spider").To String ();
Now the result will be "dotnetspider"
What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
13. What is the use of AutoEventWireup property for Aspx Page?
Ans: The Default is true. If events for Asp.Net pages are automatically connected to event-Handling functions. Otherwise False.
7. What is the base class of all exceptions? Give me some predefined exceptions?
Ans: system.exception
1. Argument Exception.
2. ArithmeticNullException.
3. DivideByZeroException.
1. What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.
2. What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
3. Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
4. You have one base class virtual function how will call that function from derived class?
Ans:
5. class a
6. {
7. public virtual int m()
8. {
9. return 1;
10. }
11. }
12. class b:a
13. {
14. public int j()
15. {
16. return m();
17. }
}
18. In which cases you use override and new base?
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
C# Language features
19. What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
20. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
**
21. class Token
22. {
23. public string Display()
24. {
25. //Implementation goes here
26. return "base";
27. }
28. }
29. class IdentifierToken:Token
30. {
31. public new string Display() //What is the use of new keyword
32. {
33. //Implementation goes here
34. return "derive";
35. }
36. }
37. static void Method(Token t)
38. {
39. Console.Write(t.Display());
40. }
41. public static void Main()
42. {
43. IdentifierToken Variable=new IdentifierToken();
44. Method(Variable); //Which Class Method is called here
45. Console.ReadLine();
46. }
47. For the above code What is the "new" keyword and Which Class Method is
48. called here
A: it will call base class Display method
49. class Token
50. {
51. public virtual string Display()
52. {
53. //Implementation goes here
54. return "base";
55. }
56. }
57. class IdentifierToken:Token
58. {
59. public override string Display() //What is the use of new keyword
60. {
61. //Implementation goes here
62. return "derive";
63. }
64. }
65. static void Method(Token t)
66. {
67. Console.Write(t.Display());
68. }
69. public static void Main()
70. {
71. IdentifierToken Variable=new IdentifierToken();
72. Method(Variable); //Which Class Method is called here
73. Console.ReadLine();
74. }
75. A: Derive
76. In which Scenario you will go for Interface or Abstract Class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
Interfaces vs. Abstract Classes
Feature Interface Abstract class
Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class.
Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.
77. see the code
78. interface ICommon
79. {int getCommon();}
80.
81. interface ICommonImplements1:ICommon
82. { }
83.
84. interface ICommonImplements2:ICommon
85. { }
86.
87. public class a:ICommonImplements1,ICommonImplements2
88. { }
How to implement getCommon method in class a? Are you seeing any problem in the implementation?
Ans:
public class a:ICommonImplements1,ICommonImplements2
{
public int getCommon()
{
return 1;
}
}
89. interface IWeather
90. {
91. void display();
92. }
93. public class A: Weather
94. {
95. public void display()
96. {
97. MessageBox.Show("A");
98. }
99. }
100. public class B:A
101. { }
102. public class C:B,IWeather
103. {
104. public void display()
105. {
106. MessageBox.Show("C");
107. }
108. }
109. When I instantiate C.display(), will it work?
110. interface IPrint
111. {
112. string Display();
113. }
114. interface IWrite
115. {
116. string Display();
117. }
118. class PrintDoc:IPrint,IWrite
119. {
120. //Here is implementation
121. }
how to implement the Display in the class printDoc (How to resolve the naming Conflict) A: no naming conflicts
class PrintDoc:IPrint,IWrite
{
public string Display()
{
return "s";
}
}
122. interface IList
123. {
124. int Count { get; set; }
125. }
126. interface ICounter
127. {
128. void Count(int i);
129. }
130. interface IListCounter: IList, ICounter {}
131. class C
132. {
133. void Test(IListCounter x)
134. {
135. x.Count(1); // Error
136. x.Count = 1; // Error
137. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
138. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
139. }
140. }
141. Write one code example for compile time binding and one for run time binding? What is early/late binding?
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
' Create a variable to hold a new object.
Dim FS As FileStream
' Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")
Ans : Static fields are not a perfect match for this scenario. The fields are initialized at some point before they are used, but after this initialization there is nothing to stop a client from changing them. Such a modification could cause unpredictable errors in other programs that use Color and assume that the values do not change. Readonly fields can be used to prevent such problems.
Assignments to a readonly field can only occur as part of the declaration,
or in an instance or static constructor in the same class.
A static readonly field can be assigned in a static constructor,
and a non-static readonly field can be assigned in an instance constructor.
Thus, the Color class can be enhanced by adding the readonly modifier to the static fields:
class Color
{
internal ushort redPart;
internal ushort bluePart;
internal ushort greenPart;
public Color(ushort red, ushort blue, ushort green) {
redPart = red;
bluePart = blue;
greenPart = green;
}
public static readonly Color Red = new Color(0xFF, 0, 0);
public static readonly Color Blue = new Color(0, 0xFF, 0);
public static readonly Color Green = new Color(0, 0, 0xFF);
public static readonly Color White = new Color(0xFF, 0xFF, 0xFF);
}
What is a constant?
Ans : A constant is a class member that represents a constant value:
a value that can be computed at compile-time.
Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies.
The rules governing constant expressions are defined in constant expression
The example
class Constants
{
public const int A = 1;
public const int B = A + 1;
}
shows a class named Constants that has two public constants.
Even though constants are considered static members, a constant declaration neither requires nor allows the static modifier. Constants can be accessed through the class, as in
class Test
{
static void Main() {
Console.WriteLine("{0}, {1}", Constants.A, Constants.B);
}
}
which prints out the values of Constants.A and Constants.B.
Q. What is the difference between Value types and Object types?
A. Value types are built-in data types in any .Net compliant language and they are stored on the application stack, whereas the Object types are user-defined types and are by default reference types and will be stored in the managed heap.
Note: A thread of discussion started here to know the depth of my understanding about the stack and heap implementation in .NET. This discussion went on for more than 12 minutes. Basically he wanted to know memory is managed in .NET by the CLR or runtime.
Q. When is a value type used over an object type?
A. Value types are used for temporary storage. They are valid only in the scope of the function or the execution block in which they are declared. Whereas the reference types are used for user-defined types which need to retain the state across function calls and have a lifetime which is defined by the usage.
Note: I also explained him about the Garbage collection mechanism here and how GC works: Application roots, marking for removal, Compaction and Finalization etc.
Q. What are different keywords used related to inheritance in C#?
A. Virtual, override, new, sealed and abstract.
Q. Given an unsigned 16 bit integer, what is the max value it can hold?
A. 65535
Q. What happens if I store more than max value in the previous scenario?
A. In .Net this scenario can be addressed in two ways: If the same is done in a checked context, the runtime will throw an OverflowException, whereas if run in unchecked context, the MSB is truncated and rest of the value is stored in the variable and the execution continues…
Note: He asked whether I was sure about this and I said, yes. But he said “Check this out to-night and you will be surprised to see the result”. Which in fact I did and didn’t find any surprise. May be there’s some undocumented feature of .NET here.
Q. What does the new keyword do w.r.t inheritance?
A. It hides the base class’s implementation.
Q. Rate yourself in OOAD and UML on a scale of 10?
A. 7-8.
Q. What is the difference between Inheritance and Composition?
A. Inheritance is a generalization relationship, used for code reuse. I cited an example of Shape as the base class and Circle, Rectangle as the derived classes. Explained him about generalization to specialization.
Composition is a strong form of containment, where the part’s lifetime is dependent on the whole. Cited and example.
Q. What is polymorphism?
A. Compile time polymorphism (Function/operator overloading examples).
Runtime polymorphism (Late binding, Virtual/Overridden functions examples).
Q. Given a base class reference to a derived class can you access the derived class methods?
A. Object Polymorphism in other words: Cited the same shape Circle example and explained the behavior.
Q. What all database components are available in .NET?
A. ADO.NET components. Connection, Command, DataReader, DataSet and DataView. Explained each.
Q. What is the advantage of using the OLE DB drivers directly?
A. Certainly the performance will improve as the abstraction layers are removed.
Q. What is the difference between a clustered index and non-clustered index?
A. In a clustered-index, the data page and the index page are same whereas in a non-clustered index, the data pages and the index page is separate.
Q. How do you implement an index?
A. I haven’t done in the past.
Q. Explain a Left outer join and a right outer join?
A. Left outer join will also involve the fields of the table on the left of the join query that are not specified in the SQL query.
Right outer join will also involve the fields of the table on the right of the join query that are not specified in the SQL query.
Q. Do you know about execution plan?
A. Execution plans are formed by the database engine to find the optimized way of executing a query. I will use the most appropriate query plan as needed.
What is the diff b/w Abstract method and virtual method?
Ans: Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived Class to override the method.
28. What is the dif b/w Array and Array list?
Ans: major difference in between array and array list is insertion and deletion of
Data, in Array List we can easily insert Data at a particular location while
In array it is not possible
Array is for homogeneous data. I.e data of same data type.
Whereas Array list is for Heterogeneous data. The data in the array list need
Not be of same data type.
29: What is diff b/w Array list and Hash table?
Ans: Array list is a collection of objects (may be of different types).
Array list is very much similar to array but it can take values of different data types.
If you want to find something in an array list you have to go through each value in array list, there’s no faster way out.
Hash table is also collection which takes a key corresponding to each value.
If you want to find something in a hash table you don’t have to go through each value in hashtable, instead search for key values and is faster.
Ex:
Creating Hashtable: Hashtable hash=new Hashtable ();
Adding items to Hashtable: hash.Add ("Author1","Mahesh Chand");
hash.Add ("Author2","James Brand");
Retrieving items value: string name=hash ["Author1"].ToString ();
Removing items: hash.Remove ("Author1");
30. What is Partial class?
31. What is diff b/w a==b and a.equals (b)?
Ans: generally we are using == for comparing with value types where as .equals method for reference types
If A and B are the objects of the class
A.equals (B) is correct method to compare two objects
32. What is Reflection?
Ans: All .Net assemblies have metadata information about the types used in our modules. This metadata information can be accessed by mechanism is called Reflection.
33. What is diff b/w Constant variable and Read-only variables?
Ans: We can’t change Constant variable values.
But we can change Read-only variables at runtime.
17. What is abstract class?
Note: This is must inherit class.
Ans: Abstract class contains General methods and Abstract methods. It contains atleast
One abstract method. The method which contain with out body is called Abstract
Method. We can not create instance for that. But we can create reference
16. What is diff b/w overloading and overriding?
Ans: Overloading is the concept of it contains same method name and diff prototypes.
Ex: Public void AAA (int a, int b);
Public void AAA (int a, int b, int c);
Overriding is the concept of it contains same method name and same prototypes
In base class and derived classes
21. What is the diff b/w string and string Builder class?
Ans: String
.It is immutable (value cannot be changed)
.if the value has to be changed then new instance should be created
Ex: string s1 = "dotnet";
string s2 = "spider";
string s3 = string.concat (s1, s2)
Stringbuilder
.it is mutable (value can be changed)
.no need to create the new instance.becz the append method used to add the new string in the same instance.
Ex:
StringBuilder s1 = new StringBuilder ("dotnet");
s1.append ("spider").To String ();
Now the result will be "dotnetspider"
What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.
Binary serialization preserves Type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example: An object can be shared between different applications by serializing it to the clipboard.
You can serialize an object to a stream, disk, memory, over a network, and so forth. Remoting uses serialization to pass objects "By Value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve Type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data.
As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
13. What is the use of AutoEventWireup property for Aspx Page?
Ans: The Default is true. If events for Asp.Net pages are automatically connected to event-Handling functions. Otherwise False.
7. What is the base class of all exceptions? Give me some predefined exceptions?
Ans: system.exception
1. Argument Exception.
2. ArithmeticNullException.
3. DivideByZeroException.
1. What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.
2. What is Method Overriding? How to override a function in C#?
Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
3. Can we call a base class method without creating instance?
Its possible If its a static method.
Its possible by inheriting from that class also.
Its possible from derived classes using base keyword.
4. You have one base class virtual function how will call that function from derived class?
Ans:
5. class a
6. {
7. public virtual int m()
8. {
9. return 1;
10. }
11. }
12. class b:a
13. {
14. public int j()
15. {
16. return m();
17. }
}
18. In which cases you use override and new base?
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
C# Language features
19. What are Sealed Classes in C#?
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
20. What is Polymorphism? How does VB.NET/C# achieve polymorphism?
**
21. class Token
22. {
23. public string Display()
24. {
25. //Implementation goes here
26. return "base";
27. }
28. }
29. class IdentifierToken:Token
30. {
31. public new string Display() //What is the use of new keyword
32. {
33. //Implementation goes here
34. return "derive";
35. }
36. }
37. static void Method(Token t)
38. {
39. Console.Write(t.Display());
40. }
41. public static void Main()
42. {
43. IdentifierToken Variable=new IdentifierToken();
44. Method(Variable); //Which Class Method is called here
45. Console.ReadLine();
46. }
47. For the above code What is the "new" keyword and Which Class Method is
48. called here
A: it will call base class Display method
49. class Token
50. {
51. public virtual string Display()
52. {
53. //Implementation goes here
54. return "base";
55. }
56. }
57. class IdentifierToken:Token
58. {
59. public override string Display() //What is the use of new keyword
60. {
61. //Implementation goes here
62. return "derive";
63. }
64. }
65. static void Method(Token t)
66. {
67. Console.Write(t.Display());
68. }
69. public static void Main()
70. {
71. IdentifierToken Variable=new IdentifierToken();
72. Method(Variable); //Which Class Method is called here
73. Console.ReadLine();
74. }
75. A: Derive
76. In which Scenario you will go for Interface or Abstract Class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
Interfaces vs. Abstract Classes
Feature Interface Abstract class
Multiple inheritance A class may implement several interfaces. A class may extend only one abstract class.
Default implementation An interface cannot provide any code at all, much less default code. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.
Constants Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.
Third party convenience An interface implementation may be added to any existing third party class. A third party class must be rewritten to extend only from the abstract class.
is-a vs -able or can-do Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.
Plug-in You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.
Homogeneity If all the various implementations share is the method signatures, then an interface works best. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.
Maintenance If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.
Speed Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty. Fast
Terseness The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.
Adding functionality If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.
77. see the code
78. interface ICommon
79. {int getCommon();}
80.
81. interface ICommonImplements1:ICommon
82. { }
83.
84. interface ICommonImplements2:ICommon
85. { }
86.
87. public class a:ICommonImplements1,ICommonImplements2
88. { }
How to implement getCommon method in class a? Are you seeing any problem in the implementation?
Ans:
public class a:ICommonImplements1,ICommonImplements2
{
public int getCommon()
{
return 1;
}
}
89. interface IWeather
90. {
91. void display();
92. }
93. public class A: Weather
94. {
95. public void display()
96. {
97. MessageBox.Show("A");
98. }
99. }
100. public class B:A
101. { }
102. public class C:B,IWeather
103. {
104. public void display()
105. {
106. MessageBox.Show("C");
107. }
108. }
109. When I instantiate C.display(), will it work?
110. interface IPrint
111. {
112. string Display();
113. }
114. interface IWrite
115. {
116. string Display();
117. }
118. class PrintDoc:IPrint,IWrite
119. {
120. //Here is implementation
121. }
how to implement the Display in the class printDoc (How to resolve the naming Conflict) A: no naming conflicts
class PrintDoc:IPrint,IWrite
{
public string Display()
{
return "s";
}
}
122. interface IList
123. {
124. int Count { get; set; }
125. }
126. interface ICounter
127. {
128. void Count(int i);
129. }
130. interface IListCounter: IList, ICounter {}
131. class C
132. {
133. void Test(IListCounter x)
134. {
135. x.Count(1); // Error
136. x.Count = 1; // Error
137. ((IList)x).Count = 1; // Ok, invokes IList.Count.set
138. ((ICounter)x).Count(1); // Ok, invokes ICounter.Count
139. }
140. }
141. Write one code example for compile time binding and one for run time binding? What is early/late binding?
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.
' Create a variable to hold a new object.
Dim FS As FileStream
' Assign a new object to the variable.
FS = New FileStream("C:\tmp.txt", FileMode.Open)
By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")
Thursday, March 25, 2010
ADO.NET
Name some of the top level objects which ADO consists?
1. Connection object is responsible for creating a connection to the database.
2. Record object represents data which is not from the database.
3. Parameter object represents a sql parameter
4. Stream object is responsible to represent data from a text page or web page.
What is the purpose of connection pooling in ADO.NET?
Connection pooling enables an application to use a connection from a pool of connections that do not need to be re-established for each use. Once a connection has been created and placed in a connection pool, an application can reuse that connection without performing the complete connection creation process.
If you have more than one lakh rows in database table,while printing that table in frontend performence will be degraded. for that what do you do to improve the performence?
Posted by: Goud.ranjith | Show/Hide Answer
increase the execution time out in web.config (or)increase the connection time out in connection string
Diff Data Grid and Repeater
Datagrid is
* one which has advanced features and lets you do lot many things like paging and sorting your data without much effort.
* DataGrid can hold text data, but not linked or embedded objects.
Whereas a DataRepeater is
* which does not have the paging feature but we can do it by coding.
* one which can hold other controls and can embed objects.
* It can embed a Datagrid within it but not viceversa.
Apart from this a Data Repeater
--is used in places where you need more control over the rendering of your data
-- have very flexible templates that give you total control over the formatting of your data
Can you edit data in the Repeater control?
No, it just reads the information from its data source
Which ADO.NET object is very fast in getting data from database?
SqlDataReader object. (Note: Even datasets also use SqlDataReader objects internally for retriving data from database.)
Can you edit data in Repeater control?
No, it is readonly and forward only control so we can't edit data in repeater control.
1. Connection object is responsible for creating a connection to the database.
2. Record object represents data which is not from the database.
3. Parameter object represents a sql parameter
4. Stream object is responsible to represent data from a text page or web page.
What is the purpose of connection pooling in ADO.NET?
Connection pooling enables an application to use a connection from a pool of connections that do not need to be re-established for each use. Once a connection has been created and placed in a connection pool, an application can reuse that connection without performing the complete connection creation process.
If you have more than one lakh rows in database table,while printing that table in frontend performence will be degraded. for that what do you do to improve the performence?
Posted by: Goud.ranjith | Show/Hide Answer
increase the execution time out in web.config (or)increase the connection time out in connection string
Diff Data Grid and Repeater
Datagrid is
* one which has advanced features and lets you do lot many things like paging and sorting your data without much effort.
* DataGrid can hold text data, but not linked or embedded objects.
Whereas a DataRepeater is
* which does not have the paging feature but we can do it by coding.
* one which can hold other controls and can embed objects.
* It can embed a Datagrid within it but not viceversa.
Apart from this a Data Repeater
--is used in places where you need more control over the rendering of your data
-- have very flexible templates that give you total control over the formatting of your data
Can you edit data in the Repeater control?
No, it just reads the information from its data source
Which ADO.NET object is very fast in getting data from database?
SqlDataReader object. (Note: Even datasets also use SqlDataReader objects internally for retriving data from database.)
Can you edit data in Repeater control?
No, it is readonly and forward only control so we can't edit data in repeater control.
Wednesday, March 24, 2010
Tuesday, March 23, 2010
Serializing, Consuming, and Binding Generics in .NET 2.0
Introduction:
Serializing, Consuming, and Binding Generics in .NET 2.0
Generics are a powerful new feature in .NET 2.0, but it's not so obvious how to use them as return values from Web services, or how to bind them to controls. Find out how to serialize, data bind, and consume generic collections in ASP.NET 2.0
Generics, a new feature introduced with .NET 2.0, provides type safety at compile time. Generics let you create data structures without committing to a specific data types in your code at design time. At compile time, the compiler ensures that the types used with the data structure are consistent with type safety. In other words, generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, their implementation is very different.
This article discusses the application of generics in .NET development and different ways in which you can leverage generic types and collections within a .NET application.
What are Generics?
Generics are code templates generalized to use the same code repeatedly with different data types without needing to rewrite any of the internal code, and thus increasing the reusability of your software components. Within the data structure, member or argument usage adapts to different data types. Generics let you avoid those all-too-common, messy, and resource-intensive conversions from reference types to native types, creating routines that are much more type-safe.
You define a generic using a slightly different notation than you're used to with non-generic types. For example, here's the basic code for a generic class named Compare that can compare two items of the same type and return the larger or smaller value, depending on which method is invoked:
public class Compare
{
public ItemType ReturnLarger
(ItemType data, ItemType data2)
{
//logic...
}
public ItemType ReturnSmaller
(ItemType data, ItemType data2)
{
//logic...
}
}
You've probably written similar code, but you've also probably written it many times, once for each type you want to compare. In contrast, you can use this generic class with any data type, ranging from basic data types such as integers to complex classes and structures. When you use the generic, you identify what data type you're planning to use with it. For example, to compare Integers with the Compare generic class, you would write code similar to the following:
Compare compare = new
Compare;
int result = compare.ReturnLarger(3,5);
To serialize and deserialize a generic class, you just need to follow two steps.
* Create an instance of the XmlSerializer class and pass the type of the generic type to be serialized as an argument
* Invoke the Serialize() or Deserialize() method of the XmlSerializer class, passing in the object to be serialized or deserialized
using System;
using System.Collections;
using System.Xml.Serialization;
[XmlRoot("KeyValuePair")]
public class KeyValuePair
{
private KeyType _key;
private ValueType _value;
public KeyValuePair()
{}
public ValueType Value
{
get{return _value; }
set{_value = value;}
}
public KeyType Key
{
get{return _key; }
set{_key = value; }
}
}
The preceding code declares a class named KeyValuePair that accepts two runtime types; one for the key element and another one for the value element. As part of the class declaration, there is also an XmlRoot attribute that ensures the root element of the serialized XML document is named "KeyValuePair." The code defines two public properties named Value and Key that simply set or get values from the private variables _value and _key respectively. Keeping the KeyValuePair class definition in mind, Listing 1 discusses the code required to serialize or deserialize an instance of the KeyValuePair class using XML serialization.
Listing 1 contains two methods named Serialize() and Deserialize(). The Serialize() method starts by declaring a KeyValuePair object with the type parameters set to int and string respectively.
KeyValuePair keyVal = new
KeyValuePair();
Then the code invokes the Key and Value properties of the KeyValuePair object to set the values appropriately.
keyVal.Key = 1;
keyVal.Value = "Production";
After doing that, you supply the KeyValuePair object as a parameter to the constructor of the XmlSerializer object, indicating the typed parameters.
XmlSerializer serializer = new
XmlSerializer(typeof
(KeyValuePair));
That's all there is to serializing a generic type. The rest of the code in Listing 1 is similar to the code examples shown earlier. The Deserialize() method works along the same lines, passing in typed parameters to the constructor of the XmlSerializer and then finally invoking the XmlSerializer.Deserialize() method to deserialize the XML data into an instance of the KeyValuePair object. If you browse to the page using the browser, you will see buttons for invoking the Serialize() and Deserialize() methods. Clicking the "Serialize" button causes the server to create an XML file named KeyValuePair.xml file created in the C:\Data directory containing the XML for the serialized KeyValuePair object. Here's how that file looks.
Production
1
Implementing Data-binding with Generic Collections
In this section, you will see how to return generic collections from a middle tier object and bind them directly to the ObjectDataSource control. The ObjectDataSource control is then bound to a GridView control so that you can display the values returned through the generic collection in the GridView.
First, create a class named Category that acts as the placeholder for capturing attributes related to a Category. The code for the Category class is as follows:
using System;
public class Category
{
private string _categoryID;
private string _name;
public string CategoryID
{
get{return _categoryID;}
set{_categoryID = value;}
}
public string Name
{
get{return _name; }
set{_name = value; }
}
}
As you can see, the implementation of the Category class is very simple and straightforward. It just has two properties, named CategoryID and Name. Next, here's a data access layer class named CategoryDB that leverages the Category class.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
public class CategoryDB
{
public CategoryDB()
{}
public IList
GetCategories()
{
IList categoryColl = new
List();
string connString =
WebConfigurationManager.
ConnectionStrings
["adventureWorks"].
ConnectionString;
using (SqlConnection sqlConn = new
SqlConnection(connString))
{
sqlConn.Open();
SqlCommand sqlCmd =
sqlConn.CreateCommand();
sqlCmd.CommandText = "Select "
"ProductCategoryID, Name from "
+"Production.ProductCategory";
//Create the SqlDataReader object
using (SqlDataReader reader =
sqlCmd.ExecuteReader())
{
while (reader.Read())
{
Category cate = new
Category();
cate.CategoryID =
reader["ProductCategoryID"].
ToString();
cate.Name =
reader["Name"].ToString();
categoryColl.Add(cate);
}
}
}
return categoryColl;
}
}
The CategoryDB class code begins by declaring an object of type IList generic collection and assigning that to the generic collection of type List. Then it opens the connection to the database, executes the query and retrieves the results in a SqlDataReader object. It then loops through the returned rows retrieving values and assigning them to a new Category object, one for each row, adding each Category object to the previously declared generic collection. After adding all the rows to the collection, it returns the collection object to the caller.
For the code to work, you need to define the connection string in the web.config as shown below:
At this point, the CategoryDB object is ready for consumption; the next step is to create a page that leverages the CategoryDB.GetCategories() method. The following code defines an ASP.NET page that data-binds the output of the GetCategories() method to a GridView control.
<%@ Page Language="C#" %>
Implementing Data Binding with
Generics
Note that the page contains an ObjectDataSource control named categoriesSource with its TypeName and SelectMethod attributes set to CategoryDB and GetCategories respectively. The page binds a GridView named gridCategories to the ObjectDataSource through its DataSourceID attribute. Loading the page in a browser results in the output shown in
Returning a Generic Collection from a Web Service
So far, you have seen how to perform data binding with a generic collection returned by the data access layer object. This section discusses how to return generic collections from a Web service, which has the advantage of letting client applications bind directly to the output returned by the Web service method.
The following code shows how to return a generic collection from a Web service. It leverages the CategoryDB class you've already seen to retrieve data from the AdventureWorks database.
<%@ WebService Language="C#" Class="CategoryService" %>
using System;
using System.Web.Services;
using System.Collections.Generic;
[WebService(Namespace =
"http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
public class CategoryService :
System.Web.Services.WebService {
[WebMethod]
public List GetCategories()
{
CategoryDB category = new
CategoryDB();
return (List)
category.GetCategories();
}
}
Figure 2. CategoryService Output: The figure shows the XML for the generic collection object returned by the CategoryService Web service. Note that the Web service returns the collection as an array of Category objects.
In the preceding code, the GetCategories() method simply invokes the GetCategories() method of the CategoryDB class and returns the result to the Web service consumer.
Now, if you browse to the Web service using the browser and follow the on-screen directions to invoke the GetCategories() method, you'll see the output shown in Figure 2.
As you can see from the above figure, the .NET framework serializes the generic collection as an array of Category objects when invoked from the browser. You can then easily bind this array of Category objects to data bound controls in the client application.
Keep It Short
As you can see, the ability to leverage generics as the middle tier return type opens up a whole avenue of new and interesting opportunities to work with data in the user interface layer. Using the techniques shown here, you can now easily serialize, deserialize, and databind generic types and collections. In addition, you can also return generic types from your Web service that can then be seamlessly consumed by client applications.
link
http://www.devx.com/dotnet/Article/30158/0/page/1
Serializing, Consuming, and Binding Generics in .NET 2.0
Generics are a powerful new feature in .NET 2.0, but it's not so obvious how to use them as return values from Web services, or how to bind them to controls. Find out how to serialize, data bind, and consume generic collections in ASP.NET 2.0
Generics, a new feature introduced with .NET 2.0, provides type safety at compile time. Generics let you create data structures without committing to a specific data types in your code at design time. At compile time, the compiler ensures that the types used with the data structure are consistent with type safety. In other words, generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, their implementation is very different.
This article discusses the application of generics in .NET development and different ways in which you can leverage generic types and collections within a .NET application.
What are Generics?
Generics are code templates generalized to use the same code repeatedly with different data types without needing to rewrite any of the internal code, and thus increasing the reusability of your software components. Within the data structure, member or argument usage adapts to different data types. Generics let you avoid those all-too-common, messy, and resource-intensive conversions from reference types to native types, creating routines that are much more type-safe.
You define a generic using a slightly different notation than you're used to with non-generic types. For example, here's the basic code for a generic class named Compare that can compare two items of the same type and return the larger or smaller value, depending on which method is invoked:
public class Compare
{
public ItemType ReturnLarger
(ItemType data, ItemType data2)
{
//logic...
}
public ItemType ReturnSmaller
(ItemType data, ItemType data2)
{
//logic...
}
}
You've probably written similar code, but you've also probably written it many times, once for each type you want to compare. In contrast, you can use this generic class with any data type, ranging from basic data types such as integers to complex classes and structures. When you use the generic, you identify what data type you're planning to use with it. For example, to compare Integers with the Compare generic class, you would write code similar to the following:
Compare
Compare
int result = compare.ReturnLarger(3,5);
To serialize and deserialize a generic class, you just need to follow two steps.
* Create an instance of the XmlSerializer class and pass the type of the generic type to be serialized as an argument
* Invoke the Serialize() or Deserialize() method of the XmlSerializer class, passing in the object to be serialized or deserialized
using System;
using System.Collections;
using System.Xml.Serialization;
[XmlRoot("KeyValuePair")]
public class KeyValuePair
{
private KeyType _key;
private ValueType _value;
public KeyValuePair()
{}
public ValueType Value
{
get{return _value; }
set{_value = value;}
}
public KeyType Key
{
get{return _key; }
set{_key = value; }
}
}
The preceding code declares a class named KeyValuePair that accepts two runtime types; one for the key element and another one for the value element. As part of the class declaration, there is also an XmlRoot attribute that ensures the root element of the serialized XML document is named "KeyValuePair." The code defines two public properties named Value and Key that simply set or get values from the private variables _value and _key respectively. Keeping the KeyValuePair class definition in mind, Listing 1 discusses the code required to serialize or deserialize an instance of the KeyValuePair class using XML serialization.
Listing 1 contains two methods named Serialize() and Deserialize(). The Serialize() method starts by declaring a KeyValuePair object with the type parameters set to int and string respectively.
KeyValuePair
KeyValuePair
Then the code invokes the Key and Value properties of the KeyValuePair object to set the values appropriately.
keyVal.Key = 1;
keyVal.Value = "Production";
After doing that, you supply the KeyValuePair object as a parameter to the constructor of the XmlSerializer object, indicating the typed parameters.
XmlSerializer serializer = new
XmlSerializer(typeof
(KeyValuePair
That's all there is to serializing a generic type. The rest of the code in Listing 1 is similar to the code examples shown earlier. The Deserialize() method works along the same lines, passing in typed parameters to the constructor of the XmlSerializer and then finally invoking the XmlSerializer.Deserialize() method to deserialize the XML data into an instance of the KeyValuePair object. If you browse to the page using the browser, you will see buttons for invoking the Serialize() and Deserialize() methods. Clicking the "Serialize" button causes the server to create an XML file named KeyValuePair.xml file created in the C:\Data directory containing the XML for the serialized KeyValuePair object. Here's how that file looks.
Implementing Data-binding with Generic Collections
In this section, you will see how to return generic collections from a middle tier object and bind them directly to the ObjectDataSource control. The ObjectDataSource control is then bound to a GridView control so that you can display the values returned through the generic collection in the GridView.
First, create a class named Category that acts as the placeholder for capturing attributes related to a Category. The code for the Category class is as follows:
using System;
public class Category
{
private string _categoryID;
private string _name;
public string CategoryID
{
get{return _categoryID;}
set{_categoryID = value;}
}
public string Name
{
get{return _name; }
set{_name = value; }
}
}
As you can see, the implementation of the Category class is very simple and straightforward. It just has two properties, named CategoryID and Name. Next, here's a data access layer class named CategoryDB that leverages the Category class.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;
public class CategoryDB
{
public CategoryDB()
{}
public IList
GetCategories()
{
IList
List
string connString =
WebConfigurationManager.
ConnectionStrings
["adventureWorks"].
ConnectionString;
using (SqlConnection sqlConn = new
SqlConnection(connString))
{
sqlConn.Open();
SqlCommand sqlCmd =
sqlConn.CreateCommand();
sqlCmd.CommandText = "Select "
"ProductCategoryID, Name from "
+"Production.ProductCategory";
//Create the SqlDataReader object
using (SqlDataReader reader =
sqlCmd.ExecuteReader())
{
while (reader.Read())
{
Category cate = new
Category();
cate.CategoryID =
reader["ProductCategoryID"].
ToString();
cate.Name =
reader["Name"].ToString();
categoryColl.Add(cate);
}
}
}
return categoryColl;
}
}
The CategoryDB class code begins by declaring an object of type IList generic collection and assigning that to the generic collection of type List. Then it opens the connection to the database, executes the query and retrieves the results in a SqlDataReader object. It then loops through the returned rows retrieving values and assigning them to a new Category object, one for each row, adding each Category object to the previously declared generic collection. After adding all the rows to the collection, it returns the collection object to the caller.
For the code to work, you need to define the connection string in the web.config as shown below:
At this point, the CategoryDB object is ready for consumption; the next step is to create a page that leverages the CategoryDB.GetCategories() method. The following code defines an ASP.NET page that data-binds the output of the GetCategories() method to a GridView control.
<%@ Page Language="C#" %>
Generics
Note that the page contains an ObjectDataSource control named categoriesSource with its TypeName and SelectMethod attributes set to CategoryDB and GetCategories respectively. The page binds a GridView named gridCategories to the ObjectDataSource through its DataSourceID attribute. Loading the page in a browser results in the output shown in
Returning a Generic Collection from a Web Service
So far, you have seen how to perform data binding with a generic collection returned by the data access layer object. This section discusses how to return generic collections from a Web service, which has the advantage of letting client applications bind directly to the output returned by the Web service method.
The following code shows how to return a generic collection from a Web service. It leverages the CategoryDB class you've already seen to retrieve data from the AdventureWorks database.
<%@ WebService Language="C#" Class="CategoryService" %>
using System;
using System.Web.Services;
using System.Collections.Generic;
[WebService(Namespace =
"http://tempuri.org/")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
public class CategoryService :
System.Web.Services.WebService {
[WebMethod]
public List
{
CategoryDB category = new
CategoryDB();
return (List
category.GetCategories();
}
}
Figure 2. CategoryService Output: The figure shows the XML for the generic collection object returned by the CategoryService Web service. Note that the Web service returns the collection as an array of Category objects.
In the preceding code, the GetCategories() method simply invokes the GetCategories() method of the CategoryDB class and returns the result to the Web service consumer.
Now, if you browse to the Web service using the browser and follow the on-screen directions to invoke the GetCategories() method, you'll see the output shown in Figure 2.
As you can see from the above figure, the .NET framework serializes the generic collection as an array of Category objects when invoked from the browser. You can then easily bind this array of Category objects to data bound controls in the client application.
Keep It Short
As you can see, the ability to leverage generics as the middle tier return type opens up a whole avenue of new and interesting opportunities to work with data in the user interface layer. Using the techniques shown here, you can now easily serialize, deserialize, and databind generic types and collections. In addition, you can also return generic types from your Web service that can then be seamlessly consumed by client applications.
link
http://www.devx.com/dotnet/Article/30158/0/page/1
Monday, March 22, 2010
Why is the Generic List Faster Than the ArrayList?
Why is the Generic List Faster Than the ArrayList?
There are two reasons:
* The TypeSafe array stores the items in itself rather than pointers to boxed objects
* In a 64 bit OS (like mine), a pointer happens to be 64 bits rather than the 32 bits integer
I won't really expand on this, the things I will remember are:
* Generics are typesafe and fast, there is no need for ArrayList
* Don't use ArrayList on structures or value types (Integers, Float...)
Apart from that, the Insertion of 100,000 items still takes 4 seconds, this is not glorious.
How Could We Make This Faster
It really depends on what you need; you will hardly find a single Collection which will be faster than all others on all the test.
If you use your list to mainly add at the end and access by Index, the List(of Integer) is probably a good choice.
On the contrary, if you require random insertion and can avoid accessing items by index then perhaps a LinkedList(Of Integer) is the way to go.
However, if you need...
* Quick insertion at any position
* Being able to access item by index
* Large lists
There are two reasons:
* The TypeSafe array stores the items in itself rather than pointers to boxed objects
* In a 64 bit OS (like mine), a pointer happens to be 64 bits rather than the 32 bits integer
I won't really expand on this, the things I will remember are:
* Generics are typesafe and fast, there is no need for ArrayList
* Don't use ArrayList on structures or value types (Integers, Float...)
Apart from that, the Insertion of 100,000 items still takes 4 seconds, this is not glorious.
How Could We Make This Faster
It really depends on what you need; you will hardly find a single Collection which will be faster than all others on all the test.
If you use your list to mainly add at the end and access by Index, the List(of Integer) is probably a good choice.
On the contrary, if you require random insertion and can avoid accessing items by index then perhaps a LinkedList(Of Integer) is the way to go.
However, if you need...
* Quick insertion at any position
* Being able to access item by index
* Large lists
ObjectSerializationInXML
Imports System
Imports System.Windows.Forms
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Namespace ObjectSerializationInXML
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim emp As New Employee()
emp.ID = 101
emp.Name = "Steve"
emp.Salary = 6000
Dim tw As TextWriter = New StreamWriter("employee.xml")
Dim xs As New XmlSerializer(GetType(Employee))
xs.Serialize(tw, emp)
tw.Close()
webBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory & "//employee.xml")
End Sub
Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fs As New FileStream("employee.xml", FileMode.Open)
Dim newXs As New XmlSerializer(GetType(Employee))
Dim emp1 As Employee = DirectCast(newXs.Deserialize(fs), Employee)
If emp1 IsNot Nothing Then
listBox1.Items.Add(emp1.ID)
listBox1.Items.Add(emp1.Name)
listBox1.Items.Add(emp1.Salary)
End If
fs.Close()
End Sub
End Class
_
Public Class Employee
Private empID As Integer
Private empName As String
Private empSalary As [Decimal]
_
Public Property ID() As Integer
Get
Return empID
End Get
Set(ByVal value As Integer)
empID = value
End Set
End Property
_
Public Property Name() As String
Get
Return empName
End Get
Set(ByVal value As String)
empName = value
End Set
End Property
_
Public Property Salary() As Decimal
Get
Return empSalary
End Get
Set(ByVal value As Decimal)
empSalary = value
End Set
End Property
End Class
End Namespace
Imports System.Windows.Forms
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Namespace ObjectSerializationInXML
Public Partial Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim emp As New Employee()
emp.ID = 101
emp.Name = "Steve"
emp.Salary = 6000
Dim tw As TextWriter = New StreamWriter("employee.xml")
Dim xs As New XmlSerializer(GetType(Employee))
xs.Serialize(tw, emp)
tw.Close()
webBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory & "//employee.xml")
End Sub
Private Sub button2_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim fs As New FileStream("employee.xml", FileMode.Open)
Dim newXs As New XmlSerializer(GetType(Employee))
Dim emp1 As Employee = DirectCast(newXs.Deserialize(fs), Employee)
If emp1 IsNot Nothing Then
listBox1.Items.Add(emp1.ID)
listBox1.Items.Add(emp1.Name)
listBox1.Items.Add(emp1.Salary)
End If
fs.Close()
End Sub
End Class
Public Class Employee
Private empID As Integer
Private empName As String
Private empSalary As [Decimal]
Public Property ID() As Integer
Get
Return empID
End Get
Set(ByVal value As Integer)
empID = value
End Set
End Property
Public Property Name() As String
Get
Return empName
End Get
Set(ByVal value As String)
empName = value
End Set
End Property
Public Property Salary() As Decimal
Get
Return empSalary
End Get
Set(ByVal value As Decimal)
empSalary = value
End Set
End Property
End Class
End Namespace
how to call from one exe to antoher exe using appdomains
Dim SecondAppDomaing As AppDomain = AppDomain.CreateDomain("Second AppDomain")
SecondAppDomaing.ExecuteAssembly(path("as string"))
SecondAppDomaing.ExecuteAssembly(path("as string"))
XML Serialize with multiple classes inherited in a class to serialize
Public Class REPORT_CONFIG
Public Property EXCHANGE() As Object
Get
EXCHANGE = mvarEXCHANGE
End Get
Set(ByVal Value As Object)
mvarEXCHANGE = Value
End Set
End Property
Public Property STATUS() As Object
Get
STATUS = mvarSTATUS
End Get
Set(ByVal Value As Object)
mvarSTATUS = Value
End Set
End Property
end class
here exchange is one class and status is another class.These two classes available in report_Config class as objects,so we have to use xml include
XML SERIALIZATION
Try
Dim oSerialiser As New XmlSerializer(GetType(REPORT_CONFIG))
Dim oStream As Stream = New FileStream("C:\REPORT_CFG_OBJ12.xml", FileMode.Create)
oSerialiser.Serialize(oStream, m_uiREPORT_CONFIG)
oStream.Close()
Catch caught As Exception
MessageBox.Show(caught.Source)
End Try
DESERIALIZATION:
Dim fs As New FileStream("C:\REPORT_CFG_OBJ12.xml", FileMode.Open)
Dim newXs As New XmlSerializer(GetType(CEMDAS.REPORT_CONFIG))
Dim OBJ_REPORT_CFG As CEMDAS.REPORT_CONFIG = DirectCast(newXs.Deserialize(fs), CEMDAS.REPORT_CONFIG)
fs.Close()
LINQ to SQL: .NET Language-Integrated Query for Relational Data
LINQ to SQL: .NET Language-Integrated Query for Relational Data
Dinesh Kulkarni, Luca Bolognese, Matt Warren, Anders Hejlsberg, Kit George
March 2007
Applies to:
Visual Studio Code Name "Orcas"
.Net Framework 3.5
Summary: LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically. (119 printed pages)
Contents
Introduction
A Quick Tour
Creating Entity Classes
The DataContext
Defining Relationships
Querying Across Relationships
Modifying and Saving Entities
Queries In-Depth
Query Execution
Object Identity
Relationships
Joins
Projections
Compiled Queries
SQL Translation
The Entity Lifecycle
Tracking Changes
Submitting Changes
Simultaneous Changes
Transactions
Stored Procedures
Entity Classes In-Depth
Using Attributes
Graph Consistency
Change Notifications
Inheritance
Advanced Topics
Creating Databases
Interoperating with ADO.NET
Change Conflict Resolution
Stored Procedures Invocation
The Entity Class Generator Tool
Generator Tool DBML Reference
Multi-tier Entities
External Mapping
NET Framework Function Support and Notes
Debugging Support
Introduction
Most programs written today manipulate data in one way or another and often this data is stored in a relational database. Yet there is a huge divide between modern programming languages and databases in how they represent and manipulate information. This impedance mismatch is visible in multiple ways. Most notable is that programming languages access information in databases through APIs that require queries to be specified as text strings. These queries are significant portions of the program logic. Yet they are opaque to the language, unable to benefit from compile-time verification and design-time features like IntelliSense.
Of course, the differences go far deeper than that. How information is represented—the data model—is quite different between the two. Modern programming languages define information in the form of objects. Relational databases use rows. Objects have unique identity as each instance is physically different from another. Rows are identified by primary key values. Objects have references that identify and link instances together. Rows are left intentionally distinct requiring related rows to be tied together loosely using foreign keys. Objects stand alone, existing as long as they are still referenced by another object. Rows exist as elements of tables, vanishing as soon as they are removed.
It is no wonder that applications expected to bridge this gap are difficult to build and maintain. It would certainly simplify the equation to get rid of one side or the other. Yet relational databases provide critical infrastructure for long-term storage and query processing, and modern programming languages are indispensable for agile development and rich computation.
Until now, it has been the job of the application developer to resolve this mismatch in each application separately. The best solutions so far have been elaborate database abstraction layers that ferry the information between the applications domain-specific object models and the tabular representation of the database, reshaping and reformatting the data each way. Yet by obscuring the true data source, these solutions end up throwing away the most compelling feature of relational databases; the ability for the data to be queried.
LINQ to SQL, a component of Visual Studio Code Name "Orcas", provides a run-time infrastructure for managing relational data as objects without losing the ability to query. It does this by translating language-integrated queries into SQL for execution by the database, and then translating the tabular results back into objects you define. Your application is then free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.
* LINQ to SQL is designed to be non-intrusive to your application.
o It is possible to migrate current ADO.NET solutions to LINQ to SQL in a piecemeal fashion (sharing the same connections and transactions) since LINQ to SQL is simply another component in the ADO.NET family. LINQ to SQL also has extensive support for stored procedures, allowing reuse of the existing enterprise assets.
* LINQ to SQL applications are easy to get started.
o Objects linked to relational data can be defined just like normal objects, only decorated with attributes to identify how properties correspond to columns. Of course, it is not even necessary to do this by hand. A design-time tool is provided to automate translating pre-existing relational database schemas into object definitions for you.
Together, the LINQ to SQL run-time infrastructure and design-time tools significantly reduce the workload for the database application developer. The following chapters provide an overview of how LINQ to SQL can be used to perform common database-related tasks. It is assumed that the reader is familiar with Language-Integrated Query and the standard query operators.
LINQ to SQL is language-agnostic. Any language built to provide Language-Integrated Query can use it to enable access to information stored in relational databases. The samples in this document are shown in both C# and Visual Basic; LINQ to SQL can be used with the LINQ-enabled version of the Visual Basic compiler as well.
A Quick Tour
The first step in building a LINQ to SQL application is declaring the object classes you will use to represent your application data. Let's walk through an example.
Creating Entity Classes
We will start with a simple class Customer and associate it with the customers table in the Northwind sample database. To do this, we need only apply a custom attribute to the top of the class declaration. LINQ to SQL defines the Table attribute for this purpose.
C#
[Table(Name="Customers")]
public class Customer
{
public string CustomerID;
public string City;
}
Visual Basic
_
Public Class Customer
Public CustomerID As String
Public City As String
End Class
The Table attribute has a Name property that you can use to specify the exact name of the database table. If no Name property is supplied, LINQ to SQL will assume the database table has the same name as the class. Only instances of classes declared as tables will be stored in the database. Instances of these types of classes are known as entities. The classes themselves are known as entity classes.
In addition to associating classes to tables you will need to denote each field or property you intend to associate with a database column. For this, LINQ to SQL defines the Column attribute.
C#
[Table(Name="Customers")]
public class Customer
{
[Column(IsPrimaryKey=true)]
public string CustomerID;
[Column]
public string City;
}
Visual Basic
_
Public Class Customer
Dinesh Kulkarni, Luca Bolognese, Matt Warren, Anders Hejlsberg, Kit George
March 2007
Applies to:
Visual Studio Code Name "Orcas"
.Net Framework 3.5
Summary: LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically. (119 printed pages)
Contents
Introduction
A Quick Tour
Creating Entity Classes
The DataContext
Defining Relationships
Querying Across Relationships
Modifying and Saving Entities
Queries In-Depth
Query Execution
Object Identity
Relationships
Joins
Projections
Compiled Queries
SQL Translation
The Entity Lifecycle
Tracking Changes
Submitting Changes
Simultaneous Changes
Transactions
Stored Procedures
Entity Classes In-Depth
Using Attributes
Graph Consistency
Change Notifications
Inheritance
Advanced Topics
Creating Databases
Interoperating with ADO.NET
Change Conflict Resolution
Stored Procedures Invocation
The Entity Class Generator Tool
Generator Tool DBML Reference
Multi-tier Entities
External Mapping
NET Framework Function Support and Notes
Debugging Support
Introduction
Most programs written today manipulate data in one way or another and often this data is stored in a relational database. Yet there is a huge divide between modern programming languages and databases in how they represent and manipulate information. This impedance mismatch is visible in multiple ways. Most notable is that programming languages access information in databases through APIs that require queries to be specified as text strings. These queries are significant portions of the program logic. Yet they are opaque to the language, unable to benefit from compile-time verification and design-time features like IntelliSense.
Of course, the differences go far deeper than that. How information is represented—the data model—is quite different between the two. Modern programming languages define information in the form of objects. Relational databases use rows. Objects have unique identity as each instance is physically different from another. Rows are identified by primary key values. Objects have references that identify and link instances together. Rows are left intentionally distinct requiring related rows to be tied together loosely using foreign keys. Objects stand alone, existing as long as they are still referenced by another object. Rows exist as elements of tables, vanishing as soon as they are removed.
It is no wonder that applications expected to bridge this gap are difficult to build and maintain. It would certainly simplify the equation to get rid of one side or the other. Yet relational databases provide critical infrastructure for long-term storage and query processing, and modern programming languages are indispensable for agile development and rich computation.
Until now, it has been the job of the application developer to resolve this mismatch in each application separately. The best solutions so far have been elaborate database abstraction layers that ferry the information between the applications domain-specific object models and the tabular representation of the database, reshaping and reformatting the data each way. Yet by obscuring the true data source, these solutions end up throwing away the most compelling feature of relational databases; the ability for the data to be queried.
LINQ to SQL, a component of Visual Studio Code Name "Orcas", provides a run-time infrastructure for managing relational data as objects without losing the ability to query. It does this by translating language-integrated queries into SQL for execution by the database, and then translating the tabular results back into objects you define. Your application is then free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically.
* LINQ to SQL is designed to be non-intrusive to your application.
o It is possible to migrate current ADO.NET solutions to LINQ to SQL in a piecemeal fashion (sharing the same connections and transactions) since LINQ to SQL is simply another component in the ADO.NET family. LINQ to SQL also has extensive support for stored procedures, allowing reuse of the existing enterprise assets.
* LINQ to SQL applications are easy to get started.
o Objects linked to relational data can be defined just like normal objects, only decorated with attributes to identify how properties correspond to columns. Of course, it is not even necessary to do this by hand. A design-time tool is provided to automate translating pre-existing relational database schemas into object definitions for you.
Together, the LINQ to SQL run-time infrastructure and design-time tools significantly reduce the workload for the database application developer. The following chapters provide an overview of how LINQ to SQL can be used to perform common database-related tasks. It is assumed that the reader is familiar with Language-Integrated Query and the standard query operators.
LINQ to SQL is language-agnostic. Any language built to provide Language-Integrated Query can use it to enable access to information stored in relational databases. The samples in this document are shown in both C# and Visual Basic; LINQ to SQL can be used with the LINQ-enabled version of the Visual Basic compiler as well.
A Quick Tour
The first step in building a LINQ to SQL application is declaring the object classes you will use to represent your application data. Let's walk through an example.
Creating Entity Classes
We will start with a simple class Customer and associate it with the customers table in the Northwind sample database. To do this, we need only apply a custom attribute to the top of the class declaration. LINQ to SQL defines the Table attribute for this purpose.
C#
[Table(Name="Customers")]
public class Customer
{
public string CustomerID;
public string City;
}
Visual Basic
ToString(..., Int32) any overload ending with an Int32 toBase
IsDBNull(Object)
GetTypeCode(Object)
ChangeType(...)
* Versions with the IFormatProvider parameter.
* Methods that involve an array (To/FromBase64CharArray, To/FromBase64String).
System.TimeSpan
Implemented
* Constructors:
TimeSpan(Long)
TimeSpan (year, month, day)
TimeSpan (year, month, day, hour, minutes, seconds)
TimeSpan (year, month, day, hour, minutes, seconds, milliseconds)
* Operators:
Comparison operators: <,==, and so on in C#; <, =, and so on in Visual Basic
+, -
* Static (Shared in Visual Basic) methods:
Compare(t1,t2)
* Non-static (Instance) methods / properties:
Ticks, Milliseconds, Seconds, Hours, Days
TotalMilliseconds, TotalSeconds, TotalMinutes, TotalHours, TotalDays,
Equals, CompareTo(TimeSpan)
Add(TimeSpan), Subtract(TimeSpan)
Duration() [= ABS], Negate()
Not implemented
ToString()
TimeSpan FromDay(Double), FromHours, all From Variants
TimeSpan Parse(String)
System.DateTime
Implemented
* Constructors:
DateTime(year, month, day)
DateTime(year, month, day, hour, minutes, seconds)
DateTime(year, month, day, hour, minutes, seconds, milliseconds)
* Operators:
Comparisons
DateTime – DateTime (gives TimeSpan)
DateTime + TimeSpan (gives DateTime)
DateTime – TimeSpan (gives DateTime)
* Static (Shared) methods:
Add(TimeSpan), AddTicks(Long),
AddDays/Hours/Milliseconds/Minutes (Double)
AddMonths/Years(Int32)
Equals
* Non-static (Instance) methods / properties:
Day, Month, Year, Hour, Minute, Second, Millisecond, DayOfWeek
CompareTo(DateTime)
TimeOfDay()
Equals
ToString()
Difference from .NET
SQL's datetime values are rounded to .000, .003 or .007 seconds, so it is less precise than those of .NET.
The range of SQL's datetime starts at January 1st, 1753.
SQL does not have a built-in type for TimeSpan. It uses different DATEDIFF methods that return 32-bit integers. One is DATEDIFF(DAY,...), which gives the number of days; another is DATEDIFF(MILLISECOND,...), which gives the number of milliseconds. An error results if the DateTimes are more than 24 days apart. In contrast, .NET uses 64-bit integers and measures TimeSpans in ticks.
To get as close as possible to the .NET semantics in SQL, LINQ to SQL translates TimeSpans into 64-bit integers and uses the two DATEDIFF methods mentioned above to calculate the number of ticks between two dates.
DateTime UtcNow is evaluated on the client when the query is translated (like any expression that does not involve database data).
Not implemented
IsDaylightSavingTime()
IsLeapYear(Int32)
DaysInMonth(Int32, Int32)
ToBinary()
ToFileTime()
ToFileTimeUtc()
ToLongDateString()
ToLongTimeString()
ToOADate()
ToShortDateString()
ToShortTimeString()
ToUniversalTime()
FromBinary(Long), FileTime, FileTimeUtc, OADate
GetDateTimeFormats(...)
constructor DateTime(Long)
Parse(String)
DayOfYear
Debugging Support
DataContext provides methods and properties to obtain the SQL generated for queries and change processing. These methods can be useful for understanding LINQ to SQL functionality and for debugging specific problems.
DataContext Methods to Get Generated SQL
Member Purpose
Log Prints SQL before it is executed. Covers query, insert, update, delete commands. Usage:
C#
db.Log = Console.Out;
Visual Basic
db.Log = Console.Out
GetQueryText(query) Returns the query text of the query without of executing it. Usage:
C#
Console.WriteLine(db.GetQueryText(db.Customers));
Visual Basic
Console.WriteLine(db.GetQueryTest(db.Customers))
GetChangeText() Returns the text of SQL commands for insert/update/delete without executing them. Usage:
C#
Console.WriteLine(db.GetChangeText());
Visual Basic
Console.WriteLine(db.GetChangeText())
Subscribe to:
Posts (Atom)
Followers
Blog Archive
-
▼
2010
(56)
-
▼
March
(13)
- CEMDAS
- asp.net
- oops
- ADO.NET
- generics advantages and limatations
- Serializing, Consuming, and Binding Generics in .N...
- Why is the Generic List Faster Than the ArrayList?
- ObjectSerializationInXML
- how to call from one exe to antoher exe using appd...
- XML Serialize with multiple classes inherited in ...
- LINQ to SQL: .NET Language-Integrated Query for Re...
- SQL SERVER – Delete Duplicate Records
- Row_Number() function in SQL Server 2005
-
▼
March
(13)