Friday, July 31, 2009

How to get uploaded image dimensions in asp.net

If you want to know the image dimension you can get the dimensions by using the following code snippet by providing the image path to the method:

public string getImageDimensions(string strPath)
{
System.Drawing.Image imgFromFile= System.Drawing.Image.FromFile(strPath);
float imgWidth = imgFromFile.PhysicalDimension.Width;
float imgHeight = imgFromFile.PhysicalDimension.Height;
string size= imgWidth.toString()+","+imgHeight.toString();
return size;
}

Where,
strPath is the path of the file.

Similary we can get the get uploaded image dimensions as follows:

public string getImageDimensions(Stream streamImgFile)
{
System.Drawing.Image imgFromStream= System.Drawing.Image.FromStream(streamImgFile);
float imgWidth = imgFromStream.PhysicalDimension.Width;
float imgHeight = imgFromStream.PhysicalDimension.Height;
string size= imgWidth.toString()+","+imgHeight.toString();
return size;
}


For e.g.here in the following code imgUploader is name of asp.net file uploader control:

string strImgUploadedType = imgUploader.PostedFile.ContentType.ToString().ToLower();
string strImUploadedFileName = imgUploader.PostedFile.FileName;

//get Dimensions from stream
string strDim= getImageDimensions(imgUploader.PostedFile.InputStream);
//Or we can use from file
string strDim= getImageDimensions(imgUploader.PostedFile.FileName);

string[] strDimArr= s.Split(',');

Response.Write( "Image Width:" + strDimArr[0]+ “
”);
Response.Write("Image Height:" + strDimArr[1]+ “
”);


The PostedFile property will contain a valid System.Web.HttpPostedFile object if file indeed was uploaded. HttpPostedFile provides us with 4 properties:

* ContentLength: size of uploaded file in bytes
* ContentType: MIME type of uploaded file, i.e. "image/gif"
* FileName: full path to uploaded file on client's system, i.e.c:\Bin\Img1.gif
* InputStream: stream object that gives us access to uploaded data

Wednesday, July 22, 2009

Adding Client-Side Script from the Code-Behind Class

All ASP.NET Web pages must be derived directly or indirectly from the Page class in the System.Web.UI namespace. The Page class contains the base set of methods, properties, and events required for a functioning Web page. Among the class's many methods are a few methods designed for injecting client-side script into the rendered HTML. These methods are called from the code-behind class and can therefore be used to emit data-driven client-side script. The pertinent Page class methods for emitting client-side script follow.

The base class is derived from the System.Web.UI.Page class, so you can access the Page class's public methods by calling them directly from your code-behind class.
Note To access the Page class's methods, you can either type in the method name directly, or utilize IntelliSense in Microsoft Visual Studio .NET by entering MyBase. (for Microsoft Visual Basic .NET), this. (for C#), or Page. (for either C# or Visual Basic .NET). If you are using Visual Basic .NET as your programming language of choice, be sure to configure Visual Studio .NET to not hide advanced members, or you won't see these client-side script methods. (To show advanced members, go to Tools | Options | Text Editor | Basic and uncheck Hide advanced members.)

RegisterClientScriptBlock(key, script)

The RegisterClientScriptBlock method adds a block of client-side script after the Web Form's rendered form element, before any Web controls contained within the Web Form. The key input parameter allows you to specify a unique key associated with this script block, whereas the script parameter includes the complete script code to emit. (This script parameter should include the actual script element, along with the client-side JavaScript or Microsoft VBScript.)

When emitting client-side script through the code-behind class of an ASP.NET Web page, typically the value of the key parameter isn't of paramount importance. Simply choose a descriptive key value. The key parameter is more pertinent when injecting client-side script code through a custom, compiled server control. There may be instances where a compiled control requires that there be a set of client-side functions. Multiple instances of the server control on one page might be able to share these common client-side script functions, so these functions need only be emitted once for the entire page, and not once per control instance. For example, the validation controls utilize client-side code to enhance the user experience. This client-side code must be present if there are any validation controls on the page, but if there are multiple validation controls, all can use this single set of shared functions.
By giving a script block a key, a control developer building a control that utilizes a set of common client-side functions can check to see if the required set of common functions has already been added by another instance of the control on the page. If so, it need not re-add the common script. To check if a script block has been added with the same key, use the IsClientScriptBlockRegistered(key) method, which will return a Boolean value indicating whether or not a script block with the same key has been registered. Realize that you can add a script block without first checking if it's registered. If you attempt to add a script block with a key that's already registered, the added script block will be ignored and the original script block will remain assigned to that key.

Note The IsClientScriptBlockRegistered method is particularly useful in two situations. First, it comes in handy when you're adding similar, but unique script blocks, and you need to insure that each script block is given a unique key. The code we'll examine later on in this article illustrates the utility of the "is registered" method. A second use is when building a control that needs some common script, especially if the script is not trivially generated. By using the IsClientScriptBlockRegistered method, you can ensure that the script common to all instances of the server control on the page is generated only once per page load, rather than once per control instance on the page.


The RegisterClientScriptBlock method is useful for adding client-side script that does not rely on any of the form fields present within the Web Form. A common use of this method is to display a client-side alert box. For example, imagine that you had a Web page with some TextBox Web controls and a Save Button. The TextBox controls might have particular values from a database. Imagine that this page allowed the user to modify these values and commit their changes by clicking the Save button. When clicking Save, the Web page would be posted back, and the Button's Click event would fire. You could create a server-side event handler for this event that updates the database. To let the user know that their changes had been saved, you might want to display an alert box that says, "Your changes have been saved." This could be accomplished by adding the following line of code to the Button's Click event handler:


The above will add the specified script content within the page's form, but before the content within the form. When the page is rendered in the user's browser they will see a client-side alert box displayed upon page load.



Note One potentially undesirable side effect of the above example is that the alert box will be displayed right after the browser received the form tag. The browser will suspend rendering of the Web page until the user clicks the alert box's OK button. This means that the user will see a white browser page until they click OK. If you want to have the page displayed completely before displaying the alert box, you can have the JavaScript inserted at the end of the form element using the RegisterStartupScript method, which we'll discuss next.


RegisterStartupScript(key, script)
The RegisterStartupScript method is quite similar to the RegisterClientScriptBlock method. The main difference is the location where the client-side script is emitted. Recall that with the RegisterClientScriptBlock the script is emitted after the start of the form element, but before the form's contents. RegisterStartupScript, on the other hand, adds the specified script at the end of the form, after all form fields. Use RegisterStartupScript to place client-side script that interacts with the rendered HTML elements. (Later we'll look at an example of setting the focus to a form field upon page load; to accomplish this you'll use the RegisterStartupScript method.)
Like RegisterClientScriptBlock, the script blocks added by RegisterStartupScript need a unique key value. Again, this key value is primarily used by custom control developers. Not surprisingly, there is an IsStartupScriptRegistered(key) method as well, which returns a Boolean value indicating if a script block with the specified key has already been registered or not.
Note For more information on using RegisterStartupScript and RegisterClientScriptBlock in creating custom, compiled server controls, read an earlier article of mine: Injecting Client-Side Script from an ASP.NET Server Control.


RegisterArrayDeclaration(arrayName, arrayValue)
If you need to create a client-side JavaScript Array object with some set values, use this method to add a value to a specific array. For example, when using validation controls in an ASP.NET Web page, an Array object (Page_Validators) is built that contains references to the set of validation controls on the page. When the form is submitted, this array is enumerated to check if the various validation controls are valid or not.
To add the values 1, 2, and 3 to a client-side Array object named FavoriteNumbers, you'd use the following server-side code:
RegisterArrayDeclaration("FavoriteNumbers", "1")
RegisterArrayDeclaration("FavoriteNumbers", "2")
RegisterArrayDeclaration("FavoriteNumbers", "3")

This code would emit the following client-side script:

Notice that each array value passed in must be a string; however, the client-side script rendered sets the values of the Array object as the contents of the string. That is, if you wanted to create an Array with the string values "Scott" and "Jisun", you'd use:
RegisterArrayDeclaration("FavoriteFolks", "'Scott'")
RegisterArrayDeclaration("FavoriteFolks ", "'Jisun'")

Notice that the second input parameters are strings that contain 'Scott' and 'Jisun'—text delimited by a single apostrophe. This would render the following client-side script:
var FavoriteFolks = new Array('Scott', 'Jisun');

RegisterHiddenField(hiddenFieldName,hiddenFieldValue)

In classic ASP there was often the need to pass around various bits of information from one page to another. A common way of accomplishing this was using hidden form fields. (A hidden form field is a form field that is not displayed, but whose value is sent on the form's submission. The syntax for creating a hidden form field is .) The need for passing information around by custom hidden form fields in ASP.NET is greatly reduced since the state of the controls in the page is automatically persisted. If, however, you find that you need to create a custom hidden form field, you can do so through the RegisterHiddenField method.
The RegisterHiddenField method accepts two input parameters: the name of the hidden field and the value. For example, to create a hidden form field with the name foo and the value bar, use the following code:
RegisterHiddenField("foo", "bar")

This would add a hidden form field within the page's form element, like so:

Friday, July 17, 2009

Features in C# 3.0

Implicitly Typed Local Variables
C# 3.0 introduces a new keyword called "var". This new keyword enables you to declare a variable whose type is implicitly inferred from the expression used to initialize the variable. For example, consider the following line of code:
var i = 30;

The preceding line initializes the variable i to value 30 and gives it the type of integer. Note that "i" is strongly typed to an integer—it is not an object or a VB6 variant, nor does it carry the overhead of an object or a variant.
We can also write for strings like…
var s = "Hello again!";


In addition to implicitly declaring variables, you can also use the var keyword for declaring arrays as well. For example, consider the following lines of code:
int[] numbers = new int[] { 1, 2, 3, 4, 5};
string[] names = new string[] { "Dave", "Doug", "Jim" };

By using the var keyword, you can rewrite the preceding lines of code as follows:
var numbers = new[] { 1, 2, 3, 4, 5};
var names = new[] { "Dave", Doug, "Jim" };

The var keyword is NOT a completely new type, instead the compiler just takes a look at the right-hand side of the expression. If the right-hand side is an int, for example, the compiler will "replace" the var keyword with int.

Object initializers
Whenever you declare a class, most of the times the class is used only as a placeholder with getters and setters for holding property values without any additional logic. For example, consider a simple class like the following:
public class Person
{
int _id;
string _firstName;
string _lastName;

public int ID
{
get{return _id;}
set{_id = value;}
}
public string FirstName
{
get{return _firstName;}
set{_firstName = value;}
}
public string LastName
{
get{return _lastName;}
set{_lastName = value;}
}
public string FullName
{
get{return FirstName + " " + LastName;}
}
}


As you can see from the above class declaration, it doesn't contain any additional logic. The get and set properties are repetitive and they simply set or get the values of the properties without adding any value. In C#, you can simplify that by leveraging the new feature named Auto-Implemented properties. By taking advantage of this new feature, you can rewrite the above code as follows:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
private set {;}
}
}

In the above code, when you declare a property, the compiler automatically creates a private, anonymous field that is available only to the property's get and set accessors. Note that the auto implemented properties must declare both a get and set accessor. However if you need to create a read-only property, modify the scope of the set accessor to be private.

Object and Collection Initializers
In previous versions of C#, you would create the object in one step and then populate its properties in a separate next step. However with C# 3.0, you can create the object as well as set its properties in a single line of code. For example, consider the following lines of code:
Person obj = new Person();
obj.ID = 1;
obj.FirstName = "Thiru";
obj.LastName = "Thangarathinam";
MessageBox.Show(obj.FullName);

In the above code, you create the Person object and set its properties appropriate values. By leveraging the object initializers feature, you can simplify the above code as follows:
Person obj = new Person { ID = 1, FirstName = "Thiru", LastName = "Thangarathinam" };
MessageBox.Show(obj.FullName);

In the above code lines of code, you directly assign the values to the properties of the Person object. Although you can simulate this behavior using constructor for the object, object initializers reduce the need to have a specific constructor for every variation of argument variation we need over time.
In C# 2.0, when you want to populate a collection, you need to write the following line of code:
List names = new List();
names.Add("David");
names.Add("Tim");
names.Add("Doug");

Now with the introduction of the new collection initializers feature in C# 3.0, you can shorten the above lines of code to a single line of code:
List names = new List {"David", "Tim", "Doug"};


Extension methods
Another cool thing is that you're able to add (static) methods to existing (default) classes. As an example, here is the code to add a ToMD5() method to the string class:

public static class StringExtensions
{
public static string ToMD5(this string s)
{
System.Security.Cryptography.MD5 md5;
md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s));
// Return the result, replace unneeded "-"
return System.BitConverter.ToString(result).Replace("-", string.Empty);
}
}



Once compiled, all string objects now have the ToMD5 method. If you placed the extension class above in a seperate namespace, you should import this namespace to enable the usage. Example below:
string s = "Hello, this string is gonna be MD5-ed!";
Console.WriteLine(s.ToMD5()); // Prints the MD5 hash


As you can see from the preceding lines of code, the extension methods allow you to write cleaner and easy-to-maintain code.
Here are some of the key characteristics of extension methods:
• The extension method as well as the class that contains the extension method should be static.
• Although extension methods are static methods, they are invoked as if they are instance methods.
• The first parameter passed to the extension method specifies the type on which they operate and it is preceded by the "this" keyword.
• From within the extension method, you can't access the private variables of the type you are extending.
• Instance methods take precedence over extension methods in situations where they have same signature.


Anonymous Types
As the name suggests, anonymous types allow you to create a type on-the-fly at compile time. The newly created type has public properties and backing fields defined for the members you initialize during construction. For example, consider the following line of code:
var obj=new{ID=1,FirstName="Thiru",LastName="Thangarathinam"};

In the above line, you just specify the various attributes you want to have in the anonymous class and assign the instantiated object to a variable of type "var". The actual type assigned to obj is determined by the compiler. Since the compiler assigns the name of the type only at compile time, you can't pass an anonymous type to another method and it can only be used within the method they were declared.
When the compiler sees the above code, it automatically declares a class as follows:
class __Anonymous1
{
private int _id = 1;
private string _firstName = "Thiru";
private string _lastName = "Thangarathinam";

public int ID
{
get{return _id;}
set{_id = value;}
}
public string FirstName
{
get{return _firstName;}
set{_firstName = value;}
}
public string LastName
{
get{return _lastName;}
set{_lastName = value;}
}
}

Anonymous Types use the Object Initializer to specify what properties the new type will be declare.
Note that the anonymous types are just meant to be placeholders for quickly defining entity types and you can't add methods or customize the behavior of an anonymous type.

Lambda Expressions
Lambda expressions are simply functions and they are declared in the context of expressions than as a member of a class. It is an inline expression or a statement block which can be used to pass arguments to a method or assign value to delegate. All lambda expressions use the lambda operator => and the left side of the operator denotes the results and the right side contains the expression to be evaluated. For instance, consider the following lambda expression:
age => age + 1

The above function takes one argument named age, and returns age + 1 as the result. As you can see, Lambda expressions follow the below syntax:
(parameter-list) => expression;

where expression can be any C# expression or a block of code. Just like anonymous methods you can use a lambda expression in place of a delegate. Here are some sample lambda expressions and their corresponding delegates.
//Explicitly typed parameter
(Person obj) => MessageBox.Show(obj.FirstName.ToUpper());

//Implicitly typed parameter
(obj) => obj.FirstName == "Thiru";

//Explicitly typed parameter
(int a, int b) => a + b

//Implicitly typed parameter
(x, y) => { return x + y; }


As you see from the preceding lines of code, lambda expressions can be written in such a way that it can infer the parameter type from the signature of the delegate it is assigned to.

Query Expressions
This feature, also known as LINQ (Language Integrated Query), allows you to write SQL-like syntax in C#.
For instance, you may have a class that describes your data as follows:
public class CoOrdinate
{
public int x ;
public int y;
}

You now could easily declare the logical equivalent of a database table inside C# as follows:
// Use Object and collection initializers
List coords = ... ;

And now that you have your data as a collection that implements IEnumerable, you easily can query this data as follows:
var filteredCoords =
from c in coords
where x == 1
select (c.x, c.y)

In the SQL-like syntax above, "from", "where", and "select" are query expressions that take advantage of C# 3.0 features such as anonymous types, extension methods, implicit typed local variables, and so forth. This way, you can leverage SQL-like syntax and work with disconnected data easily.
Each query expression is actually translated into a C#-like invocation behind the scenes. For instance, the following:
where x == 1
Translates to this:
coords.where(c => c.x == 1)

As you can see, the above looks an awful lot like a lambda expression and extension method. C# 3.0 has many other query expressions and rules that surround them.

Friday, July 3, 2009

JSON (JavaScript Object Notation)

JSON is a part of the ECMAScript standard since ECMA has defined in 1999 the eval() function that parses the format.
It has been popularized with the success of Ajax.
The JSON word appears often when one is speaking about Ajax. We know this is another data format, that can replace XML, and this format is supported by a lot of programmers. But what is exactly JSON, what are the advantages?

Why JSON?

The benefit of JSON is that it is recognized natively by JavaScript. No need for parsing an XML document to extract the data and get it throught the net.

JSON and XML

Benefits of JSON:
- The easiness of reading.
- The easiness of using.


Benefits of XML:
- XML is extensible.
- It is widely used and recognized by almost all programming languages.


Unfortunally, both XML and JSON are enable to integrate a large amount of data in binary form.

The syntax of JSON

The components of JSON:
- An object: contains objets or attributes.
- A scalar variable: Number, String, Boolean.
- An array.
- Literal values: null, true, false, "string of characters", and numerical values.
Object


It contains a member or a list of members, and each member has the form:
"name" : "value"

The syntax of the object is:
{ member, member, .... }


Array
A collection of values, separated by commas.
[ value, value, ....]


Values
A value may be: an object, an array, a litteral (string, number, true, false, null).
Nothing more is required to create a JSON file!

Example of JSON file
A simple example, designing a menu:
It is an object made of members that are an attribute and an array that holds other objects, the rows of the menu.

{
"menu": "File",
"commands": [
{
"title": "New",
"action":"CreateDoc"
},
{
"title": "Open",
"action": "OpenDoc"
},
{
"title": "Close",
"action": "CloseDoc"
}
]
}


The XML equivalent:




How to use the format
The JSON file allows to load data from the server or to send data to it, in this format. For example, storing the content of a form, just filled by an user. This involves three steps: the browser processing, the server processing, and the data exchange between them.

Client side (browser)
This is rather easy, as JSON is a part of the JavaScript definition. The content of a file, or the definition of the data is assigned to a variable, and this variable becomes an object of the program.

Server side
JSON file are used by various programming languages, including PHP and Java thanks to parsers that allow to get the content and that may even convert it into classes and attributes of the language.
The json.org includes a C parser and a list of parsers in other languages.

Data exchange
Loading a file may be accomplished from JavaScript in several ways:
- direct including of the file into the HTML page, as a JavaScript .js external file.
- loading by a JavaScript command.
- using XMLHttpRequest.


The JSON file is parsed by the eval() JavaScript function.

Sending the file to the server may be accomplished by XMLHttpRequest. The file is sent as a text file and processed by the parser of the programming language that uses it.
Example
The XMLHttpRequest code:
var req = new XMLHttpRequest();
req.open("GET", "file.json", true);
req.onreadystatechange = myCode; // the handler
req.send(null);

The JavaScript handler:
function myCode()
{
if (req.readyState == 4)
{
var doc = eval('(' + req.responseText + ')');
}
}


Using the data:
var menuName = document.getElementById('jsmenu'); // finding a field
menuName.value = doc.menu.value; // assigning a value to the field


How to access data:
doc.commands[0].title // read value of the "title" field in the array
doc.commands[0].action // read value of the "action" field in the array

XML Vs JSON

Extensible Markup Language (XML) is a text format derived from Standard Generalized Markup Language (SGML). Compared to SGML, XML is simple. HyperText Markup Language (HTML), by comparison, is even simpler. Even so, a good reference book on HTML is an inch thick. This is because the formatting and structuring of documents is a complicated business.

Most of the excitement around XML is around a new role as an interchangeable data serialization format. XML provides two enormous advantages as a data representation language:

1. It is text-based.
2. It is position-independent.


These together encouraged a higher level of application-independence than other data-interchange formats. The fact that XML was already a W3C standard meant that there wasn't much left to fight about (or so it seemed).

Unfortunately, XML is not well suited to data-interchange, much as a wrench is not well-suited to driving nails. It carries a lot of baggage, and it doesn't match the data model of most programming languages. When most programmers saw XML for the first time, they were shocked at how ugly and inefficient it was. It turns out that that first reaction was the correct one. There is another text notation that has all of the advantages of XML, but is much better suited to data-interchange. That notation is JavaScript Object Notation (JSON).

The most informed opinions on XML suggest that XML has big problems as a data-interchange format, but the disadvantages are compensated for by the benefits of interoperability and openness.

JSON promises the same benefits of interoperability and openness, but without the disadvantages.

Let's compare XML and JSON on the attributes that the XML community considers important.

Simplicity
XML is simpler than SGML, but JSON is much simpler than XML. JSON has a much smaller grammar and maps more directly onto the data structures used in modern programming languages.

Extensibility
JSON is not extensible because it does not need to be. JSON is not a document markup language, so it is not necessary to define new tags or attributes to represent data in it.

Interoperability
JSON has the same interoperability potential as XML.

Openness
JSON is at least as open as XML, perhaps more so because it is not in the center of corporate/political standardization struggles.



In summary these are some of the advantages of XML.

XML is human readable

JSON is much easier for human to read than XML. It is easier to write, too. It is also easier for machines to read and write.

XML can be used as an exchange format to enable users to move their data between similar applications
The same is true for JSON.

XML provides a structure to data so that it is richer in information
The same is true for JSON.

XML is easily processed because the structure of the data is simple and standard

JSON is processed more easily because its structure is simpler.

There is a wide range of reusable software available to programmers to handle XML so they don't have to re-invent code
JSON, being a simpler notation, needs much less specialized software. In the languages JavaScript and Python, the JSON notation is built into the programming language; no additional software is needed at all. In other languages, only a small amount of JSON-specific code is necessary. For example, a package of three simple classes that makes JSON available to Java is available for free from JSON.org.

XML separates the presentation of data from the structure of that data.
XML requires translating the structure of the data into a document structure. This mapping can be complicated. JSON structures are based on arrays and records. That is what data is made of. XML structures are based on elements (which can be nested), attributes (which cannot), raw content text, entities, DTDs, and other meta structures.

A common exchange format
JSON is a better data exchange format. XML is a better document exchange format. Use the right tool for the right job.

Many views of the one data
JSON does not provide any display capabilities because it is not a document markup language.

Self-Describing Data
XML and JSON have this in common.

Complete integration of all traditional databases and formats
(Statements about XML are sometimes given to a bit of hyperbole.) XML documents can contain any imaginable data type - from classical data like text and numbers, or multimedia objects such as sounds, to active formats like Java applets or ActiveX components.

JSON does not have a <[CDATA[]]> feature, so it is not well suited to act as a carrier of sounds or images or other large binary payloads. JSON is optimized for data. Besides, delivering executable programs in a data-interchange system could introduce dangerous security problems.

Internationalization
XML and JSON both use Unicode.

Open and extensible
XML’s one-of-a-kind open structure allows you to add other state-of-the-art elements when needed. This means that you can always adapt your system to embrace industry-specific vocabulary.

Those vocabularies can be automatically converted to JSON, making migration from XML to JSON very straightforward.

XML is easily readable by both humans and machines
JSON is easier to read for both humans and machines.

XML is object-oriented
Actually, XML is document-oriented. JSON is data-oriented. JSON can be mapped more easily to object-oriented systems.

XML is being widely adopted by the computer industry
JSON is just beginning to become known. Its simplicity and the ease of converting XML to JSON makes JSON ultimately more adoptable.