Sunday, August 29, 2010

ASP.NET 4.0 Web Forms 3 of 3

Filtering Data with the QueryExtender Control

Filtering data in data driven web pages traditionally has been performed by building Where clauses in data source controls. his approach can be complicated, and in some cases the Where syntax does not let you take advantage of the full functionality of the underlying database.

To make filtering easier, a new QueryExtender control has been added in ASP.NET 4. This control can be added to EntityDataSource or LinqDataSource controls in order to filter the data returned by these controls. Because the QueryExtender control relies on LINQ, but you do not to need to know how to write LINQ queries to use the query extender.
Variety of filtering Expression options are supported.

  1. SearchExpression
  2. RangeExpression
  3. PropertyExpression
  4. OrderByExpression
  5. CustomExpression
CSS Changes

  • DisabledCssClass property.
  • CSS for validation controls
  • CSS for the Hidden Fields Div Element
  • CSS for the Table, Image, and ImageButton Controls
  • CSS for the UpdatePanel and UpdateProgress Controls
  • CSS and ARIA Support for the Menu Control


ASP.NET Chart Control

Data series, chart areas, axes, legends, labels, titles, and more with databinding support.

Others

There are many more inclusions are there in .NET 4.0 like
  • Major enhancements in Dynamic Data (introduced in 3.5)
  • Enabling Dynamic Data for Individual Data-Bound Controls in Existing Web Applications
  • Declarative DynamicDataManager Control Syntax
  • Entity Templates - which offer way to customize data
  • New built-in field templates, EmailAddress.ascx and Url.ascx
  • Creating Links with the DynamicHyperLink Control
  • Support for Inheritance in the Data Model
  • Support for Many-to-Many Relationships (Entity Framework Only)
  • New Attributes to Control Display and Support Enumerations
  • Enhanced Support for Filters

lot more to explore.....

ASP.NET 4.0 Web Forms - 2 of 3

Routing in ASP.NET 4
ASP.NET 4 adds built-in support for routing with Web Forms. Routing is a feature that was introduced with ASP.NET 3.5 SP1 and lets you configure an application to use URLs that are meaningful to users and to search engines because they do not have to specify physical file names

  • The PageRouteHandler class is a simple HTTP handler that you use when you define routes. You no longer have to write a custom route handle
  • HttpRequest.RequestContext and Page.RouteData properties make it easier to access information that is passed in URL parameters.
  • No need to change the web.config to enable routing..


I plan to write another seperate blog for Web forms routing later



Setting Client IDs

The new ClientIDMode property makes it easier to write client script that references HTML elements rendered for server controls. Most of the Third party controls supported this earlier... Microsoft is using other vendors as their R & D department :)

Persisting Row Selection in Data Controls

A very late feature. This should have been included in .NET 3.5 at the latest... All projects were already handles such scnearios and all programmers are already aware on how to avoid default selection of rows when pagination is enabled...

Form View and List View Control Enhancements

A new property in FormView RenderTable="false" will ensure that the unexpected table row and table cell tags were rendered by the control previosuly is eliminated. This makes it easier to apply CSS style to the contents of the control.

In List View Control does not require a layout template from .NET 4.0. In 3.5 it is mandatory to specify Layout template.

ASP.NET 4.0 Web Forms - 1 of 3

Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been in this area for ASP.NET 4, such as the following:

  • The ability to set meta tags.
  • More control over view state.
  • Support for recently introduced browsers and devices.
  • Easier ways to work with browser capabilities.
  • Support for using ASP.NET routing with Web Forms.
  • More control over generated IDs.
  • The ability to persist selected rows in data controls.
  • More control over rendered HTML in the FormView and ListView controls.
  • Filtering support for data source controls.
  • Enhanced support for Web standards and accessibility.
  • Project template changes.



Meta- Tags

Two properties have been added to the Page class: MetaKeywords and MetaDescription. This will work similar to title property of the page.

Control.ViewStateMode

You can use the ViewStateMode property to enable view state for an individual control even if view state is disabled for the page.

New Browsers

Some of them are Chrome, IPhone etc... The browser definition file now includes - blackberry.browser,chrome.browser,Default.browser,firefox.browser,gateway.browser,generic.browser,ie.browser,iemobile.browser,iphone.browser,opera.browser
,safari.browser

Browser Capabilities

ASP.NET 4 includes a new feature referred to as browser capabilities provider.

In ASP.NET version 3.5 Service Pack 1, you define browser capabilities in an XML file. This file resides in a machine-level folder or an application-level folder. Most developers do not need to customize these files, but for those who do, the provider approach can be easier than dealing with complex XML syntax. The provider approach makes it possible to simplify the process by implementing a common browser definition syntax, or a database that contains up-to-date browser definitions, or even a Web service for such a database.

ASP.NET 4.0 New features

Web.config File Refactoring

The Web.config file that contains configuration information for a Web application has grown considerably over the past few releases of the .NET Framework as new features have been added. In .the .NET Framework 4, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications to be empty or to specify only which version of the framework the application is targeting

Extensible Output Caching

ASP.NET 4 adds extensibility to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. These storage options can include local or remote disks, cloud storage, and distributed cache engines.


The defaultProvider attribute for ASP.NET is AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider attribute.

Auto start Web Application

A new auto-start feature is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests. It lets you perform expensive application initialization prior to processing the first HTTP request.

Permanently Redirecting a Page

ASP.NET 4 adds a RedirectPermanent helper method that makes it easy to issue HTTP 301 (Moved Permanently) responses, as in the following example:

RedirectPermanent("/newpath/foroldcontent.aspx");

This helps in search Engines urls.

Session State Compression

ASP.NET 4 introduces a new compression option for both kinds of out-of-process session state providers. By using this option, applications that have spare CPU cycles on Web servers can achieve substantial reductions in the size of serialized session state data.

You can set this option using the new compressionEnabled attribute of the sessionState element in the configuration file. When the compressionEnabled configuration option is set to true, ASP.NET compresses (and decompresses) serialized session state by using the .NET Framework GZipStreamclass.

Expanding the Range of Allowable URLs

ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications

<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />

ASP.NET 4 always rejects URL paths that contain characters in the ASCII range of 0x00 to 0x1F, because those are invalid URL characters as defined in RFC 2396 of the IETF

jQuery Included with Web Forms and MVC

Jquery is now built in supported in .NET 4.0

.NET 4.0 New Features - other than major security enhancments

New features and improvements in the .NET Framework 4 . drill down version from http://msdn.microsoft.com/en-us/library/ms171868.aspx for reference.

Application Compatibility and Deployment

The .NET Framework 4 is highly compatible with applications that are built with earlier .NET Framework versions, except for some changes that were made to improve security, standards compliance, correctness, reliability, and performance.

In-Process Side by Side

An application to load and start multiple versions of the .NET Framework in the same process. For example, you can run applications that load add-ins (or components) that are based on the .NET Framework 2.0 SP1 and add-ins that are based on the .NET Framework 4 in the same process.



Globalization


The .NET Framework 4 provides new neutral and specific cultures, updated property values, improvements in string handling, and other improvements. For more information, see What's New in Globalization and Localization.

Garbage Collection

The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. For more information, see Fundamentals of Garbage Collection.

Dynamic Language Runtime

The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.

The expression trees are extended with new types that represent control flow, for example, System.Linq.Expressions.LoopExpression and System.Linq.Expressions.TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.

In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.


BigInteger and Complex Numbers

The new System.Numerics.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.

The new System.Numerics.Complex structure represents a complex number that supports arithmetic and trigonometric operations with complex numbers.


Tuples

The .NET Framework 4 provides the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components (that is, singletons through octuples). To support tuple objects that have nine or more components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type.

Parallel Computing

The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.

System.Func and Action Delegate(.NET 4)

System.Func<> encapsulates a method that has zero '0' to nine '9' parameter(for now in .NET 4 previously in .NET 3.5 it had 0-4 parameters and one return type) and returns a value of the type specified by the TResult parameter. It is useful because it does not require you to write custom delegate types. This makes it much easier to interop delegates with the same signature.

In all versions of System.Func, the last generic argument is the return type, all the others are the types of the parameters, in order.

Syntax for no Parameter

Func<Tresult>

Sample :-

//return type is boolean and no parameter for the method.
Func<bool> methodCall = output.SendToFile;

Assiging Lambda Expression to the Func delegate.

Func<bool> methodCall = () => output.SendToFile();


Syntax for more paramters

Suppose you have a function such as:

private static string toUpper(string str)
{
return str.ToUpport();
}

There is a version of System.Func that takes two generic arguments, the first being the type of the first parameter, the second being the return type. As such, you could write:

Func<string,string> myFunction = toUpper;
string getFunc = myFunction("SIvakuMar");
// s is now "SIVAKUMAR"

Maximum Paramter for Func Delegate

Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> Delegate Encapsulates a method that has nine parameters and returns a value of the type specified by the TResult parameter


Action Delegate

Action encapsulates a method that has nine parameters(.NET 4.0, previosuly in 3.5 it takes 4 parameters) and does not return a value.

To reference a method that has nine parameters and returns void (or in Visual Basic, that is declared as a Sub rather than as a Function), use the generic Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> delegate.

When introduced in .NET 2.0, Action method Represents the method that performs an action on the specified object. and in 3.5 Action method that takes a single parameter and does not return a value. (only the definition get changed and not the syntax) and in .NET 4.0

Extension methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type

An extension method is a static method, but with the first parameter it takes being explicitly marked as receiving the object that the method was called on.Extension methods may only appear in static classes but you cannot write an extension methods for another static class.


Extension methods require an instance of an object. You can however, write a static wrapper around

Sample1

namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}


Extension method using Wrapper


static class Extensions
{
public static long MakeCode(this SerialGenerator SG,
int ProductID, UserInfo User)// Extension method for the Make Code method of serial Generator Class.
{
return SG.MakeCode(ProductID, User.Name, User.DOB,
User.CountryCode);
}
}

Attaching implementation to Interfaces

Extension methods allows to attach implementation to interfaces, I think this is an easy way to attach implementation to the interface which is not possible in any other way as purpose of interface is to only define and not implement.

Sample
public static class Extension
{
public static void MethodA(this IMyInterface myInterface, int i)
{
Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, int i)");
}


When to use Extension Methods

Though inheritance is one of the preferred way of preferred way of extending functionality to a class , the following are the few cases where you can think about writing an extension method :- ref:-http://www.programmersheaven.com/2/CSharp3-2


  • If the class is sealed, you will be unable to inherit from it. In this case, you have no option but to use extension methods
  • You may be using some kind of object factory that instantiates objects of a given class, but you do not have the ability to modify it so that your subclass is instantiated instead.
  • Attaching Method implementation to the Interfaces (You want to implement a method that can be invoked on all classes implementing a given interface)
  • You may want to add related things to a number of other classes as like extending functionality to the string class etc... This will avoid spreading of similar functionality in different places.



More details:-http://msdn.microsoft.com/en-us/library/bb383977.aspx
http://www.programmersheaven.com/2/CSharp3-2

Var Keyword - Scenarios to remember

Multiple types for a single var

The following example will not work in var case

var SetConditionally = condition ? 500 : "badger" -> compiler cannot infer the type of setconditionnaly

Type inference understands subtyping

class Parent
{
}
class Child : Parent
{
}

The following implementation will compile and execute sucessfully . (Same works well if you would have replaced var with Parent in 2.0 but replacing var with child will not work)

var Condition = true;
var SetConditionally = Condition ? new Parent() : new Child();
//Remember GetType() is checked in runtime and not compile time.
Console.WriteLine("SetConditionally is of type " + SetConditionally.GetType().Name);



Implicit typing is necessary to insert the interface.

interface IVehicle
{
}
class Car: IVehicle
{
}
class Bike : IVehicle
{
}

The following implementation will throw compiler error.

var Condition = true;
var Vehicle = Condition ? new Car() : new Bike();
Console.WriteLine("Vehicle is of type " + Vehicle.GetType().Name);

Solve this by implicitily typing the interface

var Condition = true;
var Vehicle = Condition ? new (IVehicle)Car() : new (IVehicle)Bike();
Console.WriteLine("Vehicle is of type " + Vehicle.GetType().Name);


Elements of different type in Array

You will get a compile time error when elements of different type will be in array, following samples will throw compile time error.

var NullableInt = new [] { 1, 10, null, 42 };
var MultipleElements = new [] { "String", 100, "new", 20, 30.5 };

Variant Type from C# 3.0- or Var Keyword

VAR Keyword:-


At first glance, it appears that you’re declaring a variable of type “var”. Actually, “var” is not a type, but rather a new keyword that means, declare a variable, but not delcare its type”.

How this Works :-Type inference algorithm in the compiler analyzes your program and works out the type for you. Conceptually it is like going through your program for each occurrence of the keyword "var" and putting it in place of "var", after figuring out its type.

NO TYPES

// Before:
Dictionary<int, List<int>> Coeffs = new Dictionary<int, List<int>>();
// After:
var Coeffs = new Dictionary<int, List<int>>();


Performance

Variants in vb or any other lang use dynamic typing rather than inferring the type statically. Therefore, variants carried a runtime performance penalty. Using "var" in C# 3 does not. Your program will run just as quickly as if you had written the type in yourself.

source:-http://www.programmersheaven.com/2/CSharp3-1

New Features in C# 3.0

New Features in C# 3.0
----------------------

http://www.programmersheaven.com/2/CSharp3-1

Expression trees are immutable

Expression trees are immutable, which means that they cannot be modified directly. To change an expression tree, you must create a copy of an existing expression tree and when you create the copy, make the required changes

Mutable Trees :-LINQ to SQL has an internal tree structure that’s mutable—and immutable trees like expression trees from the System.Linq.Expression namespace.

Discussion of the sorts of problems that can arise with mutable classes. Another advantage of immutable trees is that you can effectively duplicate them just by reference assignment.

Sample:-

Expression<Func<int, int>> f = (n => 1 - n);

Expression<Func<int, int>> g = f;

f = MyRewriteFunction(f);

Here, the variable ‘g’ keeps the original expression tree value while ‘f’ is rewritten with a new value.
Notice that this is a very fast reference copy. Without the immutability guarantee you would have to physically copy the tree to get the same guarantee

(http://blogs.msdn.com/b/jomo_fisher/archive/2007/05/23/dealing-with-linq-s-immutable-expression-trees.aspx)

Wrapper Class

A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. class that "wraps" the functionality of another class or API in a simpler or merely different API.



Examples:-


public class Wrapper
{

private int x = 10;
private int y = 20;
public Wrapper()
{
// TODO: Add constructor logic here
}
public int add(int x, int y)
{
Wrapper.inside obj = new inside();
//core functionality of this method is written in the wrapped class.
int sum = obj.add(x, y);
return sum;
}

//The below class is wrapped by the wrapper class. we can access only inside this class. Outside the class, we cant access this class.

private class inside
{
public int add(int x, int y)
{
return x + y;
}
}//inside class of wrapper end here.

}// WRAPPER Class ends here


Sample wrapper class for Excel Functionality.

Wrapper class for excel functionality is very common, in almost all 3rd party grid, they use a grid to excel converter using the wrapper class/ adapter class

For more details :- http://www.tanguay.info/web/index.php?pg=codeExamples&id=389

Sample explaining Anonymous Method and Lambda Expression

ChangeInt myDelegate = new ChangeInt(
delegate(int x)
{
return x * 2;
}
);
Console.WriteLine("{0}", myDelegate(5));

Same USING LAMBDA EXPRESSION

ChangeInt myDelegate = x => x * 2;
Console.WriteLine("{0}", myDelegate(5));


If you wanted to, you could have specified the type of the argument, as follows:

ChangeInt myDelegate = (int x) => x * 2;
Console.WriteLine("{0}", myDelegate(5));

Source:-(http://www.codeproject.com/KB/cs/lambdaexpressions.aspx)

Anonymous Methods (Lambda vs anonymous method)

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods which enable you to omit the parameter list.

This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions

Lambdas are not allowed on the left side of the is or as operator. same as Anonymous methods

button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

Sample

// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };


http://www.codeproject.com/KB/cs/lambdaexpressions.aspx


The advantages of this "anonymous method" syntax are:

•You don't have to clutter up your class with private methods that are only used once in order to pass some custom code to a method.
•The code can be put in the place it's used in, rather than somewhere else in the class.
•The method doesn't have to be named.
•The return type is inferred from the signature of the delegate type that the anonymous method is being cast to.
•You can reference local variables in the "outer" method from within the anonymous method.

Lambda Expression Event Handler

SIMPLE EVENT HANDLERS
-----------------------

Textbox.TextChanged += (sender, e)=> label.Text=Textbox.Text.ToString();

Lambda Expression as Expression Tree

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

To make a lambda expression be treated as an expression tree, assign or cast it to the type Expression<T>, where T is the type of the delegate that defines the expression's signature.

Lambda expressions can be used as expression trees (hierarchies of objects defining the components of an expression – operators, property access sub-expressions, etc) instead of being directly turned to code. This way, the expressions can be analyzed at runtime.
When a lambda expression is assigned to a variable of type Expression, the compiler emits code to build an expression tree that represents the lambda expression.

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

This expression tree can also be created manually like this:

Collapse | Copy Code
Expression<Predicate<int>> expression = Expression.Lambda<Predicate<int>>(
Expression.LT(
Expression.Parameter(typeof(int), "n"),
Expression.Constant(10)
),
Expression.Parameter(typeof(int), "n")
);


An expression tree can be compiled and turned into a delegate using the Compile() method of the Expression<T>class:

//Get a compiled version of the expression, wrapped in a delegate
Predicate<int> predicate=expression.Compile();
//use the compiled expression
bool isMatch=predicate(8); //isMatch will be set to true

The Compile() method dynamically compiles IL code based on the expression, wraps it in a delegate so that it can be called just like any other delegate, and then returns the delegate

Code Sample


The following code example demonstrates how to create an expression tree that represents the lambda expression num => num < 5 (C#) or Function(num) num < 5 (Visual Basic) by using the API.



// Add the following using directive to your code file:
// using System.Linq.Expressions;

// Manually build the expression tree for
// the lambda expression num => num < 5.
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 =
Expression.Lambda<Func<int, bool>>(
numLessThanFive,
new ParameterExpression[] { numParam });

Lambda Expressions that Return Void

A lambda expression that returns void is not very useful in the context of functional programming because the only possible reason for such a function is that it has side-effects, and is not pure

http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx

Sometimes developers will use a void statement lambda expression for writing an event handler.

How to pronounce the => token(Lambda Operator)

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any)
The right side holds the expression or statement block


If the lambda expression is a predicate, expressing some condition: c => c.State == "WA" then the => can be spoken as "such that". In this example, you could say "c such that c dot state equals Washington".

If the lambda expression is a projection, returning a new type: c => new XElement("CustomerID", c.CustomerID); then the => can be spoken as "becomes".

In the above example, you could say "c becomes new XElement with a name of CustomerID and its value is c dot CustomerID". Or "maps to", or "evaluate to",

You can also say "arrow". ... so on anyway confused again :) just say lambda oprator itself when you pronounce

LAMBDA EXPRESSIONS

Lambda expressions can be summarized in one sentence as simply functions/methods.A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

The basic form for a lambda expression is:

a) argument-list => expression

b)syntax of () => { /* body of void function here */ }; //void delegate.

Examples:-

Example1

To show lambda expressions in context, consider the problem where you have an array with 10 digits in it, and you want to filter for all digits greater than 5. In this case, you can use the Where extension method, passing a lambda expression as an argument to the Where method:

int[] source = new[] { 3, 8, 4, 6, 1, 7, 9, 2, 4, 8 };

foreach (int i in source.Where(x => x > 5))
Console.WriteLine(i);

Example2-LAMBDA with 2 Arguments




// Defines a delegate that takes two ints and returns an int
public delegate int MultiplyInts(int arg, int arg2);

You can declare and initialize a delegate:

MultiplyInts myDelegate = (a, b) => a * b;
Console.WriteLine("{0}", myDelegate(5, 2));

//gets the first number smaller than 10 in the list
int result=numbers.Find( n=> n<10);

//anonymous method
numbers.Sort(delegate(int x, int y){ return y-x; });

//lambda expression
numbers.Sort((x,y)=> y-x);

Example 3 -Multiple Statements

The code used in a lambda doesn't have to be a single statement. You can include multiple statements if you enclose them inside a statement block:


Action action=
control=>
{
control.ForeColor=Color.DarkRed;
control.BackColor=Color.MistyRose;
});

Friday, August 27, 2010

What is a "Predicate delegate"?

(http://bytes.com/topic/c-sharp/answers/474304-what-predicate-delegate)


A delegate is like a function pointer. A Predicate delegate is a very cool
use of Delegates which is used with various Generic Lists, Arrays and
Collections. Since a Generic List does not specify a data type, that is, the
data type of the items in the List is set with a type parameter, how would
one write a Find() function for a Generic List? Since nothing is known about
the data type being searched for, one cannot know what sort of condition is
used to discriminate between one item and another.


The Predicate delegate is a Generic method which takes an object of type T
as a parameter. It returns true or false, indicating whether or not the
object of type T satisfies the condition it tests. The Predicate delegate is
assigned the same type as the List when the List type parameter is passed to
the instance of the Generic List created. The author of the code knows what
the data type is, and can write a method that works with the type passed to
test it and see whether it is whatever the author wants it to be. The Find()
method uses the Predicate delegate method created to test each item in the
List, and returns the first item in the List for which the Predicate
delegate returns true

As an example, let's say that we have a Generic List of type Int32:

private List Numbers = new List();

You want to find the first item in the List that is less than 5. So, you
create your method:

private static bool IsLessThanFive(int i)
{
return (i < 5);
}


int result = Numbers.Find(new Predicate(IsLessThanFive);


The IsLessThanFive Predicate delegate is called for each item in the list,
passing that item as the parameter, until one of the calls returns true.
That is the number that is assigned to result.

In addition you can use anonymous methods and delegate inference to write it all in one line of code.

int result = Numbers.Find(delegate(int i) { return i < 5; });


Atlast, the same is acheivable even without using predicates, Lamda, Anonymous methods ) mimimal knowledge in c# is good enough, to achieve any complex behaviour. However basic understanding of all above is necessary for new technologies in .NET might be.

System.Predicates

(http://msdn.microsoft.com/en-us/magazine/cc163550.aspx)
Formally, the .NET Framework documentation defines the System.Predicate delegate like this:

public delegate bool Predicate( T obj )

In real life, this definition indicates that a function that acts as a predicate must take a single value as its parameter, which must be of the same type as the data in the array or list it's working with, and must return a Boolean value. The return value indicates whether the value passed to the procedure meets your particular criteria for inclusion

Example
List.Find Method have parameter Find(Predicate)

Yield Break and Return

There are two types of yield statements - yield return (for returning the next item) and yield break (to signify the end of the iterator).

using System;
using System.Collections;

class Test
{
static void Main(string[] args)
{
foreach (string x in Foo())
{
Console.WriteLine (x);
}
}

static IEnumerable Foo()
{
yield return "Hello";
yield return "there";
}
}

Result is

Hello
there

(http://www.yoda.arachsys.com/csharp/csharp2/iterators.html)

Co Variance and ContraVariance

http://www.yoda.arachsys.com/csharp/csharp2/delegates.html

Generic Delegates

http://www.yoda.arachsys.com/csharp/csharp2/delegates.html

namespace GenericDelegate
{
// This generic delegate can call any method
// returning void and taking a single parameter.
public delegate void MyGenericDelegate<T>(T arg);


class Program
{

static void Main(string[] args)
{
Console.WriteLine
("***** Generic Delegates *****\n");
// Register target with 'traditional'
//delegate syntax.
MyGenericDelegate<string> strTarget =
new MyGenericDelegate<string>(StringTarget);
strTarget("Some string data");
// Register target using method group conversion.
MyGenericDelegate<int> intTarget = IntTarget;
intTarget(9);
Console.ReadLine();
}

static void StringTarget(string arg)
{
Console.WriteLine("arg in uppercase is: {0}", arg.ToUpper());
}

static void IntTarget(int arg)
{
Console.WriteLine("++arg is: {0}", ++arg);
}


}

}

Default Keyword

The default keyword has been given a dual identity. In addition to its use within a switch construct, it can be used to set a type parameter to its default value

Default Keyword

The default keyword has been given a dual identity. In addition to its use within a switch construct, it can be used to set a type parameter to its default value

Implementing a Basic Match class that uses Arithmetic Operator

http://en.csharp-online.net/Understanding_Generics%E2%80%94Creating_Generic_Interfaces

// Compiler error! Cannot apply
// operators to type parameters!
public class BasicMath<T>
{
public T Add(T arg1, T arg2)
{ return arg1 + arg2; }
public T Subtract(T arg1, T arg2)
{ return arg1 - arg2; }
public T Multiply(T arg1, T arg2)
{ return arg1 * arg2; }
public T Divide(T arg1, T arg2)
{ return arg1 / arg2; }
}



This can be achieved by using Interfaces
------------------------------------------

public interface IBinaryOperations<T>
{
T Add(T arg1, T arg2);
T Subtract(T arg1, T arg2);
T Multiply(T arg1, T arg2);
T Divide(T arg1, T arg2);
}




public class BasicMath : IBinaryOperations<int>
{
public int Add(int arg1, int arg2)
{ return arg1 + arg2; }

public int Subtract(int arg1, int arg2)
{ return arg1 - arg2; }

public int Multiply(int arg1, int arg2)
{ return arg1 * arg2; }

public int Divide(int arg1, int arg2)
{ return arg1 / arg2; }
}

Non Generic class extends a generic class

// Assume you have created a custom
// generic list class.
public class MyList<t>
{
private List<t> listOfData = new List<t>();
}

// Concrete types must specify the type
// parameter when deriving from a
// generic base class.
public class MyStringList : MyList<string>
{}

Saturday, August 7, 2010

Display Custom Error View with stack trace in ASP.NET MVC

Excellent ErrorHandler Sample.

Display additional stack trace details in error page in ASP.NET MVC. Scott Gu in his blog mentioned that "To help developers, the default Error view template provided by the new project template in Visual Studio is written to display additional error stack trace information"

I couldn't find as mentioned by scott gu But, got some info from the below blog on stack trace in error view.

http://geekswithblogs.net/ChristiaanVdP/archive/2009/01/08/asp.net-mvc-beta-1-ndash-error-handler-example.aspx.


<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Sorry, an error occurred while processing your request.
Action = <%= ViewData.Model.ActionName %>
Controller = <%= ViewData.Model.ControllerName %>
Message = <%= ViewData.Model.Exception.Message %>

</h2>
</asp:Content>

Using Application_Error instead of HandleError

I was behind the handle error attribute for handling error. but after all the research, I find using the Application_Error method in Global.asax found to be usefull , same as the old ASP.NET way. This was a solution post in ASP.NET forums


protected void Application_Error()
{
HttpContext ctx = HttpContext.Current;
KeyValuePair error = new KeyValuePair("ErrorMessage", ctx.Server.GetLastError().ToString());
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
string controllerName = rc.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, controllerName);
ControllerContext cc = new ControllerContext(rc, (ControllerBase)controller);
ViewResult viewResult = new ViewResult { ViewName = "Error" };
viewResult.ViewData.Add(error);
viewResult.ExecuteResult(cc);
ctx.Server.ClearError();

}

Friday, August 6, 2010

Callout tooltip

Callout Tooltip

http://www.java2s.com/Code/JavaScript/Ext-JS/Callouttooltip.htm

JQuery Callout


http://plugins.jquery.com/project/callout

Callout Sample

http://www.java2s.com/Code/JavaScriptDemo/Callouttooltip.htm

Callout tooltip

Callout Tooltip

http://www.java2s.com/Code/JavaScript/Ext-JS/Callouttooltip.htm

JQuery Callout


http://plugins.jquery.com/project/callout

Callout Sample

http://www.java2s.com/Code/JavaScriptDemo/Callouttooltip.htm

ASP.NET MVC 2 RC 2 for ASP.NET 3.5

ASP.NET MVC 2 RC 2 for ASP.NET 3.5 SP1 runtime.
Download link for C# 3.5
http://www.microsoft.com/downloads/details.aspx?FamilyID=7aba081a-19b9-44c4-a247-3882c8f749e3&displaylang=en

ASP.NET MVC 2 RC 2 for ASP.NET 3.5

ASP.NET MVC 2 RC 2 for ASP.NET 3.5 SP1 runtime.
Download link for C# 3.5
http://www.microsoft.com/downloads/details.aspx?FamilyID=7aba081a-19b9-44c4-a247-3882c8f749e3&displaylang=en

Create Custom Action Filters

Avoid adding the handleerror again and again

You could also consider creating a "LoggingController" and have your other controllers inherit from it vs. having to put a [LogRequest] attribute on every controller.

http://forums.asp.net/p/1505777/3823252.aspx

Cross-cutting concerns

Cross-cutting concerns are aspects of a program which affect other concerns.

TODO 6th AUG

Analyse on CREATE A STRONGLY TYPED VIEWS

How to pass View Data to handle Error, if we need to send more information



View Data to handle Error

http://stackoverflow.com/questions/1794936/how-do-i-pass-viewdata-to-a-handleerror-view
http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx

____________

http://volaresystems.com/Blog/post/Handling-Exceptions-in-ASPNET-MVC.aspx - low priority.
http://www.davidjuth.com/asp-net-mvc-error-handler.aspx - low priority


•http://stackoverflow.com/questions/108813/404-http-error-handler-in-asp-net-mvc-rc-5
•http://www.andornot.com/about/developerblog/2009/10/handling-404-errors-with-aspnet.aspx
•http://geekswithblogs.net/SanjayU/archive/2009/11/06/error-handling-in-asp.net-mvc-1-1-of-a-3.aspx

Double Question mark / coalesce operator

DOUBLE QUESTION MARK (this operator is named the coalesce operator) ??

The double question mark operator returns the first value that is not null. This was a feature introduced in .NET 2.0 ( mm..However, I never wrote something like this earlier)

Example 1:-

(intVal1 ?? intVal2) ?? 100 => retuns 100 if intVal1 and intVal2 is null
(intVal1 ?? intVal2) ?? 100 => retuns intVal1 if intVal2 is null and intVal1 is not null
(intVal1 ?? intVal2) ?? 100 => retuns intVal2 if intVal1 is null and intVal2 is not null

Example 2 :-

x = y ?? z; --> If y is null x will be set to z.

Ignore or Cancel exception handling for certain errors

Ignore or cancel the exceptions handling for certain cases by creating a custom ErrorHandler. It could be something like this (pseudo code):

public class CustomHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
//do nothing here.
}
}

I myself need to try this once.

Handling Errors in Error View in ASP.NET MVC

Errors can occur in the error view itself. In that case, the default ASP.NET error page is displayed. To avoid this, you can configure the application to display an error file in the customErrors section of the Web.config file

ASP.NET MVC Folder hierarchy

Instead of having many controllers in the controller directory I would like to create some hierarchy like below, as this is the scenario for any large/medium web application.

Controllers\Pricing\
Controllers\Reports\

The Concept I am searching for is called Areas as posted in
http://stackoverflow.com/questions/636711/asp-mvc-folder-hierarchy
and detailed explanation on how to do this in
http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx

Creating Own Route Handler

Lot of things to learn from this blog.WOW!!! Custom WebForm View Engine can be created by ourself. Thats really great!!!!
ASP.NET MVC - Create own Route Handler.

Also, this blog takes you the question from Nested/Hierarchial Controllers to Nested Areas. :) Must to read the following blog if you read the above one

http://haacked.com/archive/2010/01/12/ambiguous-controller-names.aspx#78365

Specify Order in ErrorHandler in ASP.NET MVC

Specifying order is very important if you use HandleError Filter Attribute.

If you want your Specific Exception Eg. Divide By Zero Error, to be viewed in MathError.aspx page and all other exception in default "Error.aspx" page.

Do the Order as follows.

[HandleError(Order =1, ExceptionType = typeof(DivideByZeroException), View = "MathError")]
[HandleError(Order=2)]

Also if you want to override the HandleError behaviour of class in the Action method you can do that by specifying the attribute in the method.

Sample

[HandleError(ExceptionType = typeof(DivideByZeroException), View = "ActionError")]
public ActionResult MaskEdit()
{

return View();
}


The reason behind specifying the Order is because Controller runtime is free to reorder attribute declarations in any manner it chooses, which is why the Order property is there in the first place,

If no Order is specified, we'll just execute the filters in the order given to us by the runtime.

Placing Error Views in appropriate directory

At the end of my Custom Error Page in ASP.NET MVC, I wrote that

I tried creating an Error folder and custom error files inside that inside the views folder but ended up unsucessfully.

HandleError(ExceptionType = typeof(DivideByZeroException), View = @"Error\MathError")


Reason :-

You can place the "Error" view either in the same directory as your other Controller specific views (for example: \Views\Test for the TestController above), or within the \Views\Shared folder (it will look first for a controller specific error view, and then if it doesn't find one it will look in the shared folder - which contains views that are shared across all controllers).

Help from :-

Scott Gu's ASP.NET MVC Blog


So my syntax View = @"Error\MathError" is wrong. and it should just be MathError, like this HandleError(ExceptionType = typeof(DivideByZeroException), View = "MathError") and MathError.aspx should be inside the directory of my other controller specific Views in my case it is welcome folder

Thursday, August 5, 2010

Custom Error Page in ASP.NET MVC

When I was playing around with HandleError attribute, I was wondering how to specify an error page other than the one inside Views\Shared\Error.aspx.


For my divide by zero error, I created Custom error page, named MathError in Views/Shared Folder, and set the Handle Error attribute as follows,

In my web.config file setting defaultredirect attribute doesn't matter and if a DivideByZero exception occur in my code then page will be redirected to "MathError.aspx" for all other error it will be Error.aspx.

[HandleError(ExceptionType = typeof(DivideByZeroException), View = "MathError")].


I tried creating an Error folder and custom error files inside that inside the views folder but ended up unsucessfully. may be I am doing something wrong. I tried the following.

HandleError(ExceptionType = typeof(DivideByZeroException), View = @"Error\MathError")

Web.Config file inside Views folder in ASP.NET MVC

The reason for 2 web.config files in the ASP.NET MVC is because

The web.config in the views folder is there to block direct access to the view aspx pages which should only get served through controllers.

Earlier, I removed this web.config earlier in my sample application, which was a mistake :)

HandleError Attibute in ASP.NET MVC.

I noticed HandleError attribute in ASP.NET MVC default templated sample and noticed mirosoft documentation states this Attribute use for handling an exception thrown by an action method. I was curious to see how this works, and so tried in a sample application, on which I modified some of the files on mvc default templated sample.

I was just trying to divide by zero to get an exception. and bad luck I got the "Yellow Screen of Death" instead of handling the error!!!!...

After some googling I found
1. Set Custom Error Mode to "On" will fix this issue- This will redirect to custom error page even in debug mode. (mm.. this is the case in ASP.NET as well, so i should have thought this first, but microsoft documentation was misleading I guess)
""
where Error.aspx location should be inside Views\Shared\ folder.
However, after setting custom error mode too, I still get the error message in the browser. However templated sample from microsoft worked well after setting the custom error mode!!!!.

Exception raised in my custom sample:-

Initially I couldn't find the reason for the exception, as I was getting Resource not found exception . i.e the HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable

However after indepth analysis, by throwing exception in the initial action I got the following exception in Default.aspx.cs, where the current path was routed.

Could not load type 'System.Web.Mvc.ViewPage'.

Noticed my Error.aspx page Inherits="System.Web.Mvc.ViewPage"

Reson for the issue in the custom sample
After comparing my templated project and googling I found that web.config in my Views folder is missing
I copied the web.config file from View folder of templated project to my custom project. I was amazed to see the reason for my error handling to work..

Finally I found,

It is not the web.config file inside the view that matters, it is because, the pageParserFilterType (System.Web.Mvc.ViewTypeParserFilter) needs to be loaded.
This can either be in global web.config or inside the views folder.


pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"

There is more to know on the ASP.NET MVC Error handling, as for any project, the error handling framework needs to be built before starting any application in MVC.

Views Web.Config to avoid page directive in each pages

Avoid Page directives on each pages by setting the pages elements in web.config file of views folder in ASP.NET MVC

http://haacked.com/archive/2009/08/04/views-on-a-diet.aspx


ASP.NET MVC Namespaces in Web.config instead of Views - ASP.NET MVC Best Practices

http://davidhayden.com/blog/dave/archive/2009/10/13/ViewNamespacesInWebConfig.aspx

ASP.NET MVC Controllers & Views in separate assemblies

Very nice CMS sample.
http://dotnetslackers.com/articles/aspnet/Storing-ASP-NET-MVC-Controllers-Views-in-separate-assemblies.aspx#1503

- Worth understanding before starting any projects in ASP.NET MVC.

Wednesday, August 4, 2010

Visual Studio Light Switch

Microsoft released a small tool for managing small internal applications by launching visual-studio-lightswitch tool today . click on this link to know more... http://bit.ly/c79QiR

Yet to analyze on including features by writing code. and can we write the normal gridview code for the grid binded using lightswitch etc...

Visual Studio Light Switch

Microsoft released a small tool for managing small internal applications by launching visual-studio-lightswitch tool today . click on this link to know more... http://bit.ly/c79QiR

Yet to analyze on including features by writing code. and can we write the normal gridview code for the grid binded using lightswitch etc...

Monday, August 2, 2010

ASP.NET MVC 3 Preview 1

Overview about what’s new in ASP.NET MVC 3.

Inclusion in IDE

  1. Selection of custom View Engine when adding Views
  2. Includes Microsoft's new RAZOR View Engine

mm...MVC 1.0/2.0 developers have more new things to learn!!! Below are some of them in this Preview.

Global Filters in Controller - days of handling errors through each methods attribute is gone
New Dynamic ViewModel Property - who knows microsoft might mention the ViewData as Obsolete or not a good practice soon!!!.. so, we need to check if there are any conversion tool available, to convert old project's viewdata to this wivew model
So far 3 new ActionResult Type in preview 1, which are related to HTTP Status.
a)HTTpNotFoundResult
b)HttpRedirectResult
c) HttpStatusCodeResult

Passing Object as Parameter. - This will automatically bind the incoming JSON post values to the .NET Product type on the server


There are Model Validation and Dependency Injection Improvements , which I am yet to analyze..

More details are available in ScottGu blog posting :- http://bit.ly/btdFOX

You can download ASP.NET MVC @ http://go.microsoft.com/fwlink/?LinkID=157073

Sunday, August 1, 2010

ASP.NET Routing

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

Stages of execution for an MVC Web project.

Stages of execution for an MVC Web project.

Receive first request for the application
In the Global.asax file, Route objects are added to the RouteTable object.

Perform routing
The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object.

Create MVC request handler

The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler.

Create controller
The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with.

Execute controller
The MvcHandler instance calls the controller's Execute method.

Invoke action
For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method.

Execute result
The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult


http://msdn.microsoft.com/en-us/magazine/dd695917.aspx

ASP.NET MVC in IIS6.0 vs 7.0

When an ASP.NET MVC Web application runs in IIS 7.0, no file name extension is required for MVC projects. However, in IIS 6.0, the handler requires that you map the .mvc file name extension to the ASP.NET ISAPI DLL.


Make sure HTTP Redirection feature is enabled for IIS
Routing won't work if HTTP Redirection is not installed.

Open Control Panel / Programs / Turn Windows Features on or off. Look under World Wide Web Services / Common HTTP Features

Check HTTP Redirection
http://blogs.msdn.com/b/rjacobs/archive/2010/06/30/system-web-routing-routetable-not-working-with-iis.aspx

ASP.NET MVC Custom Action Result

http://blog.maartenballiauw.be/post/2008/05/ASPNET-MVC-custom-ActionResult.aspx

ASP.Net MVC Features ( 4 my ref)

The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models. DI enables you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file. This makes testing easier.

Request and Response in ASP.NET MVC

The Controller class exposes Request and Response properties that can be accessed in an action method. These properties have the same semantics as the HttpRequest and HttpResponse objects that are already a part of ASP.NET.

However, the Request and Response objects of the Controller class accept objects that implement the HttpRequestBase and HttpResponseBase abstract classes instead of being sealed classes.

Sample code

public void Detail()
{
int id = Convert.ToInt32(Request["id"]);
}

HandleError in ASP.NET MVC

Need to find the need for this [HandleError] Attribute

Non Action method in Controller Class

By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute

[NonAction]
private void DoSomething()
{
// Method logic.
}

Non Action method in Controller Class

By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute

[NonAction]
private void DoSomething()
{
// Method logic.
}

Built-in action result types

Source :http://msdn.microsoft.com/en-us/library/dd410269.aspx

ViewResult
View
Renders a view as a Web page.

PartialViewResult
PartialView
Renders a partial view, which defines a section of a view that can be rendered inside another view.

RedirectResult
Redirect
Redirects to another action method by using its URL.

RedirectToRouteResult
RedirectToAction

RedirectToRoute
Redirects to another action method.

ContentResult
Content
Returns a user-defined content type.

JsonResult
Json
Returns a serialized JSON object.

JavaScriptResult
JavaScript
Returns a script that can be executed on the client.

FileResult
File
Returns binary output to write to the response.

EmptyResult
(None)
Represents a return value that is used if the action method must return a null result (void).

Action Method Return Type

When statrted my R & D in ASp.NET MVC I was confuse , to see ActionResult return type, and want to know more on the Action Method return type.

When Investigating I found that.


You can create action methods that return an object of any type, such as a string, an integer, or a Boolean value. These return types are wrapped in an appropriate ActionResult type before they are rendered to the response stream.

Path of the Controller in ASP.NET MVC

Controller is a class compiled in an assembly somewhere

The MVC application uses routing rules that are defined in the Global.asax file to parse the URL and to determine the path of the controller.

The controller then determines the appropriate action method to handle the request.

i.e Routing rule invokes XXX method of the YYYY controller in order to process the request.

Action Method in ASP.NET MVC

Action methods typically have a one-to-one mapping with user interactions. Examples of user interactions include entering a URL into the browser, clicking a link, and submitting a form. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method.

ASP.NET MVC Disadvantages

a. It is one step back from Web Forms, missing all those useful server controls. Mimicking the behavior of controls like Grid View is very difficult and cumbersome.
b. Maintaining state can become real pain.
c. For complex web pages, the mix of HTML and script syntax can become hard to understand and maintain.





Source :http://it.toolbox.com/blogs/third-angle/asp-net-web-forms-vs-asp-net-mvc-35645