Showing posts with label Asp.net Base. Show all posts
Showing posts with label Asp.net Base. Show all posts

Tuesday, June 16, 2009

To Create a DropDownList from an ENUM

You have an 'Enum' defined as follows:
public enum CompanyAddressType
{
Unknown = 0,
Primary = 1,
Warehouse = 2,
Distribution_Center = 3,
Cross_Dock = 4
}


You want to iterate through the list and put the data into an asp.net DropDownList.

Here is the simple code:


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] names = Enum.GetNames(typeof (CompanyAddressType));
var values = (CompanyAddressType[]) Enum.GetValues(typeof (CompanyAddressType));
for (int i = 0; i < names.Length; i++)
{
DropDownListCompanyAddressType.Items.Add(new ListItem(names[i], values.ToString()));
}
}
}

There are probably easier ways to do it, but this works.


Use the tips!

Wednesday, March 25, 2009

WCF Performance: Making your service run 3 times faster

Wisely changing WCF defaults can yield a significant improvement in your service performance. The exact changes need to be made and their exact effect are dependent in the scenario. The example below how to speed up a certain service 3 times faster.
Read more at http://webservices20.blogspot.com/2009/01/wcf-performance-gearing-up-your-service.

Happy Coding!

Tuesday, February 17, 2009

Interview Question asp.net 3.5 - Part 1

What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and to improve the performance of the web based applications. There are mainly three layers in three-tier architecture. the are define as follows
  1. Presentation
  2. Business Logic
  3. Database
1. First layer- Presentation contains mainly the interface code, and this is shown to user. This code could contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.

2. Second layer - is Business Logic which contains all the code of the server-side .This layer have code to interact with database and to query, manipulate, pass data to user interface and handle any input from the UI as well.

3. Third layer-Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or even a text file containing data also some additional database are also added to that layers.

Do not use design patterns in any of the following situations.


When the software being designed would not change with time.
When the requirements of the source code of the application are unique.

If any of the above applies in the current software design, there is no need to apply design patterns in the current design and increase unnecessary complexity in the design.

When to use Design Patterns
Design Patterns are particularly useful in one of the following scenarios.

* When the software application would change in due course of time?

* When the application contains source code that involves object creation and event notification?

The following are some of the major advantages of using Design Patterns in software development.
  1. Flexibility
  2. Adaptability to change
  3. Reusability
What are Design Patterns?
A Design Pattern essentially consists of a problem in a software design and a solution to the same. In Design Patterns each pattern is described with its name, the motivation behind the pattern and its applicability.

According to MSDN, "A design pattern is a description of a set of interacting classes that provide a framework for a solution to a generalized problem in a specific context or environment. In other words, a pattern suggests a solution to a particular problem or issue in object-oriented software development.

Happy Interview...!

Thursday, December 25, 2008

C# array in descending or reverse order

How do you sort a C# array in descending or reverse order? A simple way is to sort the array in ascending order, then reverse it:
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( intArray );
Array.Reverse( intArray );
Of course, this is not efficient for large arrays.

A better approach is to create a custom Comparer. Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.

Here’s a simple web application to test it:

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="SortSample.aspx.cs" Inherits="SampleApplication.SortSample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sort Ascending /Descending Order by Generic</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace SampleApplication.
{
public partial class SortSample: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int[] intArray = new int[] { 3, 1, 4, 5, 2 };
char[] charArray = new char[] { 'r', '1', 'f', 'c', 'x' };
string[] stringArray = new string[] { "array item 1", "array item 2", "array item 3", "array item 4", "array item 5" };

ArraySorter<int>.SortDescending(intArray);
ArraySorter<char>.SortDescending(charArray);
ArraySorter<string>.SortDescending(stringArray);

BindDropDownList(DropDownList1, intArray);
BindDropDownList(DropDownList2, charArray);
BindDropDownList(DropDownList3, stringArray);
}

private static void BindDropDownList(BaseDataBoundControl ddl, Array arr)
{
if(ddl !=null && arr !=null && arr.Length>0)
{
ddl.DataSource = arr;
ddl.DataBind();
}
}
static public class ArraySorter<T> where T : IComparable
{
static public void SortDescending(T[] array)
{
Array.Sort<T>(array, s_Comparer);
}

static private readonly ReverseComparer s_Comparer = new ReverseComparer();

private class ReverseComparer : IComparer<T>
{
public int Compare(T object1, T object2)
{
return -((IComparable)object1).CompareTo(object2);
}
}
}

}
}

I hope it will help you in someway.

Happy Coding!!!

Saturday, December 6, 2008

Highlight Datagrid or GridView row on mouse over in asp.net

To highlight the row and when mouse moves out, the style sheet is switched back to normal.

Use the following two steps to solve this case. This will applicable for both Gridview and Datagrid controls.

Step 1 : Create styles for normal and highlight view of the row.

<style type="text/css">
.normalrow
{
background-color:white;
}
.hightlighrow
{
background-color:#cccccc;
}
</style>
Step 2 : Now add handler for RowCreated event for the grid and add the attributes for onmouseover and onmouseout javascript events.

Following code snippet shows how this has been done.

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='hightlighrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");
}
}
Use the technology!!!

Sunday, November 30, 2008

OOPs FAQ in C# - Part II

What is an Object?

An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time.

An object can be considered a "thing" that can perform a set of activities. The set of activities that the object performs defines the object's behavior.

The state of the object changes according to the methods which are applied to it. We refer to these possible sequences of state changes as the behavior of the object. So the behavior of an object is defined by the set of methods which can be applied on it.

Objects can communicate by passing messages to each other.

What is inheritance?

Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say "A inherits from B''. Objects of class A thus have access to attributes and methods of class B without the need to redefine them.

If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.

However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass.

In the literature you may also find other terms for "superclass" and "subclass". Superclasses are also called parent classes or base classes. Subclasses may also be called child classes or just derived classes.

Inheritance Example

Like a car, truck or motorcycles have certain common characteristics- they all have wheels, engines and brakes. Hence they all could be represented by a common class Vehicle which encompasses all those attributes and methods that are common to all types of vehicles.

However they each have their own unique attributes; car has 4 wheels and is smaller is size to a truck; whereas a motorcycle has 2 wheels. Thus we see a parent-child type of relationship here where the Car, Truck or Motorcycle can inherit certain Characteristics from the parent Vehicle; at the same time having their own unique attributes. This forms the basis of inheritance; Vehicle is the Parent, Super or the Base class. Car, Truck and Motorcycle become the Child, Sub or the Derived class.

What is a Virtual Functions in class?

A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions.

A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).

The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

What is Encapsulation in Object Oriented Programming (OOPS) Languages?

Encapsulation is the procedure of covering up of data and functions into a single unit. Encapsulation (also information hiding) consists of separating the external aspects of an object which are accessible to other objects, from the internal implementation details of the object, which are hidden from other objects.

A process, encapsulation means the act of enclosing one or more items within a (physical or logical) container (Class).

Object-oriented programming is based on encapsulation. When an objects state and behavior are kept together, they are encapsulated. That is, the data that represents the state of the object and the methods (Functions and Subs) that manipulate that data are stored together as a cohesive unit.

The object takes requests from other client objects, but does not expose its the details of its data or code to them. The object alone is responsible for its own state, exposing public messages for clients, and declaring private methods that make up its implementation. The client depends on the (hopefully) simple public interface, and does not know about or depend on the details of the implementation.

For example, a HashTable object will take get() and set() requests from other objects, but does not expose its internal hash table data structures or the code strategies that it uses.

Explain the advantages of Encapsulation in Object Oriented Programming Languages.

Benefits of Encapsulation in oops: Encapsulation makes it possible to separate an objects implementation from its behavior to restrict access to its internal data. This restriction allows certain details of an objects behavior to be hidden. It allows us to create a "black box" and protects an objects internal state from corruption by its clients.

Encapsulation is a technique for minimizing interdependencies among modules by defining a strict external interface. This way, internal coding can be changed without affecting the interface, so long as the new implementation supports the same (or upwards compatible) external interface. So encapsulation prevents a program from becoming so interdependent that a small change has massive ripple effects.

The implementation of an object can be changed without affecting the application that uses it for: Improving performance, fix a bug, consolidate code or for porting.

Limitations and Restrictions of Interface

The essential idea to remember is that an interface never contains any implementation. The following restrictions and imitations are natural consequences of this:

You're not allowed any fields in an interface, not even static ones. A field is an implementation of an object attribute.

You're not allowed any constructors in an interface. A constructor contains the statements used to initialize the fields in an object, and an interface does not contain any fields!

You're not allowed a destructor in an interface. A destructor contains the statements used to destroy an object instance.

You cannot supply an access modifier. All methods in an interface are implicitly public.

You cannot nest any types (enums, structs, classes, interfaces, or delegates) inside an interface.

What is the difference between abstract class and interface?

We use abstract class and interface where two or more entities do same type of work but in different ways. Means the way of functioning is not clear while defining abstract class or interface. When functionality of each task is not clear then we define interface. If functionality of some task is clear to us but there exist some functions whose functionality differs object by object then we declare abstract class.

We can not make instance of Abstract Class as well as Interface. They only allow other classes to inherit from them. And abstract functions must be overridden by the implemented classes. Here are some differences in abstract class and interface.

An interface cannot provide code of any method or property, just the signature. We dont need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract. An abstract class can provide complete code of methods but there must exist a method or property without body.

A class can implement several interfaces but can inherit only one abstract class. Means multiple inheritance is possible in .Net through Interfaces.

What is a static class?

We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We can not create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.

Here are some more features of static class:

  • Static classes only contain static members.
  • Static classes can not be instantiated. They cannot contain Instance Constructors
  • Static classes are sealed.

What is static member of class?

A static member belongs to the class rather than to the instances of the class. In C# data fields, member functions, properties and events can be declared static. When any instances of the class are created, they cannot be used to access the static member.

To access a static class member, use the name of the class instead of an instance variable

Static methods and Static properties can only access static fields and static events.

Like: int i = Car.GetWheels;

Here Car is class name and GetWheels is static property.

Static members are often used to represent data or calculations that do not change in response to object state.

What is the difference between value parameter and reference parameter?

A value parameter is used for "in" parameter passing, in which the value of an argument is passed into a method, and modifications of the parameter do not impact the original argument. A value parameter refers to its own variable, one that is distinct from the corresponding argument. This variable is initialized by copying the value of the corresponding argument.

A reference parameter is used for "by reference" parameter passing, in which the parameter acts as an alias for a caller-provided argument. A reference parameter does not itself define a variable, but rather refers to the variable of the corresponding argument. Modifications of a reference parameter impact the corresponding argument.

What is the use of parameter array?

A parameter array enables a many-to-one relationship: many arguments can be represented by a single parameter array. In other words, parameter arrays enable variable length argument lists.

A parameter array is declared with a params modifier in C#. There can be only one parameter array for a given method, and it must always be the last parameter specified. The type of a parameter array is always a single dimensional array type. A caller can either pass a single argument of this array type, or any number of arguments of the element type of this array type.

What is a constant?

A constant is a class member that represents a constant value: a value that can be computed at compile-time.

Constants are permitted to depend on other constants within the same program as long as there are no circular dependencies. The example

class Constants {

public const int A = 1;

public const int B = A + 1;

}

shows a class named Constants that has two public constants.

Happy Programming!!!

OOPs FAQ in C# - Part I

What is the difference between indexers and properties in C#?

Comparison Between Properties and IndexersIndexers are similar to properties. Except for the differences shown in the following , all of the rules defined for property accessors apply to indexer accessors as well.

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

What type of class cannot be inherited?

A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note that a struct is implicitly sealed; so they cannot be inherited.

How do I use an alias for a namespace or class in C#?

Use the using directive to create an alias for a long namespace or class. You can then use it anywhere you normally would have used that class or namespace. The using alias has a scope within the namespace you declare it in. Sample code: // Namespace:
using act = System.Runtime.Remoting.Activation;
// Class:
using list = System.Collections.ArrayList;
...
list l = new list(); // Creates an ArrayList
act.UrlAttribute obj; // Equivalent to System.Runtime.Remoting.Activation.UrlAttribute obj

Can an abstract class have non-abstract methods?

An abstract class may contain both abstract and non-abstract methods. But an interface can contain only abstract methods.

Explain some features of interface in C# or Comparison of interface with class.

An interface cannot inherit from a class.
An interface can inherit from multiple interfaces.
A class can inherit from multiple interfaces, but only one class.
Interface members must be methods, properties, events, or indexers.

All interface members must have public access (the default).
By convention, an interface name should begin with an uppercase I.

Name two ways that you can prevent a class from being instantiated.

Ways to prevent a class from instantiated:

  • A class cannot be instantiated if it is abstract or
  • if it has a private constructor.

What's the difference between override and new in C#?

his is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class. For instance:

public class Base
{
public virtual void SomeMethod()
{
}
}
public class Derived : Base
{
public override void SomeMethod()
{
}
}
...
Base b = new Derived();
b.SomeMethod();
will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.

Now, if you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it. In that case, code like this:

public class Base
{
public virtual void SomeOtherMethod()
{
}
}
public class Derived : Base
{
public new void SomeOtherMethod()
{
}
}
...
Base b = new Derived();
Derived d = new Derived();
b.SomeOtherMethod();
d.SomeOtherMethod();

Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.

If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).

Explain Abstract, Sealed, and Static Modifiers in C#

C# provides many modifiers for use with types and type members. Of these, three can be used with classes: abstract, sealed and static.

  • abstract : Indicates that a class is to be used only as a base class for other classes. This means that you cannot create an instance of the class directly. Any class derived from it must implement all of its abstract methods and accessors. Despite its name, an abstract class can possess non-abstract methods and properties.
  • sealed : Specifies that a class cannot be inherited (used as a base class). Note that .NET does not permit a class to be both abstract and sealed.
  • static : Specifies that a class contains only static members (.NET 2.0).

Which interface(s) must a class implement in order to support the foreach statement?

Required interface for foreach statement: A class must implement the IEnumerable and IEnumerator interfaces to support the foreach statement.

How do I call one constructor from another in C#?

You use : base (parameters) or : this (parameters) just before the actual code for the constructor, depending on whether you want to call a constructor in the base class or in this class.

What is the difference between struct and class in C#?

Structs vs classes in C#

Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

  • When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.
  • Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.
  • When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.
  • There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class object. A struct can implement interfaces, and it does that exactly as classes do,
  • Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

Happy programming!!!

.Net Remoting Interview Questions

  • What is .NET Remoting?

Net remoting replaces DCOM. Web Services that uses remoting can run in any Application type i.e. Console Application, Windows Form Applications, Window Services etc. In CLR Object Remoting we can call objects across network.

  • .NET Remoting Architecture?
  1. Methods that will be called from the client are implemented in a remote object class.
  2. Client uses a proxy to call a remote object.
  3. Remote objects runs inside a process that is different from the client process
  4. For the client, the proxy looks like the real object with the same public methods.
  5. When the methods of the proxy are called, messages are created.
  6. Messages are serialized using a binary formatter class, and are sent into a client channel.
  7. The client channel communicates with the server part of the channel to transfer the message across the network.
  8. The server channel uses a formatter to deserialize the message, so that the methods can be dispatched to the remote object.
  9. The formatter and the proxy is supplied automatically.
  • What is a formatter?

A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

  • How does .NET Remoting work?

.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).

Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.

There are a number of styles of remote access:

SingleCall:
Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished. This (essentially stateless) model can be made stateful in the ASP.NET environment by using the ASP.NET state service to store application or session state.

Singleton:
All incoming requests from clients are processed by a single server object.

Client-activated object:
This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.

  • What’s Singleton activation mode?

A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.

  • What’s SingleCall activation mode used for?

If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

  • .NET Remoting Specific Advantage?

Lease-Based Lifetime :

Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure

.Net Remoting takes a Lease-base Lifetime of the object that is scaleable

Call Context :

Additional information can be passed with every method call that is not part of the argument with the help of SOAP Header

Distributed Identities :

If we pass a reference to a remote object, we will access the same object using this reference.

  • How do you define the lease of the object?

By implementing ILease interface when writing the class code.

  • What are channels in .NET Remoting?

Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.

  • How can you automatically generate interface for the remotable object in .NET with Microsoft tools?

Use the Soapsuds tool.

  • What are possible implementations of distributed applications in .NET?

.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

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

Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.

  • What security measures exist for .NET Remoting in System.Runtime.Remoting?

None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.

  • What’s a Windows process?

It’s an application that’s running and had been allocated memory.

  • What distributed process frameworks outside .NET do you know?

Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).

  • What’s a proxy of the server object in .NET Remoting?

It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.

  • What’s typical about a Windows process in regards to memory allocation?

Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.

  • Can you configure a .NET Remoting object via XML file?

Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

  • 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.

  • Advantage over Web Services?
  1. It works using purely Commmon Type System.
  2. It supports high speed binary over tcp/ip communication.
  • Advantage over COM/DCOM?
  1. It does not have extra interface language (IDL)
  2. It Works using purely managed code
  3. It's using Common Type System.. No Safearrays etc
  • Disadvantages
  1. It is not an open standard like web services.
  2. It is not as widespread and established ad DCOM.
  3. Less support for transactions,load balancing compared with DCOM.
  • Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?

Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.

  • Why do you call it a process?What’s different between process and application in .NET, not common computer usage, terminology?

A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.

  • How many processes can listen on a single TCP/IP port?

One.

Happy Programming!!!

Saturday, October 11, 2008

Setting a Default Browser for Visual Studio 2005/2008

Setting a Default Browser for Visual Studio 2005/2008 :

  • Right click on a .aspx page in your solution explorer
  • Select the "browse with" context menu option
  • In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename
  • Click the "Set as Default" button to make this the default browser when you run any page on the site.
Happy programming!!!

Thursday, October 9, 2008

Dot Net Interview Tips - Part 3

Why should I store my shared assemblies in the GAC?
You should install assemblies in the GAC only when necessary. As a general guideline, assemblies should be kept private and stored in the application's folder unless you explicitly need to share them. There are some benefits to storing shared assemblies in the GAC:

Global Location
The GAC is the known standard location for .NET shared assemblies. When an application attempts to load an assembly, the GAC is one of the first places it looks. If there's any chance that an application outside your control may someday require access to your shared assembly, you should install your assembly in the GAC so the application is sure to find it.

Security
The GAC is a system folder typically protected by administrator rights. Once an assembly is installed in the GAC, it cannot be easily modified. Also, assemblies stored in the GAC must be signed with a cryptographic key. These protections make it difficult to spoof your assembly, in other words, replace or inject your assembly with a virus or malicious code.

Version Management
.NET allows multiple versions of the same assembly to reside in the GAC so that each application can find and use the version of your assembly to which it was compiled. This helps avoid DLL Hell, where applications that may be compiled to different versions of your assembly could potentially break because they are all forced to use a single version of your assembly.

Faster Loading
The system verifies assemblies when they are first installed in the GAC, eliminating the need to verify an assembly each time it is loaded from the GAC. This can improve the startup speed of your application if you load many shared assemblies.


Why would I avoid the GAC?

The GAC should contain "global" shared assemblies only, so there are many instances when you would NOT install an assembly in the GAC:
  • The assembly is private to your application and not to be shared with other applications.
  • You want to use XCOPY or FTP copy to install a .NET application to a single folder. This eliminates the need to access the Registry and GAC and does not require administrator rights.
  • The assembly is not strong-named or you do not want tight version control.
  • COM interop and unmanaged code do not require the GAC.


How do I see assemblies installed in the GAC?

The .NET Framework includes an Assembly Cache Viewer. Open Windows Explorer, enter
%windir%\assembly in the address bar, and all global assemblies will appear in a special view that shows the assembly name, version, culture, public key token, and processor architecture.


Can I install multiple versions of the same assembly in the GAC?

Yes. Normally you would not be able to have two files with the same name in a Windows folder, but the GAC is a special folder that stores its contents by strong name. Hence, two assemblies with the same name but different versions or cultures may coexist in the GAC.


How do I add/remove assemblies from the GAC?

Assemblies added to the GAC must be signed with a strong name. There are multiple ways to add/remove assemblies from the GAC:
  • Windows Installer
  • GAC Utility
  • Assembly Cache Viewer
  • .NET Framework Configuration Administrative Tool
Windows Installer
The preferred way to add/remove assemblies from the GAC is with
Microsoft Windows Installer 2.0. Visual Studio includes a limited version of Windows Installer, and most major setup programs such as InstallShield also use Windows Installer. There are benefits to using Windows Installer:
  • Windows Installer provides a simple interface for developers to add/remove shared assemblies in the GAC and can handle private assemblies as well.
  • Installer provides a familiar interface and setup experience for the user.
  • Installer can also install application shortcuts and supporting files such as ReadMe and license agreements and can run other installation programs and scripts.
  • Installer registers and tracks references to assemblies installed in the GAC to determine which assemblies are still required.
  • Installer can repair and patch assemblies and rollback unsuccessful installations.
  • Installer can install assemblies on-demand as they are needed by applications.
GAC Utility
The .NET developer's kit includes a command line utility
GACutil.exe to interact with the GAC. This utility is intended for use in a development environment only and should not be used to install assemblies on a client PC because:
  • The GACutil license agreement states that it is not freely distributable.
  • GACutil is part of the .NET SDK, which may not be installed on many target PCs.
  • GACutil lacks many important features found in Windows Installer such as assembly repair and rollback.
Assembly Cache Viewer
Using the
Assembly Cache Viewer shown above, you can drag & drop assemblies from any folder into the GAC and also delete assemblies installed in the GAC.

.NET Framework Configuration Administrative Tool
To access the .NET Framework Configuration Tool:
  • Click Start > Control Panel.
  • Double-click on Administrative Tools.
  • Double-click on Microsoft .NET Framework 2.0 Configuration.
  • Ensure My Computer is selected in the tree.
  • In the Tasks group, click the Manage the Assembly Cache link.
  • Two links appear, enabling you to view and add assemblies in the GAC.


How do I access the GAC programmatically?

You can access the GAC from code with the fusion.dll library. Here is an excellent C# wrapper for the GAC.

You are strongly advised NOT to access the GAC from code unless you are creating an administrative or setup tool. The Fusion APIs expose your application to the inner workings of assembly binding and may cause your application to fail on future .NET versions.


How do I add my shared assembly to the Visual Studio "Add Reference" dialog?

If you add an assembly to the GAC, it will NOT automatically appear in the Visual Studio "Add Reference" dialog; instead you must add your assembly manually.

How do I access a loaded assembly?
When working with assemblies, be sure to include the Reflection namespace:
using System.Reflection;
To access your application's main assembly (i.e., the executable file):

Assembly asm = Assembly.GetExecutingAssembly();
To access an external assembly loaded by your application, call GetAssembly with a type defined in the external assembly:

Assembly asm = Assembly.GetAssembly( typeof( MyType ) );


How do I retrieve assembly attributes programmatically?

Once you have the Assembly object as shown above, you can obtain its identity attributes from its AssemblyName object:

AssemblyName asmName = asm.GetName();
Console.WriteLine( "Name={0}, Version={1}, Culture={2}, ProcessorArchitecture={3}", asmName.Name, asmName.Version, asmName.CultureInfo, asmName.ProcessorArchitecture );

For all other assembly attributes, you can load the attribute directly with the
GetCustomAttributes method:

// assembly description attribute
string asmDesc = ((AssemblyDescriptionAttribute)asm.GetCustomAttributes( typeof ( AssemblyDescriptionAttribute ), false )[0]).Description;
// assembly title attribute
string asmTitle = ((AssemblyTitleAttribute)asm.GetCustomAttributes( typeof( AssemblyTitleAttribute ), false )[0]).Title;
// etc.To view all attributes for an assembly:
object[] attributes = asm.GetCustomAttributes( true );
foreach (object obj in attributes)
{
Console.WriteLine( obj.ToString() );
}


How do I set assembly attributes?

There are two ways to set the attributes for an assembly in your development project. Using Visual Studio 2005:

Option 1: AssemblyInfo File
In the Visual Studio Solution Explorer, navigate to the Properties folder, then open the AssemblyInfo.cs file. You can directly edit the attributes in the AssemblyInfo file.

Option 2: Project Properties
Select your assembly project in the Visual Studio Solution Explorer. Click the PropertiesApplication tab. Then click the Assembly Information button. The following dialog will appear, allowing you to edit the assembly attributes.

Dot Net Interview Tips - Part 2

How do I create a strong name key file for a .NET assembly?
Visual Studio 2005 makes it easy to create a strong name key file:

  • Select your assembly project in the Visual Studio Solution Explorer.
  • Click the Properties button. The project properties will appear in the main window.
  • Select the Signing tab.
  • Check the Sign the assembly checkbox.
  • In the Choose a strong name key file drop-down, select New. The "Create Strong Name Key" dialog appears.
  • In the Key file name text box, type the desired key name. Typically this is the name of your assembly but can be anything. Visual Studio will automatically append the proper file extension.
  • If desired, you can protect the strong name key file with a password. To do so, check the Protect my key file with a password checkbox, then enter and confirm the password.
  • Click the OK button.

Now when you compile your project, Visual Studio will automatically sign your assembly with the new strong name key you have just created Or if you prefer to use the command-line, you can create a key pair file with the strong name utility sn.exe in the .NET SDK, for example:

sn -k MyKey.snk

Then you reference that key file to when compiling your code with the C# compiler csc.exe:

csc /keyfile:MyKey.snk MyCodeFile.cs



What does it mean to sign an assembly?

.NET uses digital signatures to verify the integrity of an assembly. The signatures are generated and verified using public key cryptography, specifically the RSA public key algorithm and SHA-1 hash algorithm. The developer uses a pair of cryptographic keys: a public key, which everyone can see, and a private key, which the developer must keep secret.
To create a strong-named assembly, the developer signs the assembly with his private key when building the assembly. When the system later loads the assembly, it verifies the assembly with the corresponding public key.


How do I sign an assembly?
When you compile your assembly with a strong name key file, the compiler digitally signs the assembly:

  • The compiler calculates the cryptographic digest (a hash) of your assembly contents. This is known as the compile-time digest. Modifying just a single byte of your assembly will change this hash value.
  • The compiler encrypts the digest using the 1024-bit private key from your public-private key pair file.
  • The compiler then stores the encrypted digest and public key into the assembly.


How does the system verify a signed assembly?

Sometime later, when an application attempts to load your signed assembly:
  • The .NET assembly loader calculates the cryptographic digest of the current assembly contents. This is known as the run-time digest.
  • The loader extracts the stored compile-time digest and public key from the assembly.
  • The loader uses the public key to decrypt the compile-time digest.
  • The loader then compares the run-time digest with the decrypted compile-time digest to ensure they match. If not, then the assembly has been modified since you compiled it, and the assembly load fails.
This process is different when loading shared assemblies from the GAC. Because assemblies are verified when they are first installed into the GAC–and they cannot be modified while in the GAC–the .NET assembly loader does not verify an assembly when loading it from the GAC. This can improve the startup speed of your application if you load many shared assemblies.


What is delay signing?

Delay signing is signing an assembly with its strong name public key, which is freely distributable, instead of using the private key as usual. This allows developers to use and test a strong-named assembly without access to the private key. Then at a later stage (typically just before shipping the assembly), a manager or trusted keyholder must sign the assembly with the corresponding private key.


How do I protect my private keys?

Private keys must remain secret. A hacker with your private key could spoof your signed assemblies by replacing or injecting them with a virus or other malicious code. There are a few strategies you can use to protect your private keys:
  • Password Protection - As shown above, Visual Studio will allow you to protect your strong name key file with a password.
  • Delay Signing - As mentioned above, delay signing enables your development team to build and test your assembly without access to the private key.
  • Cryptographic Container - One of the most secure ways to protect your strong name key is to store it in a secure cryptographic.


How many private keys should I have?

There are three main strategies for how many private keys a developer should use:
  • One private key for all your applications and assemblies
  • One private key for each application (an application may have multiple assemblies)
  • One private key for each assembly

Which option to use depends on your security situation and risk tolerance. With option 1, it's easier to keep a single key secure, but if your one private key is compromised, then all of your assemblies are compromised. With option 3, there are more keys to manage and hence lose, but if one key is compromised, then only one of your many assemblies is compromised. I recommend option 2 or 3 to reduce your overall exposure.



Are there problems with using strong names?

Strong names are not perfect. There are some issues to consider when using strong names:
  • Requires Exact Match - If you use strong names, your application or library must load the assembly with the exact strong name that you specify, including version and culture. Note that you can bypass this requirement with a publisher policy.
  • Cannot Lose Private Key - If your private key is lost or stolen, the security of your assembly is compromised. You will be forced to re-issue a new assembly signed with a new public-private key pair.
  • Cannot Stop Full Replacement - Strong names cannot prevent a hacker from removing the strong name signature, maliciously modifying your assembly, re-signing it with his own key, and then passing off his assembly as yours. The user must have some way to ensure the public key they have from your assembly is valid and truly came from you. Note that you can use more sophisticated signing to help with this issue.


Where are shared assemblies stored?

A shared assembly is used by multiple applications. You can store shared assemblies pretty much anywhere. However, the challenge is to ensure that all dependent applications can find the shared assembly. The recommended way to ensure this is to store shared assemblies in the Global Assembly Cache.


What is the Global Assembly Cache (GAC)?

The Global Assembly Cache is a system folder (typically C:\Windows\assembly) that contains .NET shared assemblies. Companies that wish to share assemblies with others or even just among their own applications typically store these shared assemblies in the GAC. All of the .NET framework libraries are stored in the GAC.



Monday, July 21, 2008

Visual Studio 2005 / 2008 short cut keys

Visual Studio 2005/2008 short cut keys
Using keyboard shortcuts is the best way to get things done faster in Visual Studio. Below are my favorite Visual Studio keyboard shortcuts.
  • F12 : Go to definition of a variable, object, or function.
  • SHIFT+F12 : Find all references of a function or variable.
  • CTRL+ALT+L : View Solution Explorer. I use Auto Hide for all of my tool windows to maximize screen real estate. Whenever I need to open the Solution Explorer, it’s just a shortcut away.
  • CTRL+M, O: Collapse to Definitions. This is usually the first thing I do when opening up a new class.
  • CTRL+-: Go back to the previous location in the navigation history.
  • ALT+B, B: Build Solution.
  • ALT+B, U : Build selected Project
  • ALT+B, R : Rebuild Solution
  • CTRL+ALT+Down Arrow : Show dropdown of currently open files. Type the first few letters of the file you want to select.
  • CTRL+K, CTRL+D : Format code.
  • CTRL+L : Delete entire line.

Use the technology!!!

Monday, July 14, 2008

ValidateRequest in Page directive in asp.net

ASP.NET 2.0 validates form input values for potentially dangerous entries such as the '<' and '>' characters. When I enter the value '<' and '>' in textbox in .Net web form, it returns an error like 'Sys.WebForms.PageRequestManagerServerErrorException: An unkown erroroccured while processing the request on the server. The status code returned from the server was: 500'. So I search on google indicates the below solution for this :
  • Add ValidateRequest = "false" in the Page directive.
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="sample.aspx.cs"
    Inherits="KannanDemo.sample" validateRequest="false"%>
    After added it and run the application. This time I got the error like The 'ValidateRequest' attribute is not supported by the 'Page directive.'

  • Then I found another way to solve this issue by adding <pages ValidateRequest="false"/> in System.Web of the Web.Config file. I got the result.

Note:

The main disadvantage of setting the ValidateRequest to false on a page is the openning of an opportunity to hack your page, because the ValidateRequest's job is to ensure that the most common injection attacks are not possible for your page, and so if you disable it then you should start making all the necessary changes to avoid SQL Injection, Script Injection, and so on.

Happy coding!!!

Saturday, July 12, 2008

Convert IEnumerable to DataTable in C#

Convert IEnumerable to DataTable in C#

In LINQ, there is no option to casting IEnumerable to DataTable. We need to convert manually. For this, I have created one healper class which convert any type of IEnumerable to DataTable. Use the code below for this kind of requirements.

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Reflection;



namespace KannanDotNetReference.HelperClasses

{

static public class ConvertDataTable

{

public static DataTable ConvertToDataTable<T>(this System.Collections.Generic.IEnumerable<T> varList, CreateRowDelegate<T> fn)

{

DataTable dataTable = new DataTable();



// Variable for column names.

PropertyInfo[] tableColumns = null;



// To check whether more than one elements there in varList.

foreach (T rec in varList)

{

// Use reflection to get column names, to create table.

if (tableColumns == null)

{

tableColumns = ((Type)rec.GetType()).GetProperties();

foreach (PropertyInfo pi in tableColumns)

{

Type columnType = pi.PropertyType;

if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition() == typeof(Nullable<>)))

{

columnType = columnType.GetGenericArguments()[0];

}

dataTable.Columns.Add(new DataColumn(pi.Name, columnType));

}

}



// Copying the IEnumerable value to DataRow and then added into DataTable.

DataRow dataRow = dataTable.NewRow();

foreach (PropertyInfo pi in tableColumns)

{

dataRow[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);

}

dataTable.Rows.Add(dataRow);

}

return (dataTable);

}



public delegate object[] CreateRowDelegate<T>(T t);

}

}





See the below sample which fetch all the country with their customers count from Northwind database by using LINQ.
I have created Sample.aspx with one gridview control for displaying the result. See the code below: Sample.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="KannanDotNetReference.Sample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Kannan Samples : IEnumerabl to DataTable convertor</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

See the sample.aspx.cs code below which fetch the data from Northwind by using LINQ technique. In the code GetCountry() method is using ConvertToDataTable() helper method for converting IEnumerable result to datable. See the complete codeing of Sample.aspx.cs :


using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using KannanDotNetReference.HelperClasses;



namespace KannanDotNetReference

{

public partial class Sample : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

GridView1.DataSource = GetCountry();

GridView1.DataBind();

}



private DataTable GetCountry()

{

var db = new NorthwindDataContext();

var table = db.KannanGetCountry();



DataTable dt = table.ConvertToDataTable(record => new object[] { table });



return dt;

}

}

}




Once we finished our coding part, next run this application. See the result below.


Note:

I have created one stored procedure for fetching the country with number of customers belongs to by using the below code:


CREATE PROCEDURE [dbo].[KannanGetCountry]
AS
SELECT
Country as 'CountryName',
COUNT(CustomerId) as 'CountryCount'
FROM Customers
GROUP BY Country

Happy Coding!!!

Wednesday, July 9, 2008

Publishing Web Site in asp.net 2.0

Publishing Web Site in asp.net 2.0

Compilation and Publishing in ASP.NET 2.0 is completely different than in ASP.NET 1.1. In ASP.NET 1.1, whether you debugged the code or ran it from a server, all of the .cs files were compiled into a single dll and the markup (.aspx and .ascx) remained seperate. This could often lead to problems if you declared a control in the markup but then didn't have a coresponding reference in the .cs file. All of this has changed.

When you click Build Web Site, it doesnt compile all of the .cs files into a single dll. It only validates that the code is syntactically correct. It will validate the .cs files as well as the .aspx and .ascx files.

When you run it through the debugger or you use xcopy deployment directly against the files in your web project, it uses dynamic compilation to run the web site. This means that if you change a .cs file, the next time that file is hit in a web browser, it will compile it on the fly.

So when you want to deploy the web site, you click Publish Web Site. You can also do this using the new aspnet_compiler.exe and point it to a solution file.

The Publish Web Site dialog will prompt you for a location. This can be a file path, a web site address, or ftp site. It also has three different checkbok options:

  1. Allow this precompiled site to be updatable
  2. Use fixed naming and single page assemblies
  3. Enable strong naming on precompiled assemblies

1. Allow this precompiled site to be updatable

The Allow this precompiled site to be update option when checked leaves all of the .aspx and .ascx files alone. This way they can be changed by an external tool. When it is unchecked, it compiles the entire site including .aspx and .ascx files into a single dll or multiple dlls.

When you publish with this option, we get the following in bin folder under published folder.

  1. .compile file and the corresponding file should be placed for each update of a given aspx, master file and if there is only change is code-behind class, this file should be included too.
  2. For code change in App_Code, no need to copy App_Code.compiled, just copy App_Code.
  3. For code change in Global.asax, no need to copy App_global.asax.compiled, just copy App_global.asax.dll.
  4. For changes in CSS files of App_themes CSS should be copied manually.

2. Use fixed naming and single page assemblies

For deploying assemblies of a ASP.NET 2.0 projects there are three ways to do:

  1. Single page assembly
  2. Batch assembly
  3. Merged assembly

The filename format for a particular dll will be App_web_<filename>.<random four byte hex string>.dll. . So the filename for the default control would look like this, App_web_default.ascx.2ce8cdef.dll. The random four byte hex string is supposedly the same every time you compile. It also seems to use the same string at each directory level. When unchecked there is no guarantee what the filenames will be in the dlls and entire directories will be grouped into the same dlls.

Single page assembly

In Visual Studio 2005, for a ASP.NET 2.0 web application, we can deploy separate assemblies for each pages of the site! This can be done by enabling the above option.

If the 'Allow this precompiled site to be updatable' is disabled, that means a corresponding .compile file should also be deployed with the assembly of each page. In this case, if there is any change in the page, we need not to deploy the updated .compile file in the web, as all contents are placed in the dll, but as the resource locator or for the basic rule, Atlas one version of .compile file should be placed in the bin directory of the deployment site.

Any way, no matter, whether the change has been done in content or code, the page dll MUST be deployed! For a change in content, if only .compiled is provided, there is no error, but change will not take effect!

Batch assembly

For different type of contents and codes, different sets of assemblies will be generated, if we make the above option false. So any change in the code of a page, requires the corresponding set of assemblies to be deployed.

The Use fixed naming and single page assemblies option tells the compiler to use the same names for the dlls it creates every time it compiles. It also will make the compiler create seperate dlls for every page and control on the site. This will allow for indiviudal controls to be updated without affecting any of the other ones.

For batch assembly, each dll includes a encrypted key in it's name and for separate web publishing, there are separate keys for the same type of contents, thus separate file name for the newer version.

Merged assembly

All of the coding contents can be embeded to a single assembly, like VS 2003 age, using a VS add-in named 'aspnet_merge.exe' provided by Microsoft. Unfortunately, this tool is not provided by default and should be downloaded and installed separately.

3.Enable strong naming on precompiled assemblies

Enable Strong Naming on Precompiled Assemblies is basically the same as specifynig a key in the assemblyinfo.cs in ASP.NET 1.1.

Depends on the requirement and necessity we can choose any of the method given above.

Use the technology!!!