uniform resource identifier

Thursday, July 30, 2009


A URI is a compact representation of a resource available to your application on the intranet or Internet. The Uri class defines the properties and methods for handling URIs, including parsing, comparing, and combining. The Uri class properties are read-only; to create a modifiable object, use the UriBuilder class.

Relative URIs (for example, "/new/index.htm") must be expanded with respect to a base URI so that they are absolute. The MakeRelative method is provided to convert absolute URIs to relative URIs when necessary.

The Uri constructors do not escape URI strings if the string is a well-formed URI including a scheme identifier.

The Uri properties return a canonical data representation in escaped encoding, with all characters with Unicode values greater than 127 replaced with their hexadecimal equivalents. To put the URI in canonical form, the Uri constructor performs the following steps:

*

Converts the URI scheme to lowercase.
*

Converts the host name to lowercase.
*

If the host name is an IPv6 address, the canonical IPv6 address is used. ScopeId and other optional IPv6 data are removed.
*

Removes default and empty port numbers.
*

Canonicalizes the path for hierarchical URIs by compacting sequences such as /./, /../, //, including escaped representations. Note that there are some schemes for which escaped representations are not compacted.
*

For hierarchical URIs, if the host is not terminated with a forward slash (/), one is added.
*

By default, any reserved characters in the URI are escaped in accordance with RFC 2396. This behavior changes if International Resource Identifiers or International Domain Name parsing is enabled in which case reserved characters in the URI are escaped in accordance with RFC 3986 and RFC 3987.

As part of canonicalization in the constructor for some schemes, escaped representations are compacted. The schemes for which URI will compact escaped sequences include the following: file, http, https, net.pipe, and net.tcp. For all other schemes, escaped sequences are not compacted. For example: if you percent encode the two dots ".." as "%2E%2E" then the URI constructor will compact this sequence for some schemes. For example, the following code sample shows a URI constructor for the http scheme.

Uri uri = new Uri("http://myUrl/%2E%2E/%2E%2E");
Console.WriteLine(uri.AbsoluteUri);
Console.WriteLine(uri.PathAndQuery);


When this code is executed, it returns the following output with the escaped sequence compacted.

http://myUrl/
/


The following code example shows a URI constructor for the ftp scheme:

Uri uri = new Uri("ftp://myUrl/%2E%2E/%2E%2E");
Console.WriteLine(uri.AbsoluteUri);
Console.WriteLine(uri.PathAndQuery);


When this code is executed, it returns the following output with the escaped sequence not compacted.

ftp://myUrl/%2E%2E/%2E%2E
/%2E%2E/%2E%2E


You can transform the contents of the Uri class from an escape encoded URI reference to a readable URI reference by using the ToString method. Note that some reserved characters might still be escaped in the output of the ToString method. This is to support unambiguous reconstruction of a URI from the value returned by ToString.

Some URIs include a fragment identifier or a query or both. A fragment identifier is any text that follows a number sign (#), not including the number sign; the fragment text is stored in the Fragment property. Query information is any text that follows a question mark (?) in the URI; the query text is stored in the Query property.

In the .NET Framework version 1.1, if the string specified to a constructor contains an unknown scheme and "c:\", the Uri class inserts "//" after the colon. For example, the URI xyz:c:\abc is converted to xyz://c:/abc. In the .NET Framework version 2.0, this behavior has been removed, and the example string is converted to xyz:c:/abc.
NoteNote:

The URI class supports the use of IP addresses in both quad-notation for IPv4 protocol and colon-hexadecimal for IPv6 protocol. Remember to enclose the IPv6 address in square brackets, as in http://[::1].
International Resource Identifier Support

Web addresses are typically expressed using uniform resource identifiers that consist of a very restricted set of characters:

*

Upper and lower case ASCII letters from the English alphabet.
*

Digits from 0 to 9.
*

A small number of other ASCII symbols.

The specifications for URIs are documented in RFC 2396, RFC 2732, RFC 3986, and RFC 3987 published by the Internet Engineering Task Force (IETF).

With the growth of the Internet, there is a growing need to identify resources using languages other than English. Identifiers which facilitate this need and allow non-ASCII characters (characters in the Unicode/ISO 10646 character set) are known as International Resource Identifiers (IRIs). The specifications for IRIs are documented in RFC 3987 published by IETF. Using IRIs allows a URL to contain Unicode characters.

The existing Uri class has been extended in .NET Framework v3.5, 3.0 SP1, and 2.0 SP1 to provide IRI support based on RFC 3987. Current users will not see any change from the .NET Framework 2.0 behavior unless they specifically enable IRI. This ensures application compatibility with prior versions of the .NET Framework.

To enable support for IRI, the following two changes are required:

1.

Add the following line to the machine.config file under the .NET Framework 2.0 directory



2.

Specify whether you want Internationalized Domain Name (IDN) parsing applied to the domain name and whether IRI parsing rules should be applied. This can be done in the machine.config or in the app.config file. For example, add the following:








Enabling IDN will convert all Unicode labels in a domain name to their Punycode equivalents. Punycode names contain only ASCII characters and always start with the xn-- prefix. The reason for this is to support existing DNS servers on the Internet, since most DNS servers only support ASCII characters (see RFC 3940).

Enabling IRI and IDN affects the value of the Uri..::.DnsSafeHost property. Enabling IRI and IDN can also change the behavior of the Equals, OriginalString, GetComponents, and IsWellFormedOriginalString methods.

There are three possible values for IDN depending on the DNS servers that are used:

*

idn enabled = All

This value will convert any Unicode domain names to their Punycode equivalents (IDN names).
*

idn enabled = AllExceptIntranet

This value will convert all Unicode domain names not on the local Intranet to use the Punycode equivalents (IDN names). In this case to handle international names on the local Intranet, the DNS servers that are used for the Intranet should support Unicode name resolution.
*

idn enabled = None

This value will not convert any Unicode domain names to use Punycode. This is the default value which is consistent with the .NET Framework 2.0 behaviour.

Enabling IRI parsing (iriParsing enabled = true) will do normalization and character checking according to the latest IRI rules in RFC 3986 and RFC 3987. The default value is false and will do normalization and character checking according to RFC 2396 and RFC 2732 (for IPv6 literals).

IRI and IDN processing in the Uri class can also be controlled using the System.Configuration..::.IriParsingElement , System.Configuration..::.IdnElement , and System.Configuration..::.UriSection configuration setting classes. The System.Configuration..::.IriParsingElement setting enables or disables IRI processing in the Uri class. The System.Configuration..::.IdnElement setting enables or disables IDN processing in the Uri class. The System.Configuration..::.IriParsingElement setting also indirectly controls IDN. IRI processing must be enabled for IDN processing to be possible. If IRI processing is disabled, then IDN processing will be set to the default setting where the .NET Framework 2.0 behavior is used for compatibility and IDN names are not used.

The configuration setting for the System.Configuration..::.IriParsingElement and System.Configuration..::.IdnElement will be read once when the first System..::.Uri class is constructed. Changes to configuration settings after that time are ignored.

The System..::.GenericUriParser class has also been extended to allow creating a customizable parser that supports IRI and IDN. The behavior of a System..::.GenericUriParser object is specified by passing a bitwise combination of the values available in the System..::.GenericUriParserOptions enumeration to the System..::.GenericUriParser constructor. The GenericUriParserOptions..::.IriParsing type indicates the parser supports the parsing rules specified in RFC 3987 for International Resource Identifiers (IRI). Whether IRI is used is dictated by the configuration values previously discussed.

The GenericUriParserOptions..::.Idn type indicates the parser supports Internationalized Domain Name (IDN) parsing (IDN) of host names. Whether IDN is used is dictated by the configuration values previously discussed.
Performance Considerations

If you use a Web.config file that contains URIs to initialize your application, additional time is required to process the URIs if their scheme identifiers are nonstandard. In such a case, initialize the affected parts of your application when the URIs are needed, not at start time.

Notes to Callers:

Because of security concerns, your application should use caution when accepting Uri instances from untrusted sources and with dontEscape set to true.You can check a URI string for validity by calling the IsWellFormedOriginalString method.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note:

The .NET Compact Framework does not differentiate between relative and absolute paths. Also, the .NET Compact Framework processes URI strings prefixed by the file:// scheme differently from the full .NET Framework. A relative file://myfile specification resolves as \\myfile. Using file:///myfile (three slashes) resolves as \myfile in the root directory. To ensure successful operations, specify absolute path information.
Examples

The following example creates an instance of the Uri class and uses it to create a WebRequest instance.
Visual Basic

Dim siteUri As New Uri("http://www.contoso.com/")

Dim wr As WebRequest = WebRequest.Create(siteUri)


C#

Uri siteUri = new Uri("http://www.contoso.com/");

WebRequest wr = WebRequest.Create(siteUri);


Visual C++

Uri^ siteUri = gcnew Uri( "http://www.contoso.com/" );
WebRequest^ wr = WebRequest::Create( siteUri );

JScript

var siteUri : Uri = new Uri("http://www.contoso.com/");
var wr : WebRequest = WebRequest.Create(siteUri);

LINQ QUERY

This topic gives a brief introduction to LINQ query expressions and some basic query to used to perform some action.
In few years the changing in technology and database, the user must want to performance of working is so fast ans also great challenge to retrieve data faster and not difficulty create in programming side.
It has become apparent that the next big challenge in programming technology is to reduce the complexity of accessing and integrating information that is not natively defined using OO technology. The two most common sources of non-OO information are relational databases and XML.
The major advantage of Microsoft’s LINQ Project is the general approach they have taken because they have integrated a query language irrespective of any specific part.Language Integrated Query can be used with XML,Database or anything which is capable of returning IENUMERABLE.
This is a snippet which i found in the doc itself which can express the power of LINQ and make programmers of dot net really smile.
A query is a set of instructions that describes what data to retrieve from a given data source (or sources) and what shape and organization the returned data should have. A query is distinct from the results that it produces.
Generally, the source data is organized logically as a sequence of elements of the same kind. A SQL database table contains a sequence of rows. Similarly, an ADO.NET DataTable contains a sequence of DataRow objects. In an XML file, there is a "sequence" of XML elements (although these are organized hierarchically in a tree structure). An in-memory collection contains a sequence of objects.
From an application's viewpoint, the specific type and structure of the original source data is not important. The application always sees the source data as an IEnumerable<(Of <(T>)>) or IQueryable<(Of <(T>)>) collection. In LINQ to XML, the source data is made visible as an IEnumerable< XElement>. In LINQ to DataSet, it is an IEnumerable< DataRow>. In LINQ to SQL, it is an IEnumerable or IQueryable of whatever custom objects you have defined to represent the data in the SQL table.
Given this source sequence, a query may do one of three things:
•Retrieve a subset of the elements to produce a new sequence without modifying the individual elements. The query may then sort or group the returned sequence in various ways, as shown in the following example (assume scores is an int[]):
Obtaining a Data Source
In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source (Student) and the range variable (Stud).
The first thing is to import Data.Linq namespace.
Import namespace using System.Data.Linq;
Standard Query Operators
The set of query operators defined by LINQ are exposed to the user as the Standard Query Operator API. The query operators supported by the API are
Select / SelectMany
The Select statement performs a projection on the collection to select either all the data members that make up the object or a subset of it. The SelectMany operator performs a one-to-many projection("nested"), i.e., if the objects in the collection contain another collection as a data member, SelectMany can be used to select the entire sub-collection. The user supplies a function, as a delegate, which projects the data members. Selection creates an object of a different type, which has either some or as many data members as the original class. The class must be already defined for the code to be compilable.
Where
The Where operator allows the definition of a set of predicate rules which are evaluated for each object in the collection, while objects which do not match the rule are filtered away. The predicate is supplied to the operator as a delegate.
Sum / Min / Max / Average / Aggregate
These operators take a predicate that retrieves a certain numeric value from each element in the collection and uses it to find the sum, minimum, maximum, average or aggregate values of all the elements in the collection, respectively.
Join / GroupJoin
The Join operator performs an inner join on two collections, based on matching keys for objects in each collection. It takes two functions as delegates, one for each collection, that it executes on each object in the collection to extract the key from the object. It also takes another delegate via which the user specifies which data elements, from the two matched elements, should be used to create the resultant object. The GroupJoin operator performs a group join. Like the Select operator, the results of a join are instantiations of a different class, with all the data members of both the types of the source objects, or a subset of them.
Take / TakeWhile
The Take operator selects the first n objects from a collection, while the TakeWhile operator, which takes a predicate, selects those objects which match the predicate.
Skip / SkipWhile
The Skip and SkipWhile operators are complements of Take and TakeWhile - they skip the first n objects from a collection, or those objects which match a predicate (for the case of SkipWhile).
OfType
The OfType operator is used to select the elements of a certain type.
Concat
The Concat operator concatenates two collections.
OrderBy / ThenBy
The OrderBy operator is used to specify the primary sort ordering of the elements in a collection according to some key. The default ordering is in ascending order, to reverse the order, the OrderByDescending operator is to be used. ThenBy and ThenByDescending specifies subsequent ordering of the elements. The function to extract the key value from the object is specified by the user as a delegate.
Reverse
The Reverse operator reverses a collection.
GroupBy
The GroupBy operator takes a delegate that extracts a key value and returns a collection of IGrouping objects, for each distinct key value. The IGrouping objects can then be used to enumerate all the objects for a particular key value.
Distinct
The Distinct operator removes duplicate instances of a key value from a collection. The function to retrieve the key value is to be supplied as a delegate.
Union / Intersect / Except
These operators are used to perform a union, intersection and difference operation on two sequences, respectively.
EqualAll
The EqualAll operator checks if all elements in two collections are equal.
First / FirstOrDefault / Last / LastOrDefault
These operators take a predicate. The First operator returns the first element for which the predicate yields true or throws an exception if nothing matches. The FirstOrDefault operator is like the First operator except that it returns the default value for the element type (usually a null reference) in case nothing matches the predicate. The last operator retrieves the last element to match the predicate, or throws an exception in case nothing matches. The LastOrDefault returns the default element value if nothing matches.
Single
The Single operator takes a predicate and returns the element which matches the predicate. An exception is thrown if none or more than one element match the predicate.
ElementAt
The ElementAt operator retrieves the element at a given index in the collection.
Any / All / Contains
The Any operator checks if there are any elements in the collection matching the predicate. It does not select the element, but returns true for a match. The All operator checks if all elements match the predicate. The Contains operator checks if the collection contains a given value.
Count
The Count operator counts the number of elements in the given collection.

The Standard Query Operator API also specifies certain operators that convert a collection into another type
•AsEnumerable: converts the collection to IEnumerable type.
•ToQueryable: converts the collection to IQueryable type.
•ToArray: converts the collection to an array.
•ToList: converts the collection to IList type.
•ToDictionary: converts the collection to IDictionary type, indexed by the key K.
•ToLookup: converts the collection to ILookup type, indexed by the key K.
•Cast: converts a non-generic IEnumerable collection to one of IEnumerable by casting each element to type T. Throws an exception for incompatible types.
•OfType: converts a non-generic IEnumerable collection to one of IEnumerable. Only elements of type T are included.
The query operators are defined in the IEnumerable interface as generic extension methods, and a concrete implementation is provided in the Sequence class. As a result, any class that implements the IEnumerable interface has access to these methods and is queryable. LINQ also defines a set of generic Func delegates, which define the type of delegates handled by the LINQ query methods. Any function wrapped in a Func delegate can be used by LINQ. Each of these methods returns an object implementing the IEnumerable interface, so the output of one can be used as the input to another, resulting in query composability. The functions, however, are lazily evaluated, i.e., the collections are enumerated only when the result is retrieved. The enumeration is halted as soon as a match is found, and the delegates evaluated on it. When a subsequent object in the resultant collection is retrieved, the enumeration of the source collection is continued beyond the element already evaluated. However, grouping operations, like GroupBy and OrderBy, as well as Sum, Min, Max, Average and Aggregate, require data from all elements in collection, and force an eager evaluation. LINQ does not feature a query optimizer and the query operators are evaluated in the order they are invoked. The LINQ methods are compilable in .NET Framework 2.0
Language Extensions
While LINQ is primarily implemented as a library for .NET Framework 3.5, it also defines a set of language extensions that can be optionally implemented by languages to make queries a first class language construct and provide syntactic sugar for writing queries. These language extensions have initially been implemented in C# 3.0, VB 9.0 and Oxygene, with other languages like F# and Nemerle having announced preliminary support. The language extensions include
Query syntax: A language is free to choose a query syntax that it will recognize natively. These language keywords must be translated by the compiler to appropriate LINQ method calls. The languages can implement operator reordering and other optimizations at the keyword level.
• Implicitly typed variables: This enhancement allows variables to be declared without specifying their types. The languages C# 3.0 and Oxygene declare them with the var keyword. In VB9.0, the use of the Dim keyword without type declaration accomplishes the same declaration. Such objects are still strongly typed; for these objects the compiler uses type inference to infer the type of the variables. This allows the result of the queries to be specified and their result defined without declaring the type of the intermediate variables.
• Anonymous types: Anonymous types allow classes, which contain only data member declarations, to be inferred by the compiler. This is useful for the Select and Join operators, whose result types may differ from the types of the original objects. The compiler uses type inference to determine the fields contained in the classes and generates accessors and mutators for these fields.
• Object Initializer: Object initializers allow an object to be created and initialized in a single scope, this allows creation of delegates that extract fields from an object, create a new object and assign the extracted data to the fields of the new object in a single statement, as is required for Select and Join operators.
• Lambda expressions: Lambda expressions are used to create delegates inline with other code. This allows the predicates and extraction functions to be written inline with the queries.
For example, in the query to select all the objects in a collection with SomeProperty less than 10,
int someValue = 5;

var results = from c in someCollection
let x = someValue * 2
where c.SomeProperty < x
select new {c.SomeProperty, c.OtherProperty};

foreach (var result in results)
{
Console.WriteLine(result);
}
the types of variables result, c and results all are inferred by the compiler - assuming SomeCollection is IEnumerable, c will be SomeClass, results will be IEnumerable and result will be SomeOtherClass, where SomeOtherClass will be a compiler generated class with only the SomeProperty and OtherProperty properties and their values set from the corresponding clauses of the source objects. The operators are then translated into method calls as:
IEnumerable results =
SomeCollection.Where
(
c => c.SomeProperty < (SomeValue * 2)
)
.Select
(
c => new {c.SomeProperty, c.OtherProperty}
)
foreach (SomeOtherClass result in results)
{
Console.WriteLine(result.ToString());
}
LINQ Providers
LINQ also defines another interface, IQueryable, which defines the same interfaces to the Standard Query Operators as IEnumerable. However, the concrete implementation of the interface, instead of evaluating the query, converts the query expression, with all the operators and predicates, into an expression tree. The Expression tree preserves the high level structure of the query and can be examined at runtime. The type of the source collection defines which implementation will run - if the collection type implements IEnumerable, it executes the local LINQ query execution engine and if it implements the IQueryable implementation, it invokes the expression tree-based implementation. An extension method is also defined for IEnumerable collections to be wrapped inside an IQueryable collection, to force the latter implementation.
LINQ to Objects
The LINQ to Objects provider is used for querying in-memory collections, using the local query execution engine of LINQ. The code generated by this provider refers to the implementation of the standard query operators as defined in the Sequence class and allows IEnumerable collections to be queried locally. Current implementation of LINQ to Objects uses e.g. O(n) linear search for simple lookups, and is not optimised for complex queries
LINQ to XML
The LINQ to XML provider converts an XML document to a collection of XElement objects, which are then queried against using the local execution engine that is provided as a part of the implementation of the standard query operator.
LINQ to SQL
The LINQ to SQL provider allows LINQ to be used to query SQL Server databases as well as SQL Server Compact databases. Since SQL Server data resides on a remote server, and because it already includes a querying engine, LINQ to SQL does not use the query engine of LINQ. Instead, it converts a LINQ query to a SQL query which is then sent to SQL Server for processing.[6] However, since SQL Server stores the data as relational data and LINQ works with data encapsulated in objects, the two representations must be mapped to one another. For this reason, LINQ to SQL also defines the mapping framework. The mapping is done by defining classes that correspond to the tables in the database, and containing all or a subset of the columns in the table as data members. The correspondence, along with other relational model attributes such as primary keys are specified using LINQ to SQL-defined attributes. For example,
LINQ to SQL
The LINQ to SQL provider allows LINQ to be used to query SQL Server databases as well as SQL Server Compact databases. Since SQL Server data resides on a remote server, and because it already includes a querying engine, LINQ to SQL does not use the query engine of LINQ. Instead, it converts a LINQ query to a SQL query which is then sent to SQL Server for processing. However, since SQL Server stores the data as relational data and LINQ works with data encapsulated in objects, the two representations must be mapped to one another. For this reason, LINQ to SQL also defines the mapping framework. The mapping is done by defining classes that correspond to the tables in the database, and containing all or a subset of the columns in the table as data members. The correspondence, along with other relational model attributes such as primary keys are specified using LINQ to SQL-defined attributes. For example,
[Table(Name="Customers")
public class Customer
{
[Column(IsPrimaryKey = true)]
public int CustID;

[Column]
public string CustName;
}
this class definition maps to a table named Customers and the two data members correspond to two columns. The classes must be defined before LINQ to SQL can be used. Visual Studio 2008 includes a mapping designer which can be used to create the mapping between the data schemas in the object as well as the relational domain. It can automatically create the corresponding classes from a database schema, as well as allow manual editing to create a different view by using only a subset of the tables or columns in a table.
The mapping is implemented by the DataContext which takes a connection string to the server, and can be used to generate a Table where T is the type to which the database table will be mapped. The Table encapsulates the data in the table, and implements the IQueryable interface, so that the expression tree is created, which the LINQ to SQL provider handles. It converts the query into T-SQL and retrieves the result set from the database server. Since the processing happens at the database server, local methods, which are not defined as a part of the lambda expressions representing the predicates, cannot be used. However, it can use the stored procedures on the server. Any changes to the result set are tracked and can be submitted back to the database server.
LINQ to DataSets
The LINQ to SQL provider works only with Microsoft SQL Server databases; to support any generic database, LINQ also includes the LINQ to DataSets, which uses ADO.NET to handle the communication with the database. Once the data is in ADO.NET Datasets, LINQ to Datasets execute queries against these datasets.
Other providers
The LINQ providers can be implemented by third parties for various data sources as well. Several database server specific providers are available from the database vendors. Some of the popular providers include:
HOW LINQ WORKS WITH XML:
The extensibility of the query architecture is used in the LINQ project itself to provide implementations that work over both XML and SQL data.
Xpath and Xquery which is used heavily is in the host programming language.
XmlDocument doc = new XmlDocument();
XmlElement name = doc.CreateElement(”name”);
name.InnerText = “Patrick Hines”;
XmlElement phone1 = doc.CreateElement(”phone”);
phone1.SetAttribute(”type”, “home”);
XmlElement phone2 = doc.CreateElement(”phone”);
phone2.SetAttribute(”type”, “work”);
XmlElement street1 = doc.CreateElement(”street1″);
XmlElement city = doc.CreateElement(”city”);
city.InnerText = “Mercer Island”;
XmlElement state = doc.CreateElement(”state”);
state.InnerText = “WA”;
XmlElement postal = doc.CreateElement(”postal”);
postal.InnerText = “68042″;
XmlElement address = doc.CreateElement(”address”);
address.AppendChild(street1);
address.AppendChild(city);
address.AppendChild(state);
address.AppendChild(postal);
XmlElement contact = doc.CreateElement(”contact”);
contact.AppendChild(name);
contact.AppendChild(phone1);
contact.AppendChild(phone2);
contact.AppendChild(address);
XmlElement contacts = doc.CreateElement(”contacts”);
contacts.AppendChild(contact);
doc.AppendChild(contacts);

If we see it little closer the above code , This style of coding provides few clues to the structure of the XML tree. but with LINQX it becomes more of what they as functional construct. Here is what how u code the same with LINQX

XElement contacts = new XElement
(”contacts”,new XElement(”contact”,
new XElement(”name”, “Patrick Hines”),
new XElement(”phone”, “206-555-0144″,
new XAttribute(”type”, “home”))
,new XElement(”phone”, “425-555-0145″,new XAttribute(”type”, “work”)),
new XElement(”address”,new XElement(”street1″, “123 Main t”),
new XElement(”city”, “Mercer Island”),
new XElement(”state”, “WA”),new XElement(”postal”,”6843″)
How LINQ works with database
The query operators over relational data (DLinq) build on the integration of SQL-based schema definitions into the CLR type system.
This integration provides strong typing over relational data while retaining the expressive power of the relational model and the performance of query evaluation directly in the underlying store.
What we need to know is the structure of database table we want to deal with it and create a class exactly having private variables as columns of the underlying table say may be like save that easy. Thus in simple ways we create an object of the row of that table in memory and do operation on that and ask somebody to save it. Moreover we can ask for a collection of those rows of get more than one record and do a query on it.Isn’t that great no hassles of database sql.
Create an entity class with mapping to database table like this:-
Table(Name="Students")]
public class Student
{
[Column (Id=true)]
public string StudentID;
private string _City;
[Column(Storage = "_City")]
public string City
{
get { return this._City; }
set { this._City = value; }}}
Create a Data context to load from database
static void Main(string[] args){
// Use a standard connection string
DataContext db = new DataContext(@”C:StudentRegistration.mdf”);
// Get a typed table to run queries
Table Students = db.GetTable();
Query what you get
// This is only for debugging / understanding the working of DLinq
db.Log = Console.Out;
// Query for customers in London
var Stud =
from c in Students
where c.City == “Karachi”
select c;
}



Example:
class LINQQueryExpressions
{
static void Main()
{
int[] scores = new int[] { 97, 92, 81, 60 };

IEnumerable scoreQuery =
from score in scores
where score > 80
select score;

foreach (int i in scoreQuery)
{
Console.Write(i + " ");
}
}
}
// Output: 97 92 81

Example:
IEnumerable highScoresQuery2 =
from score in scores
where score > 80
orderby score descending
select String.Format("The score is {0}", score);
Retrieve a singleton value about the source data, such as:
• The number of elements that match a certain condition.
• The element that has the greatest or least value.
• The first element that matches a condition, or the sum of particular values in a specified set of elements. For example, the following query returns the number of scores greater than 80 from the scores integer array:
int highScoreCount =
(from score in scores
where score > 80
select score)
.Count();

the use of parentheses around the query expression before the call to the Count method. You can also express this by using a new variable to store the concrete result. This technique is more readable because it keeps the variable that store the query separate from the query that stores a result.

Enumerable highScoresQuery3 =
from score in scores
where score > 80
select score;

int scoreCount = highScoresQuery3.Count();
In the previous example, the query is executed in the call to Count, because Count must iterate over the results in order to determine the number of elements returned by highScoresQuery.
Write LINQ Queries in C#
This topic shows the three ways in which you can write a LINQ query in C#:
1. Use query syntax.
2. Use method syntax.
3. Use a combination of query syntax and method syntax.
Query Syntax
The recommended way to write most queries is to use query syntax to create query expressions. The following example shows three query expressions. The first query expression demonstrates how to filter or restrict results by applying conditions with a where clause. It returns all elements in the source sequence whose values are greater than 7 or less than 3. The second expression demonstrates how to order the returned results. The third expression demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word.
/ Query #1.
List numbers = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

// The query variable can also be implicitly typed by using var
IEnumerable filteringQuery =
from num in numbers
where num < 3 || num > 7
select num;

// Query #2.
IEnumerable orderingQuery =
from num in numbers
where num < 3 || num > 7
orderby num ascending
select num;

// Query #3.
string[] groupingQuery = { "carrots", "cabbage", "broccoli", "beans", "barley" };
IEnumerable> queryFoodGroups =
from item in groupingQuery
group item by item[0];

Note that the type of the queries is IEnumerable<(Of <(T>)>) . All of these queries could be written using var as shown in the following example:
var query = from num in numbers...
Method Syntax
Some query operations must be expressed as a method call. The most common such methods are those that return singleton numeric values, such as Sum, Max, Min, Average, and so on. These methods must always be called last in any query because they represent only a single value and cannot serve as the source for an additional query operation. The following example shows a method call in a query expression:
List numbers1 = new List() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List numbers2 = new List() { 15, 14, 11, 13, 19, 18, 16, 17, 12, 10 };
// Query #4.
double average = numbers1.Average();

// Query #5.
IEnumerable concatenationQuery = numbers1.Concat(numbers2);
If the method has parameters, these are provided in the form of a lambda expression, as shown in the following example:
// Query #6.
IEnumerable largeNumbersQuery = numbers2.Where(c => c > 15);
In the previous queries, only Query #4 executes immediately. This is because it returns a single value, and not a generic IEnumerable<(Of <(T>)>) collection. The method itself has to use foreach in order to compute its value.
Each of the previous queries can be written by using implicit typing with var, as shown in the following example:
/ var is used for convenience in these queries
var average = numbers1.Average();
var concatenationQuery = numbers1.Concat(numbers2);
var largeNumbersQuery = numbers2.Where(c => c > 15);
Mixed Query and Method Syntax
This example shows how to use method syntax on the results of a query clause. Just enclose the query expression in parentheses, and then apply the dot operator and call the method. In the following example, query #7 returns a count of the numbers whose value is between 3 and 7. In general, however, it is better to use a second variable to store the result of the method call. In this manner, the query is less likely to be confused with the results of the query.
// Query #7.

// Using a query expression with method syntax
int numCount1 =
(from num in numbers1
where num < 3 || num > 7
select num).Count();

// Better: Create a new variable to store
// the method call result
IEnumerable numbersQuery =
from num in numbers1
where num < 3 || num > 7
select num;

int numCount2 = numbersQuery.Count();
Because Query #7 returns a single value and not a collection, the query executes immediately.
The previous query can be written by using implicit typing with var, as follows:
var numCount = (from num in numbers.
It can be written in method syntax as follows:
var numCount = numbers.Where(n => n < 3 || n > 7).Count();
It can be written by using explicit typing, as follows:
int numCount = numbers.Where(n => n < 3 || n > 7).Count();
Example
Query a Collection of Objects
public class StudentClass
{
#region data
protected enum GradeLevel { FirstYear = 1, SecondYear, ThirdYear, FourthYear };
protected class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public GradeLevel Year;
public List ExamScores;
}
protected static List students = new List
{
new Student {FirstName = "Terry", LastName = "Adams", ID = 120, Year = GradeLevel.SecondYear, ExamScores = new List{ 99, 82, 81, 79}},
new Student {FirstName = "Fadi", LastName = "Fakhouri", ID = 116, Year = GradeLevel.ThirdYear,ExamScores = new List{ 99, 86, 90, 94}},
new Student {FirstName = "Hanying", LastName = "Feng", ID = 117, Year = GradeLevel.FirstYear, ExamScores = new List{ 93, 92, 80, 87}},
new Student {FirstName = "Cesar", LastName = "Garcia", ID = 114, Year = GradeLevel.FourthYear,ExamScores = new List{ 97, 89, 85, 82}},
new Student {FirstName = "Debra", LastName = "Garcia", ID = 115, Year = GradeLevel.ThirdYear, ExamScores = new List{ 35, 72, 91, 70}},
new Student {FirstName = "Hugo", LastName = "Garcia", ID = 118, Year = GradeLevel.SecondYear, ExamScores = new List{ 92, 90, 83, 78}},
new Student {FirstName = "Sven", LastName = "Mortensen", ID = 113, Year = GradeLevel.FirstYear, ExamScores = new List{ 88, 94, 65, 91}},
new Student {FirstName = "Claire", LastName = "O'Donnell", ID = 112, Year = GradeLevel.FourthYear, ExamScores = new List{ 75, 84, 91, 39}},
new Student {FirstName = "Svetlana", LastName = "Omelchenko", ID = 111, Year = GradeLevel.SecondYear, ExamScores = new List{ 97, 92, 81, 60}},
new Student {FirstName = "Lance", LastName = "Tucker", ID = 119, Year = GradeLevel.ThirdYear, ExamScores = new List{ 68, 79, 88, 92}},
new Student {FirstName = "Michael", LastName = "Tucker", ID = 122, Year = GradeLevel.FirstYear, ExamScores = new List{ 94, 92, 91, 91}},
new Student {FirstName = "Eugene", LastName = "Zabokritski", ID = 121, Year = GradeLevel.FourthYear, ExamScores = new List{ 96, 85, 91, 60}}
};
#endregion

//Helper method
protected static int GetPercentile(Student s)
{
double avg = s.ExamScores.Average();
return avg > 0 ? (int)avg / 10 : 0;
}



public void QueryHighScores(int exam, int score)
{
var highScores = from student in students
where student.ExamScores[exam] > score
select new {Name = student.FirstName, Score = student.ExamScores[exam]};

foreach (var item in highScores)
{
Console.WriteLine("{0,-15}{1}", item.Name, item.Score);
}
}
}

public class Program
{
public static void Main()
{
StudentClass sc = new StudentClass();
sc.QueryHighScores(1, 90);

// Keep the console window open in debug mode
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
Eample:
Return a Query from a Method
class MQ
{
IEnumerable QueryMethod1(ref int[] ints)
{
var intsToStrings = from i in ints
where i > 4
select i.ToString();
return intsToStrings;
}

static void Main()
{
MQ app = new MQ();

int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var myQuery = app.QueryMethod1(ref nums);


//execute myQuery
foreach (string s in myQuery)
{
Console.WriteLine(s);
}

//modify myQuery
myQuery = (from str in myQuery
orderby str descending
select str).
Take(3);

// Executing myQuery after more
// composition
Console.WriteLine("After modification:");
foreach (string s in myQuery)
{
Console.WriteLine(s);
}

// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
By
Usama Wahab Khan and Atif Shahzad

Isolated Storage

Wednesday, July 29, 2009

Silverlight uses Isolated Storage as a virtual file system to store data in a hidden folder on your machine. It breaks up the data into two separate sections: Section #1 contains administrative information such as disk quota and section #2 contains the actual data. Each Silverlight application is allocated its own portion of the storage with the current quota set to be 1 MB per application.
Advantages:
1.Isolated Storage is a great alterative to using cookies, especially if you are working with large sets of data. Examples of use include undo functionality for your app, shopping cart items, window settings and any other setting your application can call up the next time it loads.
2.Isolated storage stores by user allowing server applications to dedicate unique settings per individual user.
Possible Pitfalls:
1.Administrators can set disk quota per user and assembly which means there is no guarantee on space available. For this reason, it is important to add exception handling to your code.
2.Even though Isolated Storage is placed in a hidden folder it is possible, with a bit of effort, to find the folder. Therefore the data stored is not completely secure as users can change or remove files. It should be noted though that you can use the cryptography classes to the encrypt data stored in isolated storage preventing users from changing it.
3.Machines can be locked down by administrative security policies preventing applications from writing to the IsolatedStorage. More specifically, code must have the IsolatedStorageFilePermission to work with isolated storage.
you will need to add a using statement to reference the namespace System.IO.IsolatedStorage as well as System.IO.

Example 1:

using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;//add this reference
using System.IO;

namespace SilverlightApplication10
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
SaveData("Hello There", "MyData.txt");
string test = LoadData("MyData.txt");
}

private void SaveData(string data, string fileName)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
sw.Write(data);
sw.Close();
}
}
}
}
private string LoadData(string fileName)
{
string data = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
data += lineOfData;
}
}
}
return data;
}
}
}

Example 2:

In Xaml add the class of isolated storage:

X: Class="FileReadingandWritingwithIsolatedStorage.MainPage"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.IO.IsolatedStorage;

namespace FileReadingandWritingwithIsolatedStorage
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

//how to read the file

private void btnRead_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");
txtFileName.Text = "";
}
else
{
using (StreamReader sr = new StreamReader(store.OpenFile(txtFileName.Text,
FileMode.Open, FileAccess.ReadWrite)))
{
txtContent.Text = sr.ReadToEnd();
}
}
}
}
//how to write the file
private void btnWrite_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist , we are creating one for you ");
IsolatedStorageFileStream file = store.CreateFile(txtFileName.Text);
file.Close();
}
using (StreamWriter sw = new StreamWriter(store.OpenFile(txtFileName.Text, FileMode.Open, FileAccess.Write)))
{
sw.WriteLine(txtContent.Text);
}
txtContent.Text = "";
txtFileName.Text = "";
MessageBox.Show("File Writen");
}
}
//how to Delete the file
private void btnDelete_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!(store.FileExists(txtFileName.Text)))
{
MessageBox.Show("File does not exist ");
}
else
{
store.DeleteFile(txtFileName.Text);
MessageBox.Show("Deleted");
}
txtFileName.Text = "";
}
}
}
}
By Usama Wahab Khan and Atif Shahzad

How to Deploy ASP.NET Web Application

Tuesday, July 28, 2009

Introduction
In this tutorial we are going to show you a set of techniques by which you can package and deploy your web applications .....
Alternatives
When it comes to web applications specifically, then you will encounter many techniques that can be utilized as a deployment strategy for your web application:
XCOPY Deployment
The most trivial technique is to simply copy your web application files to the production server hard drive and set a virtual directory there. The setting of a virtual directory is needed by several deployment schemes and can be achieved from Internet Information Manager Microsoft Management Consol (MMC snap-in). Because developers typically use the command line order 'XCOPY' to implement this technique, this technique is typically referred to as XCOPY Deployment.
Copy Web Site
Copy Web Site is a new technique provided in ASP.NET 2.0 and Microsoft Visual Studio 2005 (Available from the Website / Copy Web Site... Menu option). Although this technique is performed from inside Visual Studio (in contrast with the XCOPY deployment technique which is performed from outside Visual Studio), there is no compilation performed at all. All your pages are still in their source code form on the production server. Some developers see this fact as a high risk on their intellectual property. Two extra disadvantages of this technique (and in fact any other technique that does not involve any compilation before deployment) are reduced error checking and the slow initial page load.
The reduced error checking is a direct result to that no compilation is performed and hence some errors may be discovered by your users later. The initial page load slowness is also because nothing is compiled yet and the entire web application has to be compiled at the time the first page is being requested. An advantage of this technique over the XCOPY deployment is that you have the options to deploy to the File System, the Local IIS, the FTP Sites, and the Remote Sites. Please see figure 1

Pre-compilation
All of the deployment methods we mentioned so far suffer from the fact of that no compilation is performed along with the disadvantages that comes as a direct result from this fact. To ensure fast page load and some protection of your source code, you should pre-compile your web site before deployment.
Pre-compilation can be performed in-place by just adding '/Deployment/Precompile.axd' to the root URL of your web application and opening the resulting URL in Internet Explore.
Pre-compilation can also be achieved using the command line compiler 'aspnet_compiler'.
Using Microsoft Visual Studio 2005 you can still perform pre-compilation from the 'Build / Publish Web Site' menu command. Please see figure 2.

It's always desirable to package your web applications such that they are easy to deploy on the production server. Microsoft Visual Studio 2005 gives you this rich packaging option for free ... Just follow the following instructions ...
First of all you need to know that our target is to create a package (and MSI file) that contain our web application in a form that can be later easily deployed on the final production server.
Let's start by selecting 'File / New / Project' in Microsoft Visual Studio 2005. This will present you the famous set of possible project types from which you will select 'Other Project Types / Setup and Deployment' then you will select the 'Web Setup Project' icon from the side to the right. See figure 3.

In figure 3, set the appropriate project name and folder options then click OK.
You can always have the same behavior by adding the SETUP project above to your web application solution instead of creating a new separate solution. You can achieve this by selecting 'File / Add / New Project' instead of 'File / New / Project'. This way you will have a self contained web solution. The 'File / Add / New Project' method is much more recommended.
Your setup project will then open as in figure 4 below:

You will then need to add your web application files to the SETUP project we are developing now. This can be achieved by right clicking your SETUP project name in solution explorer and selecting 'Add / Project Output'. Please see figure 5.

To tune the properties of our SETUP project, we will need to press F4 while it's name is selected in the solution explore. This will bring the SETUP project's properties window. Several useful properties can be set in this window:

The last and most important step is to actually build our SETUP project. This cane be achieved by right clicking the name of our SETUP project in the solution explorer. It's this specific step that creates the MSI package / file mentioned above. This is the file you will need to distribute to your users and this is the file they will use to deploy the web application on their production server.
It's worth mentioning that the actual deployment process will be some what similar to the SETUP of any typical desktop application (with some exceptions of course). One of the many similarities is that the web application after deployment will automatically appear in the 'Add / Remove Programs' window of Windows Control Panel.
Production Server Deployment
For your users to deploy your web application they will just need to double click the MSI file. This will produce something similar to figure 6:

Protection and obfuscation of .NET executable files (.exe, .dll,...)
You must know that every of your .NET products, web application or ASP.NET custom control, can be easily decompiled. Practically every user can get your source code by using some free .Net decompiler. If your license doesn't include source code it is not enough to just exclude source code files from installation. You need additional protection.
After long analyze, we decided to use Spices.Net for protection of all products of Bean Software. Even if you can't afford complete suite, consider at least their Obfuscator. Later, I discovered .NET Reactor which also looks good and it is about ten times cheaper :). You can check Product Comparison link on NetReactor site where it is compared to some other products, it looks really impressive, and not only in price issue.

By
Usama Wahab Khan and Atif Shahzad

Deploying ASP.NET Applications

After creating and testing your ASP.NET application, the next step is to deploy the application. Deployment is the process of distributing the finished application to be installed on other computer. We can use the built-in deployment feature that comes with Visual studio .NET to create a Windows Installer file - a .msi file for the purpose of deploying applications.
Deploying Applications
To start, open the Web Application project you want to deploy. Say, you have a project named "Deploy" with ten Web pages in it. Select File->Add Project->New Project from the main menu. From the Project Types pane select Setup and Deployment Projects and from the Templates pane select Web Setup Project. Type WebSetup1 for name and specify a location in the location box and click OK. The New project dialogue box looks like the image below.

When you click OK on the above dialogue box, the project is added to the solution explorer window and also a File System Editor window appears as shown in the image below.

The File System Editor window has two panes. Select Web Application Folder in the left pane in this window. From the Action menu (on main menu), select Project Output to open the Add Project Output Group dialog box. It looks like the image below.

Make sure that Deploy is selected in the Project drop-down list and select Primary Output from the list and click OK. You also can select other options depending upon the users of your application.
Now, in the File System Editor window, select Web Application Folder and open its Properties window. The Properties window for the Web Application Folder looks like the image below.

In this window, set the VirtualDirectory property to any name, say FinishedApp. FinshedApp will be the folder on the target machine where you will install this application. The name you set for this VirtualDirectory property should not already exist on the target machine. If it does, the contents in the folder will be overwritten. Also, set the DefaultDocument property to any page in the application. The page you set in this property will be the default page for the Web Application. Once you are finished with the Properties window build the solution by selecting Build->Build WebSetup1 from the main menu. After the solution is built sucessfully, a WebSetup1.msi file is created in the Debug directory of the Web Setup project. The default path to the debug directory is as follows:
C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\deploy\WebSetup1\Debug.
Installing the Application
You can copy the WebSetup1.msi file to the target machine and double-click to install the Web Application. When you double-click the setup file the dialog that opens looks like the image below.

Click next and you will be taken to the next dialog which looks like the image below.

You can use the default Virtual Directory specified by the installer or you can specify one. Click next to install the application.

By Usama Wahab Khan and Atif Shahzad

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5 in C#

ASP.NET developers have faced the requirement of reading and writing images to the database. How to store images in the database and then display those images along with the other server controls.
First see how to upload an image and then display the uploaded image on the same page. First creating a sample database and adding a table to it. We will call the database ‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an image column along with some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to construct the database and the table.

Step 1: Create a new asp.net website. In the code-behind, add the following namespace
using System.Data.SqlClient;
Step 2:
Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button control to upload the selected image on button click.

Step 3: In the button click event, add the following code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);

connection.Open();
string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);
}
catch
{
lblResult.Text = "There was an error";
}
finally
{
connection.Close();
}

}
In the code above, we are creating a byte array equal to the length of the file. The byte array will store the image. We then load the image data into the array. The record containing the Employee Name and Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage handler. The image will then be fetched against the EmployeeID (empid).
Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is then passed to the ‘ShowEmpImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.
<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");

context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}

public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}

public bool IsReusable
{
get
{
return false;
}
}


}
Step 5: One final step. Add the following code in the button click (just above the catch block) to call the handler and display the newly inserted image from the database. In the code below, we pass the EmployeeID as a query string parameter to the Http Handler.
// Display the image from the database
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

By
Usama Wahab khan and Atif shahzad

Silverlight 3 Controls

New Controls

Global Calendar
Global Calendar provides an easy way to style individual days as well abstracting out calendar logic allowing the ability to define custom Gregorian calendars.
Same API as Calendar with two new properties: CalendarDayButtonStyleSelector and Calendar Info.
New: Hotkey Ctrl + Home selects the current date or extends the current selection when used in conjunction with Shift.
Rating
Represents a control that can be used to display or allow users to interactively select a rating value. Ratings can be whole or partial stars. By default the control displays stars but can be easily styled to use a different rating metaphor.
TreeMap
The TreeMap visualization displays a hierarchy of data as a set of nested rectangles, where the area of each rectangle represents a chosen metric from the data. Through the use of Interpolators, other properties such as background colour, font size and font color can be varied to represent other metrics. TemplateSelectors allow the control to be easily extended to have different layouts or color schemes for different levels or branches within the hierarchy.
New Extensions
ItemsControlExtensions
Provides useful extensions to ItemsControl:
Get various collections representing the items and their containers.
Get an items host or ScrollViewer.
ScrollViewerExtensions
Provides useful extensions to ScrollViewer to make basic scrolling tasks easier:
Enable mouse wheel scrolling in XAML!
Scroll by page or line.
Scroll to top, bottom, left or right.
Scroll items into view.
TreeViewExtensions
Provides useful extensions to TreeView and TreeViewItem to greatly simplify common TreeView tasks:
Set selected item
Easily add connecting lines and CheckBoxes
Expand and collapse items.
Get items and their containers for parents, siblings and descendants.
Get path.




Accordion
Breaking Change: Removed HeaderTemplate on Accordion, use ItemTemplate.
New: Accordion introduces AccordionButtonStyle making the scenarios where you would like to set the ClickMode to hover on the AccordionItems easy.
Accordion reacts to size changes on both content and header and will trigger a new layout-pass.
AccordionItem will treat its content the same as Grid, making scrollbars visible on content that supports it. AccordionItem no longer has a ScrollViewer in its template.
AccordionItem makes content sizing easy by setting Horizontal/Vertical-ContentAlignment.
AccordionItem now exposes a TargetSize property, allowing you to do calculations of expected size versus current size.
Header is databound making databinding straightforward.
Accordion is able to work with duplicate items (using the SelectedIndices property)
Design-time experience is improved; allowing AccordionItems to open inside Blend.
Lots of layout improvements.
Charting
WPF is now an official platform for Charting!
Breaking Change: IRequireGlobalSeriesIndex's GlobalSeriesIndexChanged method takes a nullable int parameter.
Improved performance of internal data structures for many common scenarios.
Numerous bug fixes for animation inconsistencies between Silverlight and WPF.
Fixed handling of data objects with non-unique hash codes.
Corrected behavior of charts at very small sizes and during animations.
Proper RoutedEvent support for DataPointSeries.SelectionChangedEvent.
Better handling of non-double data by shared Series.
Addition of StrokeMiterLimit to the Polyline used by LineSeries.
Fixes for edge case scenarios when removing a Series.
Ability to set Series.Title with a Binding (on Silverlight 3 and WPF).
Automatic inheritance of the Foreground property by the Title control.
Visual improvements to the LegendItem DataPoint marker.
Significant BubbleSeries performance improvement.
Fixed: Removing a PieSeries from a Chart's Series collection causes a NullReferenceException
Fixed: Chart series title not binding
DataForm Breaking Changes
DataFormFields have all been removed and DataForm.Fields collection has been removed. They have been replaced with the new DataField control, which is a control that wraps content with a label and DescriptionViewer.
Must now explicitly specify Mode=TwoWay on bindings in the DataField.
FieldEditEnding and FieldEditEnded have been removed.
GetFieldElement() has been removed.
ItemEditEnding, ItemEditEnded, CommitItemEdit() have been changed to EditEnding, EditEnded, and CommitEdit() respectively.
CanMoveToXXXXItem have been removed, as they can be derived from the collection given to the DataForm.
CanUserAdd/DeleteItems have been removed, as they are implied through CommandButtonsVisibility.
IsEditing and IsAddingItem have been removed, as they are implied through Mode.
FieldLabelPosition and FieldLabelStyle have become LabelPosition and LabelStyle.
WrapAfter and Orientation have been removed.
The type names DataFormFieldLabelPosition and DataFormDescriptionViewerPosition have been changed to DataFieldLabelPosition and DataFieldDescriptionViewerPosition.
DomainUpDown
Space bar now moves the DomainUpDown into edit mode.
Better handling of mouse-events in edit mode.
Fixed: SL2 Input control DomainUpDown
Expander
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
HeaderedContentControl
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3.
Fixed: HeaderedContentControl throws exception when its content is replaced (under some condition)
Navigation (released as part of the SDK)
New: Pages can be “cached” so they can be re-used on subsequent navigation to the same URI.
TabControl
Fixed: Changing TabControl tabs causing TreeView.SelectionItemChanged event to fire on every node
Time Picker / TimeUpDown
Setting an initial value will be propagated correctly.
Full UI Automation hierarchy implemented.
Renamed the BalloonHint states to TimeHint.
Various minor bug fixes.
Fixed: TimePicker does not show initial Value set in Xaml
Fixed: Buttonspinner disabled state is unnecessary
Fixed: TimePicker - Not able to select a time in dropdown list that is already selected by clicking or with enter key
TransitioningContentControl
Changed the template to have two ContentPresenters instead of ContentControls.
Fixed bug where switching between content would raise exception in certain scenarios.
Handles setting the Transition to a transition that is not yet there (if template hasn’t been loaded yet).
Fixed: System.ArgumentException while using TransitioningContentControl
TreeView (released as part of the SDK)
Fixed: TreeView Scrolls when adding new TreeViewItem
Fixed: TreeView: The App crashes when we add a button as TreeViewItem content
Themes
Fixed: BureauBlueTheme PasswordBox Style always displays vertical scrollbar
ValidationSummary (released as part of the SDK)
The control formally known as ErrorSummary is now ValidationSummary.
Viewbox
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
WrapPanel
Breaking Change: Moved from Silverlight 3 Beta SDK to Silverlight 3
SilverLight 3 Categories:

Silverlight Controls
AutoCompleteBox
Represents a control that provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.

Represents a control that provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.

TreeView
Represents a control that displays hierarchical data in a tree structure that has items that can expand and collapse.

NumericUpDown
Represents a control that enables single value selection from a numeric range of values through a Spinner and TextBox.

Accordion
Represents a collection of collapsed and expanded AccordionItem controls.

TimeUpDown
Represents a control that uses a spinner and textbox to allow a user to input time.

TimePicker & ListTimePickerPopup
TimePicker represents a control that allows the user to select a time.
ListTimePickerPopup represents a time picker popup that allows choosing time from a ListBox.

TimePicker & RangeTimePickerPopup
TimePicker represents a control that allows the user to select a time.
RangeTimePickerPopup represents a time picker popup that allows choosing time through 3 sliders: Hours, Minutes and seconds.

DomainUpDown
Represents a control that enables single value selection from a domain of values through a Spinner and TextBox.

GlobalCalendar
Represents a control that enables a user to select a date by using a visual calendar display as well as providing extension points for representing modified Gregorian calendar systems.
Rating
Represents a control that can be used to display or allow users to interactively select a rating value.
TreeMap
Displays a hierarchy of data as a set of nested rectangles
Expander
Represents a control that displays a header and has a collapsible content window.

HeaderedContentControl
The base class for all controls that contain single content and have a header.

HeaderedItemsControl
Represents a control that contains multiple items and have a header.

Label
Represents the text label for a control.

Viewbox
Defines a content decorator that can stretch and scale a single child to fill the available space.

DockPanel
Defines an area where you can arrange child elements either horizontally or vertically, relative to each other.

WrapPanel
Positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box.

GridSplitter
Represents a control that redistributes space between the rows of columns of a Grid control.

TabControl
Represents a control that contains multiple items that share the same space on the screen.

DatePicker
Represents a control that allows the user to select a date.

Calendar
Represents a control that enables a user to select a date by using a visual calendar display.

LayoutTransformer
Represents a control that applies a layout transformation to its Content.

TransitioningContentControl
Represents a control with a single piece of content and when that content changes performs a transition animation.

Chart:
ColumnSeries
Represents a control that contains a data series to be rendered in column format.

PieSeries
Represents a control that contains a data series to be rendered in pie format.

AreaSeries
Represents a control that contains a data series to be rendered in X/Y line format.

BarSeries
Represents a control that contains a data series to be rendered in bar format.

LineSeries
Represents a control that contains a data series to be rendered in X/Y line format.

ScatterSeries
Represents a control that contains a data series to be rendered in X/Y scatter format.

BubbleSeries
Represents a control that contains a data series to be rendered in X/Y line format. A third axis binding determines the size of the data point.

DynamicSeries
Using a ObservableCollection (or INotifyCollectionChanged) as a Series.ItemSource causes the Chart to update once the underlying data source updates.

Theming

ImplicitStyleManager
Encapsulates an attached behavior that propagates styles in a framework element's associated resource dictionary to its children. The class also provides attached properties that allow the resource dictionary to be loaded from an external source.

ExpressionDarkTheme
Implicitly applies the Expression dark theme to all of its descendent FrameworkElements.

ExpressionLightTheme
Implicitly applies the Expression light theme to all of its descendent FrameworkElements.

RainierPurpleTheme
Implicitly applies the Rainier purple theme to all of its descendent FrameworkElements.

RainierOrangeTheme
Implicitly applies the Rainier orange theme to all of its descendent FrameworkElements.

ShinyBlueTheme
Implicitly applies the Shiny Blue theme to all of its descendent FrameworkElements

ShinyRedTheme
Implicitly applies the Shiny Red theme to all of its descendent FrameworkElements.

BureauBlackTheme
Implicitly applies the Bureau Black theme to all of its descendent FrameworkElements.

BureauBlueTheme
Implicitly applies the Bureau Blue theme to all of its descendent FrameworkElements

WhistlerBlueTheme
Implicitly applies the Whistler Blue theme to all of its descendent FrameworkElements.

TwilightBlueTheme
Implicitly applies the Twilight Blue theme to all of its descendent FrameworkElements.

BubbleCremeTheme
Implicitly applies the Bubble Creme theme to all of its descendent FrameworkElements.


By
Usama Wahab Khan and Atif Shahzad