Tuesday, September 20, 2011

A Study of Delegates


Introduction

Many of us already have some idea of delegates. But let's go deep inside and examine how the CLR/runtime and the compiler interprets the delegates, and what happens when you declare and manipulate delegates.
A delegate is a reference type, thus it does not hold the actual value, rather it holds the address of an object residing somewhere in the heap. To make the understanding of delegates simple, compilers represent the delegates in a different way than how it is interpreted by the CLR/runtime. We will first study how the compiler exposes delegates, and then we will jump into some ground realities of delegates from the CLR/runtime perspective.

Delegates and .NET Compilers

To make life simpler, most .NET compilers symbolize delegates as pointers to a function, just like the function pointers we have in C++. Thus, in C#, you declare delegates as follows:
public delegate void MyDelegate (int someParam, string anotherParam);
From a C# compiler perspective, MyDelagate is a delegate that could hold the address of a function that has the similar signature.
The ability of holding the address of a function makes delegates ideal for:
  1. Callback functionality
  2. Event modeling
  3. Having more than one implementation against a method
Though the C# compiler exposes delegates as reference types, you could not instantiate the delegate by using thenew operator; rather delegates could be instantiated by:
  1. Providing the name of the method to the delegate. These types of delegates are known as "Named Delegates".
    void DoSomething(int someParam, string anotherParam)
    {
        //Method implementation
    
    }
    
    MyDelegate del = DoSomething;
    //del is a Named Delegate holding 
    
    //the address of function DoSomething.
  2. Providing the implementation of the method to the delegate. These type of delegates are known as "Anonymous Delegates".
    del = delegate(int someParam, string anotherParam)
          { //Method implementation };
Invoking of named or anonymous delegates is same as calling the function:
Del (29, "some value");

Named Delegates

Named delegates could hold the address of instance methods as well as the address of static methods. If the return type of a method is inheriting from the return type defined in the delegate, then the delegate is known as aCovariance Delegate. If the parameters of the methods are the base types of the parameters defined in the delegate, then the delegate is known as a Contravariance Delegate.
public delegate ICollection MyDelegate (int someParam, 
                                 string anotherParam); 

IList DoSomething()
{
    //Method implementation

}

MyDelegate del = DoSomething;

//As IList is child of ICollection thus, 

//Del is covariance delegate.

public delegate ICollection MyDelegate (IList param);

IList DoSomething(ICollection param)
{
    //Method implementation

}

MyDelegate del = DoSomething;

//As IList is child of ICollection thus, 

//Del is contravariance delegate.

Anonymous Delegates

If an anonymous delegate is referring to some local variables, then the life of that variable would be extended to the life of that delegate.
public delegate void MyDelegate (int someParam, string anotherParam); 

MyDelegate del
void DoSomething()
{
    int n;
    del = delegate(int someParam, string anotherParam)
    { 
        n++;
    }    
}
//In above example life of local variable n 

//would be same as life of anonymous delegate del.

Delegates and the CLR/Runtime

.NET compilers have made our life easy in handling delegates. In reality, there is neither any concept of pointers to a function nor any significance to the word "delegate" in the CLR/runtime. Rather, the CLR provides an abstract classSystem.Delegate that holds the reference of a static method or class instance and the instance method of that class. The System.Delegate has two properties.
  • Target: Holds the reference of an instance on which the current delegate invokes the instance method. If the method is a static method, this property holds a null value.
  • Method: Holds the instance of the MethodInfo class for the method represented by the delegate.
The delegate also exposes the DynamicInvoke function to call the method represented by the Method property. This function takes an array of objects that are the arguments to pass to the target method. If the target method does not take any arguments, the parameter to the DynamicInvoke function would be null.
The CLR also exposes an abstract class System.MultiCastDelegate that inherits from System.Delegate.System.MultiCastDelegate maintains a list, called the Invocation List, of a delegate object. When a multicast delegate is invoked, all the delegates in the invocation list are called synchronously. TheSystem.MultiCastDelegate exposes the Combine method to add delegates to the invocation list.
When you define a delegate in C#, a new class with the name of the delegate inheriting fromSystem.MultiCastDelegate is created by the C# compiler.
public delegate ICollection MyDelegate (IList param);
The above statement causes a a new class to be added in your assembly by the C# compiler.
public class MyDelegate : System.MultiCastDelegate
You can view this class by opening your assembly using the Ildasm utility.
When you assign a method to a delegate, an instance of the compiler generated class is created with the Targetand Method as parameter to this class. In case the method is static, null is passed to the argument, Target.
As compiler generated classes are inheriting from System.MultiCastDelegate, thus delegate could hold the addresses of more than one method. C# exposes a simple method to add a method in the invocation list of underlying multiCast delegate object.
MyDelegate del;
del += DoSomething;
del += DoAnotherThing;
Internally, the C# compiler is calls the Combine method of the compiler-generated delegate class to add the methods to the invocation list.
When you invoke a delegate, C# internally calls the DynamicInvoke method of the compiler generated class. The compiler generated class also exposes methods to invoke the target methods asynchronously.
A delegate is known as an Open Instance Delegate if the Target is also provided at the time of invocation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Understanding Covariance and Contravariance in .NET 4.0


A couple of years back, while working on a project, we got a compilation exception related to Generics.
Let A base class BaseVO and classes deriving from BaseVO. For example, “FlightVO : BaseVO”.My idealistic assumption was that since: “FlightVO” inherits from BaseVO, and since BaseVO b = new FlightVO() is valid as per inheritance, then:
“List lstBaseVO = new List() would also be valid.”
But duh !!! Instead, I get a compilation exception that says:
Argument ’1′: cannot convert from 
  ‘System.Collections.Generic.List’ 
  to ‘System.Collections.Generic.List’
Since I was so sure about my assumption being right, I posted it on the MSDN forum just to confirm that it was a “bug” :-) in Generics. Thread in MSDN forum: http://social.msdn.microsoft.com/Forums/bg-BG/netfxbcl/thread/e4863bda-3f24-4a28-af55-230baaff5e7b.
Those were the .NET 3.0 days and one of the MVP moderators gave a pretty good explanation as to why my assumption was wrong. Here’s his explanation:
“List and List are distinct types, you can’t convert List toList. If it were possible, you could pass a List to a method acceptingList and that method could add an object of type Base to the list, which violates the promise that the original list only contains objects of type Derived”.
I assume someone in the CLR team might have found my assumption quite viable and it got shape in .NET 4.0 as“Covariance and Contravariance in Generics” :-).
So the above case is a valid example where “Covariance in Generics” can be used.
However, if we compile List lstBaseVO = new List() in .NET 4.0, it would still give the same compilation error for the very explanation given by our MVP friend. In order to make it covariant compliant, our modified piece of code would look like:
IEnumerable< BaseVO > lstBaseVO = new List< FlightVO >();
The above statement is valid because, in .NET 4.0, List : IEnumerable where type ‘T’ is marked as covariant.
Here’s a quick summarization about variance in Generics.
  1. What are the programming constructs where covariance and contravariance are applicable? Variant type parameters are restricted to generic interfaces and generic delegate types thereby ensuring type safety.
  2. In what scenarios would we want to use variance in Generics? Let's look at a code snippet.
covariance example
So, covariance and contravariance of generic type parameters enable us to use constructed generic types [A] whose type arguments [Athlete] are more derived (covariance) or less derived (contravariance) than the type argument [Person] of a target constructed type [ISample].
Covariance seems very natural because it behaves like polymorphism, whereas Contravariance seems counterintuitive. One thing that we need to be clear about is that both Covariance and Contravariance both adhere to the thumb rule of “Inheritance” which says,
“A derived class instance can be assigned to a base class variable”
Now, let’s look at a Contravariance example.
contravariiance1
Line 2 of code snippet might make you feel that the thumb rule of inheritance is being violated. I.e., the derived class variable d is being assigned an instance of the Base class.
However, that isn’t the case. Let’s understand each line of the code snippet.
contravariiance2
contravariiance4
contravariiance3
In general, a covariant type parameter can be used as the return type of a generic delegate/interface, and contravariant type parameters can be used as input parameter types.
A brief summary of facts about variance in the common language runtime:
  1. A generic interface or generic delegate type can have both covariant and contravariant type parameters.
  2. Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type.
  3. How do we define variant generic interfaces and delegates?
Starting with the .NET Framework 4, Visual Basic and C# have keywords that enable you to mark the generic type parameters of interfaces and delegates as covariant or contravariant.
  • A covariant type parameter is marked with the out keyword. You cannot use a covariant type parameter as a generic type constraint for interface methods. E.g., T Display(); is an invalid statement.
  • A contravariant type parameter is marked with the in keyword. You can use a contravariant type parameter as a generic type constraint for an interface method.
Thank you.

Your Azure Web Role and Full IIS – Culture Changes


On Azure SDK v1.3 onwards, your web role can enjoy the benefits full IIS capabilities. It means that your application has now fully controlled by IIS 7.x. Prior to v1.3, your web role was hosted on “Hosted Web Core” (HWC – hmmm, another acronym), a feature introduced in IIS 7.0. HWC can be seen as a raw IIS without having IIS monitoring and administrative features. Hence, you can have your own IIS for a specific web application. It runs in a different process (WaWebHost.exe) and has a dedicated single application pool. So, the mental model of your web role application would be:
WaWebHost
An Azure web role consists of two logical parts in the assembly, one is RoleEntryPoint implementation and another one is your actual web application. Your typical Azure web role has:
  • Web role lifecycle code (RoleEntry – OnStart, OnRun and OnStop) and Service model (csdef and cscfg)
  • Web application code and web configuration (web.config)
In HWC, both Web role and web application logical artifacts are resided in a single process (WaWebHost.exe) as shown in figure 1. In the new full IIS capability feature, web role artifacts are loaded into a process calledWaIISHost.exe. The web application code as usual is in w3wp.exe. This is shown in figure 2.
WaIISHost
This creates some culture changes in the approach we previously did. I have experimented only on DevFabric and am yet to test on Azure. Probably, I’ll update later. The changes are:
  • Process with different accounts. WaIISHost and w3wp are now running in two different account privileges. Generally, WaIISHost runs in higher privilege and this would cause some code in your web application which was previously enjoyed this high privilege benefit. For example, you can create or access an machine level environment variable from your web application in HWC mode. In Full IIS, this makes exception.
  • Global Configuration Setting Publisher. In HWC, it is enough to initialize global configuration setting publisher once in RoleEntryPoint.OnStart(). However, now in two different processes, you have to again set the publisher either in your framework start up or Application_Start(), otherwise it throws an exception with message “SetConfigurationSettingPublisher needs to be called beforeFromConfigurationSetting can be used”. Instead of being held up with two different initializations,CloudStorageAccount.Parse() is quite simple and elegant. It just want the connection string detail as a string which can be provided by RoleEnvironment.GetConfigurationSettingValue(…). This is safer too.
  • Application_End will not be encountered. In full IIS, Application_End() will never be called when you stop the debugging like you normally did in HWC.
  • Static variables in RoleEntryPoint are not accessible from your web application. Since these two applications are running in two different processes, sharing objects through static variable is not possible in Full IIS. Instead, try to use machine level environment variable or local resource.

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-ShareAlike 2.5 License

C# & SQLite – System.Data.SQLite

Building an VS2010 project using an SQLite embedded database.. Project codename &quotContact&qout; I’ll be demostrating how to insert, edit and delete records from the database First of all you’ll have to aquire a few files and install a few necessary software packets. SQLite ADO.Net pro
  • Building an VS2010 project using an SQLite embedded database
  • Project codename &quotContact&qout;
  • I’ll be demostrating how to insert, edit and delete records from the database
First of all you’ll have to aquire a few files and install a few necessary software packets.

SQLite Admin Tool

This tool I chose the Full install and I’m pleased with the result.

SQLite ADO.Net Provider

This tool I installed in a C:\Temp file and I choze not to register the DLL files. Why because I just needed to include the main DLL in my project.
First we create a SQLite dB named "Contact.3db" using the SQLite Admin tool. I added a table "Contact" with a few fields and inserted a few records of data to play with.
CREATE TABLE [Contact] (
[contact_id] INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL,
[FirstName] vARCHAR(50)  NULL,
[LastName] vARCHAR(50)  NULL)
Next I created a VS2010 project named "Contact" and added a few folders and files
  • Add a folder[Database] and insert an existing Item "Contact.3db"
  • Change the property  "Copy to Output Directory" -> "Copy Always"
Next I added the ecential SQLite DLL to my project.
System.Data.SQLite.dll -> change the property "Copy to Output Directory" -> "Copy Always"
SQLite.Interop.dll -> change the property "Copy to Output Directory" -> "Copy Always"
Remark: Both files [ System.Data.SQLite.dll , SQLite.Interop.dll ] must be included just under the root project "Contact".
Contact
->  System.Data.SQLite.dll ->  SQLite.Interop.dll
Next I added a Folder named "Classes" and created to classes to handel all dB transactions..
dBFunctions.cs and dBHelper.cs
Next I added a Folder named "Forms" and created a few forms to handel Interaction / Interface
ContactList.cs , BaseContact.cs , NewContact.cs ,  EditContact.cs , DeleteContact.cs
And this includes my files within my project.

You can download the source code here

How to clear a TextBox value in a single click in C# .NET


protected void Button2_Click(object sender, EventArgs e)
{
    ClearInputs(Page.Controls);
}
void ClearInputs(ControlCollection ctrls)
{
    foreach (Control ctrl in ctrls)
    {
        if (ctrl is TextBox)
            ((TextBox)ctrl).Text = string.Empty;
        ClearInputs(ctrl.Controls);
    }
}

Friday, September 16, 2011

Sending HTML e-mail with embedded images

I've seen a couple posts on this before but they all seem to miss out a critical piece of code that without, causes the images to be embedded but they do not display correctly in some e-mail clients (such as Outlook 2003/2007). The following code will make it work across a number of clients I've tested it with and I've also thrown in a basic way to have a plain text e-mail attached as well in case the client does not support HTML.

Disclaimer: I've chosen to use the media type of JPEG, it's not ideal but it's something I threw together to get the main point across. You should really get the file extension and use a switch statement for the different media types.

public static void SendMessageWithEmbeddedImages()
{
  string htmlMessage = @"<html>

                         <body>
                         <img src='cid:EmbeddedContent_1' />
                         </body>
                         </html>";
  SmtpClient client = new SmtpClient("mail.server.com");
  MailMessage msg = new MailMessage("noreply@deventerprise.net",
                                    "someone@deventerprise.net");
  // Create the HTML view

  AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
                                               htmlMessage,
                                               Encoding.UTF8,
                                               MediaTypeNames.Text.Html);
  // Create a plain text message for client that don't support HTML
  AlternateView plainView = AlternateView.CreateAlternateViewFromString(
                                              Regex.Replace(htmlMessage,
                                                            "<[^>]+?>",
                                                            string.Empty),
                                              Encoding.UTF8,
                                              MediaTypeNames.Text.Plain);
  string mediaType = MediaTypeNames.Image.Jpeg;
  LinkedResource img = new LinkedResource(@"C:\Images\MyImage.jpg", mediaType);
  // Make sure you set all these values!!!

  img.ContentId = "EmbeddedContent_1";
  img.ContentType.MediaType = mediaType;
  img.TransferEncoding = TransferEncoding.Base64;
  img.ContentType.Name = img.ContentId;
  img.ContentLink = new Uri("cid:" + img.ContentId);
  htmlView.LinkedResources.Add(img);
  //////////////////////////////////////////////////////////////
  msg.AlternateViews.Add(plainView);
  msg.AlternateViews.Add(htmlView);
  msg.IsBodyHtml = true;
  msg.Subject = "Some subject";
  client.Send(msg);
}

I couldn't find this information anywhere but I tried setting a whole bunch of things until the images displayed correctly, hope this helps someone with the same issues.


Expect to see this feature in my Command Line E-mailer application so that sending HTML e-mails appear the way you designed them locally when they arrive at the recipient.

Android applications in C# using Visual Studio

Getting Started

To get everything installed read this guide. Then you can read about the API and architecture to get a better understanding about how it all gels together. Pretty much everything you need including signing up for the newsletter can be found by going directly to www.monodroid.net.
Once you have everything installed it’s pretty easy to get going. The beauty about diving in using a language you are familiar with, means you can get used to the Android SDK without having any knowledge of Java or even C++ (for more advanced features). MonoDroid wraps up all the calls using standard .NET constructs through a JNI bridge, plus, you get all of the power of the standard .NET API’s which work in Linux/Android.

Hello Android

Following the tradition of “Hello World”, let’s jump right in and write an Android application.
  1. Make sure that you have everything installed, this guide couldn’t have made it easier.
  2. Create a new Project in Visual Studio: New MonoDroid project in Visual Studio 2010
  3. MonoDroid does most of the heavy lifting for you. If you’re familiar with Android projects in Eclipse you should have any problems with the structure. Android uses layout and string resource files (the right way) for the UI. Activities are like UI controllers, all the info you need is on the Android Developers website.
  4. Just run the application to check everything is working correctly, if you don’t have a device attached or an emulator running then now is the time to create one: Select a device to connect the debugger 

    If you don’t see anything then just click “Start emulator image”: Select an emulator to start or create a new one
    Once again MonoDroid holds your hand by signing the package and also installing the Mono runtime if it’s not already available.
    WARNING: If you are running an emulator then this will take a while, if you have a monster PC that does it in seconds then I hate you.
  5. Unlock the phone/emulator and click the button: The default Hello World application 
    That’s it! There is a lot of documentation on writing Android applications. Java isn't that far off in syntax to C# so it will be easy to pick up sample code all over the place.


More Information

The best place to start is the MonoDroid API design documentation. Do yourself a favour and browse the classes in the Android namespace. Make sure you check Android.Provider which gives you access to things like Contacts, Settings, Calls Logs etc. through static classes.
This Justin guy slicked the domain www.mono-droid.com in July 2010 already so this isn’t new, just widely available now and free for the time being. There is a lot of useful information on installing and developing here. He’s got videos too, everyone loves videos.

Thursday, September 15, 2011

Interview Questions and Answer on .Net,C#,ASP.NET,SQL Server

Interview Questions and Answer on .Net,C#,ASP.NET,SQL Server

  • All .NET training videos and explanation are not just theory and one liners. They are in depth videos with source code and explanation and finally taking out the actual meat which you need to speak before the interviewer to impress him.
  • We do not just provide videos and leave the developers on their own.Online support via live meeting from Microsoft MVP's takes this product to a greater height.
  • We understand no one can see 500 videos at one go. We organize regularC# training on various topics so that your learning curve is reduced to a great extent.
  • Around 500 videos covering right from .NET, CSharp Interview Questions and Answers. You are either a fresher /senior architect /project manager this solution is for every level.
  • Full DVD delivered to your doorsteps( only for USA , India and Canada).
  • Mock interviews, Mock interviews , Mock interviews and Mock interviews makes this solution and perfect package for your job search. These mock interviews are conducted by our specialist to evaluate how much you are prepared and ready.
  • Superb one liner interview answer cheat sheet to make you revise in a day.
  • Videos are not just theory and talks , its Step by Step demonstration with actual code and fundamentals.
  • Money back if you are not satisfied with our videos and support.
Summary of Topics Covered in .Net Training
We understand that working on a project is one thing but clearing interviews needs a change of mind set and this solution is especially meant for the same. From the same aspect we have divided our interview videos are divided in 5 essential categories :-
  • Basic .NET, ASP.NET, OOPS and SQL Server. Interview questions and answers
  • New technologies WCF, WPF, Silverlight , LINQ, Azure, EF and 4.0. Interview questions and answers
  • Design pattern, UML, Architecture, Estimation, Project management, VSTS. Interview questions and answers
  • Complete Invoicing project end to end. Interview questions and answers
  • Server products (Sharepoint 2007 questions and answer videos). Interview questions and answers
  • Best practices and SQL performance tuning. Interview questions and answers
Details of the above .Net Training Topics
Below is our detail video list of the above main .Net Training topics. All .net training videos go in-depth with source code and then explaining you the one liner which you need to speak in the interview.

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.
  • What is IL code, CLR, CTS, GAC & GC?
  • How can we do Assembly versioning?
  • can you explain how ASP.NET application life cycle and page life cycle events fire?
  • What is the problem with Functional Programming?
  • Can you define OOP and the 4 principles of OOP?
  • What are Classes and Objects?
  • What is Inheritance?
  • What is Polymorphism, overloading, overriding and virtual?
  • Can you explain encapsulation and abstraction?
  • What is an abstract class?
  • Define Interface & What is the diff. between abstract & interface?
  • What problem does Delegate Solve ?
  • What is a Multicast delegate ?
  • What are events and what's the difference between delegates and events?
  • How can we make Asynchronous method calls using delegates ?
  • What is a stack, Heap, Value types and Reference types ?
  • What is boxing and unboxing ?
  • Can you explain ASP.NET application and Page life cycle ?
  • What is Authentication, Authorization, Principal & Identity objects?
  • How can we do Inproc and outProc session management ?
  • How can we windows , forms and passport authentication and authorization in ASP.NET ?
  • In a parent child relationship which constructor fires first ?
MVC ASP.NET Q & A series
  • How to create a simple "Hello World" using ASP.NET MVC template? - Lab 1
  • How to pass data from controller to views? - Lab 2
  • Can we see a simple sample of model using MVC template? - Lab 3
  • How can we create simple input screens using MVC template? - Lab 4
  • How can we create MVC views faster and make them strong typed by using HTML helper? - Lab 5
  • Can we see how easy it is do unit testing for MVC application? - Lab 6
  • What is MVC routing? - Lab 7
  • How can we set default values & validate MVC routes? - Lab 8
  • How we can define actions & navigate from one page to other page? - Lab 9
WCF, WPF, Silverlight, LINQ, Azure and EF 4.0 interview question and answers
  • What is SOA, Services and Messages ?
  • What is the difference between Service and Component?
  • What are basic steps to create a WCF service ?
  • What are endpoints, address, contracts and bindings?
  • What are various ways of hosting WCF service?
  • What is the difference of hosting a WCF service on IIS and Self hosting?
  • What is the difference between BasicHttpBinding and WsHttpBinding?
  • How can we do debugging and tracing in WCF?
  • Can you explain transactions in WCF (theory)?
  • How can we self host WCF service ?
  • What are the different ways of implementing WCF Security?
  • How can we implement SSL security on WCF(Transport Security)?
  • How can we implement transport security plus message security in WCF ?
  • How can we do WCF instancing ?
  • How Can we do WCF Concurency and throttling?
  • Can you explain the architecture of Silverlight ?
  • What are the basic things needed to make a silverlight application ?
  • How can we do transformations in SilverLight ?
  • Can you explain animation fundamentals in SilverLight?
  • What are the different layout methodologies in SilverLight?
  • Can you explain one way , two way and one time bindings?
  • How can we consume WCF service in SilverLight?
  • How can we connect databases using SilverLight?
  • What is LINQ and can you explain same with example?
  • Can you explain a simple example of LINQ to SQL?
  • How can we define relationships using LINQ to SQL?
  • How can we optimize LINQ relationships queries using ‘DataLoadOptions’?
  • Can we see a simple example of how we can do CRUD using LINQ to SQL?
  • How can we call a stored procedure using LINQ?
  • What is the need of WPF when we had GDI, GDI+ and DirectX?
  • Can you explain how we can make a simple WPF application?
  • Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?
  • Can you explain the Architecture of WPF?
  • What is Azure?
  • Can you explain Azure Costing?
  • Can we see a simple Azure sample program?
  • What are the different steps to create a simple Worker application?
  • Can we understand Blobs in steps, Tables & Queues ?
  • Can we see a simple example for Azure tables?
  • What is Package and One click deploy(Deployment Part - 1) ?
  • What is Web.config transformation (Deployment Part-2)?
  • What is MEF and how can we implement the same?
  • How is MEF different from DIIOC?
  • Can you show us a simple implementation of MEF in Silverlight ?
Design pattern, Estimation, VSTS, Project management interview questions and answers

Design Pattern Training / Interview Questions and Answers
  • Introduction
  • Factory Design Pattern
  • Abstract Factory Design Pattern
  • Builder Design Pattern
  • Prototype Design Pattern
  • Singleton Design Pattern
  • Adapter Design Pattern
  • Bridge Design Pattern
  • Composite Design Pattern
  • Decorator Design Pattern
  • Facade Design Pattern
  • Flyweight Design Pattern
  • Proxy Design Pattern
  • Mediator Design Pattern
  • Memento Design Pattern
  • Interpreter Design Pattern
  • Iterator Design Pattern
  • COR Design Pattern
  • Command Design Pattren
  • State Design Pattern
  • Strategy Design Pattern
  • Observer Design Pattern
  • Template Design Pattern
  • Visitor Design Pattern
  • Dependency IOC Design pattern
  • MVC , MVP , DI IOC and MVVM Training / Interview Questions and Answers


UML Training / Interview Questions and Answers
  • Introduction
  • Use Case Diagrams
  • Class Digrams
  • Object Diagrams
  • Sequence Digrams
  • Collaboration Diagrams
  • Activity Diagram
  • State chart Diagrams
  • Component Diagrams
  • Deployment Diagrams
  • Stereo Types Diagrams
  • Package Diagram and UML Project Flow.
Function points Training / Interview Questions and Answers
  • Introduction
  • Application Boundary
  • EI Fundamentals
  • EO Fundamentals
  • EQ Fundamentals
  • EIF
  • Fundamentals
  • ILF Fundamentals
  • GSC Fundamentals
  • Productivity Factor
  • Costing and a complete estimation of customer screen using function points.
  • FXCOP and Stylecop Training / Interview Questions and Answers


VSTS Training / Interview Questions and Answers
  • VSTS questions and answer videos
  • What is Unit Testing & can we see an example of the same?
  • How can we write data driven test using NUNIT & VS Test?
  • Can we see simple example of a unit test for database operation?
  • How can we do automated testing using Visual Studio Test?
  • How can we do Load Testing using VSTS test?
  • Can you explain database unit testing?
  • How can we do test coverage using VSTS system?
  • How can we do manual Testing using VSTS?
  • What is Ordered Test in VSTS test?



Enterprise Application Blocks Training
  • Introduction
  • Validation Application Block
  • Logging Application Block
  • Exception error Handling
  • Data Application Block
  • Caching Application Block
  • Security Application Block
  • Policy Injection Application Block and
  • Unity Application Block


Complete .NET invoicing project end to end
  • Introduction to .NET Projects
  • Different levels of Programming
  • Necessary Tools
  • What should we learn ?
  • The IIS
  • Making UI using .net IDE
  • Database, The SQL Server
  • Connecting ASP.net with Database
  • Loading the Data Grid
  • Update and Delete
  • Validations
  • Issue with the Code
  • Two Tier Architecture
  • Three Tier Architecture
  • Database Normalization
  • Session and State Management
  • Using Enterprise Application Block
  • Aggregation and Composition
  • Implementing Interfaces and Factory
  • Inheritance relationship
  • Abstract Class Implementation


Share point interview Training / Interview Questions and Answers videos
  • What is SharePoint, WSS and MOSS?
  • How does WSS actually work?
  • What is Site and SiteCollection?
  • What is the use of SQL server in SharePoint & use of Virtual path provider?
  • What is Ghosting and UnGhosting in SharePoint?
  • How can we create a site in SharePoint?
  • How can we Customize a SharePoint Site?
  • What kind of readymade functional modules exists collaboration?
  • Can you display a simple Custom Page in SharePoint?
  • How can we implement behind code ASPX pages in SharePoint?
  • What is the concept of features in SharePoint?
  • I want a feature to be only displayed to admin?
  • How do we debug SharePoint error’s?
  • Why customized pages are parsed using no-compile mode?
  • Can you explain WSS model?
  • How can we use custom controls in SharePoint?
  • How can we display ASCX control in SharePoint pages?
  • What are Web Parts?
  • How can we deploy a simple Webpart in SharePoint?
  • How can we achieve customization and personalization using WebParts?
  • How can we create custom editor for WebPart?
  • SharePoint is about centralizing documents, how similar is to the windows folder?
  • What are custom fields and content types?
  • Can you explain SharePoint Workflows?
  • What is a three-state Workflow in SharePoint?
  • How can we create sharepoint workflow using sharepoint designer?


.NET best practices and SQL Server Training / Interview Questions and Answers
  • Basics :- Query plan, Logical operators and Logical reads
  • Point 1 :- Unique keys improve table scan performance.
  • Point 2 :- Choose Table scan for small & Seek scan for large records
  • Point 3 :- Use Covering index to reduce RID (Row Identifier) lookup
  • Point4:- Keep index size as small as possible.
  • Point5:- use numeric as compared to text data type.
  • Point6:- use indexed view for aggregated SQL Queries
  • Finding high memory consuming functions
  • Improve garbage collector performance using finalize/dispose pattern
  • How to use performance counters to gather performance data

Wednesday, September 14, 2011

What is URL Routing?


What is URL Routing?

URL routing was a capability we first introduced with ASP.NET 3.5 SP1, and which is already used within ASP.NET MVC applications to expose clean, SEO-friendly “web 2.0” URLs.  URL routinglets you configure an application to accept request URLs that do not map to physical files. Instead, you can use routing to define URLs that are semantically meaningful to users and that can help with search-engine optimization (SEO).

Mapping URLs using ASP.NET MVC


The URL Routing engine introduced with ASP.NET 3.5 SP1 provides a powerful way to handle incoming URLs.  Typically you write code as part of application startup to register/map URLs that match a specific URL format to code handlers. 
Below is an example of how you can use ASP.NET MVC today to map the /products/software URL to a controller class called “Products” that has an action method named “Browse”:

 


The first “products-browse” parameter to the MapRoute() helper method above is a friendly name for the route.  The second “products/{category}” parameter is the URL filter that matches the/products/software URL – and which treats the second segment of the URL as a parameter value called “category”.  This parameter will then be passed to the ProductsController’s Browse() action method to process.

Mapping URLs using ASP.NET Web Forms


ASP.NET 4.0 now allows you to also use the URL Routing engine to map URLs to ASP.NET Web Forms pages as well as ASP.NET MVC Controllers. 
Below is an example of how you can use the new MapPageRoute() helper method in ASP.NET 4.0 to map the /products/software URL to a “Products.aspx” page that lives immediately under the application root directory:



The first two parameters to the MapPageRoute() helper are the same as in MapRoute(). The first parameter provides a friendly name for the route, and the second specifies the URL format to match.  The third parameter, though, points to a Products.aspx page to handle the URL instead of a controller class.  You can optionally specify additional parameters to MapPageRoute() that take advantage of features like “route constraints” and provide “default values for parameters” just like you can with ASP.NET MVC based route registrations.
Within the Products.aspx page you can then write code like below that uses the new Page.RouteData property in ASP.NET 4.0 to retrieve the “category” parameter value mapped using the/products/{category} URL filter, and then databind the category products to display them:

In addition to programmatically accessing incoming route parameters using code like above, you can also take advantage of the new declarative control with any ASP.NET DataSource control to declaratively bind a value from a route as well.  For example, below we are using a statement to bind the select statement’s @category parameter from the /products/{category} parameter in the URL route:

 




Retrieving URLs within an ASP.NET Web Form

The URL routing engine in ASP.NET can be used to both map incoming URLs to code handlers, as well as be used to programmatically generate outgoing URLs using the same mapping registration logic. 
For example, above when we mapped the /products/{category} URL we gave it a “friendly name” of “products-browse”.  This allows us to now also use the new Page.GetRouteUrl() helper method to lookup the route within the URL routing system, optionally specify parameters to it, and then retrieve an actual URL that it maps back to.  For example, the below code would retrieve a URL value of “/products/software”:



You can access the above helper method within either your code-behind file or within your .aspx markup. 
There is also now a Response.RedirectToRoute() set of methods that you can use to redirect users to a route (regardless of whether it is a MVC or Web Forms handled one) and optionally pass parameters to it.

Handling PostBack Scenarios

URL Routing with ASP.NET 4.0 fully supports postback scenarios.  The

control will automatically emit the same URL that caused the page to be rendered.  For example, if you access a page with a /products/software URL then any server-side control within it would render out a HTML element back to the client – which means that any postback scenarios that happen on the page will preserve the original URL. 
This makes supporting clean, SEO friendly, URLs easy with Web Forms and postback scenarios – and avoids some of the tricks people need to use today when using URL rewriting modules to achieve similar effects.