Wednesday, September 28, 2016

How can we maintain sessions in MVC?

Sessions can be maintained in MVC by three ways: tempdata, viewdata, and viewbag.

What is ViewStart Page in ASP.Net MVC?

This page is used to make sure common layout page will be used for multiple views. Code written in this file will be executed first when application is being loaded.

What are AJAX Helpers in ASP.Net MVC?

AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs the request asynchronously and these are extension methods of AJAXHelper class which exists in namespace - System.Web.ASP.Net MVC.

What is MVC?

MVC is an architectural pattern which separates the representation and user interaction. It’s divided into three broader sections, Model, View, and Controller. Below is how each one of them handles the task.
  • The View is responsible for the look and feel.
  • Model represents the real world object and provides data to the View.
  • The Controller is responsible for taking the end user request and loading the appropriate Model and View.

Tuesday, March 11, 2014

How do you validate email

protected void btnValidate_Click(object sender, EventArgs e)
{
bool isEmail = Regex.IsMatch(txtEmail.Text.Trim(), @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");
if (!isEmail)
{
   lblerrormsg.Text = "Enter Valid Email ID..";
   lblerrormsg.ForeColor = System.Drawing.Color.Red;
   return;
}
else
{
   lblerrormsg.Text = "Valid Email";
   lblerrormsg.ForeColor = System.Drawing.Color.Green;
}
}

Wednesday, January 22, 2014

What is master page?

Master Page is used in web application
We can say master page as a template for the other pages in our project.
For creating a constant look and feel for all our pages in web application.
It acts as a placeholder for the other pages or content.
If a user makes a request to a webpage it merges with masterpage and will provide the output .

What is publisher subscriber model? Any design pattern can be implemented for it?

It is also called as Observer design pattern.
Windows Communication Foundation (WCF) is the best exampled for this model.
The user can publish a Service and it can be consumed by many clients at the end point.
The Publisher gives the data to the clients who have subscribed to their methods.

What is Nuget?

It is Visual Studio extension and a open source project
By using Nuget we can easily add,update and remove libraries in Visual Studio Projects.
When you add or remove a library it copies/removes necessary files to your application.
It is a quick way to add reference to our application.

What is difference between a.equals(b) and a==b?

“==” --> It compares reference
"Equals" --> It compares object by VALUE.

Monday, January 28, 2013

What is the difference between the Page_Init and Page_Load events?

Page_Init

The Page_Init event is the first to occur when an ASP.NET page is executed.This is where you perform any initialization steps that you need to set up or create instances of server controls.You can't access controls in this event because there is no guarantee that they have been created yet.
The Page_Init event fires only the first time the page is loaded.
When you postback to any page, the Page_Init event doesn't fire.

Page_Load
The Page_Load event fires each time the page loads, postback or not.

This event occurs only when all the objects on the page have been created and are available for use.



Thursday, November 1, 2012

what is Marshaling?

Marshaling is a process of making an object in one process (the server) available to another process (the client). There are two ways to achieve the marshalling.

Marshal by value: The server creates a copy of the object passes the copy to the client. When a client makes a call to an object marshaled by value (MBV), the server creates an exact copy and sends that copy to the client. The client can then use the object's data and executable functionality directly within its own process or application domain without making additional calls to the server. Objects that the application accesses frequently are best remoted using MBV.

Marshal by reference: The client creates a proxy for the object and then uses the proxy to access the object. When a client makes a call to an object marshaled by reference (MBR), the .NET framework creates a proxy in the client's application domain and the client uses that proxy to access the original object on the server. Large objects that the application accesses relatively infrequently are good candidates for MBR.

What are remotable objects in .NET Remoting?

Remotable objects are the objects that can be marshaled across the application domains.
You can marshal by value, where a deep copy of the object is created and then passed to the receiver.
You can also marshal by reference, where just a reference to an existing object is passed.

When would you use .NET Remoting and when Web services?

.Net Remoting
Used for more efficient exchange of information when you control both ends of the application.

Web Services
Used for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

If I’m developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users?

use the security state maintained using a database. (Use Authentication mode as database


Which are the namespaces that are imported automatically by Visual Studio in ASP.Net?

There are 7 namespaces which are imported automatically.

 
System

System.Collections

System.IO

System.web

System.web.UI

System.web.UI.HTMLControls

System.web.UI.WebControls

What are the types of Authentication? Describe

There are 3 types of Authentication.
(a)Windows Authentication
(b) Forms Authentication
(c) Passport Authentication.


Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users.

Forms authentication allows you to create your own list/database of users and validate the identity of those users when they visit your Web site.

Passport authentication uses the Microsoft centralized authentication provider to identify users. Passport provides a way to for users to use a single identity across multiple Web applications. To use Passport authentication in your Web application, you must install the Passport SDK.

Thursday, October 25, 2012

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming

Aspect-Oriented

Aspect-oriented programming looks at how many components or pieces of a system might need to interact. The intersections of these pieces are what are important in AOP. "Crosscutting" is a slice across several units, all of which interact during some operation.
Interface-Oriented
Interface-oriented programming is a contract-based approach. Nether side of the interface cares how the other does its work, only that the two sides can communicate via an agreed-upon contract. WSDL-based web services are the prime example of this.

Object-Oriented
Object-Oriented programming is based on abstraction, encapsulation (data hiding), polymorphism and inheritance. Classes implement these concepts to build objects controlling or implementing a system.

Abstraction allows loose coupling between components by providing a layer between objects so that one object isn't concerned with how the other implements its business rules. (Interfaces, layers) Great stuff when you want to isolate parts of the system so they can be swapped out without killing the rest of the sytsem.

Encapsulation allows abstraction to work by hiding details of a class's implementation from calling classes. (Public vs. private fields)

Inheritance enables base (parent) classes to have common functionality defined in it and passed down to child classes. A Shape class might have a field for color which is inherited by child classes of Square or Circle type.

Polymorphism enables implementation of same-named public fields, allowing different classes to perform different actions on the same call - rendering a Square or Circle object differently in a graphic program, even though they might both be subclassed from a base Shape class. (Overriding)

What are trace switches?

Trace switches helps us to control and govern the tracing behavior of a project. There are two types of trace switches ‘BooleanSwitch’ and ‘TraceSwitch’. BooleanSwitch, as the name says, is a kind of on/off switch which can be either enabled (true) or disabled (false).

‘TraceSwitch’ on the other hand offers more options rather than simple true/false like ‘BooleanSwitch’. Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a switch to a particular level, it includes all levels from the indicated level down. For example, if you set a TraceSwitch’s Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to TraceLevel.Warning, will be taken in to account.

Below are the various levels in ‘TraceSwitch’ object.
 
Off a Outputs no messages to Trace Listeners

Error a Outputs only error messages to Trace Listeners

Warning a Outputs error and warning messages to Trace Listeners

Info a Outputs informational, warning and error messages to Trace Listeners

Verbose a Outputs all messages to Trace Listeners

 
 
 
 
 
 
 
 

What is the main difference between Gridlayout and FlowLayout ?

GridLayout provides absolute positioning for controls placed on the page. Developers that have their roots in rich-client development environments like Visual Basic will find it easier to develop their pages using absolute positioning, because they can place items exactly where they want them. On the other hand, FlowLayout positions items down the page like traditional HTML. Experienced Web developers favor this approach because it results in pages that are compatible with a wider range of browsers.

If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in Flow layout you can see more of using HTML table to position elements which is compatible with wide range of browsers.



What is the difference between “Web farms” and “Web garden”?

Web farm
Used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic which decides which web server from the farm handles the request. For instance we have two servers “Server1″ and “Server2″ which have the same configuration and content. So there is a special switch which stands in between these two servers and the users and routes the request accordingly.

A router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. So for request1 it route’s server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24×7 uptime.

The routing logic can be a number of different options:

Round-robin: Each node gets a request sent to it “in turn”. So, server1 gets a request, then server2 again, then server1, then server2 again.

Least Active Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes

Fastest Reply Whichever node replies faster is the one that gets new requests. This is also a good option – especially if there are nodes that might not be “equal” in performance. If one performs better than the other, then send more requests there rather than which is moving slowly?

Web Garden

All requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e. without web garden we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.

But when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU.
In short we can define a model in which multiple processes run on multiple CPUs in a single server machine are known as a Web garden.



If cookies are not enabled at browser end does form Authentication work?

No,it does not work

ASP used STA threading model, what is the threading model used for ASP.NET ?

ASP.NET uses MTA threading model

Tuesday, October 23, 2012

What are the benefits of service orientation?

[1] Isolation : Changing the internals of one service does not force changes, rebuilding or restarting of other services.

[2] Behavior is separated from constraints : Relocating, outsourcing or restricting a service requires changes only in the policy but not to the service itself.

[3] Location independent : Whether a service is on the same machine or different, it can be accessed in the similar manner.

[4] Scale invariant : Services scale in all the directions. Let's take an example a service can be scaled out by fronting it with a router service that distributes traffic among a farm of services.

[5] Transport/protocol/format neutral : The communication details between parties are flexible but not fixed.

[6] Time independent : Services can make use of queue-based communication, when they do not have to be online at the same time to interact.

[7] Platform and implementation independent : A service need not know anything about another service's execution environment to interact with it.

[8] Address agnostic : Services can employ a discovery mechanism to locate each other without any prior notion about where they reside.

Set Operators in Linq

There are mainly five types of Set Operators in Linq.


1. Distinct

2. Concat

3. Union

4. Intersect

5. Except

1.Distinct
public void DistinctFunction()
{
int[] seq1 = { 1, 2, 3, 3, 4, 2, 5, 4, 5, 2, 1 };
var distinctValues = seq1.Distinct();
Console.WriteLine("Distinct Values in the array : ");
foreach (var n in distinctValues)
{
Console.WriteLine(n);
}
}
OutputDistinct Values in the array :
1
2
3
4
5



2.Concat
public void ConcatFunction()
{
int[] seq1 = { 1, 2, 3 }, seq2 = { 3, 4, 5 };
var concatValues = seq1.Concat(seq2);
Console.WriteLine("Concatenation of two array : ");
foreach (var n in concatValues)
{
Console.WriteLine(n); }
 }
OutputConcatenation of two array :
1
2
3
3
4
5

3.Union

public void UnionFunction()
{
    int[] seq1 = { 1, 2, 3 }, seq2 = { 3, 4, 5 };
 
    var unionValues = seq1.Union(seq2);
 
    Console.WriteLine("Union of two array : ");
    foreach (var n in unionValues)
    {
        Console.WriteLine(n);
    }
}

Output

Union of two array :
1
2
3
4
5


4.Intersect
public void IntersectFunction() {    int[] seq1 = { 1, 2, 3 }, seq2 = { 3, 4, 5 };    var unionValues = seq1.Intersect(seq2);    Console.WriteLine("Intersection of two array : ");    f oreach (var n in unionValues)    {      Console.WriteLine(n);    } } OutputIntersection of two array :  3   5.Except public void ExceptFunction() {  int[] seq1 = { 1, 2, 3 }, seq2 = { 3, 4, 5 };  var unionValues = seq1.Except(seq2); Console.WriteLine("Applying Except Function on two arrays : "); foreach (var n in unionValues) {  Console.WriteLine(n);  } } OutputApplying Except Function on two arrays :  1  2






Ordering Operators in Linq

There are mainly five types of Ordering Operators in Linq.


1. OrderBy

2. OrderByDescending

3. ThenBy

4. ThenByDescending

5. Reverse



1.OrderBy
public void OrderBy()
{
    string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
 
    var sortedNames = names.OrderBy (s => s);
    var sortedNamesLengthWise = names.OrderBy (s => s.Length);
 
    Console.WriteLine("Sorted List: ");
    foreach (var n in sortedNames)
    {
        Console.WriteLine(n);
    }
    Console.WriteLine("Sorted List LengthWise: ");
    foreach (var nlw in sortedNamesLengthWise)
    {
        Console.WriteLine(nlw);
    }
}

OutPut

Sorted List:
Dick
Harry
Jay
Mary
Tom


2.OrderByDescending
public void OrderByDescending()
{
    string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
 
    var sortedNames = names.OrderByDescending(s => s);
    var sortedNamesLengthWise = names.OrderByDescending(s => s.Length);
 
    Console.WriteLine("Sorted Descending : ");
    foreach (var n in sortedNames)
    {
        Console.WriteLine(n);
    }
    Console.WriteLine("Sorted Descending LengthWise: ");
    foreach (var nlw in sortedNamesLengthWise)
    {
        Console.WriteLine(nlw);
    }
}

OutPut

Sorted List:
Tom
Mary
Jay
Harry
Dick
Sorted List LengthWise:
Harry
Dick
Mary
Tom
Jay

3.ThenBy
public void ThenBy()
{
    string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
 
    var sortedNames = names.OrderBy(s => s.Length).ThenBy (s => s);
    var sortedNamesLengthWise = names.OrderBy (s => s.Length).ThenBy (s => s[1]).ThenBy (s => s[0]);
 
    Console.WriteLine("Sorting By Length then alphabetically : ");
    foreach (var n in sortedNames)
    {
        Console.WriteLine(n);
    }
    Console.WriteLine("By length, then second character, then first character : ");
    foreach (var nlw in sortedNamesLengthWise)
    {
        Console.WriteLine(nlw);
    }
}

OutPut

Sorting By Length then alphabetically :
Jay
Tom
Dick
Mary
Harry

By length, then second character, then first character :

Jay
Tom
Mary
Dick
Harry

4.ThenByDescending

public void ThenByDescending()
{
 string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
var sortedNames = names.OrderBy(s => s.Length).ThenByDescending(s => s);
Console.WriteLine("Sorting By Length then alphabetically in descending order : ");
foreach (var n in sortedNames)
 {
 Console.WriteLine(n);
 }
}
OutPutSorting By Length then alphabetically in descending order :
Tom
Jay
Mary
Dick
Harry

5.Reverse

public void Reverse()
{
 string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
var reverse = names.Reverse();
Console.WriteLine("Reversing the collection : ");
foreach (var r in reverse)
 {
   Console.WriteLine(r);
  }
}
OutPutReversing the collection :
Jay
Mary
Harry
Dick
Tom







Which is the process of tying a control of the application to any column or row of the DataTable so that the data stored in the database table can be displayed in that control?


Data Binding

Which is considered as an object on which data retrieved from the database is stored?

Dataset

How do you catch all exceptions?

Using a catch statement that specifies no parameters

What does DOM stands for?


Document Object Model

what is ACID?

A-Atomocity

C-Consistency

I-Isolation

D-Durability

Observer pattern defines.......?

One to Many Relation

Network Cable lines on----------layer


Physical Layer

DBCC stands for............

Database Console Commands

Is it possible to access one aspx page's view state data into another aspx page? If so, How?


possible through cross page post back

What is the purpose of machine key in asp.net?

To encrypt forms authentication tickets and to encrypt ViewState

Write the sql query for entering a comma-separated string into a table

select data from dbo.split('string1.string2,string3', ',')

How many types of SQL Replication are there

3 Types

What is SQL Replication?

Replication is a set of technologies for copying and distributing data and database objects from one database to another and then synchronizing between databases to maintain consistency

What is Code Name of Sql Server 2011..?

Denali

What is the Code Name of Sql Server 2005..?

Yukon

Whats the purpose of Linked Server in microsoft sql server?

 Remote server access

Thursday, October 4, 2012

What is Service Broker?

Service Broker is a message-queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable.




What are the basic functions for master, msdb, model, tempdb and resource databases?

The master database holds information for all databases located on the SQL Server instance and is theglue that holds the engine together. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care.


The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.

The tempdb holds temporary objects such as global and local temporary tables and stored procedures.

The model is essentially a template database used in the creation of any new user database created in the instance.

The resoure Database is a read-only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.

Wednesday, October 3, 2012

Value Type Vs Reference Type

VALUE TYPE
-
Value type derives from System.ValueType which derives from System.Object
-Value types directly contains their values
-
When you copy from one value type variable to another it copies all the data. So if you change one variable it does not affect another variable.
-Value Type are stored in Stack.
-
Value type has default value. For eg: int i; So i has default value of 0.
-
Runtime can create, delete, remove the value type quickly. So no garbage collection needed.
-
It does not contain null values unless you can make it as nullable type.
-There are three categories in value type
1Built-in Type
- Integral type (sbyte, byte, char, short, ushort, int, uint, long, ulong)
- Floating point type (float, double)
- Decimal type (decimal)
2Bool
3Struct,Enum
REFERENCE TYPE
-
Reference Type is derive from System.Object
-
Reference Type variable stores address of their data.
-
It has the pointer to points to the data.
-
When you copy from one reference type variable to another it copies only the reference. So if you change one variable it will affect another.
-
Reference types are stored in the Heap.
-
Reference types always has null values.
-
The memory used by the reference type will handled by Garbage Collection.
-
Class, Interface, Object, String, Arrays, Stream, Exception, Delegate, StringBuilder are the reference type.

TYPES IN C#

C# is a strongly typed language. Each variable and constants has type. A type has following information:


- It specifies the storage space that the type occupies.

- The location of the memory of that type occupies.

- The base type that it inherits from.



There are two built in types in C#.


1. Value Type

2. Reference Type.



 

VALUE TYPE



- Value type derives from System.ValueType which derives from System.Object.

- Value types directly contains their values.

- When you copy from one value type variable to another it copies all the data. So if you change one variable it does not affect another variable.

- Value Type are stored in Stack.

- Value type has default value. For eg: int i; So i has default value of 0.

- Runtime can create, delete, remove the value type quickly. So no garbage collection needed.

- It does not contain null values unless you can make it as nullable type.



There are three categories in value type.


1. Built in Type

- Integral type (sbyte, byte, char, short, ushort, int, uint, long, ulong)

- Floating point type (float, double)

- Decimal type (decimal)

2. Bool

2. Struct , Enum





REFERENCE TYPE


- Reference Type is derive from System.Object

- Reference Type variable stores address of their data.

- It has the pointer to points to the data.

- When you copy from one reference type variable to another it copies only the reference. So if you change one variable it will affect another

- Reference types are stored in the Heap.

- Reference types always has null values.

- The memory used by the reference type will handled by Garbage Collection

- Class, Interface, Object, String, Arrays, Stream, Exception, Delegate, StringBuilder are the reference type.



Wednesday, May 30, 2012

What is the difference between CLR and DLR in C#?

The Common Language Runtime (CLR) is the core set of services offered by .NET – a type system, JIT, a garbage collector, &c. Those are available to all .NET languages, hence the "Common" part.



The Dynamic Language Runtime (DLR) builds atop of this and offers services for dynamic languages: dynamic types, dynamic method dispatch, code generation, &c. The idea is to make those things uniform and share them among dynamic languages so that they work predictably and similar, just like things on the CLR are across all languages too.

In a way those are comparable, a "normal" language on .NET uses the CLR, a dynamic language should use the DLR, but will use the CLR as well. They are basic sets of functionality that the designers considered to be good when they are common across languages. IronPython and IronRuby were implemented on top of the DLR, as is C# 4's dynamic feature.









what is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.




What is this C# syntax called?

SomeFunction (() => {


DoSomething (); });

What is the name of this syntax (the () => ...)?

Answer: This is called Lambda Expression (parameterless lambda expression)

What does mscorlib stand for?

Microsoft Common Object Runtime Library

Wednesday, April 4, 2012

Why CLR called Virtual Execution System (VES) ??

The VES (usually referred to as the runtime) is the environment in which the CIL byte code is executed. The VES reads the byte code generated by the C# compiler and uses something called a Just in Time (JIT) compiler to compile the byte code down to the native machine code of the processor on which it is running. While this code is executing it does so in conjunction with a runtime agent which essentially manages the execution process. As a result, this executing code is known as managed code and the process handles issues such as garbage collection (to handle memory allocation and deallocation), memory access and type safety to ensure that the code does not do anything it is not supposed to do.

A term that is often used in connection with the VES is the Common Language Runtime (CLR). The CLR is officially the name given to Microsoft's implementation of the VES component of the CLI specification.

It is worth noting that the JIT process can introduce a startup delay on execution of an application. One option available with .Net to avoid this problem is to pre-compile CLI byte code down to native machine code using the NGEN compiler. Because the NGEN compilation must take place on the target processor architecture this is step is often performed at the point that the application in question is installed by the user.

Thursday, March 29, 2012

Do Enum Supports Inharitence

Enums do not supports inheritance since they are value type and therefor are sealed.

Do Enum Supports Inharitence

Enums do not supports inheritance since they are value type and therefor are sealed.

Special folders in ASP.Net

With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.Net by introducing a suite of new features and functionalities.

ASP.Net defines several special folders. When a new Web site is created the App_Data folder is created by default; it can contain a SQL Server 2005 Express Edition database, another database, or an XML data file that will be used in the Web site.

These folders are also data directories.

App_Browsers folder - Contains browser definitions (.browser files) files that ASP.Net uses to identify individual browsers and determine their capabilities. Browser definition files are used to determine the client browser capabilities. These files are often used to help support mobile application.

App_Data folder - App_Data folder is used to store file that can be used as database files (.mdf, .mdb and xml files). The user account that is used to run the application (for example, the local ASPNET account) has permissions to read, write, and create files in this folder. Various ASP.NET application features, such as the providers for membership and roles, as well as the Web Site Administration Tool, are configured to work with the App_Data folder specifically.

Bin folder - Contains compiled assemblies (.dll files), for code that you want to reference in your application, as in earlier versions of Visual Studio. Any classes represented by code in the Bin folder are automatically referenced in your Web site.

App_LocalResources folder - Contains .resx files that are bound to a specific page. You can define multiple .resx files for each page, each .resx file representing a different language or language/culture combination.

App_GlobalResource folder - Like the App_LocalResources folders, but contains .resx files that are not bound to a specific page. Resource values in .resx files in the App_GlobalResource folders can be accessed programmatically from application code.

App_Code folder - Contains source code files. The code is compiled as part of your application and is referenced automatically. The App_Code folder works much like the Bin folder, except that you can put source code in it instead of compiled code. While you are working in Visual Web Developer, the source code in the App_Code folder is compiled dynamically so that IntelliSense can reference any classes defined in the files.

App_Themes folder - Contain sub-folders that each defines a specific theme or look and feel for you Web site. Sub-folders consist of a collection of files (such as .skin, .css and image files) that define the appearance of ASP.Net Web pages and controls.

App_WebReferences folder - Contains files used to create a reference to a Web service (in the same project or external to the project), including .disco, .xsd, .discomap and .wsdl files.

Note: Special folders can be added to a Web site from the Visual Studio menu system. Typically this involves right-clicking the Web Application project and selecting Add ASP.NET folder.

Design Patterns which are used in .NET Framework base class library

As we know that .net is an OOPs based language so we can easily implement design patterns in our projects but some times it comes to mind that, which all design patters microsoft .NET Base Class Library is using internally.

Observer Pattern:
This observer design pattern is used for delegates and events.

Iterator Pattern:
Iterator design pattern used in foreach in C# and For Each in Visual Basic .NET

Decorator Pattern:
System.IO.Stream :Any useful executable program involves either reading input, writing output, or both. Regardless of the source of the data being read or written, it can be treated abstractly as a sequence of bytes. .NET uses the System.IO.Stream class to represent this abstraction.

CryptoStream :System.Security.Cryptography.CryptoStream to encrypt and decrypt Streams on the fly, without the rest of the application needing to know anything more than the fact that it is a Stream.

Adapter Pattern:
By allowing managed classes and COM components to interact despite their interface differences, RCWs are an example of the Adapter pattern. The Adapter pattern lets you adapt one interface to another. COM doesn't understand the System.String class, so the RCW adapts it to something that it can understand. Even though you can't change how a legacy component works, you can still interact with it. Adapters are frequently used like this.

Factory Pattern:
System.Convert: System.Convert class contains a host of static methods that work like factory design pattern.

System.Net.WebRequest:
This class is used to request and receive a response from a resource on the Internet.FTP, HTTP, and file system requests are supported by default. To create a request, call the Create method and pass in a URI. The Create method itself determines the appropriate protocol for the request and returns the appropriate subclass of WebRequest: HttpWebRequest, FtpWebRequest, or FileWebRequest. The caller doesn't need to know the specifics of each protocol, only how to invoke the factory and work with the WebRequest that gets returned. If the URI changes from an HTTP address to an FTP address, the code won't have to change at all.

Strategy Pattern:
Both Array and ArrayList provide the capability to sort the objects contained in the collection via the Sort method. Strategy Design Pattern is used with Array and Arraylist to sort them using different strategy without changing any client code using IComparable interface

Composite Pattern in ASP.NET:
ASP.NET has lots of controls. A control may be a simple single item like a Literal, or it could be composed of a complex collection of child controls, like a DataGrid is. Regardless, calling the Render method on either of these controls should still perform the same intuitive function.

Because the domain of controls is so diverse, there are several intermediate derived classes like WebControl and BaseDataList that serve as base classes for other controls. Though these classes expose additional properties and methods, they still retain the child management functions and core operations inherited from Control. In fact, the use of the Composite pattern helps to hide their complexity, if desired. Regardless of whether a control is a Literal or a DataGrid, the use of Composite means you can just call Render and everything will sort itself out.

Template Method Pattern:
custom controls are example of Template Method Pattern.

Tuesday, January 24, 2012

What is lazy loading?

The "Lazy Loading" design pattern actually equips the developer with the art of providing data only when a property is called for. In other words, it is a on-demand loading. It is an efficient technique to improve performance.

What is delay signing?

Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key.This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

Monday, November 28, 2011

Difference between Association, Aggregation and Inheritance relationships.

An Association is a relationship between similar objects or objects with common structures.

Example:
An employee object is associated with manager object.
Aggregation is “a part of” relationship.
Example:
A student object is a part of College object.
Inheritance is a “is a “relationship where one or more classes are derived from a base class. The derived class has the base class plus its own characteristics.
Example:
French_Student class can be a derived class of student class.

Features of Static/Shared classes.

Static classes are used when any change made to an object should not affect the data and functions of the class. They can be used to create data and functions without the need of an instance.

Following are features of Static/Shared classes:-

-They can not be instantiated. By default a object is created on the first method call to that object.
-Static/Shared classes can not be inherited.
-Static/Shared classes can have only static members.
-Static/Shared classes can have only static constructor.

Explain the concepts and capabilities of cross page posting

Cross Page Posting: It refers to the scenario where on event of some controls posts from one page to another instead of a normal postback. Normal postback is when for e.g. a button (or any control that postbacks) is clicked and web page is submits the page back to itself which means a return trip. In Cross page posting, on click of a button there would be no return trip.

Cross-page posting is done at the control level. It is possible to create a page that posts to different pages depending on what button the user clicks on. It is handled by done by changing the postbackurl property of the controls.

What are Extender provider components? Explain how to use an extender provider in the project.

An extender provider is a component that provides properties to other components.

Implementing an extender provider:

•Use the ProvidePropertyAttribute, which specifies the name of the property that an implementer of IExtenderProvider provides to other components, attribute to specify the property provided by your extender provider.
•Implement the provided property.
•Track which controls receive your provided property.
•Implement the IExtenderProvider, which defines the interface for extending properties to other components in a containe, interface.

What is the GAC? What problem does it solve?

Global Assembly Cache (GAC):

Any system that has the CLR (common language runtime) installed, has a machine-wide code cache known as GAC.

Assemblies deployed in the global assembly cache need to have a strong name.

The Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.

What are implementation inheritance and interface inheritance?

Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.

Interface inheritance is when a class inherits only the signatures of the functions from another class.

What is the use of System.Environment class in C#.NET?

The System.Environment class can be used to retrieve information like:
command-line arguments
the exit code
environment variable settings
contents of the call stack
time since last system boot
the version of the common language runtime.

What is the difference between const and readonly in C#.NET?

The read only can be modified by the class it is contained in. However, the const cannot be modified. It needs to be instantiated only at the compile time.

What is strong-typing versus weak-typing? Which is preferred? Why?

In weak typing, it is allowed to define a block of memory as another type (casting).
Languages like C, C++ are weakly and statically typed.
Languages like Perl and PHP are weakly typed as you can add numbers to strings and they will implicitly coerce it.

Languages like Java, C# and Python are strongly typed. In these the type conversion needs to be explicitly handled.

For scripts we use weak typing.

In big programs, we use strong typing which can reduce errors at compile time

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Interface oriented approach compels to develop the software based on the contract.
Object oriented approach emphasizes on its aspects like:
Abstraction
Encapsulation
Inheritance
Polymorphism
Cross cutting concerns cannot be implemented in object oriented programming.
That’s not the case with aspect-oriented. However, there is a risk of system failure in this situation.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

•XML Web services are more restricted than objects exposed over .NET Remoting.
•XML Web services support open standards that target cross-platform use.
•XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
•XML Web services support only SOAP message formatting, which uses larger XML text messages.
•Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
•XML Web services are designed for use between companies and organizations.
•XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
•Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET

How to add a ReadOnly property in C#.NET?

Properties can be made read-only by having only a get accessor in the implementation.

public class X
{
public X(int id)
{
x_id = id;
}
public int ID
{
get
{
return x_id;
}
}
}

How to prevent a class from being inherited in C#.NET?

The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.

Explain the use of virtual, sealed, override, and abstract.

The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.

The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.

Explain the use of virtual, sealed, override, and abstract.

The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.

The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.

An abstract virtual method means that the definition of the method needs to be given in the derived class.

How does the XmlSerializer work? What ACL permissions does a process using it require?

The XmlSerializer constructor generates a pair of classes derived from XmlSerializationReader and XmlSerializationWriter by analysis of the classes using reflection.

Temporary C# files are created and compiled into a temporary assembly and then loaded into a process.

The XmlSerializer caches the temporary assemblies on a per-type basis as the code generated like this is expensive. This cached assembly is used after a class is created

Therefore the XmlSerialize requires full permissions on the temporary directory which is a user profile temp directory for windows applications

Explain the difference between Server.Transfer and response.Redirect.

Redirect and Transfer both cause a new page to be processed. The difference lies in the way the interaction between the client and the server occurs.

Response.Redirect messages the client browser asking it to request for another page.
e.g. if a browser is on page A which has a Response.Redirect, then it asked to request for another page B by the server. When the client browser requests for it, then it is provided with the requested page B.

With Server.Transfer, the browser is not requested to ask for another page. Instead it is directly provided with the page B. In this scenario, the browser address bar continues to show the address of the previous URL.

Navigation methods in ASP.NET

Hyperlink control
Response.Redirect method
Server.Transfer method
Server.Execute method
Window.Open method

Hyperlink control
This is server control use for navigation to another page specified in the NavigateURL property. Hyperlink control doesn’t expose any server side event.

Response.Redirect method
This method is used to navigate to another page from code. You can use this method to navigate from a Linkbutton or ImageButton control.
For example

Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Response.Redirect("Page2.aspx")
End Sub

Server.Transfer method
This method can be used only with .aspx file. It allows to retain some information between the requests when its preserveForm argument is set to true.

Server.Execute method
Like Server.Transfer, this method is also used with .aspx file only. This method enables new page execution while still displaying the current web form.

Window.Open method
Display a page in a new browser window on the client.

What are circular references? Explain how garbage collection deals with circular references.

A circular reference is a run-around wherein the 2 or more resources are interdependent on each other rendering the entire chain of references to be unusable.

There are quite a few ways of handling the problem of detecting and collecting cyclic references.

1. A system may explicitly forbid reference cycles.
2. Systems at times ignore cycles when they have short lives and a small amount of cyclic garbage. In this case a methodology of avoiding cyclic data structures is applied at the expense of efficiency.
3. Another solution is to periodically use a tracing garbage collector cycles.
Other types of methods to deal with cyclic references are:
•Weighted reference counting
•Indirect reference counting

What is Finalize method in .NET?

Object.Finalize method in .NET is typically used to clean and release unmanaged resources like OS files, window etc. Even though Garbage collector in .NET has the ability to determine the life time of such objects, however, with no knowledge how to clean them. The Finalize method allows an object to clean up such unmanaged resources when the garbage collector wishes to reclaim the memory. However, Finalize method should be avoided until necessary as it affects the performance because reclaiming the memory used by objects with Finalize methods requires at least two garbage collections.

What is Finalize method in .NET?

Object.Finalize method in .NET is typically used to clean and release unmanaged resources like OS files, window etc. Even though Garbage collector in .NET has the ability to determine the life time of such objects, however, with no knowledge how to clean them. The Finalize method allows an object to clean up such unmanaged resources when the garbage collector wishes to reclaim the memory. However, Finalize method should be avoided until necessary as it affects the performance because reclaiming the memory used by objects with Finalize methods requires at least two garbage collections.

Explain the concepts of CTS and CLS(Common Language Specification).

CTS
When different languages are integrated and want to communicate, it is certain that the languages have their own data types and different declaration styles. CTS define how these different variables are declared and used in run time. E.g. VB offers an Integer data type while C++ offers long data type. Using CTS, these data types are converted to System32 which itself a data type of CLS.

CLS
Any language(s) that intend to use the Common Language Infrastructure needs to communicate with other CLS-Compliant language. This communication is based on set of rules laid by CLS. These rules define a subset of CTS.

Explain different properties of Object Oriented Systems.

An object oriented system revolves around a Class and objects. A class is used to describe characteristics of any entity of the real world. An object is a pattern of the class. An actual object created at runtime is called as an instance. A class, apart from characteristics has some functions to perform called as methods. For.e.g A class named "Food" has attributes like 'price', 'quantity'. "Food" class has methods like Serve_food(), bill_food().

•Objects in Object Oriented Systems interact through messages.
Inheritance:- The main class or the root class is called as a Base Class. Any class which is expected to have ALL properties of the base class along with its own is called as a Derived class. The process of deriving such a class is Derived class. For the "Food" class, a Derived class can be "Class Chinesefood".
Abstraction:- Abstraction is creating models or classes of some broad concept. Abstraction can be achieved through Inheritance or even Composition.
Encapsulation:- Encapsulation is a collection of functions of a class and object. The "Food" class is an encapsulated form. It is achieved by specifying which class can use which members (private, public, protected) of an object.
Polymorphism:- Polymorphism means existing in different forms. Inheritance is an example of Polymorphism. A base class exists in different forms as derived classes. Operator overloading is an example of Polymorphism in which an operator can be applied in different situations.

Difference between abstract classes and interfaces.

When a derived class is inherited from an Abstract class, no other class can be extended then. Interface can be used in any scenario. Abstract class contains abstract method, i.e. actual implementation logic. On the other hand, interfaces have no implementation logic. Every method in an interface must be abstract. This is not necessary in case of abstract classes.

Abstract class in NET

An Abstract class is only used for inheritance. This means it acts as a base class for its derived classes. One cannot use it to create objects. When a class is declared as “Abstract”, it can only be inherited and not instantiated. MustInherit Keyword can be used to declare a class as abstract.
Abstract classes can also specify abstract members.

Abstract class in NET

An Abstract class is only used for inheritance. This means it acts as a base class for its derived classes. One cannot use it to create objects. When a class is declared as “Abstract”, it can only be inherited and not instantiated. MustInherit Keyword can be used to declare a class as abstract.
Abstract classes can also specify abstract members.

How to achieve polymorphism in C#.NET?

Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.

It can be achieved in the following ways:
Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.

To completely take over a class member from a base class, the base class has to declare that member as virtual.

What is QueryString? Benefits and limitations of using querystring.

Advantages:

a. Supported by all the browsers
b. No extra effort is needed to code.
c. Easy to use.

Disadvantages:


a. All the attributes and values are visible to the end user. Therefore, they are not secure.
b. There is a limit to URL length of 255 characters.

Explain when should we use StringBuilder class instead of the String class.

Whenever any of the methods of String class is used to modify the string, a new object is created and memory is allocated to that object. If there are repeated modifications on the string, the performance can get hampered making it costly. Whereas, the StringBuilder class can be used for modifications over and over again without creating a new object. So one situation where a StringBuilder class might be of use is, if we are manipulation string in a loop.

Explain when should we use StringBuilder class instead of the String class.

Whenever any of the methods of String class is used to modify the string, a new object is created and memory is allocated to that object. If there are repeated modifications on the string, the performance can get hampered making it costly. Whereas, the StringBuilder class can be used for modifications over and over again without creating a new object. So one situation where a StringBuilder class might be of use is, if we are manipulation string in a loop.

What are code groups in .NET?

Code group is a logical grouping of code that follows some given conditions for membership. Code groups have some permission sets that are checked before to grant the membership of the code group.

What are code groups in .NET?

Code group is a logical grouping of code that follows some given conditions for membership. Code groups have some permission sets that are checked before to grant the membership of the code group.

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred.

Benefit of Primary Interop Assembly (PIA)

A primary interop assembly contains type definitions (as metadata) of types implemented with COM.

Only a single PIA can exist, which needs to be signed with a strong name by the publisher of the COM type library.

One PIA can wrap multiple versions of the same type library.

A COM type library imported as an assembly can be a PIA only if it has been signed and published by the same publisher.

Therefore, only the publisher of a type library can produce a true PIA, that can be considered as the unit of an official type definition for interoperating with the underlying COM types.

Explain why we use XML Serialization

Serialization allows persisting objects. XML serializations stores objects in form of XML which has become a storage standard. The main advantage with XML is that it is platform, language independent. Any other software can practically read XML and write data, hence interoperability is an added advantage with XML serialization. XML also has the power to show relationships between various objects which is also advantageous when performing serialization of objects along with other related objects.

Explain why we use XML Serialization

Serialization allows persisting objects. XML serializations stores objects in form of XML which has become a storage standard. The main advantage with XML is that it is platform, language independent. Any other software can practically read XML and write data, hence interoperability is an added advantage with XML serialization. XML also has the power to show relationships between various objects which is also advantageous when performing serialization of objects along with other related objects.

Why is an object pool required?

The request for the creation of an object is served by allocating an object from the pool.

This reduces the overhead of creating and re-creating objects each time an object creation is required.

To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

How does object pooling and connection pooling differ?

In Object pooling, you can control the number of connections.

In connection pooling, you can control the maximum number reached.

When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.

In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy

What is an object pool in .NET?

An object pool is a container of objects that holds a list of other objects that are ready to be used.

It keeps track of:

•Objects that are currently in use
•The number of objects the pool holds
•Whether this number should be increased
The request for the creation of an object is served by allocating an object from the pool.

This reduces the overhead of creating and re-creating objects each time an object creation is required.

What is the JIT? What is NGEN? What are limitations and benefits of each?

Just In Time Compiler compiles the code just before it is run.
Due to this the code takes longer time to start however it is more efficient compilation since the compiler has more information about the target system.

NGen is used to pre-just in time code which yields faster startup time but the compiler produces less efficient code because it has less information.

Explain the use of static members with example using C#.NET.

Static members are not associated with a particular instance of any class.
They need to be qualified with the class name to be called.
Since they are not associated with object instances, they do not have access to non-static members.
i.e.: "this" cannot be used, which represents the current object instance.

What are generics in C#.NET?

Generic types to maximize code reuse, type safety, and performance.
They can be used to create collection classes.
Generic collection classes in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace.

The classes and the methods can treat the values of different types uniformly with the use if generics.

The usage of generics is advantageous as:

•They facilitate type safety
•They facilitate improved performance
•They facilitate reduced code
•They promote the usage of parameterized types
•The CLR compiles and stores information related to the generic types when they are instantiated. (The generic type instance refers to the location in memory of the reference type to which it is bound for all the instances of the generic type.)

Define most commonly used interfaces in .Net Framework

IComparable: It is implemented by types for ordering and sorting. The implementation types must implement one single method i.e. CompareTo.

IDisposable:This is implemented to manage release of unmanaged resources from memory. The garbage collector acts on its own and hence the Dispose method is used to call the garbage collector to free unmanaged resources through this interface.

IConvertible: It is implemented to convert value of the implementing type into another CLR compatible type. If the conversion fails then an invalidcastexception is thrown.

ICloneable: Allows creating objects of a class having same values as another instance using the Clone method.

IEquatable:Implemented to create type specific methods to know the equality between various objects.

IFormattable:Implemented to convert object into string representations. Objects can define their own specific string representation through this interface’s ToString() method.

How do you create a resource-only assembly?

Resources are nonexecutable data in an application and the data can be updated without recompiling application. Resource assemblies can be created as follows:
Add resource files to an empty project.
Built the project.
The resource will get compiled into assembly.

What does an assembly contain?

An assembly contains following information:
Assembly manifest: Information about the assembly.
Type metadata: Information about the types.
IL Code
Resource files.

An assembly manifest contains the following information:

Identity of the assembly
Types and resources
Files
Security permissions

Define .Net Assembly.

It is a primary unit of deployment in a Microsoft .NET Framework application. It is called as building block of an application which provides all required execution information to common language runtime.

An assembly perform following functions:
It contains IL code that gets executed by common language runtime.
It forms a security boundary.
An assembly is the unit at which permissions are requested and granted.
It ensures type safety by establishing name scope for types at the runtime.
It contains version information.
It allows side-by-side execution of multiple versions of same assembly.

Assemblies can be static or dynamic.
Static assemblies are created when the program is compiled using .Net compiler. It exists as PE file either in .exe or .dll. However, dynamic assemblies are created at runtime and run from the memory without getting saved on the disk.

Which .exe performs conversion of .txt / .restext files to .resources / .resx files and vice-versa ?

Resgen.Exe

Which .exe performs conversion of .txt / .restext files to .resources / .resx files and vice-versa ?

Resgen.Exe

Thursday, November 24, 2011

Page.AsyncTimeout Property

'<'asp:Page AsyncTimeout="TimeSpan" '/>'
A TimeSpan that contains the allowed time interval for completion of the asynchronous task. The default time interval is 45 seconds.

page.ClientQueryString

The ClientQueryString property contains the query string portion of the URL requested by the browser.
For example, if the requested URL is "http://www.xyz.com/default.aspx?id=100", the ClientQueryString property will contain "id=100".

supprted in following versions:
4, 3.5, 3.0, 2.0

How do I use the aspnet_merge.exe command line to merge precompiled assemblies?

aspnet_merge.exe d:\PrecompiledWebSiteDemo -w YourAssemblyName.dll

What is the difference between the updatable and without non-updatable option while precompiling ASP.NET website?

When precompiling the ASP.NET website, there is an option "Allow this precompiled site to be updatable" in Publish Utility using Visual Web Developer or the –u option while using aspnet_compiler command line. If we enable "Allow this precompiled site to be updatable" option, it doesn’t mean that we can change everything on the precompiled website. Let’s see what the difference is while the "Allow this precompiled site to be updatable" option is enabled or not:
Precompiling without the updatable option checked:

If this option is disabled, the compiler will not only compile source code into assembly, but also produces assemblies from markup of page, resource files, etc. In the output, compiler removes all the source code and markup from page which will leave a placeholder with empty content. To change the website except for its configuration, we need to recompile the website and redeploy the layout.

Precompiling with updatable option checked:

With this option enabled, the compiler will not remove the markup of page and so we can make limited changes, such as change the arrangement of controls, colors, fonts, and other appearance aspects of pages. Additionally, when the page is requested, ASP.NET will perform further compilation in order to create output from the markup.

What is smart navigation?

Smart Navigation is obsolete in .NET 2.0. It works with 1.1 & versions before it. The SetFocus and MaintainScrollPositionOnPostBack are used instead

Smart Navigation basically enhances a web pages' performance by doing the following:

* It eliminates the flash caused during navigation
* It persists element focus during postbacks
* It persists scroll position during postbacks between pages
* It retains the lasts page information in the history of the browser

I suggest not to use SmartNavigation because it does not work with many browsers.
From .Net2.0 versions Page.MaintainScrollPositionOnPostBack is used in the place of smartnavigation

Wednesday, November 23, 2011

How to use more than one web.config in asp.net

By default when a webspplication in created we get root folder web.config
set the appsettings tag as follows
(Iam removing the start and end tag symbols due to publishing problems,instead i use '(' and ')' in place of '<' and '>'.Please replace while you test this code)
(appsettings)
(add key="rootfolder" value="Root Folder web.config"/)
(add key="test1" value="Testing the application for root folder web.config"/)
(/appSettings )

in Default.aspx
(html xmlns="http://www.w3.org/1999/xhtml")
(head runat="server")
(title)RootFolder web.config(/title)
(/head)
(body)
(form id="form1" runat="server")
(div)
(b)
Root Folder values
(/b)
(/div)
(br /)
(div)
AppKey value:
(b)
(asp:Label ID="lbltxt" runat="server" Text="(%$appSettings:rootfolder %)"/)
(/b)
(br /)
Appkey Test value:
(b)
(asp:Label ID="Label1" runat="server" Text="(%$appSettings:test1 %)"/)
(/b)
(/div)
(/form)
(/body)
(/html)

Run your application
Output:
AppKey value:Root Folder web.config
AppKey Test value:Testing the application for root folder web.config

Create SubRoot Folder and add web.config and one aspx page and name it as test.aspx

add settings in web.config in subroot folder
(appSettings)
(add key="subrootfolder" value="Sub Root Folder web.config"/)
(add key="test1" value="Testing the application for sub root folder web.config"/)
(/appSettings )

in Test.aspx
(html xmlns="http://www.w3.org/1999/xhtml")
(head id="Head1" runat="server")
(title)SubRoot Folder web.config(/title)
(/head)
(body)
(form id="form1" runat="server")
(div)
(b)
SubRoot Folder values
(/b)
(/div)
(br /)
(div)
AppKey value:
(b)
(asp:Label ID="lbltxt" runat="server" Text="(%$appSettings:subrootfolder %)"/)
(/b)
(br /)
Appkey Test value:
(b)
(asp:Label ID="Label1" runat="server" Text="(%$appSettings:test1 %)"/)
(/b)
(/div)
(/form)
(/body)
(/html)

Run application and test.aspx as start page
Output
AppKey value:Sub Root Folder web.config
AppKey Test value:Testing the application for sub root folder web.config

If you observe above outputs Default.aspx page getting values from root folder web.config file and ChildPage.aspx page getting values from subroot folder web.config file.

Modifying Configuration Settings at Runtime

Adding New Key-Value Pairs
// Adds a key and value to the App.config
public void AddKey(string strKey, string strValue)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
try
{
if (KeyExists(strKey))
throw new ArgumentException("Key name: <" + strKey + "> already exists in the configuration.");
XmlNode newChild = appSettingsNode.FirstChild.Clone();
newChild.Attributes["key"].Value = strKey;
newChild.Attributes["value"].Value = strValue;
appSettingsNode.AppendChild(newChild);
//We have to save the configuration in two places,
//because while we have a root App.config,
//we also have an ApplicationName.exe.config.
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
catch (Exception ex)
{
throw ex;
}
}

Updating Key-Value Pairs
// Updates a key within the App.config
public void UpdateKey(string strKey, string newValue)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
childNode.Attributes["value"].Value = newValue;
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory +
"..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Deleting Key-Value Pairs
// Deletes a key from the App.config
public void DeleteKey(string strKey)
{
if (!KeyExists(strKey))
throw new ArgumentNullException("Key", "<" + strKey + "> does not exist in the configuration. Update failed.");
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
appSettingsNode.RemoveChild(childNode);
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Helper Method
// Determines if a key exists within the App.config
public bool KeyExists(string strKey)
{
XmlNode appSettingsNode =
xmlDoc.SelectSingleNode("configuration/appSettings");
// Attempt to locate the requested setting.
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
return true;
}
return false;
}