Published on Tuesday, November 18, 2008
In JavaScript, we don't have to worry about specifying the data type
of a number (e.g. integer, float, etc.) as we would do with other programming languages such as
C or Java. In fact, JavaScript only features one primitive data type for representing numbers:
the number data type.
Following is how to create numbers in JavaScript:
var aInteger = 3; // An integer
var aInteger2 = -3; // A negative integer
var aFloat = 2.5; // A float
var aFloat2 = -2.5; // A negative float
var aFloat3 = .5; // A float (0.5)
var aFloat4 = 2.5e100 ; // A float (2.5 x 10 to the power of 100)
var anHex = 0xaa; // An hexadecimal ((10 x 16) + 10 = 170)
JavaScript also features a Number object which is dynamically wrapped around the primitive
data type number to provide additional functionality, when needed. This allows us to write:
var x = 5; // a number (primitive data type)
var testResult1 = x.toString(); // invoking a function exposed by the Number wrapper object
The Number wrapper object only exists while needed. JavaScript will dynamically create it
when needed, and automatically discarded. To be noted, if we apply the typeof operator to a number, we
will get "number" as result (the primitive data type), not "Number" (the wrapper object):
var y = 5; // a number
var testResult2 = typeof(y); // get the type
However, a Number object can also be instantiated:
var z = new Number(5); // instantiate a Number object
var testResult3 = typeof(z); // get the type
The Number object can be used as if it was a primitive data type. For example,
we can sum two Number objects using the sum operator:
var num1 = new Number(2); // operand 1
var num2 = new Number(4); // operand 2
var testResult4 = num1 + num2; // sum the two numbers
The Number() constructor also exposes the following constants:
- MAX_VALUE: The largest number representable by JavaScript;
- MIN_VALUE: The smallest number representable by JavaScript;
- NaN: Not a Number;
- NEGATIVE_INFINITY: The value representing negative infinity;
- POSITIVE_INFINITY: The value representing infinity.
To be noted, these constant cannot be accessed through Number objects. Instead,
they need to be accessed through the constructor as follows:
var aNumberObject = new Number(26);
var testResult5 = aNumberObject.MAX_VALUE; // Returns undefined
var testResult6 = Number.MAX_VALUE; // Correct usage
In the next article we will discuss
how to convert strings to numbers in JavaScript
.
Happy Coding!
Published on Tuesday, November 18, 2008
Previously we looked at how the parseInt() function can be used to convert float
values to integer in JavaScript.
The parseInt() function can also be used to convert numbers expressed in a
base different than 10 to integers in base 10:
var test3 = 0xF; // hex representing 15 in base 10
var result3 = parseInt(test3); // returns an integer
The parseInt() method also accepts an additional parameter that allows
specifying the base or radix for the conversion:
var test4 = "0xf"; // string representing hex
var result4 = parseInt(test4, 16); // convert to int
var test5 = "f"; // string representing hex
var result5 = parseInt(test5, 16); // convert to int
However, note that if you want to convert an hexadecimal using the parseInt() function,
you will have to pass it as a string.
This is because the toString() method of the Number
object converts hexadecimals to their base 10 notation (e.g. 0xf is converted to 15)
rather than their hexadecimal notation, while the parseInt() function is
expecting the number in its original notation:
var test6 = 0xF; // an hexadecimal number
var result6 = test6.toString(); // returns "15" instead of "0xf"
var result7 = parseInt(test6, 16); // returns 21 instead of 15!
Happy Coding!
Published on Tuesday, November 18, 2008
Converting float values to integer values allows converting, for example 1.25 to 1.
In order to perform such as conversion in JavaScript, we can use the parseInt() method:
var test1 = 2.5; // a float
var testResult1 = parseInt(test1); // returns an integer
Note that the parseInt() function accepts a string as paramter. However, since JavaScript
automatically converts numbers to strings when necessary, it doesn't matter if you
will pass a string or a number to the function.
In the following example, we pass a string to the function:
var test2 = "2.5"; // a string representing a float
var testResult2 = parseInt(test2); // returns an integer
Next we will look at how the parseInt() function can be used to
convert an hexadecimal
to an integer in base 10 in JavaScript.
Happy Coding!
Published on Tuesday, November 18, 2008
In the previous article
we saw that converting string to
numbers in JavaScript is very trivial, and that
often JavaScript performs the convesion automatically for us.
Similarly, converting numbers to strings is very trivial,
and is performed automatically by JavaScript when needed.
For example, some operators such as the sum operator (+) will
automatically transform numbers to strings when one of the operands
is a string:
var operand1 = 15;
var operand2 = " houses";
var testResult1 = operand1 + operand2;
As shown in the example above, the sum operator will convert the numeric operand to
a string when one of the two operands is a string, and will then concatenate the two string
rather than performing the arithmetic addition.
Explicitely converting a number to a string in JavaScript
JavaScript also allows to explicitely convert a number to a string by using the String()
function and the toString() method of the Number object:
var test2 = 15;
var test2Converted = String(test2); // convert to string
var testResult2 = test2Converted.length; // get the number of characters in test2Converted
var test3 = 150;
var test3Converted = test3.toString(10) // convert to string
var testResult3 = test3Converted.length; // get the number of characters in test3Converted
The toString() method accepts an optional parameter that allows specifying the base or radix
for the conversion:
var test4 = 4; // a number in the base 10 system;
var testResult4 = test4.toString(2); // transform to base 2 and convert to string;
In addition, from JavaScript 1.5 and ECMAScript v3, the Number object exposes the following new
methods:
- toFixed()
- toExponential()
- toPrecision()
The toFixed() method allows converting a number to a string and allows specifying how many digits
after the decimal point should be stored in the string:
var testResult5 = Math.PI.toFixed(2); // returns "3.14" instead of "3.14159265"
Rounding is automatically performed by JavaScript if necessary.
The toExponential() function converts the number to a string
using exponential notation. The optional paramter indicates the
number of digits after the decimal point:
var test6 = 1024;
var testResult6 = test6.toExponential(3);
Rounding is automatically performed by JavaScript if necessary.
Finally, the toPrecision method converts a number to a string using the number
of digits specified as parameter:
var test7 = 199.99;
var testResult7 = test7.toPrecision(4);
As you can appreciate from the example above, rounding is automatically
performed by JavaScript, when necessary.
In the next article we will have a look at
how to convert a float to an integer in JavaScript.
Happy Coding!
Published on Tuesday, November 18, 2008
Converting strings to numbers in JavaScript is very trivial. In fact, JavaScript automatically
converts string values to numeric values when needed.
For example, the multiply (*) and divide (/) operators require both the operand to be numbers. If
one or both of the operands are string values instead of numeric values, JavaScript
will automatically try to convert them to numbers:
var operand1 = 5; // a numeric value
var operand2 = "3"; // a string value
var testResult1 = operand1 * operand2; // multiply the two operands
However, the sum operator (+) will try to convert operands to string, if one of them
is a string, and perform a string concatenation rather than an arithmetic addition:
var operand1 = 5; // a numeric value
var operand2 = "3"; // a string value
var testResult2 = operand1 + operand2; // concatenate
Explicitely converting a string to a number
To explicitly convert a string value to a numeric value, the parseInt() and parseFloat() functions can be used:
var operand1 = 5; // a numeric value
var operand2 = "3"; // a string value
var testResult3 = operand1 + parseInt(operand2); // sum
The parseInt function also accepts a second parameter that allows specifying the base or radix
for the conversion:
var stringValue = "10"; // a string value
var testResult4 = parseInt(stringValue, 2); // returns "10" in base 2 ((0 * 1) + (1 * 2) = 2)
One of the good features of the parseInt() and parseFloat() functions is that they are quite flexible
when it comes to parsing strings that also include non-numeric characters
var s = "10 houses";
var testResult5 = parseInt(s); // returns 10
There is also an alternative way of converting a string to a number in JavaScript, which consist
in using the more generic Number() constructor:
var aString = "5.25";
var testResult6 = Number(aString);
However, the more generic Number() constructor is less flexible than the parseInt() and
parseFloat() functions as it does not allow non numeric characters to appear after the
number, with the exception of the space character:
var test7 = "5 houses";
var testResult7 = Number(test7); // returns NaN (Not a Number)
Next we will see how to convert a number to a string in JavaScript.
Happy Coding!
Published on Tuesday, January 15, 2008
HTTP POST requests allow you to post some data while executing the request. The data is contained in
the content of the request.
Usually the data is formatted as follows:
name=value&name2=value2&name3=value3
It is also possible to format data in other formats as well (e.g. JSON).
Here is how to execute an HTTP POST request in .NET:
'The URL we would like to post the data to
Dim uri As String = "http://www.schisani.com/Default.aspx"
'The three parameters we would like to post to the page (name, surname and age)
Dim parameters As String = "name=giammarco&surname=schisani&age=25"
Dim httpWebRequest As System.Net.HttpWebRequest = httpWebRequest.Create(uri)
'Specify that we are going to execute a POST request.
httpWebRequest.Method = "POST"
'Specify the content type of our request. If we were passing a JSON string, instead of
'"name=giammarco&surname=schisani&age=25", we would set a content type equal to "application/json".
httpWebRequest.ContentType = "application/x-www-form-urlencoded"
'Write the parameters
Dim requestStream As System.IO.Stream = httpWebRequest.GetRequestStream()
Dim streamwriter As System.IO.StreamWriter = New System.IO.StreamWriter(requestStream)
streamwriter.Write(parameters)
streamwriter.Close()
Very often we also need to read the response to our request. The following line can be added
to the code above to read the response to our request:
Dim httpWebResponse As System.Net.HttpWebResponse = httpWebRequest.GetResponse()
Happy Coding!
Published on Tuesday, December 18, 2007
I serialize objects to XML for a number of reasons, including transmitting objects
using webservices or saving the state of an object to the file system.
Here is how your serialize an object in .NET:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
public class Person
{
public int age;
public string name;
}
class Program
{
static void Main(string[] args)
{
// Instantiate object to be serialized
Person p = new Person();
p.age = 25;
p.name = "Giammarco";
// XmlSerializer will serialize the object
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeof(Person));
// Serialize the p obejct and save it to a file
System.IO.TextWriter writer = new System.IO.StreamWriter(@"serialized.xml");
xmlSerializer.Serialize(writer, p);
// Close the stream
writer.Close();
}
}
Now let's read the same file and deserialize the content to an object:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
public class Person
{
public int age;
public string name;
}
class Program
{
static void Main(string[] args)
{
// Will read the XML file
System.IO.TextReader textReader =
new System.IO.StreamReader(@"serialized.xml");
// XmlSerializer will deserialize the object
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeof(Person));
// Deserialize
Person p = (Person)xmlSerializer.Deserialize(textReader);
// Release resources
textReader.Close();
// Output some info about the deserialized object
Console.WriteLine("Age: " + p.age);
Console.WriteLine("Name: " + p.name);
// Wait for user input before closing the console
Console.WriteLine("Press any key to continue...");
Console.ReadKey ();
}
}
I have also posted another recipe about serializing objects to JSON in .NET.
Happy Coding!
Published on Saturday, December 15, 2007
The following example shows how to read multiple rows of data in ADO.NET 2.0.
The results are stored in a collection of "User" objects, defined as follows:
Public Class User
Public FirstName As String
Public LastName As String
End Class
The example uses a number of try-catch statements that can be often avoided.
Remember to include the "System.Data.SqlClient" reference.
In VB.NET
'The connection string to the database.
'The "SERVER" is the name of the SQL Server. For example, this could be:
' - db.schisani.com,123 (123 is the port number) or
' - computerName/sqlServerInstanceName,123 (123 is the port number) or
' - computerName/sqlServerInstance (if the server is running on the default port).
'The "UID" is the username for your SQL account.
'The "PWD" is the password for your SQL account.
'The "DATABASE" is the name of the database o schema you are connecting to.
'The "Connection Timeout" is expressed in seconds.
Dim connectionString As String = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###"
Using sqlConn As SqlConnection = New SqlConnection(connectionString)
'Tell the SqlCommand what query to execute and what SqlConnection to use.
Using sqlCmd As SqlCommand = New SqlCommand("SELECT userFirstName, userLastName FROM tblUser WHERE userID > 50 AND userID < 100)", sqlConn)
'Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID)
'Open the SqlConnection before executing the query.
Try
sqlConn.Open()
Catch ex As Exception
'There is a problem connecting to the instance of the SQL Server.
'For example, the connection string might be wrong,
'or the SQL Server might not be available to you.
End Try
'Execute the query.
Try
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While (sqlReader.Read())
Try
Dim resultSet As System.Collections.Generic.List(Of User) = _
New System.Collections.Generic.List(Of User)
Dim user As User = New User()
'Read the values in the row.
user.FirstName = CStr(sqlReader("userFirstName"))
user.LastName = CStr(sqlReader("userLastName"))
'Add the user to the result set
resultSet.Add(user)
Catch ex As Exception
'There was a problem reading the values stored in the SqlDataReader.
'For example, you might be requesting values that are not contained
'in the SqlDataReader, or their type might be different from the one
'you are expecting (e.g. NULL instead of String).
End Try
End While
Catch ex As Exception
'There was a problem executing the query. For examaple, your SQL statement
'might be wrong, or you might not have permission to read data from the
'specified table.
End Try
End Using
End Using
In C#
//The connection string to the database.
//The "SERVER" is the name of the SQL Server. For example, this could be:
// - db.schisani.com,123 (123 is the port number) or
// - computerName/sqlServerInstanceName,123 (123 is the port number) or
// - computerName/sqlServerInstance (if the server is running on the default port).
//The "UID" is the username for your SQL account.
//The "PWD" is the password for your SQL account.
//The "DATABASE" is the name of the database o schema you are connecting to.
//The "Connection Timeout" is expressed in seconds.
string connectionString = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###";
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
//Tell the SqlCommand what query to execute and what SqlConnection to use.
using (SqlCommand sqlCmd = new SqlCommand("SELECT userFirstName, userLastName FROM tblUser WHERE userID > 50 AND userID < 100)", sqlConn)) {
//Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID);
//Open the SqlConnection before executing the query.
try {
sqlConn.Open();
}
catch (Exception ex) {
//There is a problem connecting to the instance of the SQL Server.
//For example, the connection string might be wrong,
//or the SQL Server might not be available to you.
}
//Execute the query.
try {
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while ((sqlReader.Read())) {
try {
System.Collections.Generic.List resultSet = new System.Collections.Generic.List();
User user = new User();
//Read the values in the row.
user.FirstName = (string)sqlReader("userFirstName");
user.LastName = (string)sqlReader("userLastName");
//Add the user to the result set
resultSet.Add(user);
}
catch (Exception ex) {
//There was a problem reading the values stored in the SqlDataReader.
//For example, you might be requesting values that are not contained
//in the SqlDataReader, or their type might be different from the one
//you are expecting (e.g. NULL instead of String).
}
}
}
catch (Exception ex) {
//There was a problem executing the query. For examaple, your SQL statement
//might be wrong, or you might not have permission to read data from the
//specified table.
}
}
}
Happy Coding!
Published on Saturday, December 15, 2007
The following example shows how to read a single row of data in ADO.NET 2.0.
The example uses a number of try-catch statements that can be often avoided.
Remember to include the "System.Data.SqlClient" reference.
In VB.NET
'The connection string to the database.
'The "SERVER" is the name of the SQL Server. For example, this could be:
' - db.schisani.com,123 (123 is the port number) or
' - computerName/sqlServerInstanceName,123 (123 is the port number) or
' - computerName/sqlServerInstance (if the server is running on the default port).
'The "UID" is the username for your SQL account.
'The "PWD" is the password for your SQL account.
'The "DATABASE" is the name of the database o schema you are connecting to.
'The "Connection Timeout" is expressed in seconds.
Dim connectionString As String = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###"
Using sqlConn As SqlConnection = New SqlConnection(connectionString)
'Tell the SqlCommand what query to execute and what SqlConnection to use.
Using sqlCmd As SqlCommand = New SqlCommand("SELECT TOP 1 userFirstName, userLastName FROM tblUser WHERE userID = @userID)", sqlConn)
'Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID)
'Open the SqlConnection before executing the query.
Try
sqlConn.Open()
Catch ex As Exception
'There is a problem connecting to the instance of the SQL Server.
'For example, the connection string might be wrong,
'or the SQL Server might not be available to you.
End Try
'Execute the query.
Try
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If (sqlReader.Read() = True) Then
'The record has been found.
Try
'Read the values in the row.
Dim userFirstName As String = CStr(sqlReader("userFirstName"))
Dim userLastName As String = CStr(sqlReader("userLastName"))
Catch ex As Exception
'There was a problem reading the values stored in the SqlDataReader.
'For example, you might be requesting values that are not contained
'in the SqlDataReader, or their type might be different from the one
'you are expecting (e.g. NULL instead of String).
End Try
Else
'The record has not been found.
End If
Catch ex As Exception
'There was a problem executing the query. For examaple, your SQL statement
'might be wrong, or you might not have permission to read data from the
'specified table.
End Try
End Using
End Using
In C#
//The connection string to the database.
//The "SERVER" is the name of the SQL Server. For example, this could be:
// - db.schisani.com,123 (123 is the port number) or
// - computerName/sqlServerInstanceName,123 (123 is the port number) or
// - computerName/sqlServerInstance (if the server is running on the default port).
//The "UID" is the username for your SQL account.
//The "PWD" is the password for your SQL account.
//The "DATABASE" is the name of the database o schema you are connecting to.
//The "Connection Timeout" is expressed in seconds.
string connectionString = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###";
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
//Tell the SqlCommand what query to execute and what SqlConnection to use.
using (SqlCommand sqlCmd = new SqlCommand("SELECT TOP 1 userFirstName, userLastName FROM tblUser WHERE userID = @userID)", sqlConn)) {
//Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID);
//Open the SqlConnection before executing the query.
try {
sqlConn.Open();
}
catch (Exception ex) {
//There is a problem connecting to the instance of the SQL Server.
//For example, the connection string might be wrong,
//or the SQL Server might not be available to you.
}
//Execute the query.
try {
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
if ((sqlReader.Read() == true)) {
//The record has been found.
try {
//Read the values in the row.
string userFirstName = (string)sqlReader("userFirstName");
string userLastName = (string)sqlReader("userLastName");
}
catch (Exception ex) {
//There was a problem reading the values stored in the SqlDataReader.
//For example, you might be requesting values that are not contained
//in the SqlDataReader, or their type might be different from the one
//you are expecting (e.g. NULL instead of String).
}
}
else {
//The record has not been found.
}
}
catch (Exception ex) {
//There was a problem executing the query. For examaple, your SQL statement
//might be wrong, or you might not have permission to read data from the
//specified table.
}
}
}
Happy Coding!
Published on Saturday, December 15, 2007
The following example shows how to execute a scalar query in ADO.NET 2.0. A scalar query
allows retriving a single value from the database (e.g. the name of a user).
The example uses a number of try-catch statements that can be often avoided.
Remember to include the "System.Data.SqlClient" reference.
In VB.NET
'The connection string to the database.
'The "SERVER" is the name of the SQL Server. For example, this could be:
' - db.schisani.com,123 (123 is the port number) or
' - computerName/sqlServerInstanceName,123 (123 is the port number) or
' - computerName/sqlServerInstance (if the server is running on the default port).
'The "UID" is the username for your SQL account.
'The "PWD" is the password for your SQL account.
'The "DATABASE" is the name of the database o schema you are connecting to.
'The "Connect Timeout" is expressed in seconds.
Dim connectionString As String = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###"
Using sqlConn As SqlConnection = New SqlConnection(connectionString)
'Tell the SqlCommand what query to execute and what SqlConnection to use.
Using sqlCmd As SqlCommand = New SqlCommand("SELECT TOP 1 userFirstName FROM tblUser WHERE userID = @userID)", sqlConn)
'Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID)
'Open the SqlConnection before executing the query.
Try
sqlConn.Open()
Catch ex As Exception
'There is a problem connecting to the instance of the SQL Server.
'For example, the connection string might be wrong,
'or the SQL Server might not be available to you.
End Try
'Execute the query.
Try
Dim result As Object = sqlCmd.ExecuteScalar()
If (result = Nothing) Then
'The SQL Query did not return a value. No record was found matching the
'search criteria.
Else
'The SQL Query returned a value. Let's cast it to the correct type.
Dim name As String = CStr(result)
End If
Catch ex As Exception
'There was a problem executing the query. For examaple, your SQL statement
'might be wrong, or you might not have permission to read data from the
'specified table.
End Try
End Using
End Using
In C#
//The connection string to the database.
//The "SERVER" is the name of the SQL Server. For example, this could be:
// - db.schisani.com,123 (123 is the port number) or
// - computerName/sqlServerInstanceName,123 (123 is the port number) or
// - computerName/sqlServerInstance (if the server is running on the default port).
//The "UID" is the username for your SQL account.
//The "PWD" is the password for your SQL account.
//The "DATABASE" is the name of the database o schema you are connecting to.
//The "Connect Timeout" is expressed in seconds.
string connectionString = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###";
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
//Tell the SqlCommand what query to execute and what SqlConnection to use.
using (SqlCommand sqlCmd = new SqlCommand("SELECT TOP 1 userFirstName FROM tblUser WHERE userID = @userID)", sqlConn)) {
//Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userID", userID);
//Open the SqlConnection before executing the query.
try {
sqlConn.Open();
}
catch (Exception ex) {
//There is a problem connecting to the instance of the SQL Server.
//For example, the connection string might be wrong,
//or the SQL Server might not be available to you.
}
//Execute the query.
try {
object result = sqlCmd.ExecuteScalar();
if ((result == null)) {
}
//The SQL Query did not return a value. No record was found matching the
//search criteria.
else {
//The SQL Query returned a value. Let's cast it to the correct type.
string name = (string)result;
}
}
catch (Exception ex) {
//There was a problem executing the query. For examaple, your SQL statement
//might be wrong, or you might not have permission to read data from the
//specified table.
}
}
}
Happy Coding!
Published on Saturday, December 15, 2007
The following example shows how to execute a SQL Insert statement in ADO.NET 2.0.
The example uses a number of try-catch statements that can be often avoided.
Remember to include the "System.Data.SqlClient" reference.
In VB.NET
Public Sub InsertNewRecord(ByVal userFirstName As String, ByVal userLastName As String)
'The connection string to the database.
'The "SERVER" is the name of the SQL Server. For example, this could be:
' - db.schisani.com,123 (123 is the port number) or
' - computerName/sqlServerInstanceName,123 (123 is the port number) or
' - computerName/sqlServerInstance (if the server is running on the default port).
'The "UID" is the username for your SQL account.
'The "PWD" is the password for your SQL account.
'The "DATABASE" is the name of the database o schema you are connecting to.
'The "Connection Timeout" is expressed in seconds.
Dim connectionString As String = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###"
Using sqlConn As SqlConnection = New SqlConnection(connectionString)
'Tell the SqlCommand what query to execute and what SqlConnection to use.
Using sqlCmd As SqlCommand = New SqlCommand("INSERT INTO tblUser (userFirstName, userLastName) VALUES (@userFirstName, @userLastName)", sqlConn)
'Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userFirstName", userFirstName)
sqlCmd.Parameters.AddWithValue("@userLastName", userLastName)
'Open the SqlConnection before executing the query.
Try
sqlConn.Open()
Catch ex As Exception
'There is a problem connecting to the instance of the SQL Server.
'For example, the connection string might be wrong,
'or the SQL Server might not be available to you.
End Try
'Execute the query.
Try
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
'There was a problem executing the query. For examaple, your SQL statement
'might be wrong, or you might not have permission to create records in the
'specified table.
End Try
End Using
End Using
End Sub
In C#
public void InsertNewRecord(string userFirstName, string userLastName)
{
//The connection string to the database.
//The "SERVER" is the name of the SQL Server. For example, this could be:
// - db.schisani.com,123 (123 is the port number) or
// - computerName/sqlServerInstanceName,123 (123 is the port number) or
// - computerName/sqlServerInstance (if the server is running on the default port).
//The "UID" is the username for your SQL account.
//The "PWD" is the password for your SQL account.
//The "DATABASE" is the name of the database o schema you are connecting to.
//The "Connection Timeout" is expressed in seconds.
string connectionString = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###";
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
//Tell the SqlCommand what query to execute and what SqlConnection to use.
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO tblUser (userFirstName, userLastName) VALUES (@userFirstName, @userLastName)", sqlConn)) {
//Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userFirstName", userFirstName);
sqlCmd.Parameters.AddWithValue("@userLastName", userLastName);
//Open the SqlConnection before executing the query.
try {
sqlConn.Open();
}
catch (Exception ex) {
//There is a problem connecting to the instance of the SQL Server.
//For example, the connection string might be wrong,
//or the SQL Server might not be available to you.
}
//Execute the query.
try {
sqlCmd.ExecuteNonQuery();
}
catch (Exception ex) {
//There was a problem executing the query. For examaple, your SQL statement
//might be wrong, or you might not have permission to create records in the
//specified table.
}
}
}
}
Happy Coding!
Published on Saturday, December 15, 2007
The following example shows how to execute a SQL Update statement in ADO.NET 2.0.
The example uses a number of try-catch statements that can be often avoided.
Remember to include the "System.Data.SqlClient" reference.
In VB.NET
Public Sub UpdateUserFirstName(ByVal userFirstName As String, ByVal userID)
'The connection string to the database.
'The "SERVER" is the name of the SQL Server. For example, this could be:
' - db.schisani.com,123 (123 is the port number) or
' - computerName/sqlServerInstanceName,123 (123 is the port number) or
' - computerName/sqlServerInstance (if the server is running on the default port).
'The "UID" is the username for your SQL account.
'The "PWD" is the password for your SQL account.
'The "DATABASE" is the name of the database o schema you are connecting to.
'The "Connection Timeout" is expressed in seconds.
Dim connectionString As String = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###"
Using sqlConn As SqlConnection = New SqlConnection(connectionString)
'Tell the SqlCommand what query to execute and what SqlConnection to use.
Using sqlCmd As SqlCommand = New SqlCommand("UPDATE tblUser SET userFirstName = @userFirstName WHERE userID = @userID", sqlConn)
'Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userFirstName", userFirstName)
sqlCmd.Parameters.AddWithValue("@userID", userID)
'Open the SqlConnection before executing the query.
Try
sqlConn.Open()
Catch ex As Exception
'There is a problem connecting to the instance of the SQL Server.
'For example, the connection string might be wrong,
'or the SQL Server might not be available to you.
End Try
Try
'Execute the SQL Update.
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
'There was a problem executing the query. For examaple, your SQL statement
'might be wrong, or you might not have permission to update records in the
'specified table.
End Try
End Using
End Using
End Sub
In C#
public void UpdateUserFirstName(string userFirstName, object userID)
{
//The connection string to the database.
//The "SERVER" is the name of the SQL Server. For example, this could be:
// - db.schisani.com,123 (123 is the port number) or
// - computerName/sqlServerInstanceName,123 (123 is the port number) or
// - computerName/sqlServerInstance (if the server is running on the default port).
//The "UID" is the username for your SQL account.
//The "PWD" is the password for your SQL account.
//The "DATABASE" is the name of the database o schema you are connecting to.
//The "Connection Timeout" is expressed in seconds.
string connectionString = "SERVER=###;UID=###;PWD=###;DATABASE=###;Connect Timeout=###";
using (SqlConnection sqlConn = new SqlConnection(connectionString)) {
//Tell the SqlCommand what query to execute and what SqlConnection to use.
using (SqlCommand sqlCmd = new SqlCommand("UPDATE tblUser SET userFirstName = @userFirstName WHERE userID = @userID", sqlConn)) {
//Add SqlParameters to the SqlCommand
sqlCmd.Parameters.AddWithValue("@userFirstName", userFirstName);
sqlCmd.Parameters.AddWithValue("@userID", userID);
//Open the SqlConnection before executing the query.
try {
sqlConn.Open();
}
catch (Exception ex) {
//There is a problem connecting to the instance of the SQL Server.
//For example, the connection string might be wrong,
//or the SQL Server might not be available to you.
}
try {
//Execute the SQL Update.
sqlCmd.ExecuteNonQuery();
}
catch (Exception ex) {
//There was a problem executing the query. For examaple, your SQL statement
//might be wrong, or you might not have permission to update records in the
//specified table.
}
}
}
}
Happy Coding!
Published on Friday, December 14, 2007
Sometimes we want an .aspx page to return something that it is not a web page
(for example, an image or a JSON string).
To achieve this, we need to:
-
Call the "Response.ClearHeaders()" method;
-
Change the "Response.ContentType" property as needed.
Here you can find
a good list of values for the "Response.ContentType" property.
The recipe:
Response.ClearHeaders()
Response.ContentType = "text/html"
Happy Coding!
Published on Friday, December 14, 2007
When developing custom controls in ASP.NET, we often need to save the state of the control
accross postbacks.
In ASP.NET, saving the state of the control is achieved by populating the
ViewState property of the control. The viewstate is saved as a string in the content of the
response.
So, we need to serialize our control as a string, in order to be able to save its
state.
First and foremost, the control must be marked as "Serializable":
<Serializable()> _
Public Class SimpleControl
Inherits System.Web.UI.Control
End Class
Then, we need to implement the "ISerializable" interface:
<Serializable()> _
Public Class SimpleControl
Inherits System.Web.UI.Control
Implements System.Runtime.Serialization.ISerializable
Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, _
ByVal context As System.Runtime.Serialization.StreamingContext) _
Implements System.Runtime.Serialization.ISerializable.GetObjectData
End Sub
End Class
In the "GetObjectData" method, we need to store the information to be serialized into
the "info" object passed as paramter. In the example below, our control will have a String
as property called "Text", that needs to be saved accross postbacks. The "Text" property
will have to be serialized:
<Serializable()> _
Public Class SimpleControl
Inherits System.Web.UI.Control
Implements System.Runtime.Serialization.ISerializable
Property Text() As String
Get
If (Me.ViewState("Text") Is Nothing) Then
Me.ViewState("Text") = String.Empty
End If
Return CType(Me.ViewState("Text"), System.String)
End Get
Set(ByVal value As String)
Me.ViewState("Text") = value
End Set
End Property
Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, _
ByVal context As System.Runtime.Serialization.StreamingContext) _
Implements System.Runtime.Serialization.ISerializable.GetObjectData
info.AddValue("Text", Me.Text, Type.GetType("System.String"))
End Sub
End Class
And voilĂ , the control is now serializable.
Happy Coding!
Published on Wednesday, December 12, 2007
Using the ASP.NET AJAX "UpdatePanel" control allows to quickly implementing ajax-like functionality
in any web page.
I call it "ajax-like" because I believe ASP.NET 2.0 AJAX does not know how to
handle concurrent ajax request: if you have two update panels on your web page and try to update
the first by clicking a button and then try to update the second by clicking a second button before
the first asynchronous postback is completed, the first action is lost and the first update panel
does not get updated. Anyway, here is how to use it:
First and foremost, you will have to have ASP.NET Ajax installed. After that, you will have to
add a "ScriptManager" object to your page or to your masterpage. Remember the script manager
should always go at the top of the page, straight after the "form" opening tag:
<asp:ScriptManager ID="scriptManager1" runat="server" />
After that you can place your UpdatePanel in the page:
<asp:UpdatePanel ID="updatePanel1" runat="server" >
<ContentTemplate>
<b>Date inside the update panel:</b>
<asp:Label ID="lblInside" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnDoPartialPostback" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
The "Triggers" represents the events that will trigget the update.
Happy Coding!
Published on Wednesday, December 12, 2007
An easy way to achieve url rewriting in ASP.NET 2.0 and IIS 6 is to use HTTP Handlers. In the following recipe we will configure our website to accept requests to a url
similar to "http://www.domainname.com/usedcars/alfa romeo/146/used.car". The request will be passed to another web page (e.g.
"http://www.domainname.com/usedcars.aspx?makeName=alfa rome&modelName=146") without having our server to send an HTTP 302 Redirect
message to the browser.
To achieve that, first you need to create a class that implements the IHttpHandler interface. The class
will handle the requests:
public class Rewriter : System.Web.IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// E.g. "/usedcars/alfa romeo/146/used.car"
string rawUrl = context.Request.RawUrl.ToLower();
// Remove "/usedcars/"
rawUrl = rawUrl.Substring(10);
// "alfa romeo"
string makeName = rawUrl.Substring(0, rawUrl.IndexOf("/"));
// Remove "alfa romeo/"
rawUrl = rawUrl.Substring(rawUrl.IndexOf("/") + 1);
// Get the model name (e.g. 146)
string modelName = rawUrl.Substring(0, rawUrl.IndexOf("/"));
// Prepare the url
string targetUrl = String.Format("~/usedcars.aspx?modelName={0}&makeName={1}", modelName, makeName);
// Url encode the string
string encodedTargetUrl = context.Server.UrlEncode(targetUrl);
// Send the right document
context.Server.Transfer(targetUrl);
}
public bool IsReusable
{
get
{
return false;
}
}
}
After that, you need to add the handler to the web.config file:
<httpHandlers>
<add verb="*" path="*.car" type="Rewriter"/>
</httpHandlers>
And I think you're pretty much ready to go!
Happy Coding!
Published on Wednesday, December 12, 2007
Often you need to nest repeaters. There are many ways of achieving this. A "clean" one consists in
creating a DataRelation between two DataTables:
// Get the first DataTable and assing a name to it
dsSchisaniTableAdapters.tblMakeTableAdapter adapterMake = new dsSchisaniTableAdapters.tblMakeTableAdapter();
dsSchisani.tblMakeDataTable tblMake = adapterMake.GetMake();
tblMake.TableName = "tblMake";
// Get the second DataTable and assign a name to it
dsSchisaniTableAdapters.tblModelTableAdapter adapterModel = new dsSchisaniTableAdapters.tblModelTableAdapter();
dsSchisani.tblModelDataTable tblModel = adapterModel.GetModel();
tblModel.TableName = "tblModel";
// Instantiate a DataSet and add the two DataTables to it
DataSet ds = new DataSet("dsReviews");
ds.Tables.Add(tblMake);
ds.Tables.Add(tblModel);
// Instantiate a new DataRelation
ds.Relations.Add(new DataRelation("fkMake_makeID",
((dsSchisani.tblMakeDataTable)ds.Tables["tblMake"]).makeIDColumn,
((dsSchisani.tblModelDataTable)ds.Tables["tblModel"]).fkMake_makeIDColumn));
// Bind the repeater to the dataset
repMake.DataSource = ds;
repMake.DataBind();
You have the two nested repeaters on your ASPX page as follows:
<%-- Parent repeater--%>
<asp:Repeater ID="repMake" runat="server" OnItemDataBound="repMake_ItemDataBound" >
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "MakeName") %>
<ul>
<%-- Child repeater --%>
<asp:Repeater ID="repModel" runat="server" >
<ItemTemplate>
<li>
<%-- Get a value from the parent repeater's data source (e.g. makeName) --%>
<%# DataBinder.Eval(((System.Web.UI.WebControls.RepeaterItem)Container.Parent.Parent).DataItem, "MakeName") %>
-
<%-- Get a value from the child repater's data source (e.g. modelName) --%>
<%# Eval("ModelName") %>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
</ItemTemplate>
</asp:Repeater>
And you populate the child or inner repeater every time a new item is bound to the parent repeater:
// On repMake.ItemDateBound...
protected void repMake_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
// Find the repModel
Repeater repModel = e.Item.FindControl("repModel") as Repeater;
// Set the datasource for the child repeater as the result of the CreateChildView opeation
// on the relation we added to the dataset earlier on.
repModel.DataSource = e.Item.DataItem.CreateChildView("fkMake_makeID");
// Bind the child repeater
repModel.DataBind();
}
They couldn't make it any easier!
Happy coding!
Published on Wednesday, December 12, 2007
I first found URL Encoding useful when I needed to include an equal ("=") character in one of the
parameters of the querystring.
To encode a string using the .NET framework:
Dim stringToBeEncoded As String = "lorem==ips??==?asd=1"
Dim encodedString As String = System.Web.HttpUtility.UrlEncode(stringToBeEncoded)
Decoding the string is as easy as encoding it:
'Encoding the string
Dim stringToBeEncoded As String = "lorem==ips??==?asd=1"
Dim encodedString As String = System.Web.HttpUtility.UrlEncode(stringToBeEncoded)
'Decoding the string
Dim decodedString As String = System.Web.HttpUtility.UrlDecode(encodedString)
One of the things to be aware of is that there is no need to decode the URL when retriving values
using the Response.Querystring object. Values provided by the object are already URL decoded for us.
Happy Coding!
Published on Monday, December 10, 2007
This comes handy in a lot of different situations. I use it when I need to extract some data from a
web page, or when someone is exposing a web service in JSON, for example.
Here is the recipe in C#:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.schisani.com");
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
string content = streamReader.ReadToEnd();
And here is the recipe in Visual Basic:
Dim httpWebRequest As HttpWebRequest = httpWebRequest.Create("http://www.schisani.com")
Dim webResponse As WebResponse = httpWebRequest.GetResponse()
Dim stream As Stream = webResponse.GetResponseStream()
Dim streamReader As StreamReader = New StreamReader(stream)
Dim content As String = streamReader.ReadToEnd()
For the "HttpWebRequest" and the "WebResponse" classes, you need to import the "System.Net" namespace.
For the "Stream" and "StreamReader" classes, you need to import the "System.IO" namespace.
In Visual Basic:
Imports System.Net
Imports System.IO
In C#:
Using System.Net;
Using System.IO;
Happy Coding!
Published on Sunday, December 09, 2007
There are a few libraries out there to serialize or deserialize objects in
JSON. The "JavascriptObjectSerializer"
class in the "Microsoft.Web.Script.Serialization" namespace worked fine for me.
To use this class you need to add a reference to the "System.Web" and "System.Web.Extensions"
dlls. The "System.Web.Extensions" dll comes with Asp.Net AJAX.
Please note that the following recipe has been developed using .NET 2.0.
Here is how to serialize and deserialize an object:
using System;
using System.Web.Script.Serialization;
namespace SerializationJSON
{
class Program
{
public class Person
{
public string name;
public string age;
}
static void Main(string[] args)
{
// Instantiate new Person object, to be serialized
Person p = new Person();
p.age = "25";
p.name = "Giammarco Schisani";
// Instantiate a new JavaScriptSerializer
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
// Serialize
string pSerialized = javaScriptSerializer.Serialize(p);
// Echo serialized object to console
Console.WriteLine(pSerialized);
Console.WriteLine("Press any key to deserialize the string now...");
Console.ReadLine();
// Deserialize the result into a new object p1
Person p1 = javaScriptSerializer.Deserialize(pSerialized);
// Echo p1's properties to the console
Console.WriteLine("I have just deserialized the text above.");
Console.WriteLine("p1.age = " + p1.age);
Console.WriteLine("p2.name = " + p1.name);
Console.WriteLine("Press any key to close the test application.");
Console.ReadLine();
}
}
}
Happy Coding!