Saturday, August 4, 2012

Event Bubbling

Event Bubbling is nothing but events raised by child controls is handled by the parent control. Example: Suppose consider datagrid as parent control in which there are several child controls.There can be a column of link buttons right.Each link button has click event.Instead of writing event routine for each link button write one routine for parent which will handlde the click events of the child link button events.

protected override bool OnBubbleEvent(object source, EventArgs e) {
if (e is CommandEventArgs) {
// Adds information about an Item to the
// CommandEvent.
TemplatedListCommandEventArgs args =
new TemplatedListCommandEventArgs(this, source, (CommandEventArgs)e);
RaiseBubbleEvent(this, args);
return true;
}
return false;
}

Refer: http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx

COM Callable Wrapper(CCW)


When a COM client calls a .NET object, the common language runtime creates the managed object and a COM callable wrapper (CCW) for the object. Unable to reference a .NET object directly, COM clients use the CCW as a proxy for the managed object.

The runtime creates exactly one CCW for a managed object, regardless of the number of COM clients requesting its services. As the following illustration shows, multiple COM clients can hold a reference to the CCW that exposes the INew interface. The CCW, in turn, holds a single reference to the managed object that implements the interface and is garbage collected. Both COM and .NET clients can make requests on the same managed object simultaneously.

Accessing .NET objects through COM callable wrapper

COM callable wrapper


COM callable wrappers are invisible to other classes running within the .NET Framework. Their primary purpose is to marshal calls between managed and unmanaged code; however, CCWs also manage the object identity and object lifetime of the managed objects they wrap.

Ref-http://msdn.microsoft.com/en-us/library/f07c8z1c.aspx

Daemon Thread

 
Daemon term is mainly used in UNIX. Normally when a thread is created in Java, by default it is a non-daemon thread. Whenever a Java Program is executed, the Java Virtual Machine (JVM) will not exit until any non-daemon threads are still running. This means if the main thread of an application ends and the remaining threads left are Daemon threads, then the JVM will exit killing all the daemon threads without warning.

A daemon thread should be used for some background task that might provide a service to the applications. e.g. a Server thread listening on a port for the clients` requests. A thread for which an exit method is not provided or which does not have an exit mechanism can be marked as a daemon thread.
 

Difference Between Web Farm and Web Garden

Web Farms and Web Garden are very common terminology for any production deployment. Though these terms looks same but the things are totally different. Many beginners very confused with these two terms. Here you can find the basic difference between the Web Farm and Web Garden.


Web Farm

After developing our asp.net web application we host it on IIS Server.  Now one standalone server is sufficient to process ASP.NET Request and response for a small web sites but when the site comes for big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are  running behind the Load Balancer.
This is the most common scenarios for any web based production environment. Where Client will hit an Virtual IP ( vIP) . Which is the IP address of Load Balancer. When Load balancer received the request based on the server load it will redirect the request to particular Server.

Web Garden
All IIS Request process by worker process ( w3wp.exe). By default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden.   Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.
There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode "out proc" and we can use "Session State Server" or "SQL-Server Session State".

Ref- http://www.codeproject.com/Articles/114910/What-is-the-difference-between-Web-Farm-and-Web-Ga

Monday, June 4, 2012

How to check string is palindrome or not in .NET

public bool isPalindrome(String str)
{
    if (String.IsNullOrEmpty(str))
        return false;
 
    int length = str.Length;
 
    str = str.ToLower();
 
    for (int i = 0; i < (length / 2); i++)
    {
        if (str[i] != str[length - 1 - i])
            return false;
    }
 
    return true;
}

How to generate Fibonacci series in c#

Open a console application project in c# language in your editor and just paste the following code in your class's brackets -

static void Main(string[] args)
{
     int previous = -1; int next = 1;
     int position;
    Console.WriteLine("Enter the position");
    position = int.Parse(Console.ReadLine());
   for (int i = 0; i < position; i++)
   {
        int sum = next + previous; previous = next;
        next = sum;
       Console.WriteLine(next);
   }
   Console.ReadLine();
}


Tip: One problem with the implementation in this article is that the int types will overflow past the 47th Fibonacci number. To solve this problem, you can use the double type. Change Fibonacci() to return double. Additionally, change previous , next , and position to be of type double.


Output
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377

Saturday, June 2, 2012

Indexer in C#

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.



class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];
    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)       
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}
// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        // Use [] notation on the type.
        stringCollection[0] = "My Name is Psingh";
        System.Console.WriteLine(stringCollection[0]);
    }
}

Output:
"My Name is Psingh"


 

Comparison Between Properties and Indexers

Indexers are similar to properties. Except for the differences shown in the following table, all of the rules defined for property accessors apply to indexer accessors as well.

PropertyIndexer
Identified by its name.Identified by its signature.
Accessed through a simple name or a member access.Accessed through an element access.
Can be a static or an instance member.Must be an instance member.
A get accessor of a property has no parameters.A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicit value parameter.A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

IQueryable vs. IEnumerable in terms of LINQ to SQL queries

IQueryable inherited IEnumerable, so it obviously get all the functionality IEnumerable has. The working style of both is still different. There are still lot many differences exists between the two which impact the decision we took in usage of either one. Both of these suits for particular scenarios. Following are some differences using which we can took decision to use anyone of these optimally.
ParameterIQueryableIEnumerable
Extension MethodsExtension methods defined for IQueryable take expression objects. Means, the delegate IQueryable extension methods receives is an expression tree.Extension methods defined for IEnumerable take functional objects. Means, the delegate IEnumerable extension methods receives is a method to invoke.
Great ForIQueryable allows out-of-memory things like remote data source operations, such as working with database or web service.IEnumerable is great for working with sequences (in-memory collections), that are iterated in-memory.
Supported QueriesIQueryable supports LINQ to SQL queries.IEnumerable supports LINQ to Object and LINQ to XML queries.
Deferred ExecutionIQueryable supports lazy loading (Suited for scenarios like paging and composition based queries).IEnumerable lost lazy loadnig ability on the external provider.
Moving between itemsIQueryable provides many methods to move between the items.IEnumerable doesn’t have the concept of moving between items, it is forward only collection.
Filtering MechanismIQueryable executes query on server side along with all the filters applied.IEnumerable executes select query on server side, loads data in-memory and then executes filter at client side.
CreateQuery and Execute MethodsIQueryable has these two additional methods. Both takes expression as input. CreateQuery returns IQueryable representing expression tree. Execute returns result of the query.NA
Custom Querying CapabilityIQueryable provides additional functionality to implement custom querying with LINQ.IEnumerable does not have custom querying capability.
Performance PerspectiveIQueryable gives best performance when used for out-of-memory data store operations (that is external to .NET CLR memory).IEnumerable gives best performance when used to manipulate in-memory collections.


IEnumerable: IEnumerable is best suitable for working with in-memory collection. IEnumerable doesn’t move between items, it is forward only collection.
IQueryable: IQueryable best suits for remote data source, like a database or web service. IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).


So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable

Thursday, May 24, 2012

How will implement Page Fragment Caching?

How will implement Page Fragment Caching?

Page fragment caching involves the caching of a fragment of the page, rather than the entire page. When portions of the page are need to be dynamically created for each user request this is best method as compared to page caching. You can wrap Web Forms user control and cache the control so that these portions of the page don’t need to be recreated each time.

How can you cache different version of same page using ASP.NET cache object ?

How can you cache different version of same page using ASP.NET cache object ?

Output cache functionality is achieved by using "OutputCache" attribute on ASP.NET page header. Below is the syntax
  1. VaryByParam :- Caches different version depending on input parameters send through HTTP POST/GET. 
  2. VaryByHeader:- Caches different version depending on the contents of the page header. 
  3. VaryByCustom:-Lets you customize the way the cache handles page variations by declaring the attribute and overriding the GetVaryByCustomString handler. 
  4. VaryByControl:-Caches different versions of a user control based on the value of properties of ASP objects in the control.

What are different types of caching using cache object of ASP.NET?

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and displayed in a Web browser:
  1. Page Output Caching - Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static. 
  2. Page Fragment Caching - If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.

What is Cache Callback and Scavenging in Cache?

What is Cache Callback in Cache?

Cache object is dependent on its dependencies example file based, time based etc...Cache items remove the object when cache dependencies change.ASP.NET provides capability to execute a callback method when that item is removed from cache.

What is scavenging?

When server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls the items scavenging are removed first

What are dependencies in cache and types of dependencies?

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that item to be removed from the cache under specific activities of dependencies.Example if the cache object is dependent on file and when the file data changes you want the cache object to be update.

 Following are the supported dependency :-
1. File dependency :- Allows you to invalidate a specific cache item when a disk based file or files change.

2. Time-based expiration :- Allows you to invalidate a specific cache item depending on predefined time.

3. Key dependency :-Allows you to invalidate a specific cache item depending when another cached item changes.

Application State vs Session State

Application state variables:
The data stored in these variables is available to all the users i.e. all the active sessions.

Session state variables:
These are available to the single session who has created the variables.


Are Application state variables available throughout the current process?

Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on multiple servers or on multiple processors within a server, each process has its own Application state.

ASP.NET, C# "DateTime" format and "DateTime.ToString()" Patterns

1 MM/dd/yyyy  08/22/06
2 dddd, dd MMMM yyyy  Tuesday, 22 August 2006
3 dddd, dd MMMM yyyy HH:mm  Tuesday, 22 August 2006 06:30
4 dddd, dd MMMM yyyy hh:mm tt  Tuesday, 22 August 2006 06:30 AM
5 dddd, dd MMMM yyyy H:mm  Tuesday, 22 August 2006 6:30
6 dddd, dd MMMM yyyy h:mm tt  Tuesday, 22 August 2006 6:30 AM
7 dddd, dd MMMM yyyy HH:mm:ss  Tuesday, 22 August 2006 06:30:07
8 MM/dd/yyyy HH:mm  08/22/2006 06:30
9 MM/dd/yyyy hh:mm tt  08/22/2006 06:30 AM
10 MM/dd/yyyy H:mm  08/22/2006 6:30
11 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
12 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
13 MM/dd/yyyy h:mm tt  08/22/2006 6:30 AM
14 MM/dd/yyyy HH:mm:ss  08/22/2006 06:30:07
15 MMMM dd  August 22
16 MMMM dd  August 22
17 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK  2006-08-22T06:30:07.7199222-04:00
18 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK  2006-08-22T06:30:07.7199222-04:00
19 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'  Tue, 22 Aug 2006 06:30:07 GMT
20 ddd, dd MMM yyyy HH':'mm':'ss 'GMT'  Tue, 22 Aug 2006 06:30:07 GMT
21 yyyy'-'MM'-'dd'T'HH':'mm':'ss  2006-08-22T06:30:07
22 HH:mm  06:30
23 hh:mm tt  06:30 AM
24 H:mm  6:30
25 h:mm tt  6:30 AM
26 HH:mm:ss  06:30:07
27 yyyy'-'MM'-'dd HH':'mm':'ss'Z'  2006-08-22 06:30:07Z
28 dddd, dd MMMM yyyy HH:mm:ss  Tuesday, 22 August 2006 06:30:07
29 yyyy MMMM  2006 August
30 yyyy MMMM  2006 August

What is the Unchecked Keyword in C#?

The unchecked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions. It can be used as an operator or a statement according to the following forms.
The unchecked statement:
unchecked block
The unchecked operator:
unchecked (expression)
where:
block
The statement block that contains the expressions to be evaluated in an unchecked context.
expression
The expression to be evaluated in an unchecked context. Notice that the expression must be in parentheses ( ).

What is the checked keyword in C#?

The checked keyword is used to control the overflow-checking context for integral-type arithmetic operations and conversions. It can be used as an operator or a statement according to the following forms.
The checked statement:
checked block
The checked operator:
checked (expression)
where:
block
The statement block that contains the expressions to be evaluated in a checked context.
expression
The expression to be evaluated in a checked context. Notice that the expression must be in parentheses ( ).

What is "USING and how to use the "USING" statement.

The following example shows how to use the using statement.

using (Font font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}


File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}


Multiple instances of a type can be declared in a using statement, as shown in the following example.

using (Font font3 = new Font("Arial", 10.0f),
            font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}


You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.
            Font font2 = new Font("Arial", 10.0f);
            using (font2) // not recommended
            {
                // use font2
            }
            // font2 is still in scope
            // but the method call throws an exception
            float f = font2.GetHeight(); 


Reference:http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Monday, May 14, 2012

Using jQuery and JSON Action methods in MVC

  1. jQuery + JSON Action Methods = Cool
    It is easy to return a JSON object instead of a view.
    public JsonResult Create(string CategoryName)
    {
        var category = new Models.Category();
        category.Name = CategoryName;
        category.URLName = CategoryName.ToLower().Replace(" ", "-");
        categoryRepository.Add(category);
        categoryRepository.Save();
    
        return Json(category);
    }
    <script class="str" type="<span">
    "text/javascript" language="javascript">
        $("#CreateNewCategory").click(function() {
            $.getJSON("/category/create/",
                      { "CategoryName": $("#NewCategoryName").val() },
                      CategoryAdded);
                  });
    
                  function CategoryAdded(category) {
                      $("#CategoryList").append("
    
  2. + category.URLName + "/cat\">" + category.Name + "
  3. "
    ); } </script>

Sunday, May 13, 2012

What is Repository Pattern in ASP.NET MVC?

What is Repository Pattern in ASP.NET MVC?
Repository pattern is usefult for decoupling entity operations form presentation, which allows easy mocking and unit testing.
“The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation”
“Most common queries should also be hard coded to the Repositories as methods.”
Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
    private IMyRepository repository;
 
    // overloaded constructor
    public myController(IMyRepository repository)
    {
        this.repository = repository;
    }
 
    // default constructor for framework to call
    public myController()
    {
        //concreate implementation
        myController(new someRepository());
    }
...
 
    public ActionResult Load()
    {
        // loading data from repository
        var myData = repository.Load();
    }
}

What is difference between Viewbag and Viewdata in ASP.NET MVC?

What is difference between Viewbag and Viewdata in ASP.NET MVC?

The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

How to access Viewstate values of this page in the next page?

How to access Viewstate values of this page in the next page?

PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
 string lbl = posterLabel.Text;

How to call javascript function on the change of Dropdown List in ASP.NET MVC?

How to call javascript function on the change of Dropdown List in ASP.NET MVC?
Create a java-script function:
Call the function:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Products, "Value", "Text"),
"Please Select a product", new { id = "dropDown1",
onchange="selectedIndexChanged()" })%>

What is the ‘page lifecycle’ of an ASP.NET MVC?

What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

Friday, May 11, 2012

Remove MVC Action from Cache

For removing the Cache from the action so it get refresh each time, use the below stuff
 
public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted ( ActionExecutedContext context )
    {
        context.HttpContext.Response.Cache.SetCacheability( HttpCacheability.NoCache );
    }
}

[HttpGet]
[NoCache]
public JsonResult GetSomeStuff ()
{
    ...
}

Monday, April 9, 2012

What is new in ASP.NET 3.5

ASP.NET AJAX
In ASP.NET 2.0, ASP.NET AJAX was used as an extension to it. You had to download the extensions and install it. However in ASP.NET 3.5, ASP.NET AJAX is integrated into the .NET Framework, thereby making the process of building cool user interfaces easier and intuitive.
The integration between webparts and the update panel is much smoother. Another noticeable feature is that you can now add ASP.NET AJAX Control Extenders to the toolbox in VS2008. Even though this is an IDE specific feature, however I feel it deserves a mention over here for developers, who had to add extenders using source view earlier. It is also worth noting that Windows Communication Foundation (WCF) now supports JSON along with other standard protocols like  SOAP, RSS and POX.
New Controls
The ListView and DataPager are new controls added along with a new datasource control called the LinqDataSource.
ListView
The ListView control is quiet flexible and contains features of the Gridview, Datagrid, Repeater and similar list controls available in ASP.NET 2.0. It provides the ability to insert, delete, page (using Data Pager), sort and edit data. However one feature of the ListView control that stands apart, is that it gives you a great amount of flexibility over the markup generated. So you have a complete control on how the data is to be displayed. You can now render your data without using the tag. You also get a rich set of templates with the ListView control.
DataPager
DataPager provides paging support to the ListView control. The best advantage is that you need not have to keep it ‘tied’ with the control on which the paging is being done. You can keep it anywhere on the page.
DataPager gives you a consistent way of paging with the controls that support it. Currently only ListView supports it as it implements the IPageableItemContainer. However support is likely to be added to other List controls as well.
LINQ
LINQ (Language Integrated Query) adds native data querying capability to C# and VB.NET along with the compiler and Intellisense support. LINQ is a component of .NET 3.5. LINQ defines operators that allow you to code your query in a consistent manner over databases, objects and XML.  The ASP.NET LinqDataSource control allows you to use LINQ to filter, order and group data before binding to the List controls.
ASP.NET Merge Tool
ASP.NET 3.5 includes a new merge tool (aspnet_merge.exe). This tool lets you combine and manage assemblies created by aspnet_compiler.exe. This tool was available earlier as an add-on.
New Assemblies
The new assemblies that would be of use to ASP.NET 3.5 developers are as follows:
·         System.Core.dll - Includes the implementation for LINQ to Objects
·         System.Data.Linq.dll - Includes the implementation for LINQ to SQL
·         System.Xml.Linq.dll - Includes the implementation for LINQ to XML
·         System.Data.DataSetExtensions.dll - Includes the implementation for LINQ to DataSet
·         System.Web.Extensions.dll: Includes the implementation for ASP.NET AJAX (new enhancements added) and new web controls as explained earlier.
Some Other Important Points
1.    ASP.NET 3.5 provides better support to IIS7. IIS7 and ASP.NET 3.5 modules and handlers support unified configuration.
2.    You can have multiple versions of ASP.NET on the same machine.
3.    For those who are wondering what happened to ASP.NET 3.0, well there isn’t anything called ASP.NET 3.0.
4.    VS 2002 worked with ASP.NET 1.0, VS 2003 worked with ASP.NET 1.1, and VS 2005 worked with ASP.NET 2.0. However VS 2008 supports multi-targeting, i.e it works with ASP.NET 2.0, and ASP.NET 3.5. 

Monday, March 26, 2012

C#'s const vs. readonly

A quick synopsis on the differences between 'const' and 'readonly' in C#:
'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

Handlers vs. Modules

Modules are units of code that have registered for one or more pipeline events. They perform authentication, authorization, logging, etc. There is one task that is reserved for a special module, known as a handler. The handler’s unique job is to retrieve the resource that is requested in the URL. All resources served by IIS are mapped to a handler in configuration. If the configuration mapping does not exist, requests for the resource will receive a 404 HTTP status. In addition to the configuration mapping, which takes place before the pipeline begins, the handler mapping can be changed during request execution in the MAP_REQUEST_HANDLER event. This allows scenarios such as URL rewriting to work. Handlers are notified, or executed, in the EXECUTE_REQUEST_HANDLER step. (Note that only the mapped handler is notified, as you would expect.)

What is an application domain?

An application domain is the CLR equivalent of an operation system’s
process. An application domain is used to isolate applications from one
another. This is the same way an operating system process works. The
separation is required so that applications do not affect one another.
This separation is achieved by making sure than any given unique
virtual address space runs exactly one application and scopes the
resources for the process or application domain using that address space.

What are Object Initializers?

The Object initializers are the features for programming concepts which was introduced in C#.Net.

The aim of using Object Initializers is to initializing the accessible fields or properties
of an object without the need to write any parametrized constructor or separate
statements.

Sample:

using System;
class Student
{
int rollno;
string stdName;
static void Main()
{
Student s = new Student(){rollno=1,stdName="Ramesh" }; //Object Initializer
}
}

What is the purpose of IIS application pools?

We use application pools for isolation purpose. Every application within an application pool used the same worker process. 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.

In simplest words we use application pools for ISOLATION purpose.

Tuesday, March 20, 2012

Constructor in C#

  • A constructor is a special method whose task is to initialize the object of its class.
  • It is special because its name is the same as the class name.
  • They do not have return types, not even void and therefore they cannot return values.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • Constructor is invoked whenever an object of its associated class is created.
  • Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().

this Keyword in ASP.NET

this Keyword

Each object has a reference “this” which points to itself.

Two uses of this keyword.

o Can be used to refer to the current object.

o It can also be used by one constructor to explicitly invoke another constructor of the same class.

Thursday, February 23, 2012

Design Pattern Interview Questions

  1. Factory Design Pattern
  2. Abstract Factory Design Pattern
  3. Builder Design Pattern
  4. Prototype Design Pattern
  5. Singleton Design Pattern
  6. Adapter Design Pattern
  7. Bridge Design Pattern
  8. Composite Design Pattern
  9. Decorator Design Pattern
  10. Facade Design Pattern
  11. Flyweight Design Pattern
  12. Proxy Design Pattern
  13. Mediator Design Pattern
  14. Memento Design Pattern
  15. Interpreter Design Pattern
  16. Iterator Design Pattern
  17. COR Design Pattern
  18. Command Design Pattren
  19. State Design Pattern
  20. Strategy Design Pattern
  21. Observer Design Pattern
  22. Template Design Pattern
  23. Visitor Design Pattern
  24. Dependency IOC Design pattern

WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview questions

  1. What is SOA, Services and Messages ?
  2. What is the difference between Service and Component?
  3. What are basic steps to create a WCF service ?
  4. What are endpoints, address, contracts and bindings?
  5. What are various ways of hosting WCF service?
  6. What is the difference of hosting a WCF service on IIS and Self hosting?
  7. What is the difference between BasicHttpBinding and WsHttpBinding?
  8. How can we do debugging and tracing in WCF?
  9. Can you explain transactions in WCF (theory)?
  10. How can we self host WCF service ?
  11. What are the different ways of implementing WCF Security?
  12. How can we implement SSL security on WCF(Transport Security)?
  13. How can we implement transport security plus message security in WCF ?
  14. How can we do WCF instancing ?
  15. How Can we do WCF Concurency and throttling?
  16. Can you explain the architecture of Silverlight ?
  17. What are the basic things needed to make a silverlight application ?
  18. How can we do transformations in SilverLight ?
  19. Can you explain animation fundamentals in SilverLight?
  20. What are the different layout methodologies in SilverLight?
  21. Can you explain one way , two way and one time bindings?
  22. How can we consume WCF service in SilverLight?
  23. How can we connect databases using SilverLight?
  24. What is LINQ and can you explain same with example?
  25. Can you explain a simple example of LINQ to SQL?
  26. How can we define relationships using LINQ to SQL?
  27. How can we optimize LINQ relationships queries using ‘DataLoadOptions’?
  28. Can we see a simple example of how we can do CRUD using LINQ to SQL?
  29. How can we call a stored procedure using LINQ?
  30. What is the need of WPF when we had GDI, GDI+ and DirectX?
  31. Can you explain how we can make a simple WPF application?
  32. Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?
  33. Can you explain the Architecture of WPF?
  34. What is Azure?
  35. Can you explain Azure Costing?
  36. Can we see a simple Azure sample program?
  37. What are the different steps to create a simple Worker application?
  38. Can we understand Blobs in steps, Tables & Queues ?
  39. Can we see a simple example for Azure tables?
  40. What is Package and One click deploy(Deployment Part - 1) ?
  41. What is Web.config transformation (Deployment Part-2)?
  42. What is MEF and how can we implement the same?
  43. How is MEF different from DIIOC?
  44. Can you show us a simple implementation of MEF in Silverlight ?

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions

  1. What is IL code, CLR, CTS, GAC & GC?
  2. How can we do Assembly versioning?
  3. can you explain how ASP.NET application life cycle and page life cycle events fire?
  4. What is the problem with Functional Programming?
  5. Can you define OOP and the 4 principles of OOP?
  6. What are Classes and Objects?
  7. What is Inheritance?
  8. What is Polymorphism, overloading, overriding and virtual?
  9. Can you explain encapsulation and abstraction?
  10. What is an abstract class?
  11. Define Interface & What is the diff. between abstract & interface?
  12. What problem does Delegate Solve ?
  13. What is a Multicast delegate ?
  14. What are events and what's the difference between delegates and events?
  15. How can we make Asynchronous method calls using delegates ?
  16. What is a stack, Heap, Value types and Reference types ?
  17. What is boxing and unboxing ?
  18. Can you explain ASP.NET application and Page life cycle ?
  19. What is Authentication, Authorization, Principal & Identity objects?
  20. How can we do Inproc and outProc session management ?
  21. How can we windows , forms and passport authentication and authorization in ASP.NET ?
  22. In a parent child relationship which constructor fires first ?

C#'s const vs. readonly

C#'s const vs. readonly

A quick synopsis on the differences between 'const' and 'readonly' in C#:
'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.

'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

http Handlers vs. Modules

Modules are units of code that have registered for one or more pipeline events. They perform authentication, authorization, logging, etc. There is one task that is reserved for a special module, known as a handler. The handler’s unique job is to retrieve the resource that is requested in the URL. All resources served by IIS are mapped to a handler in configuration. If the configuration mapping does not exist, requests for the resource will receive a 404 HTTP status. In addition to the configuration mapping, which takes place before the pipeline begins, the handler mapping can be changed during request execution in the MAP_REQUEST_HANDLER event. This allows scenarios such as URL rewriting to work. Handlers are notified, or executed, in the EXECUTE_REQUEST_HANDLER step. (Note that only the mapped handler is notified, as you would expect.)

Friday, February 17, 2012

An Interface is a Value type or reference type?

Select from following answers:
  1. Value Type
  2. Reference Type
  3. Vaule type or reference type
  4. both

Because , Interface is a Contract, When we design Interface and implement it in other object , that object will implement this. So, when a struct implement an interface ,that time it is value type and in case of class it is reference type.

What are the different ways to deploy a assembly ?

Basically there are three different ways to deploy an assembly the are

1. Using a MSI Installer

2. Using a CAB archive

3. Using a XCOPY Command

exact difference between IQueryable and IEnumerable interface ?

IEnumerable is applicable for in-memory data querying, and in contrast IQueryable allows remote execution, like web service or database querying.

What is the difference between N-layer and N-tier architecture?

N-layers of application may reside on the same physical computer(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces.Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other.Communication between layers is explicit and loosely coupled.With strict layering, components in one layer can interact only with componentsin the same layer or with components from the layer directly below it.


The main benefits of the layered architectural style are:
Abstraction,Isolation, Manageability, Performance, Reusability, Testability.


N-tiers architecture usually have atleast three separate logical parts,each located on separate physical server.Each tier is responsible with specific functionality.Each tier is completely independent from all other tier, except for those immediately above and below it.Communication between tiers is typically asynchronous in order to support better scalability.


The main benefit of tier architecture styles are
1.Maintainability. Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.
2.Scalability. Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.
3.Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.
4.Availability. Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.

Difference between XElement and XDocument

Both are the classes defined by System.Xml.Linq namespace

XElement class
represents an XML fragment
XDocument class represents an entire XML document with all associated meta-data.

example:

XDocument d = new XDocument(
      new XComment("hello"),
      new XElement("book",
              new XElement("bookname", "ASP.NET"),
             new XElement("authorname", "techmedia"),
       )
);

Advantages and disadvantages of LINQ over Stored procedures

Below is the three advantages of LINQ over stored procedures.

Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at runtime exception.
 
 
The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precompiled. In case of LINQ the queries need to be compile before the execution. So according to this, I can say stored procedures are faster in performance as compared to LINQ.
 

Thursday, February 16, 2012

Removing some querystring values from collection

Below code is used for removing the query string parameters from the collection of parameters-

Dim isreadonly As PropertyInfo = GetType(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)

' make collection editable
isreadonly.SetValue(HttpContext.Current.Request.QueryString, False, Nothing)

' remove
HttpContext.Current.Request.QueryString.Remove("uid")
HttpContext.Current.Request.QueryString.Remove("pwd")

HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath + "?" & Convert.ToString(HttpContext.Current.Request.QueryString))Rem

Monday, February 13, 2012

What is the difference between Authentication and authorization?

This can be a tricky question. These two concepts seem altogether similar but there is
wide range of difference. Authentication is verifying the identity of a user and authorization
is process where we check does this identity have access rights to the system. In short we
can say the following authentication is the process of obtaining some sort of credentials
from the users and using those credentials to verify the user’s identity. Authorization is
the process of allowing an authenticated user access to resources. Authentication always
proceed to Authorization; even if your application lets anonymous users connect and use
the application, it still authenticates them as being anonymous.

What is the difference between Server.Transfer and response.Redirect ?

Following are the major differences between them:-
√ Response.Redirect sends message to the browser saying it to move to some
different page, while server.transfer does not send any message to the browser
but rather redirects the user directly from the server itself. So in server.transfer
there is no round trip while response.redirect has a round trip and hence puts
a load on server.
√ Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is www.yahoo.com you can use server.transfer to move
to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e.
within websites. This cross server redirect is possible only using
Response.redirect.
√ With server.transfer you can preserve your information. It has a parameter
called as “preserveForm”. So the existing query string etc. will be able in the
calling page.

What is event bubbling ?

Server controls like Datagrid, DataList, Repeater can have other child controls inside
them. Example DataGrid can have combo box inside datagrid. These child control do not
raise there events by themselves, rather they pass the event to the container parent (which
can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event.
As the child control send there events to parent this is termed as event bubbling.

Why is it preferred to not use finalize for clean up?

Problem with finalize is that garbage collection has to make two rounds in order to remove
objects which have finalize methods.
Below figure will make things clear regarding the two rounds of garbage collection rounds
performed for the objects having finalized methods.
In this scenario there are three objects Object1, Object2 and Object3. Object2 has the
finalize method overridden and remaining objects do not have the finalize method
overridden.
Now when garbage collector runs for the first time it searches for objects whose memory
has to free. He can see three objects but only cleans the memory for Object1 and Object3.
Object2 it pushes to the finalization queue.
Now garbage collector runs for the second time. He see’s there are no objects to be
released and then checks for the finalization queue and at this moment it clears object2
from the memory.
So if you notice that object2 was released from memory in the second round and not first.
That’s why the best practice is not to write clean up Non.NET resources in Finalize
method rather use the DISPOSE.

What is the difference between Class and structure’s ?

Following are the key differences between them :-
√ Structure are value types and classes are reference types. So structures use
stack and classes use heap.
√ Structures members can not be declared as protected, but class members can
be. You can not do inheritance in structures.
√ Structures do not require constructors while classes require.
√ Objects created from classes are terminated using Garbage collector. Structures
are not destroyed using GC.

What are similarities between Class and structure ?

Following are the similarities between classes and structures :-
√ Both can have constructors, methods, properties, fields, constants,
enumerations, events, and event handlers.
√ Structures and classes can implement interface.
√ Both of them can have constructors with and without parameter.
√ Both can have delegates and events.

What are the different accessibility levels defined in .NET ?


Following are the five levels of access modifiers :-
Private : Only members of class have access.
Protected :-All members in current class and in derived classes can access the
variables.
Friend (internal in C#) :- Only members in current project have access to the
elements.
Protected friend (protected internal in C#) :- All members in current project
and all members in derived class can access the variables.
Public :- All members have access in all classes and projects.

Difference between Shadowing and Overriding

Following are the differences between shadowing and overriding :-
√ Overriding redefines only the implementation while shadowing redefines the
whole element.
√ In overriding derived classes can refer the parent class element by using “ME”
keyword, but in shadowing you can access it by “MYBASE”.

What is shadowing ?

When two elements in a program have same name, one of them can hide and shadow the
other one. So in such cases the element which shadowed the main element is referenced.
Below is a sample code, there are two classes “ClsParent” and “ClsShadowedParent”. In
“ClsParent” there is a variable “x” which is a integer. “ClsShadowedParent” overrides
“ClsParent” and shadows the “x” variable to a string.
Note:- In Sample CD “WindowsShadowing” is folder which has the sample code. If you
run the program you can have two output’s one which shows a integer and other which shows
a string.
Public Class ClsParent
         Public x As Integer
End Class
Public Class ClsShadowedParent
       Inherits ClsParent 
       Public Shadows x As String
End Class

Different properties provided by Objectoriented systems

Following are characteristic’s of Object Oriented System’s :-

Abstraction
It allows complex real world to be represented in simplified manner. Example color is
abstracted to RGB. By just making the combination of these three colors we can achieve
any color in world.It’s a model of real world or concept.

Encapsulation
It is a process of hiding all the internal details of an object from the outside world.

Communication using messages
When application wants to achieve certain task it can only be done using combination of
objects. A single object can not do all the task. Example if we want to make order processing
form.We will use Customer object, Order object, Product object and Payment object to
achieve this functionality. In short these objects should communicate with each other.
This is achieved when objects send messages to each other.

Object lifetime
All objects have life time.Objects are created ,and initialized, necessary functionalities
are done and later the object is destroyed. Every object have there own state and identity
which differ from instance to instance.

Class hierarchies (Inheritance and aggregation)
This is the simplest relationship between objects. Example every customer has sales. So
Customer object and sales object have an association relation between them.

In object oriented world objects have relation and hierarchies in between them. There are
basically three kind of relationship in Object Oriented world :-
1.Association
This is the simplest relationship between objects. Example every customer has sales. So
Customer object and sales object have an association relation between them

2.Aggregation
This is also called as composition model. Example in order to make a “Accounts” class it
has use other objects example “Voucher”, “Journal” and “Cash” objects. So accounts
class is aggregation of these three objects.

3.Inheritance
Hierarchy is used to define more specialized classes based on a preexisting generalized
class. Example we have VEHICLE class and we can inherit this class make more
specialized class like CAR, which will add new attributes and use some existing qualities
of the parent class. Its shows more of a parent-child relationship. This kind of hierarchy
is called inheritance.


Polymorphism
When inheritance is used to extend a generalized class to a more specialized class, it
includes behavior of the top class(Generalized class). The inheriting class often implement
a behavior that can be somewhat different than the generalized class, but the name of the
behavior can be same. It is important that a given instance of an object use the correct
behavior, and the property of polymorphism allows this to happen automatically.

What is the relation between Classes and Objects ?

They look very much same but are not same. Class is a definition, while object is a instance of the class created. Class is a blue print while objects are actual objects existing in real world. Example we have class CAR which has attributes and methods like Speed, Brakes, Type of Car etc. Class CAR is just a prototype, now we can create real time objects which can be used to provide functionality. Example we can create a Maruti car object with 100 km speed and urgent brakes.

What is OOPS, Class and Objects?

 What is Object Oriented Programming ?
It is a problem solving technique to develop software systems. It is a technique to think real world in terms of objects. Object maps the software model to real world concept. These objects have responsibilities and provide services to application or other objects.


What’s a Class ?
A class describes all the attributes of objects, as well as the methods that implement the behavior of member objects. It’s a comprehensive data type which represents a blue print of objects. It’s a template of object.


What’s an Object ?
It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Objects are members of a class. Attributes and behavior of an object are defined by the class definition.