Difference between Custom Controls and User Controls.
1.User Control is a page file with extension .ascx which can only be used withina single application. But custom controls are assemblies(dll files) that can be used in multiple applications.
2.User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in anaspx page u have to drag the user Control from the solution Explorer to designer page.But Custom Controls can be added to ToolBox of VS.NET.
3.User Controls can be viewed as a sort of generic controls during the design time.The proper GUI of user controls can be viewed only during the run time.But Custom Controls can be viewed during the design time.
4. User controls are created from existing Webserver and html server controls .But a developer who creates custom controls have to render every thing from the scratch.
Wednesday, June 23, 2010
Recommendations for Abstract Classes vs. Interfaces
Difference between Interface and abstract class :
The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.
Both interfaces and abstract classes are useful for component interaction. If a method requires an interface as an argument, then any object that implements that interface can be used in the argument.
This method could accept any object that implemented IWidget as the widget argument, even though the implementations of IWidget might be quite different. Abstract classes also allow for this kind of polymorphism, but with a few caveats:
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
The choice of whether to design your functionality as an interface or an abstract class (a MustInherit class in Visual Basic) can sometimes be a difficult one. An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may be fully implemented, but is more usually partially implemented or not implemented at all, thereby encapsulating common functionality for inherited classes. For details, see Abstract Classes.
An interface, by contrast, is a totally abstract set of members that can be thought of as defining a contract for conduct. The implementation of an interface is left completely to the developer.
Both interfaces and abstract classes are useful for component interaction. If a method requires an interface as an argument, then any object that implements that interface can be used in the argument.
This method could accept any object that implemented IWidget as the widget argument, even though the implementations of IWidget might be quite different. Abstract classes also allow for this kind of polymorphism, but with a few caveats:
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Wednesday, May 19, 2010
WCF related interview Questions
ONLY WCF related Question:
Debugging:
What tools are used for the debugging WCF?
Is it possible to log the messages on the service side? On the client side? How to switch on the logging?
What the difference between the service messages and transport messages?
What the difference between the SoapUi utility and the VS2008 test functionality used for the Web-service testing?
Describe how to use the LoadGen to test WS. What kind of tests?
Configuration files:
Enumerate the high level elements of the section.
What is the name attribute of the element?
What is the contract attribute of the element?
What is the difference in the attributes the binging and the bindingConfiguration of the element?
What is the difference in the attributes the binging and the bindingName of the element?
Are the addresses, the bindings, the contracts unique between services?
How are dependent the app.config and the machine.config files?
Enumerate the high level of the and element.
Service contracts:
Enumerate three message exchange patterns in the WCF model.
If the service operation returns void, what is the message exchange pattern? Is the client waiting the operation to be completed in this case?
What the difference between the request-response pattern and the duplex pattern?
Is the server set up the client address or the client set it up in the duplex communication ? Server uses This address to sent the data back to the client.
Fault contracts:
In what order do we have to catch the exceptions: TimoutException, FaultException, FaultException, CommunicationException?
You are developing WS. Do you have to include the error(s)/success nodes into the response or to use the fault message to handle errors of the WS? What is the difference in these approuches?
WCF versions:
In what version of the .NET was the WCF introduced?
What was the main functionality set for the first version of the WCF?
What new WCF things were in the next versions of the .NET?
Sessions, Instancing, and Concurrency:
Why we need the sessions?
Where session stores the session information? What is the general store for the WCF session?
What is it a correlation? What parameters are mandatory for the correlation?
Who initiate the WCF session, service or a client?
What order are the delivered messages processed in during the session?
How can we create a singleton service?
Does the SessionMode.NotAllowed increase the performance?
What is it the Terminating and Initiating of the OperationContract? Could be the OperationContract Terminating and Initiating at the same time?
How does a client start a session?
Transports:
How to enable streaming?
What types of the operation contract parameters could be streamed?
Do we have to change the maxReceivedMessageSize parameter to use streaming?
What types of the quota have the WCF transports?
What is it the Teredo? How can we use it?
What is it the Net.TCP Port Sharing? How can we use it?
Queues and Reliable Sessions:
What types of reliable messaging are implemented in the WCF?
What is it the Reliable session?
Is the Reliable session asynchronous?
Is the Reliable session tied to the transport session?
Can the Reliable session be established with the one-way, or the request-reply, or with the duplex, or with all those exchange message patterns?
Do the system-provided bindings have the support for the Reliable session and what the binding options are enabled by default?
Reliable sessions in Windows Communication Foundation (WCF) use a transfer window. What is it the Transfer window? What does it means for the sender, for the receiver? How is it depend of the latency?
What is it the Transmission queue and the Target queue? What is the difference?
What is it the Dead-letter queue and the Poison queue? What is the difference?
Could the two-way service operations be used with queued binding?
Could the ExactlyOnce property of the netMsmqBinding be true if the queue is not transactional?
When is the MsmqIntegrationBinding or the NetMsmqBinding used?
Is there an error in the Msmq address the "net.msmq://MyHost/private$/MyQueue"?
Can we use the public queues without the Windows domain? If cannot then why?
Is the MsmqIntegrationBinding used the msmq.formatname scheme or the net.msmq scheme?
Hosting:
What hosting functionality is unique for the Vista OS?
Do we have to use the relative addresses when hosting in the IIS or the absolute addresses? Why?
Could the IIS-hosted WCF service make use of HTTP transport security if the IIS virtual derectory that contains the service does not support it?
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Debugging:
What tools are used for the debugging WCF?
Is it possible to log the messages on the service side? On the client side? How to switch on the logging?
What the difference between the service messages and transport messages?
What the difference between the SoapUi utility and the VS2008 test functionality used for the Web-service testing?
Describe how to use the LoadGen to test WS. What kind of tests?
Configuration files:
Enumerate the high level elements of the
What is the name attribute of the
What is the contract attribute of the
What is the difference in the attributes the binging and the bindingConfiguration of the
What is the difference in the attributes the binging and the bindingName of the
Are the addresses, the bindings, the contracts unique between services?
How are dependent the app.config and the machine.config files?
Enumerate the high level of the
Service contracts:
Enumerate three message exchange patterns in the WCF model.
If the service operation returns void, what is the message exchange pattern? Is the client waiting the operation to be completed in this case?
What the difference between the request-response pattern and the duplex pattern?
Is the server set up the client address or the client set it up in the duplex communication ? Server uses This address to sent the data back to the client.
Fault contracts:
In what order do we have to catch the exceptions: TimoutException, FaultException, FaultException
You are developing WS. Do you have to include the error(s)/success nodes into the response or to use the fault message to handle errors of the WS? What is the difference in these approuches?
WCF versions:
In what version of the .NET was the WCF introduced?
What was the main functionality set for the first version of the WCF?
What new WCF things were in the next versions of the .NET?
Sessions, Instancing, and Concurrency:
Why we need the sessions?
Where session stores the session information? What is the general store for the WCF session?
What is it a correlation? What parameters are mandatory for the correlation?
Who initiate the WCF session, service or a client?
What order are the delivered messages processed in during the session?
How can we create a singleton service?
Does the SessionMode.NotAllowed increase the performance?
What is it the Terminating and Initiating of the OperationContract? Could be the OperationContract Terminating and Initiating at the same time?
How does a client start a session?
Transports:
How to enable streaming?
What types of the operation contract parameters could be streamed?
Do we have to change the maxReceivedMessageSize parameter to use streaming?
What types of the quota have the WCF transports?
What is it the Teredo? How can we use it?
What is it the Net.TCP Port Sharing? How can we use it?
Queues and Reliable Sessions:
What types of reliable messaging are implemented in the WCF?
What is it the Reliable session?
Is the Reliable session asynchronous?
Is the Reliable session tied to the transport session?
Can the Reliable session be established with the one-way, or the request-reply, or with the duplex, or with all those exchange message patterns?
Do the system-provided bindings have the support for the Reliable session and what the binding options are enabled by default?
Reliable sessions in Windows Communication Foundation (WCF) use a transfer window. What is it the Transfer window? What does it means for the sender, for the receiver? How is it depend of the latency?
What is it the Transmission queue and the Target queue? What is the difference?
What is it the Dead-letter queue and the Poison queue? What is the difference?
Could the two-way service operations be used with queued binding?
Could the ExactlyOnce property of the netMsmqBinding be true if the queue is not transactional?
When is the MsmqIntegrationBinding or the NetMsmqBinding used?
Is there an error in the Msmq address the "net.msmq://MyHost/private$/MyQueue"?
Can we use the public queues without the Windows domain? If cannot then why?
Is the MsmqIntegrationBinding used the msmq.formatname scheme or the net.msmq scheme?
Hosting:
What hosting functionality is unique for the Vista OS?
Do we have to use the relative addresses when hosting in the IIS or the absolute addresses? Why?
Could the IIS-hosted WCF service make use of HTTP transport security if the IIS virtual derectory that contains the service does not support it?
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Monday, May 3, 2010
Sonata .NET interview Questions
Last week one of my friend attended SONATA Software .NET interview....
Here are the Questions:
1.what is a constructor ?
2.types constructor ?
3.how can we call parameterized constructor from Default constructor & Vice versa.. ?
4.Difference between Interface & Abstract class ?
5.What is WCF ?
6.Difference between WebService & WCF ?
7.Difference between viewstate & Session state ?
8.Difference between delete & truncate ?
9.Difference between virtual & abstract key words?
10.types of variables Private Protected Public
11.How can u swap 2 variables values without using temp variables
12.Types of binding(ploymorphism).
13.Difference between build & rebuild ?
14. Scenario in SQL SERVER :
Emp table with GRADE(A,B,C),SAL,EMPID
Write a single update statement
to add
for A grade 1000 bonus,B 3000, c 5000
u need to write a single statement to upadte the records based on the Grade
15.Difference between Array.Clone & Array.Copy
16.Can we Rollback Truncate ?
Ans :Yes: like this
Write truncate within transaction
Begin Tran
truncate table tablename
ROLLBACK
SONATA INTERVIEW QUESTIONS FOR EXPERIENCED
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Here are the Questions:
1.what is a constructor ?
2.types constructor ?
3.how can we call parameterized constructor from Default constructor & Vice versa.. ?
4.Difference between Interface & Abstract class ?
5.What is WCF ?
6.Difference between WebService & WCF ?
7.Difference between viewstate & Session state ?
8.Difference between delete & truncate ?
9.Difference between virtual & abstract key words?
10.types of variables Private Protected Public
11.How can u swap 2 variables values without using temp variables
12.Types of binding(ploymorphism).
13.Difference between build & rebuild ?
14. Scenario in SQL SERVER :
Emp table with GRADE(A,B,C),SAL,EMPID
Write a single update statement
to add
for A grade 1000 bonus,B 3000, c 5000
u need to write a single statement to upadte the records based on the Grade
15.Difference between Array.Clone & Array.Copy
16.Can we Rollback Truncate ?
Ans :Yes: like this
Write truncate within transaction
Begin Tran
truncate table tablename
ROLLBACK
SONATA INTERVIEW QUESTIONS FOR EXPERIENCED
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Sunday, March 21, 2010
Set the Cacheability of an ASP.NET Page declaratively
Set the Cacheability of an ASP.NET Page declaratively
The cacheability of a page or user control refers to whether or not a page can be cached on a device during its response life cycle. These devices include the client (browser) making the request, the Web server responding to the request, and any cache-capable devices, such as proxy servers, that are in the request or response stream.
If you know at design time what cacheability setting you need for a page, you can set cacheability declaratively. The page will then use the same cacheability settings for all requests.
To set a page's cacheability declaratively
1. Include an @ OutputCache directive in the page and define Duration and VaryByParam attributes.
2. Include a Location attribute in the @ OutputCache directive and define its value as one of the following values in the OutputCacheLocation enumeration: Any, Client, Downstream, Server, ServerAndClient, or None.
The following code shows how to set the page's cacheability to 60 seconds:
<%@ OutputCache Duration="60" VaryByParam="None"%>
Note
The default setting is Any. If you do not define a Location attribute, the page output can be cached on all cache-capable network devices that are involved in the response. These include the requesting client, the origin server, and any proxy servers through which the response passes.
To set a page's cacheability declaratively using a cache profile
1. Define a cache profile in your application's Web.config file and in the profile, include duration and varyByParam settings.
The following configuration element defines a cache profile named Cache30Seconds, which will cache the page on the server for 30 seconds.
2. Include an @ OutputCachedirective in each ASP.NET page that uses the profile, and set the CacheProfile attribute to the name of the cache profile defined in your Web.config file.
The following code specifies that the page should use the cache profile named Cache30Seconds:
<%@ OutputCache CacheProfile="Cache30Seconds" %>
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
The cacheability of a page or user control refers to whether or not a page can be cached on a device during its response life cycle. These devices include the client (browser) making the request, the Web server responding to the request, and any cache-capable devices, such as proxy servers, that are in the request or response stream.
If you know at design time what cacheability setting you need for a page, you can set cacheability declaratively. The page will then use the same cacheability settings for all requests.
To set a page's cacheability declaratively
1. Include an @ OutputCache directive in the page and define Duration and VaryByParam attributes.
2. Include a Location attribute in the @ OutputCache directive and define its value as one of the following values in the OutputCacheLocation enumeration: Any, Client, Downstream, Server, ServerAndClient, or None.
The following code shows how to set the page's cacheability to 60 seconds:
<%@ OutputCache Duration="60" VaryByParam="None"%>
Note
The default setting is Any. If you do not define a Location attribute, the page output can be cached on all cache-capable network devices that are involved in the response. These include the requesting client, the origin server, and any proxy servers through which the response passes.
To set a page's cacheability declaratively using a cache profile
1. Define a cache profile in your application's Web.config file and in the profile, include duration and varyByParam settings.
The following
2. Include an @ OutputCachedirective in each ASP.NET page that uses the profile, and set the CacheProfile attribute to the name of the cache profile defined in your Web.config file.
The following code specifies that the page should use the cache profile named Cache30Seconds:
<%@ OutputCache CacheProfile="Cache30Seconds" %>
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
.NET Framework Interview Questions
.NET Framework Interview Questions
What is the Microsoft.NET?
.NET is a set of technologies designed to transform the internet into a full scale distributed platform. It provides new ways of connecting systems, information and devices through a collection of web services. It also provides a language independent, consistent programming model across all tiers of an application.
The goal of the .NET platform is to simplify web development by providing all of the tools and technologies that one needs to build distributed web applications.
What is the .NET Framework?
The .NET Framework is set of technologies that form an integral part of the .NET Platform. It is Microsoft's managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.
The .NET Framework has two main components: the common language runtime (CLR) and .NET Framework class library. The CLR is the foundation of the .NET framework and provides a common set of services for projects that act as building blocks to build up applications across all tiers. It simplifies development and provides a robust and simplified environment which provides common services to build application. The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality.
What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of code and provides useful services for the implementation of the program. In addition to executing code, CLR provides services such as memory management, thread management, security management, code verification, compilation, and other system services. It enforces rules that in turn provide a robust and secure execution environment for .NET applications.
What is CTS?
Common Type System (CTS) describes the data types that can be used by managed code. CTS define how these types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and high performance code execution. The rules defined in CTS can be used to define your own classes and values.
What is CLS?
Common Language Specification (CLS) defines the rules and standards to which languages must adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit from classes defined in VB.NET or other .NET compatible languages.
What is managed code?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. The code that runs within the common language runtime is called managed code.
What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate language (MSIL). The common language runtime includes a JIT compiler for converting this MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this metadata is standardized across all .NET languages, a program written in one language can understand the metadata and execute code, written in a different language. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.
What is JIT?
JIT is a compiler that converts MSIL to native code. The native code consists of hardware specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT converts the MSIL as it is needed during execution. This converted native code is stored so that it is accessible for subsequent calls.
What is portable executable (PE)?
PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
What is an application domain?
Application domain is the boundary within which an application runs. A process can contain multiple application domains. Application domains provide an isolated environment to applications that is similar to the isolation provided by processes. An application running inside one application domain cannot directly access the code running inside another application domain. To access the code running in another application domain, an application needs to use a proxy.
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unit for application development and deployment in the .NET Framework. An assembly contains a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the CLR with the information it needs to be aware of type implementations.
What are the contents of assembly?
A static assembly can consist of four elements:
Assembly manifest - Contains the assembly metadata. An assembly manifest contains the information about the identity and version of the assembly. It also contains the information required to resolve references to types and resources.
Type metadata - Binary information that describes a program.
Microsoft intermediate language (MSIL) code.
A set of resources.
What are the different types of assembly?
Assemblies can also be private or shared. A private assembly is installed in the installation directory of an application and is accessible to that application only. On the other hand, a shared assembly is shared by multiple applications. A shared assembly has a strong name and is installed in the GAC.
We also have satellite assemblies that are often used to deploy language-specific resources for an application.
What is a dynamic assembly?
A dynamic assembly is created dynamically at run time when an application requires the types within these assemblies.
What is a strong name?
You need to assign a strong name to an assembly to place it in the GAC and make it globally accessible. A strong name consists of a name that consists of an assembly's identity (text name, version number, and culture information), a public key and a digital signature generated over the assembly. The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows verification and key pair and signature generation.
What is GAC?
What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: Sn -k mykey.snk
- In AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile ("mykey.snk")]
- recompile project, and then install it to GAC in two ways:
drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool)
gacutil -i abc.dll
What is the caspol.exe tool used for?
The caspol tool grants and modifies permissions to code groups at the user policy, machine policy, and enterprise policy levels.
What is a garbage collector?
A garbage collector performs periodic checks on the managed heap to identify objects that are no longer required by the program and removes them from memory.
What are generations and how are they used by the garbage collector?
Generations are the division of objects on the managed heap used by the garbage collector. This mechanism allows the garbage collector to perform highly optimized garbage collection. The unreachable objects are placed in generation 0, the reachable objects are placed in generation 1, and the objects that survive the collection process are promoted to higher generations.
What is Ilasm.exe used for?
Ilasm.exe is a tool that generates PE files from MSIL code. You can run the resulting executable to determine whether the MSIL code performs as expected.
What is Ildasm.exe used for?
Ildasm.exe is a tool that takes a PE file containing the MSIL code as a parameter and creates a text file that contains managed code.
What is the ResGen.exe tool used for?
ResGen.exe is a tool that is used to convert resource files in the form of .txt or .resx files to common language runtime binary .resources files that can be compiled into satellite assemblies.
Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the View State.
Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.
You have created an ASP.NET Application. How will you run it?
With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your pages. It functions as a local Web server. The only limitation is that remote machines cannot access pages running on this local server. The second option is to deploy a Web application to a computer running IIS version 5 or 6 or 7.
Explain the AutoPostBack feature in ASP.NET?
AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.
How do you disable AutoPostBack?
Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the controls of a page. AutoPostBack is caused by a control on the page.
What are the different code models available in ASP.NET 2.0?
There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.
Which base class does the web form inherit from?
Page class in the System.Web.UI namespace.
Which are the new special folders that are introduced in ASP.NET 2.0?
There are seven new folders introduced in ASP.NET 2.0 :
\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.
\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).
\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.
\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.
\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.
\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.
\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.
Explain the ViewState in ASP.NET?
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.
What does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.
There is an excellent article by Peter Bromberg to understand Viewstate in depth.
Explain the ASP.NET Page Directives?
Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:
@ Assembly - Links an assembly to the current page or user control declaratively.
@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).
@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.
@ Import - Imports a namespace into a page or user control explicitly.
@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.
@ MasterType - Defines the class or virtual path used to type the Master property of a page.
@ OutputCache - Controls the output caching policies of a page or user control declaratively.
@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.
@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.
@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.
This list has been taken from here.
Explain the Validation Controls used in ASP.NET 2.0?
Validation controls allows you to validate a control against a set of rules. There are 6 different validation controls used in ASP.NET 2.0.
RequiredFieldValidator – Checks if the control is not empty when the form is submitted.
CompareValidator – Compares the value of one control to another using a comparison operator (equal, less than, greater than etc).
RangeValidator – Checks whether a value falls within a given range of number, date or string.
RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a regular expression. Eg: Email validation.
CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled by the built in validators.
ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot or in a message box.
How do you identify that the page is post back?
By checking the IsPostBack property. If IsPostBack is true, the page has been posted back.
What are Master Pages?
Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.
How is a Master Page different from an ASP.NET page?
The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.
How do you attach an exisiting page to a Master page?
By using the MasterPageFile attribute in the @Page directive and removing some markup.
How do you set the title of an ASP.NET page that is attached to a Master Page?
By using the Title property of the @Page directive in the content page. Eg:
<@Page MasterPageFile="Sample.master" Title="I hold content" %>
What is a nested master page? How do you create them?
A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.
What are Themes?
Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.
What are skins?
A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:
Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.
What is the difference between Skins and Css files?
Css is applied to HTML controls whereas skins are applied to server controls.
What is a User Control?
User controls are reusable controls, similar to web pages. They cannot be accessed directly.
Explain briefly the steps in creating a user control?
Create a file with .ascx extension and place the @Control directive at top of the page.
Included the user control in a Web Forms page using a @Register directive
What is a Custom Control?
Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.
What are the differences between user and custom controls?
User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.
User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.
A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.
A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.
User controls are good for static layout whereas custom controls are good for dynamic layout.
Where do you store your connection string information?
The connection string can be stored in configuration files (web.config).
What is the difference between ‘Web.config’ and ‘Machine.config’?
Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.
Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.
There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.
What is the difference between Server.Transfer and Response.Redirect?
Response. Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the web server to a different page and transfers the page processing to a different page.
Response. Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response. Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.
What method do you use to explicitly kill a users session?
Session. Abandon ().
What is a web service?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services
What is XHTML? Are ASP.NET Pages compliant with XHTML?
In simple words, XHTML is a stricter and cleaner version of HTML. XHTML stands for EXtensible Hypertext Markup Language and is a W3C Recommendation.
Yes, ASP.NET 2.0 Pages are XHTML compliant. However the freedom has been given to the user to include the appropriate document type declaration.
More info can be found at http://msdn2.microsoft.com/en-us/library/exc57y7e.aspx
Can I deploy the application without deploying the source code on the server?
Yes. You can obfuscate your code by using a new precompilation process called ‘precompilation for deployment’. You can use the aspnet_compiler.exe to precompile a site. This process builds each page in your web application into a single application DLL and some placeholder files. These files can then be deployed to the server.
You can also accomplish the same task using Visual Studio 2005 by using the Build->Publish menu.
Does ViewState affect performance? What is the ideal size of a ViewState? How can you compress a viewstate?
Viewstate stores the state of controls in HTML hidden fields. At times, this information can grow in size. This does affect the overall responsiveness of the page, thereby affecting performance. The ideal size of a viewstate should be not more than 25-30% of the page size.
Viewstate can be compressed to almost 50% of its size. .NET also provides the GZipStream or DeflateStream to compress viewstate. Another option is explained by Scott Hanselmann over here.
How can you detect if a view state has been tampered?
By setting the EnableViewStateMac to true in the @Page directive. This attribute checks the encoded and encrypted view state for tampering.
Can I use different programming languages in the same application?
Yes. Each page can be written with a different programming language in the same application. You can create a few pages in C# and a few in VB.NET.
Can the App_Code folder contain source code files in different programming languages?
No. All source code files kept in the App_Code folder must be in the same programming language.
How do you secure your connection string information?
By using the Protected Configuration feature.
How do you secure your configuration files to be accessed remotely by unauthorized users?
ASP.NET configures IIS to deny access to any user that requests access to the Machine.config or Web.config files.
How can I configure ASP.NET applications that are running on a remote machine?
You can use the Web Site Administration Tool to configure remote websites.
How many web.config files can I have in an application?
You can keep multiple web.config files in an application. You can place a Web.config file inside a folder or wherever you need (apart from some exceptions) to override the configuration settings that are inherited from a configuration file located at a higher level in the hierarchy.
I have created a configuration setting in my web.config and have kept it at the root level. How do I prevent it from being overridden by another web.config that appears lower in the hierarchy?
By setting the element's Override attribute to false.
What is the difference between Response.Write and Response.Output.Write?
As quoted by Scott Hanselman, the short answer is that the latter gives you String. Format-style output and the former don’t.
To get a detailed explanation, follow this link.
What is Cross Page Posting? How is it done?
By default, ASP.NET submits a form to the same page. In cross-page posting, the form is submitted to a different page. This is done by setting the ‘PostBackUrl’ property of the button (that causes postback) to the desired page. In the code-behind of the page to which the form has been posted, use the ‘FindControl’ method of the ‘PreviousPage’ property to reference the data of the control in the first page.
Can you change a Master Page dynamically at runtime? How?
Yes. To change a master page, set the MasterPageFile property to point to the .master page during the PreInit page event.
How do you apply Themes to an entire application?
By specifying the theme in the web.config file.
Eg:
How do you exclude an ASP.NET page from using Themes?
To remove themes from your page, use the EnableTheming attribute of the Page directive.
Your client complains that he has a large form that collects user input. He wants to break the form into sections, keeping the information in the forms related. Which control will you use?
The ASP.NET Wizard Control.
To learn more about this control, visit this link.
Do web services support data reader?
No. However it does support a dataset.
What is use of the AutoEventWireup attribute in the Page directive?
The AutoEventWireUp is a Boolean attribute that allows automatic wire up of page events when this attribute is set to true on the page. It is set to true by default for a C# web form whereas it is set as False for VB.NET forms. Pages developed with Visual Studio .NET have this attribute set to false, and page events are individually tied to handlers.
What happens when you change the web.config file at run time?
ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.
Can you programmatically access IIS configuration settings?
Yes. You can use ADSI, WMI, or COM interfaces to configure IIS programmatically.
How does Application Pools work in IIS 6.0?
As explained under the IIS documentation, when you run IIS 6.0 in worker process isolation mode, you can separate different Web applications and Web sites into groups known as application pools. An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process. Because each worker process operates as a separate instance of the worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker process that services another. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This ensures that if a worker process fails, it does not affect the applications running in other application pools.
Use multiple application pools when you want to help ensure that applications and Web sites are confidential and secure. For example, an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools. Likewise, an ISP that hosts Web sites and applications for competing companies might run each companys Web services on the same server, but in different application pools. Using different application pools to isolate applications helps prevent one customer from accessing, changing, or using confidential information from another customer’s site.
In HTTP.sys, an application pool is represented by a request queue, from which the user-mode worker processes that service an application pool collect the requests. Each pool can manage requests for one or more unique Web applications, which you assign to the application pool based on their URLs. Application pools, then, are essentially worker process configurations that service groups of namespaces.
Multiple application pools can operate at the same time. An application, as defined by its URL, can only be served by one application pool at any time. While one application pool is servicing a request, you cannot route the request to another application pool. However, you can assign applications to another application pool while the server is running.
What is an application server?
As defined in Wikipedia, an application server is a software engine that delivers applications to client computers or devices. The application server runs your server code. Some well known application servers are IIS (Microsoft), Web Logic Server (BEA), JBoss (Red Hat), Web Sphere (IBM).
Compare C# and VB.NET
A detailed comparison can be found over here.
What is a base class and derived class?
A class is a template for creating an object. The class from which other classes derive fundamental functionality is called a base class. For e.g. If Class Y derives from Class X, then Class X is a base class.
The class which derives functionality from a base class is called a derived class. If Class Y derives from Class X, then Class Y is a derived class.
What is an extender class?
An extender class allows you to extend the functionality of an existing control. It is used in Windows forms applications to add properties to controls.
A demonstration of extender classes can be found over here.
What is inheritance?
Inheritance represents the relationship between two classes where one type derives functionality from a second type and then extends it by adding new methods, properties, events, fields and constants.
C# support two types of inheritance:
Implementation inheritance
Interface inheritance
What is implementation and interface inheritance?
When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance.
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also be derived from one or more interfaces. Hence they support Interface inheritance.
Source: Exforsys.
What is inheritance hierarchy?
The class which derives functionality from a base class is called a derived class. A derived class can also act as a base class for another class. Thus it is possible to create a tree-like structure that illustrates the relationship between all related classes. This structure is known as the inheritance hierarchy.
How do you prevent a class from being inherited?
In VB.NET you use the NotInheritable modifier to prevent programmers from using the class as a base class. In C#, use the sealed keyword.
When should you use inheritance?
Read this.
Define Overriding?
Overriding is a concept where a method in a derived class uses the same name, return type, and arguments as a method in its base class. In other words, if the derived class contains its own implementation of the method rather than using the method in the base class, the process is called overriding.
Can you use multiple inheritance in .NET?
.NET supports only single inheritance. However the purpose is accomplished using multiple interfaces.
Why don’t we have multiple inheritance in .NET?
There are several reasons for this. In simple words, the efforts are more, benefits are less. Different languages have different implementation requirements of multiple inheritance. So in order to implement multiple inheritance, we need to study the implementation aspects of all the languages that are CLR compliant and then implement a common methodology of implementing it. This is too much of efforts. Moreover multiple interface inheritance very much covers the benefits that multiple inheritance has.
What is an Interface?
An interface is a standard or contract that contains only the signatures of methods or events. The implementation is done in the class that inherits from this interface. Interfaces are primarily used to set a common standard or contract.
When should you use abstract class vs. interface or what is the difference between an abstract class and interface?
I would suggest you to read this. There is a good comparison given over here.
What are events and delegates?
An event is a message sent by a control to notify the occurrence of an action. However it is not known which object receives the event. For this reason, .NET provides a special type called Delegate which acts as an intermediary between the sender object and receiver object.
What is business logic?
It is the functionality which handles the exchange of information between database and a user interface.
What is a component?
Component is a group of logically related classes and methods. A component is a class that implements the IComponent interface or uses a class that implements IComponent interface.
What is a control?
A control is a component that provides user-interface (UI) capabilities.
What are the differences between a control and a component?
The differences can be studied over here.
What are design patterns?
Design patterns are common solutions to common design problems.
What is a connection pool?
A connection pool is a ‘collection of connections’ which are shared between the clients requesting one. Once the connection is closed, it returns back to the pool. This allows the connections to be reused.
What is a flat file?
A flat file is the name given to text, which can be read or written only sequentially.
What are functional and non-functional requirements?
Functional requirements define the behavior of a system whereas non-functional requirements specify how the system should behave; in other words they specify the quality requirements and judge the behavior of a system.
E.g.
Functional - Display a chart which shows the maximum number of products sold in a region.
Non-functional – The data presented in the chart must be updated every 5 minutes.
What is the global assembly cache (GAC)?
GAC is a machine-wide cache of assemblies that allows .NET applications to share libraries. GAC solves some of the problems associated with dll’s (DLL Hell).
What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the memory where the reference types are stored.
Check this link for the differences.
What is instrumentation?
It is the ability to monitor an application so that information about the application’s progress, performance and status can be captured and reported.
What is code review?
The process of examining the source code generally through a peer, to verify it against best practices.
What is logging?
Logging is the process of persisting information about the status of an application.
What are mock-ups?
Mock-ups are a set of designs in the form of screens, diagrams, snapshots etc., that helps verify the design and acquire feedback about the application’s requirements and use cases, at an early stage of the design process.
What is a Form?
A form is a representation of any window displayed in your application. Form can be used to create standard, borderless, floating, modal windows.
What is a multiple-document interface (MDI)?
A user interface container that enables a user to work with more than one document at a time. E.g. Microsoft Excel.
What is a single-document interface (SDI)?
A user interface that is created to manage graphical user interfaces and controls into single windows. E.g. Microsoft Word
What is BLOB?
A BLOB (binary large object) is a large item such as an image or an exe represented in binary form.
What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish self-updating applications that can be installed and run with minimal user interaction.
What is object role modeling (ORM)?
It is a logical model for designing and querying database models. There are various ORM tools in the market like Case Talk, Microsoft Visio for Enterprise Architects, Infagon etc.
What is a private assembly?
A private assembly is local to the installation directory of an application and is used only by that application.
What is a shared assembly?
A shared assembly is kept in the global assembly cache (GAC) and can be used by one or more applications on a machine.
What is the difference between user and custom controls?
User controls are easier to create whereas custom controls require extra effort.
User controls are used when the layout is static whereas custom controls are used in dynamic layouts.
A user control cannot be added to the toolbox whereas a custom control can be.
A separate copy of a user control is required in every application that uses it whereas since custom controls are stored in the GAC, only a single copy can be used by all applications.
Where do custom controls reside?
In the global assembly cache (GAC).
What is a third-party control?
A third-party control is one that is not created by the owners of a project. They are usually used to save time and resources and reuse the functionality developed by others (third-party).
What is a binary formatter?
Binary formatter is used to serialize and deserialize an object in binary format.
What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
Object obj = x;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int) obj;
Boxing/Unboxing is quiet an expensive operation.
What is a COM Callable Wrapper (CCW)?
CCW is a wrapper created by the common language runtime (CLR) that enables COM components to access .NET objects.
What is a Runtime Callable Wrapper (RCW)?
RCW is a wrapper created by the common language runtime (CLR) to enable .NET components to call COM components.
What is a digital signature?
A digital signature is an electronic signature used to verify/guarantee the identity of the individual who is sending the message.
What is garbage collection?
Garbage collection is the process of managing the allocation and release of memory in your applications. Read this article for more information.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures and regions.
What is localization?
Localization is the process of customizing applications that support a given culture and regions.
What is MIME?
The definition of MIME or Multipurpose Internet Mail Extensions as stated in MSDN is “MIME is a standard that can be used to include content of various types in a single message. MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to include multiple content, both textual and non-textual. Parts of the message may be images, audio, or text in different character sets. The MIME standard derives from RFCs such as 2821 and 2822”.
Deleting Multiple Rows in a Grid View
If you have used Hotmail or any other similar email client, you might have observed that we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a GridView. A GridView allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with GridView.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a GridView with functionality to delete multiple rows at a time.
Perform the following steps:
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database. Create queries for the Select and Delete commands. The resultant code will look similar as given below :
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1. Create a TemplateField inside the to add custom content to each column.
2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
ID="btnMultipleRowDelete"
OnClick="btnMultipleRowDelete_Click"
runat="server"
Text="Delete Rows" />
In Code behind file (.cs), code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
//Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
if (checkbox.Checked)
{
// Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
SqlDataSource1.Delete();
}
}
}
Run the code, and select a few rows in the grid. On clicking the ‘Delete Rows’ button, the selected rows get deleted.
Rather than deleting rows one at a time, deleting them in a batch is a good practice. I would encourage you to read Scott Mitchell’s article for the same.
Conclusion
By default, the gridview provides the functionality to delete a single row at a time. In this article, we explored how to extend the functionality of the grid view and delete multiple rows. I hope this article was useful and I thank you for viewing it.
Sending Email In ASP.NET 2.0
In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email from ASP.NET are as follows :
Step 1: Declare the System.Net.Mail namespace
using System.Net.Mail;
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
public MailMessage ( string from, string to, string subject, string body )
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
MailMessage message = new MailMessage ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail");
Step 3: To add an attachment to the message, use the Attachment class.
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
message.Attachments.Add(attach);
Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.
SmtpClient client = new SmtpClient("localhost");
client.Send(message);
Additionally, if required, you
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
References :
http://msdn2.microsoft.com/En-US/library/system.net.mail.mailmessage.aspx
Conclusion:
In this short article, we explored how easy it is to send Email’s with attachments using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
What is the Microsoft.NET?
.NET is a set of technologies designed to transform the internet into a full scale distributed platform. It provides new ways of connecting systems, information and devices through a collection of web services. It also provides a language independent, consistent programming model across all tiers of an application.
The goal of the .NET platform is to simplify web development by providing all of the tools and technologies that one needs to build distributed web applications.
What is the .NET Framework?
The .NET Framework is set of technologies that form an integral part of the .NET Platform. It is Microsoft's managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.
The .NET Framework has two main components: the common language runtime (CLR) and .NET Framework class library. The CLR is the foundation of the .NET framework and provides a common set of services for projects that act as building blocks to build up applications across all tiers. It simplifies development and provides a robust and simplified environment which provides common services to build application. The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality.
What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of code and provides useful services for the implementation of the program. In addition to executing code, CLR provides services such as memory management, thread management, security management, code verification, compilation, and other system services. It enforces rules that in turn provide a robust and secure execution environment for .NET applications.
What is CTS?
Common Type System (CTS) describes the data types that can be used by managed code. CTS define how these types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and high performance code execution. The rules defined in CTS can be used to define your own classes and values.
What is CLS?
Common Language Specification (CLS) defines the rules and standards to which languages must adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit from classes defined in VB.NET or other .NET compatible languages.
What is managed code?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. The code that runs within the common language runtime is called managed code.
What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate language (MSIL). The common language runtime includes a JIT compiler for converting this MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this metadata is standardized across all .NET languages, a program written in one language can understand the metadata and execute code, written in a different language. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.
What is JIT?
JIT is a compiler that converts MSIL to native code. The native code consists of hardware specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT converts the MSIL as it is needed during execution. This converted native code is stored so that it is accessible for subsequent calls.
What is portable executable (PE)?
PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
What is an application domain?
Application domain is the boundary within which an application runs. A process can contain multiple application domains. Application domains provide an isolated environment to applications that is similar to the isolation provided by processes. An application running inside one application domain cannot directly access the code running inside another application domain. To access the code running in another application domain, an application needs to use a proxy.
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unit for application development and deployment in the .NET Framework. An assembly contains a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the CLR with the information it needs to be aware of type implementations.
What are the contents of assembly?
A static assembly can consist of four elements:
Assembly manifest - Contains the assembly metadata. An assembly manifest contains the information about the identity and version of the assembly. It also contains the information required to resolve references to types and resources.
Type metadata - Binary information that describes a program.
Microsoft intermediate language (MSIL) code.
A set of resources.
What are the different types of assembly?
Assemblies can also be private or shared. A private assembly is installed in the installation directory of an application and is accessible to that application only. On the other hand, a shared assembly is shared by multiple applications. A shared assembly has a strong name and is installed in the GAC.
We also have satellite assemblies that are often used to deploy language-specific resources for an application.
What is a dynamic assembly?
A dynamic assembly is created dynamically at run time when an application requires the types within these assemblies.
What is a strong name?
You need to assign a strong name to an assembly to place it in the GAC and make it globally accessible. A strong name consists of a name that consists of an assembly's identity (text name, version number, and culture information), a public key and a digital signature generated over the assembly. The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows verification and key pair and signature generation.
What is GAC?
What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: Sn -k mykey.snk
- In AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile ("mykey.snk")]
- recompile project, and then install it to GAC in two ways:
drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool)
gacutil -i abc.dll
What is the caspol.exe tool used for?
The caspol tool grants and modifies permissions to code groups at the user policy, machine policy, and enterprise policy levels.
What is a garbage collector?
A garbage collector performs periodic checks on the managed heap to identify objects that are no longer required by the program and removes them from memory.
What are generations and how are they used by the garbage collector?
Generations are the division of objects on the managed heap used by the garbage collector. This mechanism allows the garbage collector to perform highly optimized garbage collection. The unreachable objects are placed in generation 0, the reachable objects are placed in generation 1, and the objects that survive the collection process are promoted to higher generations.
What is Ilasm.exe used for?
Ilasm.exe is a tool that generates PE files from MSIL code. You can run the resulting executable to determine whether the MSIL code performs as expected.
What is Ildasm.exe used for?
Ildasm.exe is a tool that takes a PE file containing the MSIL code as a parameter and creates a text file that contains managed code.
What is the ResGen.exe tool used for?
ResGen.exe is a tool that is used to convert resource files in the form of .txt or .resx files to common language runtime binary .resources files that can be compiled into satellite assemblies.
Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the View State.
Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.
You have created an ASP.NET Application. How will you run it?
With ASP.NET 2.0, Visual Studio comes with an inbuilt ASP.NET Development Server to test your pages. It functions as a local Web server. The only limitation is that remote machines cannot access pages running on this local server. The second option is to deploy a Web application to a computer running IIS version 5 or 6 or 7.
Explain the AutoPostBack feature in ASP.NET?
AutoPostBack allows a control to automatically postback when an event is fired. For eg: If we have a Button control and want the event to be posted to the server for processing, we can set AutoPostBack = True on the button.
How do you disable AutoPostBack?
Hence the AutoPostBack can be disabled on an ASP.NET page by disabling AutoPostBack on all the controls of a page. AutoPostBack is caused by a control on the page.
What are the different code models available in ASP.NET 2.0?
There are 2 code models available in ASP.NET 2.0. One is the single-file page and the other one is the code behind page.
Which base class does the web form inherit from?
Page class in the System.Web.UI namespace.
Which are the new special folders that are introduced in ASP.NET 2.0?
There are seven new folders introduced in ASP.NET 2.0 :
\App_Browsers folder – Holds browser definitions(.brower) files which identify the browser and their capabilities.
\App_Code folder – Contains source code (.cs, .vb) files which are automatically compiled when placed in this folder. Additionally placing web service files generates a proxy class(out of .wsdl) and a typed dataset (out of .xsd).
\App_Data folder – Contains data store files like .mdf (Sql Express files), .mdb, XML files etc. This folder also stores the local db to maintain membership and role information.
\App_GlobalResources folder – Contains assembly resource files (.resx) which when placed in this folder are compiled automatically. In earlier versions, we were required to manually use the resgen.exe tool to compile resource files. These files can be accessed globally in the application.
\App_LocalResources folder – Contains assembly resource files (.resx) which can be used by a specific page or control.
\App_Themes folder – This folder contains .css and .skin files that define the appearance of web pages and controls.
\App_WebReferences folder – Replaces the previously used Web References folder. This folder contains the .disco, .wsdl, .xsd files that get generated when accessing remote web services.
Explain the ViewState in ASP.NET?
Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.
What does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.
There is an excellent article by Peter Bromberg to understand Viewstate in depth.
Explain the ASP.NET Page Directives?
Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:
@ Assembly - Links an assembly to the current page or user control declaratively.
@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).
@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively.
@ Import - Imports a namespace into a page or user control explicitly.
@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.
@ MasterType - Defines the class or virtual path used to type the Master property of a page.
@ OutputCache - Controls the output caching policies of a page or user control declaratively.
@ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
@ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.
@ Reference - Links a page, user control, or COM control to the current page or user control declaratively.
@ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.
This list has been taken from here.
Explain the Validation Controls used in ASP.NET 2.0?
Validation controls allows you to validate a control against a set of rules. There are 6 different validation controls used in ASP.NET 2.0.
RequiredFieldValidator – Checks if the control is not empty when the form is submitted.
CompareValidator – Compares the value of one control to another using a comparison operator (equal, less than, greater than etc).
RangeValidator – Checks whether a value falls within a given range of number, date or string.
RegularExpressionValidator – Confirms that the value of a control matches a pattern defined by a regular expression. Eg: Email validation.
CustomValidator – Calls your own custom validation logic to perform validations that cannot be handled by the built in validators.
ValidationSummary – Show a summary of errors raised by each control on the page on a specific spot or in a message box.
How do you identify that the page is post back?
By checking the IsPostBack property. If IsPostBack is true, the page has been posted back.
What are Master Pages?
Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.
How is a Master Page different from an ASP.NET page?
The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.
How do you attach an exisiting page to a Master page?
By using the MasterPageFile attribute in the @Page directive and removing some markup.
How do you set the title of an ASP.NET page that is attached to a Master Page?
By using the Title property of the @Page directive in the content page. Eg:
<@Page MasterPageFile="Sample.master" Title="I hold content" %>
What is a nested master page? How do you create them?
A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.
What are Themes?
Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.
What are skins?
A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:
Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.
What is the difference between Skins and Css files?
Css is applied to HTML controls whereas skins are applied to server controls.
What is a User Control?
User controls are reusable controls, similar to web pages. They cannot be accessed directly.
Explain briefly the steps in creating a user control?
Create a file with .ascx extension and place the @Control directive at top of the page.
Included the user control in a Web Forms page using a @Register directive
What is a Custom Control?
Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.
What are the differences between user and custom controls?
User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.
User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.
A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.
A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.
User controls are good for static layout whereas custom controls are good for dynamic layout.
Where do you store your connection string information?
The connection string can be stored in configuration files (web.config).
What is the difference between ‘Web.config’ and ‘Machine.config’?
Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.
Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.
There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.
What is the difference between Server.Transfer and Response.Redirect?
Response. Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the web server to a different page and transfers the page processing to a different page.
Response. Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response. Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.
What method do you use to explicitly kill a users session?
Session. Abandon ().
What is a web service?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services
What is XHTML? Are ASP.NET Pages compliant with XHTML?
In simple words, XHTML is a stricter and cleaner version of HTML. XHTML stands for EXtensible Hypertext Markup Language and is a W3C Recommendation.
Yes, ASP.NET 2.0 Pages are XHTML compliant. However the freedom has been given to the user to include the appropriate document type declaration.
More info can be found at http://msdn2.microsoft.com/en-us/library/exc57y7e.aspx
Can I deploy the application without deploying the source code on the server?
Yes. You can obfuscate your code by using a new precompilation process called ‘precompilation for deployment’. You can use the aspnet_compiler.exe to precompile a site. This process builds each page in your web application into a single application DLL and some placeholder files. These files can then be deployed to the server.
You can also accomplish the same task using Visual Studio 2005 by using the Build->Publish menu.
Does ViewState affect performance? What is the ideal size of a ViewState? How can you compress a viewstate?
Viewstate stores the state of controls in HTML hidden fields. At times, this information can grow in size. This does affect the overall responsiveness of the page, thereby affecting performance. The ideal size of a viewstate should be not more than 25-30% of the page size.
Viewstate can be compressed to almost 50% of its size. .NET also provides the GZipStream or DeflateStream to compress viewstate. Another option is explained by Scott Hanselmann over here.
How can you detect if a view state has been tampered?
By setting the EnableViewStateMac to true in the @Page directive. This attribute checks the encoded and encrypted view state for tampering.
Can I use different programming languages in the same application?
Yes. Each page can be written with a different programming language in the same application. You can create a few pages in C# and a few in VB.NET.
Can the App_Code folder contain source code files in different programming languages?
No. All source code files kept in the App_Code folder must be in the same programming language.
How do you secure your connection string information?
By using the Protected Configuration feature.
How do you secure your configuration files to be accessed remotely by unauthorized users?
ASP.NET configures IIS to deny access to any user that requests access to the Machine.config or Web.config files.
How can I configure ASP.NET applications that are running on a remote machine?
You can use the Web Site Administration Tool to configure remote websites.
How many web.config files can I have in an application?
You can keep multiple web.config files in an application. You can place a Web.config file inside a folder or wherever you need (apart from some exceptions) to override the configuration settings that are inherited from a configuration file located at a higher level in the hierarchy.
I have created a configuration setting in my web.config and have kept it at the root level. How do I prevent it from being overridden by another web.config that appears lower in the hierarchy?
By setting the element's Override attribute to false.
What is the difference between Response.Write and Response.Output.Write?
As quoted by Scott Hanselman, the short answer is that the latter gives you String. Format-style output and the former don’t.
To get a detailed explanation, follow this link.
What is Cross Page Posting? How is it done?
By default, ASP.NET submits a form to the same page. In cross-page posting, the form is submitted to a different page. This is done by setting the ‘PostBackUrl’ property of the button (that causes postback) to the desired page. In the code-behind of the page to which the form has been posted, use the ‘FindControl’ method of the ‘PreviousPage’ property to reference the data of the control in the first page.
Can you change a Master Page dynamically at runtime? How?
Yes. To change a master page, set the MasterPageFile property to point to the .master page during the PreInit page event.
How do you apply Themes to an entire application?
By specifying the theme in the web.config file.
Eg:
How do you exclude an ASP.NET page from using Themes?
To remove themes from your page, use the EnableTheming attribute of the Page directive.
Your client complains that he has a large form that collects user input. He wants to break the form into sections, keeping the information in the forms related. Which control will you use?
The ASP.NET Wizard Control.
To learn more about this control, visit this link.
Do web services support data reader?
No. However it does support a dataset.
What is use of the AutoEventWireup attribute in the Page directive?
The AutoEventWireUp is a Boolean attribute that allows automatic wire up of page events when this attribute is set to true on the page. It is set to true by default for a C# web form whereas it is set as False for VB.NET forms. Pages developed with Visual Studio .NET have this attribute set to false, and page events are individually tied to handlers.
What happens when you change the web.config file at run time?
ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.
Can you programmatically access IIS configuration settings?
Yes. You can use ADSI, WMI, or COM interfaces to configure IIS programmatically.
How does Application Pools work in IIS 6.0?
As explained under the IIS documentation, when you run IIS 6.0 in worker process isolation mode, you can separate different Web applications and Web sites into groups known as application pools. An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.
Every application within an application pool shares the same worker process. Because each worker process operates as a separate instance of the worker process executable, W3wp.exe, the worker process that services one application pool is separated from the worker process that services another. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This ensures that if a worker process fails, it does not affect the applications running in other application pools.
Use multiple application pools when you want to help ensure that applications and Web sites are confidential and secure. For example, an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools. Likewise, an ISP that hosts Web sites and applications for competing companies might run each companys Web services on the same server, but in different application pools. Using different application pools to isolate applications helps prevent one customer from accessing, changing, or using confidential information from another customer’s site.
In HTTP.sys, an application pool is represented by a request queue, from which the user-mode worker processes that service an application pool collect the requests. Each pool can manage requests for one or more unique Web applications, which you assign to the application pool based on their URLs. Application pools, then, are essentially worker process configurations that service groups of namespaces.
Multiple application pools can operate at the same time. An application, as defined by its URL, can only be served by one application pool at any time. While one application pool is servicing a request, you cannot route the request to another application pool. However, you can assign applications to another application pool while the server is running.
What is an application server?
As defined in Wikipedia, an application server is a software engine that delivers applications to client computers or devices. The application server runs your server code. Some well known application servers are IIS (Microsoft), Web Logic Server (BEA), JBoss (Red Hat), Web Sphere (IBM).
Compare C# and VB.NET
A detailed comparison can be found over here.
What is a base class and derived class?
A class is a template for creating an object. The class from which other classes derive fundamental functionality is called a base class. For e.g. If Class Y derives from Class X, then Class X is a base class.
The class which derives functionality from a base class is called a derived class. If Class Y derives from Class X, then Class Y is a derived class.
What is an extender class?
An extender class allows you to extend the functionality of an existing control. It is used in Windows forms applications to add properties to controls.
A demonstration of extender classes can be found over here.
What is inheritance?
Inheritance represents the relationship between two classes where one type derives functionality from a second type and then extends it by adding new methods, properties, events, fields and constants.
C# support two types of inheritance:
Implementation inheritance
Interface inheritance
What is implementation and interface inheritance?
When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance.
When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.
In general Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also be derived from one or more interfaces. Hence they support Interface inheritance.
Source: Exforsys.
What is inheritance hierarchy?
The class which derives functionality from a base class is called a derived class. A derived class can also act as a base class for another class. Thus it is possible to create a tree-like structure that illustrates the relationship between all related classes. This structure is known as the inheritance hierarchy.
How do you prevent a class from being inherited?
In VB.NET you use the NotInheritable modifier to prevent programmers from using the class as a base class. In C#, use the sealed keyword.
When should you use inheritance?
Read this.
Define Overriding?
Overriding is a concept where a method in a derived class uses the same name, return type, and arguments as a method in its base class. In other words, if the derived class contains its own implementation of the method rather than using the method in the base class, the process is called overriding.
Can you use multiple inheritance in .NET?
.NET supports only single inheritance. However the purpose is accomplished using multiple interfaces.
Why don’t we have multiple inheritance in .NET?
There are several reasons for this. In simple words, the efforts are more, benefits are less. Different languages have different implementation requirements of multiple inheritance. So in order to implement multiple inheritance, we need to study the implementation aspects of all the languages that are CLR compliant and then implement a common methodology of implementing it. This is too much of efforts. Moreover multiple interface inheritance very much covers the benefits that multiple inheritance has.
What is an Interface?
An interface is a standard or contract that contains only the signatures of methods or events. The implementation is done in the class that inherits from this interface. Interfaces are primarily used to set a common standard or contract.
When should you use abstract class vs. interface or what is the difference between an abstract class and interface?
I would suggest you to read this. There is a good comparison given over here.
What are events and delegates?
An event is a message sent by a control to notify the occurrence of an action. However it is not known which object receives the event. For this reason, .NET provides a special type called Delegate which acts as an intermediary between the sender object and receiver object.
What is business logic?
It is the functionality which handles the exchange of information between database and a user interface.
What is a component?
Component is a group of logically related classes and methods. A component is a class that implements the IComponent interface or uses a class that implements IComponent interface.
What is a control?
A control is a component that provides user-interface (UI) capabilities.
What are the differences between a control and a component?
The differences can be studied over here.
What are design patterns?
Design patterns are common solutions to common design problems.
What is a connection pool?
A connection pool is a ‘collection of connections’ which are shared between the clients requesting one. Once the connection is closed, it returns back to the pool. This allows the connections to be reused.
What is a flat file?
A flat file is the name given to text, which can be read or written only sequentially.
What are functional and non-functional requirements?
Functional requirements define the behavior of a system whereas non-functional requirements specify how the system should behave; in other words they specify the quality requirements and judge the behavior of a system.
E.g.
Functional - Display a chart which shows the maximum number of products sold in a region.
Non-functional – The data presented in the chart must be updated every 5 minutes.
What is the global assembly cache (GAC)?
GAC is a machine-wide cache of assemblies that allows .NET applications to share libraries. GAC solves some of the problems associated with dll’s (DLL Hell).
What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the memory where the reference types are stored.
Check this link for the differences.
What is instrumentation?
It is the ability to monitor an application so that information about the application’s progress, performance and status can be captured and reported.
What is code review?
The process of examining the source code generally through a peer, to verify it against best practices.
What is logging?
Logging is the process of persisting information about the status of an application.
What are mock-ups?
Mock-ups are a set of designs in the form of screens, diagrams, snapshots etc., that helps verify the design and acquire feedback about the application’s requirements and use cases, at an early stage of the design process.
What is a Form?
A form is a representation of any window displayed in your application. Form can be used to create standard, borderless, floating, modal windows.
What is a multiple-document interface (MDI)?
A user interface container that enables a user to work with more than one document at a time. E.g. Microsoft Excel.
What is a single-document interface (SDI)?
A user interface that is created to manage graphical user interfaces and controls into single windows. E.g. Microsoft Word
What is BLOB?
A BLOB (binary large object) is a large item such as an image or an exe represented in binary form.
What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish self-updating applications that can be installed and run with minimal user interaction.
What is object role modeling (ORM)?
It is a logical model for designing and querying database models. There are various ORM tools in the market like Case Talk, Microsoft Visio for Enterprise Architects, Infagon etc.
What is a private assembly?
A private assembly is local to the installation directory of an application and is used only by that application.
What is a shared assembly?
A shared assembly is kept in the global assembly cache (GAC) and can be used by one or more applications on a machine.
What is the difference between user and custom controls?
User controls are easier to create whereas custom controls require extra effort.
User controls are used when the layout is static whereas custom controls are used in dynamic layouts.
A user control cannot be added to the toolbox whereas a custom control can be.
A separate copy of a user control is required in every application that uses it whereas since custom controls are stored in the GAC, only a single copy can be used by all applications.
Where do custom controls reside?
In the global assembly cache (GAC).
What is a third-party control?
A third-party control is one that is not created by the owners of a project. They are usually used to save time and resources and reuse the functionality developed by others (third-party).
What is a binary formatter?
Binary formatter is used to serialize and deserialize an object in binary format.
What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
Object obj = x;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int) obj;
Boxing/Unboxing is quiet an expensive operation.
What is a COM Callable Wrapper (CCW)?
CCW is a wrapper created by the common language runtime (CLR) that enables COM components to access .NET objects.
What is a Runtime Callable Wrapper (RCW)?
RCW is a wrapper created by the common language runtime (CLR) to enable .NET components to call COM components.
What is a digital signature?
A digital signature is an electronic signature used to verify/guarantee the identity of the individual who is sending the message.
What is garbage collection?
Garbage collection is the process of managing the allocation and release of memory in your applications. Read this article for more information.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures and regions.
What is localization?
Localization is the process of customizing applications that support a given culture and regions.
What is MIME?
The definition of MIME or Multipurpose Internet Mail Extensions as stated in MSDN is “MIME is a standard that can be used to include content of various types in a single message. MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to include multiple content, both textual and non-textual. Parts of the message may be images, audio, or text in different character sets. The MIME standard derives from RFCs such as 2821 and 2822”.
Deleting Multiple Rows in a Grid View
If you have used Hotmail or any other similar email client, you might have observed that we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a GridView. A GridView allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with GridView.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a GridView with functionality to delete multiple rows at a time.
Perform the following steps:
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database. Create queries for the Select and Delete commands. The resultant code will look similar as given below :
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1. Create a TemplateField inside the
2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
OnClick="btnMultipleRowDelete_Click"
runat="server"
Text="Delete Rows" />
In Code behind file (.cs), code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
//Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
if (checkbox.Checked)
{
// Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
SqlDataSource1.Delete();
}
}
}
Run the code, and select a few rows in the grid. On clicking the ‘Delete Rows’ button, the selected rows get deleted.
Rather than deleting rows one at a time, deleting them in a batch is a good practice. I would encourage you to read Scott Mitchell’s article for the same.
Conclusion
By default, the gridview provides the functionality to delete a single row at a time. In this article, we explored how to extend the functionality of the grid view and delete multiple rows. I hope this article was useful and I thank you for viewing it.
Sending Email In ASP.NET 2.0
In ASP.NET, sending emails has become simpler. The classes required to send an email are contained in the System.Net.Mail. The steps required to send an email from ASP.NET are as follows :
Step 1: Declare the System.Net.Mail namespace
using System.Net.Mail;
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
public MailMessage ( string from, string to, string subject, string body )
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
MailMessage message = new MailMessage ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail");
Step 3: To add an attachment to the message, use the Attachment class.
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
message.Attachments.Add(attach);
Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.
SmtpClient client = new SmtpClient("localhost");
client.Send(message);
Additionally, if required, you
client.Timeout = 500;
// Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
References :
http://msdn2.microsoft.com/En-US/library/system.net.mail.mailmessage.aspx
Conclusion:
In this short article, we explored how easy it is to send Email’s with attachments using the classes in System.Net.Mail. This approach of sending mails will remain the same for web as well as windows application.
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Friday, March 19, 2010
Sort a list of integers descending C#
These search terms have been highlighted: list sort decending
The Sort method of the List class sorts everything the default way : ascending.
You can use the Reverse method of this class to get what you want or you could implement the IComparer interface like in this snippet.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private class SortIntDescending : IComparer
{
int IComparer.Compare(int a, int b) //implement Compare
{ if (a > b) return -1; //normally greater than = 1
if (a < b) return 1; // normally smaller than = -1
else return 0; // equal
} }
static List intlist = new List(); // make a list
static void Main(string[] args)
{
intlist.Add(5); //fill the list with 5 ints
intlist.Add(3);
intlist.Add(5);
intlist.Add(15);
intlist.Add(7);
Console.WriteLine("Unsorted list :");
Printlist(intlist); Console.WriteLine();
// intlist.Sort(); uses the default Comparer, which is ascending
intlist.Sort(new SortIntDescending()); //sort descending
Console.WriteLine("Sorted descending list :");
Printlist(intlist);
Console.ReadKey(); //wait for keydown
}
static void Printlist(List L)
{
foreach (int i in L) //print on the console
{
Console.WriteLine(i);
} } }}
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
The Sort method of the List class sorts everything the default way : ascending.
You can use the Reverse method of this class to get what you want or you could implement the IComparer interface like in this snippet.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
private class SortIntDescending : IComparer
{
int IComparer
{ if (a > b) return -1; //normally greater than = 1
if (a < b) return 1; // normally smaller than = -1
else return 0; // equal
} }
static List
static void Main(string[] args)
{
intlist.Add(5); //fill the list with 5 ints
intlist.Add(3);
intlist.Add(5);
intlist.Add(15);
intlist.Add(7);
Console.WriteLine("Unsorted list :");
Printlist(intlist); Console.WriteLine();
// intlist.Sort(); uses the default Comparer, which is ascending
intlist.Sort(new SortIntDescending()); //sort descending
Console.WriteLine("Sorted descending list :");
Printlist(intlist);
Console.ReadKey(); //wait for keydown
}
static void Printlist(List
{
foreach (int i in L) //print on the console
{
Console.WriteLine(i);
} } }}
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Thursday, March 18, 2010
How to convert strings to lower, upper, or title (proper) case by using Visual C#
This article demonstrates how to convert a string to uppercase, lowercase, or title (or proper) case.
Although you can use methods of the String class to convert a string to uppercase or lowercase, you must use a method in the TextInfo class of the System.Globalization namespace to convert a string to title case. The String class does not include a built-in method to convert a string to title case.
Convert String Using the String Class
This section describes how to use the methods of the String class to convert a string to uppercase and lowercase.
Convert a String to Uppercase
The String class has a static method named ToUpper. You can use this method to convert a string to uppercase.
For example:
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
Convert a String to Lowercase
The ToLower method is the complement of the ToUpper method. ToLower converts a string to lowercase.
For example:
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
Convert String Using the TextInfo Class
This section describes how to use the TextInfo class to convert a string to title case.
Convert a String to Title Case
The String class does not include a method that converts a string to title case. The ToTitleCase method resides in the TextInfo class, which is a member of the System.Globalization namespace. Unlike the ToUpper and ToLower methods of the String class, the ToTitleCase method is not a static method and requires an instance of the class.
When you use the TextInfo class, you must specify cultural information. In most situations, you can default to the culture that is currently in use. Culture information is a property of the thread on which the code is running. To obtain the culture information, you must gain access to the current thread and retrieve the CurrentCulture property from that thread. Once you accomplish this, you can create the TextInfo object.
For example:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
The TextInfo class also includes the ToUpper and ToLower methods. Use these methods of TextInfo if you need to specify culture options.
Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));
Note on the InvariantCulture Property
When you use the Globalization namespace to convert data, if you store the converted data instead of displaying it for the user, you may want to use the InvariantCulture property of CultureInfo class.
InvariantCulture is neither a neutral nor a specific culture; it is a culture that is culture-insensitive. If you use InvariantCulture when you store data, the data is stored in a consistent manner, regardless of any specific user or cultural system settings that may be in effect. For more information, refer to the References section.
The preceding code sample uses the CultureInfo properties of the current thread:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
To use InvariantCulture in the same scenario, use the following code:
CultureInfo cultureInfo = CultureInfo.InvariantCulture;
for more : http://support.microsoft.com/kb/312890
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Although you can use methods of the String class to convert a string to uppercase or lowercase, you must use a method in the TextInfo class of the System.Globalization namespace to convert a string to title case. The String class does not include a built-in method to convert a string to title case.
Convert String Using the String Class
This section describes how to use the methods of the String class to convert a string to uppercase and lowercase.
Convert a String to Uppercase
The String class has a static method named ToUpper. You can use this method to convert a string to uppercase.
For example:
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
Convert a String to Lowercase
The ToLower method is the complement of the ToUpper method. ToLower converts a string to lowercase.
For example:
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
Convert String Using the TextInfo Class
This section describes how to use the TextInfo class to convert a string to title case.
Convert a String to Title Case
The String class does not include a method that converts a string to title case. The ToTitleCase method resides in the TextInfo class, which is a member of the System.Globalization namespace. Unlike the ToUpper and ToLower methods of the String class, the ToTitleCase method is not a static method and requires an instance of the class.
When you use the TextInfo class, you must specify cultural information. In most situations, you can default to the culture that is currently in use. Culture information is a property of the thread on which the code is running. To obtain the culture information, you must gain access to the current thread and retrieve the CurrentCulture property from that thread. Once you accomplish this, you can create the TextInfo object.
For example:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
The TextInfo class also includes the ToUpper and ToLower methods. Use these methods of TextInfo if you need to specify culture options.
Console.WriteLine(textInfo.ToTitleCase(title));
Console.WriteLine(textInfo.ToLower(title));
Console.WriteLine(textInfo.ToUpper(title));
Note on the InvariantCulture Property
When you use the Globalization namespace to convert data, if you store the converted data instead of displaying it for the user, you may want to use the InvariantCulture property of CultureInfo class.
InvariantCulture is neither a neutral nor a specific culture; it is a culture that is culture-insensitive. If you use InvariantCulture when you store data, the data is stored in a consistent manner, regardless of any specific user or cultural system settings that may be in effect. For more information, refer to the References section.
The preceding code sample uses the CultureInfo properties of the current thread:
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
To use InvariantCulture in the same scenario, use the following code:
CultureInfo cultureInfo = CultureInfo.InvariantCulture;
for more : http://support.microsoft.com/kb/312890
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
.net Interview questions in Cognizant for 5+ Exp
One of my friend attended Cognizant last week....
Here are the questions.....
1. what are different Session modes
2. how to set session mode in web.config when application requires load balancing kind of thing.
3. how to encrypt view state info
4. different objects will be used to fill dataset
5. which event will be fired first and which event will be fired last in global.asax
6. is there any difference in performance of the application which is created in vb.net and same applications created in c#.net
7. page life cycle
8. where do we get view state info in page life cycle
InitComplete event
9. different authentications in ASP.NEt
10. isolation levels
11. different validation controls
12. difference between SP and view
13. types of triggers
14. types of user defined functions
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Here are the questions.....
1. what are different Session modes
2. how to set session mode in web.config when application requires load balancing kind of thing.
3. how to encrypt view state info
4. different objects will be used to fill dataset
5. which event will be fired first and which event will be fired last in global.asax
6. is there any difference in performance of the application which is created in vb.net and same applications created in c#.net
7. page life cycle
8. where do we get view state info in page life cycle
InitComplete event
9. different authentications in ASP.NEt
10. isolation levels
11. different validation controls
12. difference between SP and view
13. types of triggers
14. types of user defined functions
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Thursday, March 11, 2010
Anonymous Methods C#.NET 3.5
Anonymous Methods
I love Anonymous Methods in C# 2.0. The idea behind anonymous methods it to write methods inline to the code so you don't have to go through the trouble of declaring a formal named method. They are mainly used for small methods that don't require any need for reuse.
Instead of declaring a separate method IsAbe to find Abe in a list of strings:
class Program
{
static void Main(string[] args)
{
List names = new List();
names.Add("Dave");
names.Add("John");
names.Add("Abe");
names.Add("Barney");
names.Add("Chuck");
string abe = names.Find(IsAbe);
Console.WriteLine(abe);
}
public static bool IsAbe(string name)
{
return name.Equals("Abe");
}
}
You can declare an anonymous method inline to save you the trouble:
class Program
{
static void Main(string[] args)
{
List names = new List();
names.Add("Dave");
names.Add("John");
names.Add("Abe");
names.Add("Barney");
names.Add("Chuck");
string abe = names.Find(delegate(string name)
{
return name.Equals("Abe");
});
Console.WriteLine(abe);
}
}
It can get a lot fancier than that, but that is basically the gist. Declare the method inline to the code for easy stuff not needing reuse, because it saves some typing and puts the method closer to where it is being used which helps with maintenance.
C# supports delegates for invoking one or multiple methods. Delegates provide operators and methods for adding and removing target methods, and are used extensively throughout the .NET Framework for events, callbacks, asynchronous calls, and multithreading. However, you are sometimes forced to define a method just for the sake of using a delegate. In such cases, there is no need for multiple targets, and the code involved is often relatively short and simple. Anonymous methods is a new feature in C# 2.0 that lets you define an anonymous (that is, nameless) method called by a delegate.
For example, the following is a conventional SomeMethod method definition and delegate invocation:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = new SomeDelegate(SomeMethod);
del();
}
void SomeMethod() {MessageBox.Show("Hello");}
}
You can define and implement this with an anonymous method:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
MessageBox.Show("Hello");
};
del();
}
}
The anonymous method is defined in-line and not as a member method of any class. Additionally, there is no way to apply custom attributes to an anonymous method, nor can the anonymous method define generic types or add generic constraints.
You should note two interesting things about anonymous methods: the overloaded use of the delegate reserved keyword and the delegate assignment. You will see how the compiler implements an anonymous method, but it is quite clear from looking at the code that the compiler has to infer the type of the delegate used, instantiate a new delegate object of the inferred type, wrap the new delegate around the anonymous method, and assign it to the delegate used in the definition of the anonymous method (del in the previous example).
Anonymous methods can be used anywhere that a delegate type is expected. You can pass an anonymous method into any method that accepts the appropriate delegate type as a parameter:
Passing Parameters to Anonymous Methods
When defining an anonymous method with parameters, you define the parameter types and names after the delegate keyword just as if it were a conventional method. The method signature must match the definition of the delegate to which it is assigned. When invoking the delegate, you pass the parameter's values, just as with a normal delegate invocation:
class SomeClass
{
delegate void SomeDelegate(string str);
public void InvokeMethod()
{
SomeDelegate del = delegate(string str)
{
MessageBox.Show(str);
};
del("Hello");
}
}
If the anonymous method has no parameters, you can use a pair of empty parens after the delegate keyword:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
MessageBox.Show("Hello");
};
del();
}
}
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
I love Anonymous Methods in C# 2.0. The idea behind anonymous methods it to write methods inline to the code so you don't have to go through the trouble of declaring a formal named method. They are mainly used for small methods that don't require any need for reuse.
Instead of declaring a separate method IsAbe to find Abe in a list of strings:
class Program
{
static void Main(string[] args)
{
List
names.Add("Dave");
names.Add("John");
names.Add("Abe");
names.Add("Barney");
names.Add("Chuck");
string abe = names.Find(IsAbe);
Console.WriteLine(abe);
}
public static bool IsAbe(string name)
{
return name.Equals("Abe");
}
}
You can declare an anonymous method inline to save you the trouble:
class Program
{
static void Main(string[] args)
{
List
names.Add("Dave");
names.Add("John");
names.Add("Abe");
names.Add("Barney");
names.Add("Chuck");
string abe = names.Find(delegate(string name)
{
return name.Equals("Abe");
});
Console.WriteLine(abe);
}
}
It can get a lot fancier than that, but that is basically the gist. Declare the method inline to the code for easy stuff not needing reuse, because it saves some typing and puts the method closer to where it is being used which helps with maintenance.
C# supports delegates for invoking one or multiple methods. Delegates provide operators and methods for adding and removing target methods, and are used extensively throughout the .NET Framework for events, callbacks, asynchronous calls, and multithreading. However, you are sometimes forced to define a method just for the sake of using a delegate. In such cases, there is no need for multiple targets, and the code involved is often relatively short and simple. Anonymous methods is a new feature in C# 2.0 that lets you define an anonymous (that is, nameless) method called by a delegate.
For example, the following is a conventional SomeMethod method definition and delegate invocation:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = new SomeDelegate(SomeMethod);
del();
}
void SomeMethod() {MessageBox.Show("Hello");}
}
You can define and implement this with an anonymous method:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
MessageBox.Show("Hello");
};
del();
}
}
The anonymous method is defined in-line and not as a member method of any class. Additionally, there is no way to apply custom attributes to an anonymous method, nor can the anonymous method define generic types or add generic constraints.
You should note two interesting things about anonymous methods: the overloaded use of the delegate reserved keyword and the delegate assignment. You will see how the compiler implements an anonymous method, but it is quite clear from looking at the code that the compiler has to infer the type of the delegate used, instantiate a new delegate object of the inferred type, wrap the new delegate around the anonymous method, and assign it to the delegate used in the definition of the anonymous method (del in the previous example).
Anonymous methods can be used anywhere that a delegate type is expected. You can pass an anonymous method into any method that accepts the appropriate delegate type as a parameter:
Passing Parameters to Anonymous Methods
When defining an anonymous method with parameters, you define the parameter types and names after the delegate keyword just as if it were a conventional method. The method signature must match the definition of the delegate to which it is assigned. When invoking the delegate, you pass the parameter's values, just as with a normal delegate invocation:
class SomeClass
{
delegate void SomeDelegate(string str);
public void InvokeMethod()
{
SomeDelegate del = delegate(string str)
{
MessageBox.Show(str);
};
del("Hello");
}
}
If the anonymous method has no parameters, you can use a pair of empty parens after the delegate keyword:
class SomeClass
{
delegate void SomeDelegate();
public void InvokeMethod()
{
SomeDelegate del = delegate()
{
MessageBox.Show("Hello");
};
del();
}
}
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
LINQ_Ex-Ordering_Operators C#.NET 3.5
Ordering Operators
________________________________________
OrderBy - Simple 1
This sample prints an alphabetically sorted version of an input string array. The sample uses orderby to perform the sort.
publicvoid Linq28() {
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w
select w;
Console.WriteLine("The sorted list of words:");
foreach (var w in sortedWords) {
Console.WriteLine(w);
}
}
ResultThe sorted list of words:
apple
blueberry
cherry
________________________________________
OrderBy - Simple 2
This sample prints a version of an input string array sorted by the length each element. The sample uses orderby to sort the words.
public void Linq29() {
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w.Length
select w;
Console.WriteLine("The sorted list of words (by length):");
foreach (var w in sortedWords) {
Console.WriteLine(w);
}
}
Result
The sorted list of words (by length):
apple
cherry
blueberry
OrderBy - Simple 3
This sample prints all of the products sorted alphabetically by the product name. The sample uses orderby to perform the sort.
public void Linq30() {
List products = GetProductList();
var sortedProducts =
from p in products
orderby p.ProductName
select p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=17 ProductName=Alice Mutton Category=Meat/Poultry UnitPrice=39.0000 UnitsInStock=0
ProductID=3 ProductName=Aniseed Syrup Category=Condiments UnitPrice=10.0000 UnitsInStock=13
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=60 ProductName=Camembert Pierrot Category=Dairy Products UnitPrice=34.0000 UnitsInStock=19
ProductID=18 ProductName=Carnarvon Tigers Category=Seafood UnitPrice=62.5000 UnitsInStock=42
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=5 ProductName=Chef Anton's Gumbo Mix Category=Condiments UnitPrice=21.3500 UnitsInStock=0
ProductID=48 ProductName=Chocolade Category=Confections UnitPrice=12.7500 UnitsInStock=15
ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
ProductID=58 ProductName=Escargots de Bourgogne Category=Seafood UnitPrice=13.2500 UnitsInStock=62
ProductID=52 ProductName=Filo Mix Category=Grains/Cereals UnitPrice=7.0000 UnitsInStock=38
ProductID=71 ProductName=Flotemysost Category=Dairy Products UnitPrice=21.5000 UnitsInStock=26
ProductID=33 ProductName=Geitost Category=Dairy Products UnitPrice=2.5000 UnitsInStock=112
ProductID=15 ProductName=Genen Shouyu Category=Condiments UnitPrice=15.5000 UnitsInStock=39
ProductID=56 ProductName=Gnocchi di nonna Alice Category=Grains/Cereals UnitPrice=38.0000 UnitsInStock=21
ProductID=31 ProductName=Gorgonzola Telino Category=Dairy Products UnitPrice=12.5000 UnitsInStock=0
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=37 ProductName=Gravad lax Category=Seafood UnitPrice=26.0000 UnitsInStock=11
ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20
ProductID=69 ProductName=Gudbrandsdalsost Category=Dairy Products UnitPrice=36.0000 UnitsInStock=26
ProductID=44 ProductName=Gula Malacca Category=Condiments UnitPrice=19.4500 UnitsInStock=27
ProductID=26 ProductName=Gumbär Gummibärchen Category=Confections UnitPrice=31.2300 UnitsInStock=15
ProductID=22 ProductName=Gustaf's Knäckebröd Category=Grains/Cereals UnitPrice=21.0000 UnitsInStock=104
ProductID=10 ProductName=Ikura Category=Seafood UnitPrice=31.0000 UnitsInStock=31
ProductID=36 ProductName=Inlagd Sill Category=Seafood UnitPrice=19.0000 UnitsInStock=112
ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
ProductID=41 ProductName=Jack's New England Clam Chowder Category=Seafood UnitPrice=9.6500 UnitsInStock=85
OrderBy - Comparer
This sample prints an array of strings, sorted according to a case insensitive alphanumeric sort. The sample uses OrderBy, passing a lambda function that performs the comparison.
public class CaseInsensitiveComparer : IComparer
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
public void Linq31() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
OrderByDescending - Simple 1
This sample prints a sorted version of an array of doubles. The numbers are printed in descending order. The sample uses orderby and descending to sort the numbers from highest to lowest.
public void Linq32() {
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var sortedDoubles =
from d in doubles
orderby d descending
select d;
Console.WriteLine("The doubles from highest to lowest:");
foreach (var d in sortedDoubles) {
Console.WriteLine(d);
}
}
Result
The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7
OrderByDescending - Simple 2
This sample prints a list of products sorted by the number of units of each product that are in stock. The sample uses orderby and descending to perform the sort.
public void Linq33() {
List products = GetProductList();
var sortedProducts =
from p in products
orderby p.UnitsInStock descending
select p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=55 ProductName=Pâté chinois Category=Meat/Poultry UnitPrice=24.0000 UnitsInStock=115
ProductID=61 ProductName=Sirop d'érable Category=Condiments UnitPrice=28.5000 UnitsInStock=113
ProductID=36 ProductName=Inlagd Sill Category=Seafood UnitPrice=19.0000 UnitsInStock=112
ProductID=33 ProductName=Geitost Category=Dairy Products UnitPrice=2.5000 UnitsInStock=112
ProductID=34 ProductName=Sasquatch Ale Category=Beverages UnitPrice=14.0000 UnitsInStock=111
ProductID=22 ProductName=Gustaf's Knäckebröd Category=Grains/Cereals UnitPrice=21.0000 UnitsInStock=104
ProductID=73 ProductName=Röd Kaviar Category=Seafood UnitPrice=15.0000 UnitsInStock=101
ProductID=46 ProductName=Spegesild Category=Seafood UnitPrice=12.0000 UnitsInStock=95
ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86
ProductID=41 ProductName=Jack's New England Clam Chowder Category=Seafood UnitPrice=9.6500 UnitsInStock=85
ProductID=59 ProductName=Raclette Courdavault Category=Dairy Products UnitPrice=55.0000 UnitsInStock=79
ProductID=65 ProductName=Louisiana Fiery Hot Pepper Sauce Category=Condiments UnitPrice=21.0500 UnitsInStock=76
ProductID=25 ProductName=NuNuCa Nuá-Nougat-Creme Category=Confections UnitPrice=14.0000 UnitsInStock=76
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=50 ProductName=Valkoinen suklaa Category=Confections UnitPrice=16.2500 UnitsInStock=65
ProductID=58 ProductName=Escargots de Bourgogne Category=Seafood UnitPrice=13.2500 UnitsInStock=62
ProductID=23 ProductName=Tunnbröd Category=Grains/Cereals UnitPrice=9.0000 UnitsInStock=61
ProductID=76 ProductName=Lakkalikööri Category=Beverages UnitPrice=18.0000 UnitsInStock=57
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=67 ProductName=Laughing Lumberjack Lager Category=Beverages UnitPrice=14.0000 UnitsInStock=52
OrderByDescending - Comparer
This sample prints a sorted version of an array of strings. The output is sorted alphabetically in descending order, using a case insensitive comparision.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq34() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
ClOvEr
cHeRry
bRaNcH
BlUeBeRrY
aPPLE
AbAcUs
ThenBy - Simple
This sample uses a compound orderby to sort a list of digits first by length of their name, and then alphabetically.
publicvoid Linq35() {
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits =
from d in digits
orderby d.Length, d
select d;
Console.WriteLine("Sorted digits:");
foreach (var d in sortedDigits) {
Console.WriteLine(d);
}
}
Result
Sorted digits:
one
six
two
five
four
nine
zero
eight
seven
three
ThenBy - Comparer
This sample prints an array of string values sorted first by length, then sorted alphabetically, using a case-insentive comparison.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq36() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords =
words.OrderBy(a => a.Length)
.ThenBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
aPPLE
AbAcUs
bRaNcH
cHeRry
ClOvEr
BlUeBeRrY
ThenByDescending - Simple
This sample uses a compound orderby to sort a list of products, first by category, and then by unit price, from highest to lowest.
publicvoid Linq37() {
List products = GetProductList();var sortedProducts =
from p in products
orderby p.Category, p.UnitPrice descendingselect p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=35 ProductName=Steeleye Stout Category=Beverages UnitPrice=18.0000 UnitsInStock=20
ProductID=76 ProductName=Lakkalikööri Category=Beverages UnitPrice=18.0000 UnitsInStock=57
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=70 ProductName=Outback Lager Category=Beverages UnitPrice=15.0000 UnitsInStock=15
ProductID=34 ProductName=Sasquatch Ale Category=Beverages UnitPrice=14.0000 UnitsInStock=111
ProductID=67 ProductName=Laughing Lumberjack Lager Category=Beverages UnitPrice=14.0000 UnitsInStock=52
ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20
ProductID=63 ProductName=Vegie-spread Category=Condiments UnitPrice=43.9000 UnitsInStock=24
ProductID=8 ProductName=Northwoods Cranberry Sauce Category=Condiments UnitPrice=40.0000 UnitsInStock=6
ProductID=61 ProductName=Sirop d'érable Category=Condiments UnitPrice=28.5000 UnitsInStock=113
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=5 ProductName=Chef Anton's Gumbo Mix Category=Condiments UnitPrice=21.3500 UnitsInStock=0
ProductID=65 ProductName=Louisiana Fiery Hot Pepper Sauce Category=Condiments UnitPrice=21.0500 UnitsInStock=76
ThenByDescending - Comparer
This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive descending sort of the words in an array.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq38() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords =
words.OrderBy(a => a.Length)
.ThenByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
aPPLE
ClOvEr
cHeRry
bRaNcH
AbAcUs
BlUeBeRrY
Reverse
This sample prints a list strings from an input string array where each element has the second letter 'i'. The output list is printed in reverse order. The sample uses a query operator to gather the elements that have 'i' as the second letter and then reverses the sequence using the Reverse method.
publicvoid Linq39() {
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var reversedIDigits = (
from d in digits
where d[1] == 'i'
select d)
.Reverse();
Console.WriteLine("A backwards list of the digits with a second character of 'i':");
foreach (var d in reversedIDigits) {
Console.WriteLine(d);
}
}
Result
A backwards list of the digits with a second character of 'i':
nine
eight
six
five
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
________________________________________
OrderBy - Simple 1
This sample prints an alphabetically sorted version of an input string array. The sample uses orderby to perform the sort.
publicvoid Linq28() {
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w
select w;
Console.WriteLine("The sorted list of words:");
foreach (var w in sortedWords) {
Console.WriteLine(w);
}
}
ResultThe sorted list of words:
apple
blueberry
cherry
________________________________________
OrderBy - Simple 2
This sample prints a version of an input string array sorted by the length each element. The sample uses orderby to sort the words.
public void Linq29() {
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w.Length
select w;
Console.WriteLine("The sorted list of words (by length):");
foreach (var w in sortedWords) {
Console.WriteLine(w);
}
}
Result
The sorted list of words (by length):
apple
cherry
blueberry
OrderBy - Simple 3
This sample prints all of the products sorted alphabetically by the product name. The sample uses orderby to perform the sort.
public void Linq30() {
List products = GetProductList();
var sortedProducts =
from p in products
orderby p.ProductName
select p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=17 ProductName=Alice Mutton Category=Meat/Poultry UnitPrice=39.0000 UnitsInStock=0
ProductID=3 ProductName=Aniseed Syrup Category=Condiments UnitPrice=10.0000 UnitsInStock=13
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=60 ProductName=Camembert Pierrot Category=Dairy Products UnitPrice=34.0000 UnitsInStock=19
ProductID=18 ProductName=Carnarvon Tigers Category=Seafood UnitPrice=62.5000 UnitsInStock=42
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=5 ProductName=Chef Anton's Gumbo Mix Category=Condiments UnitPrice=21.3500 UnitsInStock=0
ProductID=48 ProductName=Chocolade Category=Confections UnitPrice=12.7500 UnitsInStock=15
ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
ProductID=58 ProductName=Escargots de Bourgogne Category=Seafood UnitPrice=13.2500 UnitsInStock=62
ProductID=52 ProductName=Filo Mix Category=Grains/Cereals UnitPrice=7.0000 UnitsInStock=38
ProductID=71 ProductName=Flotemysost Category=Dairy Products UnitPrice=21.5000 UnitsInStock=26
ProductID=33 ProductName=Geitost Category=Dairy Products UnitPrice=2.5000 UnitsInStock=112
ProductID=15 ProductName=Genen Shouyu Category=Condiments UnitPrice=15.5000 UnitsInStock=39
ProductID=56 ProductName=Gnocchi di nonna Alice Category=Grains/Cereals UnitPrice=38.0000 UnitsInStock=21
ProductID=31 ProductName=Gorgonzola Telino Category=Dairy Products UnitPrice=12.5000 UnitsInStock=0
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=37 ProductName=Gravad lax Category=Seafood UnitPrice=26.0000 UnitsInStock=11
ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20
ProductID=69 ProductName=Gudbrandsdalsost Category=Dairy Products UnitPrice=36.0000 UnitsInStock=26
ProductID=44 ProductName=Gula Malacca Category=Condiments UnitPrice=19.4500 UnitsInStock=27
ProductID=26 ProductName=Gumbär Gummibärchen Category=Confections UnitPrice=31.2300 UnitsInStock=15
ProductID=22 ProductName=Gustaf's Knäckebröd Category=Grains/Cereals UnitPrice=21.0000 UnitsInStock=104
ProductID=10 ProductName=Ikura Category=Seafood UnitPrice=31.0000 UnitsInStock=31
ProductID=36 ProductName=Inlagd Sill Category=Seafood UnitPrice=19.0000 UnitsInStock=112
ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
ProductID=41 ProductName=Jack's New England Clam Chowder Category=Seafood UnitPrice=9.6500 UnitsInStock=85
OrderBy - Comparer
This sample prints an array of strings, sorted according to a case insensitive alphanumeric sort. The sample uses OrderBy, passing a lambda function that performs the comparison.
public class CaseInsensitiveComparer : IComparer
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
public void Linq31() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
OrderByDescending - Simple 1
This sample prints a sorted version of an array of doubles. The numbers are printed in descending order. The sample uses orderby and descending to sort the numbers from highest to lowest.
public void Linq32() {
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var sortedDoubles =
from d in doubles
orderby d descending
select d;
Console.WriteLine("The doubles from highest to lowest:");
foreach (var d in sortedDoubles) {
Console.WriteLine(d);
}
}
Result
The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7
OrderByDescending - Simple 2
This sample prints a list of products sorted by the number of units of each product that are in stock. The sample uses orderby and descending to perform the sort.
public void Linq33() {
List products = GetProductList();
var sortedProducts =
from p in products
orderby p.UnitsInStock descending
select p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
ProductID=40 ProductName=Boston Crab Meat Category=Seafood UnitPrice=18.4000 UnitsInStock=123
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=55 ProductName=Pâté chinois Category=Meat/Poultry UnitPrice=24.0000 UnitsInStock=115
ProductID=61 ProductName=Sirop d'érable Category=Condiments UnitPrice=28.5000 UnitsInStock=113
ProductID=36 ProductName=Inlagd Sill Category=Seafood UnitPrice=19.0000 UnitsInStock=112
ProductID=33 ProductName=Geitost Category=Dairy Products UnitPrice=2.5000 UnitsInStock=112
ProductID=34 ProductName=Sasquatch Ale Category=Beverages UnitPrice=14.0000 UnitsInStock=111
ProductID=22 ProductName=Gustaf's Knäckebröd Category=Grains/Cereals UnitPrice=21.0000 UnitsInStock=104
ProductID=73 ProductName=Röd Kaviar Category=Seafood UnitPrice=15.0000 UnitsInStock=101
ProductID=46 ProductName=Spegesild Category=Seafood UnitPrice=12.0000 UnitsInStock=95
ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86
ProductID=41 ProductName=Jack's New England Clam Chowder Category=Seafood UnitPrice=9.6500 UnitsInStock=85
ProductID=59 ProductName=Raclette Courdavault Category=Dairy Products UnitPrice=55.0000 UnitsInStock=79
ProductID=65 ProductName=Louisiana Fiery Hot Pepper Sauce Category=Condiments UnitPrice=21.0500 UnitsInStock=76
ProductID=25 ProductName=NuNuCa Nuá-Nougat-Creme Category=Confections UnitPrice=14.0000 UnitsInStock=76
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=50 ProductName=Valkoinen suklaa Category=Confections UnitPrice=16.2500 UnitsInStock=65
ProductID=58 ProductName=Escargots de Bourgogne Category=Seafood UnitPrice=13.2500 UnitsInStock=62
ProductID=23 ProductName=Tunnbröd Category=Grains/Cereals UnitPrice=9.0000 UnitsInStock=61
ProductID=76 ProductName=Lakkalikööri Category=Beverages UnitPrice=18.0000 UnitsInStock=57
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=67 ProductName=Laughing Lumberjack Lager Category=Beverages UnitPrice=14.0000 UnitsInStock=52
OrderByDescending - Comparer
This sample prints a sorted version of an array of strings. The output is sorted alphabetically in descending order, using a case insensitive comparision.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq34() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
ClOvEr
cHeRry
bRaNcH
BlUeBeRrY
aPPLE
AbAcUs
ThenBy - Simple
This sample uses a compound orderby to sort a list of digits first by length of their name, and then alphabetically.
publicvoid Linq35() {
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits =
from d in digits
orderby d.Length, d
select d;
Console.WriteLine("Sorted digits:");
foreach (var d in sortedDigits) {
Console.WriteLine(d);
}
}
Result
Sorted digits:
one
six
two
five
four
nine
zero
eight
seven
three
ThenBy - Comparer
This sample prints an array of string values sorted first by length, then sorted alphabetically, using a case-insentive comparison.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq36() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords =
words.OrderBy(a => a.Length)
.ThenBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
aPPLE
AbAcUs
bRaNcH
cHeRry
ClOvEr
BlUeBeRrY
ThenByDescending - Simple
This sample uses a compound orderby to sort a list of products, first by category, and then by unit price, from highest to lowest.
publicvoid Linq37() {
List products = GetProductList();var sortedProducts =
from p in products
orderby p.Category, p.UnitPrice descendingselect p;
ObjectDumper.Write(sortedProducts);
}
Result
ProductID=38 ProductName=Côte de Blaye Category=Beverages UnitPrice=263.5000 UnitsInStock=17
ProductID=43 ProductName=Ipoh Coffee Category=Beverages UnitPrice=46.0000 UnitsInStock=17
ProductID=2 ProductName=Chang Category=Beverages UnitPrice=19.0000 UnitsInStock=17
ProductID=35 ProductName=Steeleye Stout Category=Beverages UnitPrice=18.0000 UnitsInStock=20
ProductID=76 ProductName=Lakkalikööri Category=Beverages UnitPrice=18.0000 UnitsInStock=57
ProductID=39 ProductName=Chartreuse verte Category=Beverages UnitPrice=18.0000 UnitsInStock=69
ProductID=1 ProductName=Chai Category=Beverages UnitPrice=18.0000 UnitsInStock=39
ProductID=70 ProductName=Outback Lager Category=Beverages UnitPrice=15.0000 UnitsInStock=15
ProductID=34 ProductName=Sasquatch Ale Category=Beverages UnitPrice=14.0000 UnitsInStock=111
ProductID=67 ProductName=Laughing Lumberjack Lager Category=Beverages UnitPrice=14.0000 UnitsInStock=52
ProductID=75 ProductName=Rhönbräu Klosterbier Category=Beverages UnitPrice=7.7500 UnitsInStock=125
ProductID=24 ProductName=Guaraná Fantástica Category=Beverages UnitPrice=4.5000 UnitsInStock=20
ProductID=63 ProductName=Vegie-spread Category=Condiments UnitPrice=43.9000 UnitsInStock=24
ProductID=8 ProductName=Northwoods Cranberry Sauce Category=Condiments UnitPrice=40.0000 UnitsInStock=6
ProductID=61 ProductName=Sirop d'érable Category=Condiments UnitPrice=28.5000 UnitsInStock=113
ProductID=6 ProductName=Grandma's Boysenberry Spread Category=Condiments UnitPrice=25.0000 UnitsInStock=120
ProductID=4 ProductName=Chef Anton's Cajun Seasoning Category=Condiments UnitPrice=22.0000 UnitsInStock=53
ProductID=5 ProductName=Chef Anton's Gumbo Mix Category=Condiments UnitPrice=21.3500 UnitsInStock=0
ProductID=65 ProductName=Louisiana Fiery Hot Pepper Sauce Category=Condiments UnitPrice=21.0500 UnitsInStock=76
ThenByDescending - Comparer
This sample uses an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive descending sort of the words in an array.
public class CaseInsensitiveComparer : IComparerspan class="qs-keyword">string>
{
publicint Compare(string x, string y)
{
returnstring.Compare(x, y, true);
}
}
publicvoid Linq38() {
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry"};
var sortedWords =
words.OrderBy(a => a.Length)
.ThenByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
Result
aPPLE
ClOvEr
cHeRry
bRaNcH
AbAcUs
BlUeBeRrY
Reverse
This sample prints a list strings from an input string array where each element has the second letter 'i'. The output list is printed in reverse order. The sample uses a query operator to gather the elements that have 'i' as the second letter and then reverses the sequence using the Reverse method.
publicvoid Linq39() {
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var reversedIDigits = (
from d in digits
where d[1] == 'i'
select d)
.Reverse();
Console.WriteLine("A backwards list of the digits with a second character of 'i':");
foreach (var d in reversedIDigits) {
Console.WriteLine(d);
}
}
Result
A backwards list of the digits with a second character of 'i':
nine
eight
six
five
We collect videos & images from online sites like youtube and some other websites which provide them. And most of the News is also gathered from other online websites. Any material downloaded or otherwise obtained through the use of the service is done at your own discretion and risk and that you will be solely responsible for any damage to your computer system or loss of data that results from the download of any such material.
If you feel that the content on the site is illegal or Privacy please contact us at srinuchalla@gmail.com and such videos, images or any Content will be removed with immediate effect.
Subscribe to:
Posts (Atom)