Welcome to Kanbal.com



Introduction

Microsoft has introduced generics in .net 2.0 to improve the productivity and reduce the overhead of the CRL. This will also help to reduce the boxing and unboxing and runtime error.

What are generics?

Generics are classes, structures, interfaces, methods that have placeholders for one or more types they store.

Example:

public class ExampleForGeneric

{

}

Here is the parameter to the class where the class can store type T.

The letter T can be replaced with any word. The above class is only a template, so we cannot create an instance for this class. We can create the instance only after replace the T with any specific Type.

Example

ExampleForGeneric<SomeOtherClassName> objExampleForGeneric = new ExampleForGeneric<SomeOtherClassName>();

This is the way, we can create instance to this class.

Why Generics?

Let's take a simple example with Array List

A single ArrayList can support any type

ArrayList objAL = new ArrayList();

objAL.Add("Kannan");

objAL.Add(222);

objAL.Add(myobj); //here myObj is a object of one of my other class.

for (int iCounter = 0; iCounter < objAL.Count; iCounter++)

{

String myString = objAL[iCounter]; // this will through exception at runtime.

}

Now we have added three different types to this ArrayList. Inorder to read them back, we have used a for loop. When we compile this application, we will not get any compile time exception. However, while executing the application we will get runtime exception because we are trying to assign myobj to a String.

To avoid this error we should read them back to Object. Again, boxing and unboxing is also overhead to the CLR.

This is the right time to use Generics. Lets see an another example with Generics.

List<String> objList = new List<String>();

objList.Add("Kannan");

objList.Add("Amutha");

objList.Add("Chandrasekaran");

for (int iCounter = 0; iCounter < objList.Count; iCounter++)

{

Console.WriteLine(objList[iCounter]);

}

In the above example, we are strongly typing the List as string. So if we add any other type apart from String then the compiler will through exception. Because the List<String> is a Strong Typed Class and there is no need for a boxing and unboxing. So with generics we have avoided both runtime exception and boxing, unboxing.

Generic Method

A Generic method might use type parameter as its return value or as the type is one of the formal parameter.

Here is the simple example for Generic Method

public class ExampleForGenerics

{
private
T GenericMethod(T arg)

{
T someValue = arg;
}

}

In the above class the method GenericMethod is a geniric method.

Generic method can appear in a non-generic type also. It is important to note that a method is not a generic just because of it belongs to a geniric type, or even its has a formal parameters whose types are generic parameters of the enclosing type.

A method is generic only if it has its own list of type parameters. In the following code, only the method Generic is generic method.

public class SimpleClass

{

T Generic(T args)

{

}

}

public class GenericClass

{

T NonGeneric(T args)

{

}

}

Microsoft provided few namespace for Generics in .net 2.0

System.Collections.Generic offers following classes

  1. Dictionary
  2. List
  3. Queue
  4. Stack
  5. Sorted List
  6. Linked List

System.Collections.ObjectModel offers

  1. Collections
  2. ReadOnlyCollections
  3. KeyedCollections

Other Generic Types

  1. Nullable types
  2. Array Segment
  3. Event Handlers

Here is the simple comparision with Generic and Non-Generic objects

Object

Generic

Runtime check

Compile time checks

Weakly types objects

Strongly typed objects

Required boxing and unboxing for value typed objects

Reduce the need for boxing

So for we have seen the generics in .net 2.0 and its use.

When should I Generics?

If a data structure or utility class offers a generic version, use generic versions

If your code target to .Net 1.1, then you should not use Generics.

  • Web Forms contain blocks of code that are processed on the server.
  • The first time a Web Form is requested, the entire page is compiled.
  • Subsequent requests are served from this compiled page.
  • Web Forms can contain page directives, which are global settings for the page. Common page directives enable you to turn off session state and ViewState management.
  • Web Forms can contain both server-sides, including SSIs (Server Side Includes), which enable you to dynamically insert the contents of a file into your Web form, and user controls. User controls are object oriented and use a more programmatic approach to code encapsulation than SSIs.
  • Web Forms can also contain as much HTML and client-side script, such as JavaScript, as desired.
  • Microsoft used the advantage of Visual Basic (VB) in ASP.NET. ASP.NET simplifies Web page development with form-based programming. In ASP.NET, these Forms are called Web Forms and are analogous to VB Forms, replacing ASP Pages.
  • As a part of the .NET Framework, ASP.NET can be used to write Web applications as well as for writing Web services. Similar to VB, Web Forms programming is also event based.
  • .aspx extension: An ASP.NET Web Forms page is a declarative text file with an .aspx file name extension.
  • @Page directive: Defines page-specific (.aspx file) attributes used by the ASP.NET page parser and compiler.
<%@Page attribute="value" [attribute="value"...] %>
  • Framework is an object model
  • Denoted by the runat="server" attribute
  • Contain Client-side and Server-side code
  • Contain HTML and server controls
<Form runat="server"> </Form>

File Open Dialog box in C#

To Open or to Save file we use dialog box in all the windows applications. To use open or save dialog box we should use the following directive statement.

using System.Windows.Forms;

Because these dialog boxes are defined in System.windows.Forms.

In the following code i have used the file open dialog box for demo.

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = "Kanbal.com open dialog box demo";
openFileDialog.InitialDirectory =
@"c:\Program Files";
openFileDialog.Filter =
"All files (*.*)|*.*|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory =
true;

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFileName.Text = openFileDialog.FileName;
}

The above code will display the open dialog box with all files filter like exactly below.

open-dialog-box


You can use various properties like Title, Filter, InitialDirectory to make your dialog box more friendly.

CSharp supports converting String to Int in many ways. The following are the few examples to do that.

Example 1:

Int32 intValue = Convert.ToInt32("String Value");

Here the String Value can be 10 or 100 or any number value. This Convert Class contains many methods which, can convert a String to any other datatype which .Net supports

 

Following are the few for your idea.

 

DateTime dateValue = Convert.ToDateTime("String Value");

Double doubleValue = Convert.ToDouble("String Value");

 

I have copied this table from MSDN which could help you to understand this more.

 

Name Description
ChangeType Overloaded. Returns an object of a specified type whose value is equivalent to a specified object.
FromBase64CharArray Converts a subset of a Unicode character array, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array. Parameters specify the subset in the input array and the number of elements to convert.
FromBase64String Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.
GetTypeCode Returns the TypeCode for the specified object.
IsDBNull Returns an indication whether the specified object is of type DBNull.
ToBase64CharArray Overloaded. Converts a subset of an 8-bit unsigned integer array to an equivalent subset of a Unicode character array encoded with base-64 digits.
ToBase64String Overloaded. Converts the value of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits.
ToBoolean Overloaded. Converts a specified value to an equivalent Boolean value.
ToByte Overloaded. Converts a specified value to an 8-bit unsigned integer.
ToChar Overloaded. Converts a specified value to a Unicode character.
ToDateTime Overloaded. Converts a specified value to a DateTime value.
ToDecimal Overloaded. Converts a specified value to a decimal number.
ToDouble Overloaded. Converts a specified value to a double-precision floating-point number.
ToInt16 Overloaded. Converts a specified value to a 16-bit signed integer.
ToInt32 Overloaded. Converts a specified value to a 32-bit signed integer.
ToInt64 Overloaded. Converts a specified value to a 64-bit signed integer.
ToSByte Overloaded. Converts a specified value to an 8-bit signed integer.
ToSingle Overloaded. Converts a specified value to a single-precision floating-point number.
ToString Overloaded. Converts the specified value to its equivalent string representation.
ToUInt16 Overloaded. Converts a specified value to a 16-bit unsigned integer.
ToUInt32 Overloaded. Converts a specified value to a 32-bit unsigned integer.
ToUInt64 Overloaded. Converts a specified value to a 64-bit unsigned integer.

 

 

The another way is using Parse. Most of the datatype might have this Parse method.

 

Example 2:

 

Int32 x = Int32.Parse("10000");


You can explore this by typing the datatype and place a dot(.) next to the type.  Check the below for more clarity.

 

Double.Parse

DateTime.Parse

 

You can read boxing and unboxing after this.

 

 

LINQ - Language Integrated Query

LINQ enable us to query the collection objects to get the result based on the condition. The follwoing example will give you an idea about a basic LINQ query.

For example,
List<Person> PersonList = new List<Person>(){
new Person(){Name = "Raja", Age = 25},
new Person(){Name = "Kannan", Age = 28},
new Person(){Name = "Vijay", Age = 27},
new Person(){Name = "Ashok", Age = 30}
};

The above code will create a list of type Person with 4 items in it.

Consider a situation where you need to filter the items who is have age on or below 28.
This scenario can be filtered using the following query.

var query = from p in PersonList
where p.Age <= 28
select p;

The above query will read each items from PersonList into the local variable p, and checks whether p.Age <=28. If the condition is satisfied, that item 'p' will be added in to result.

List<Person> resultList = query.ToList();

'var' is new data type which can hold any type of data. In our example, it holds the LINQ query. But, the query will not hold any result of that query. The result of the query can be taken by converting that 'query' into List using ToList(), or it can be taken which we iterate the query using 'foreach'. Until that, it will just hold the query.


To sort the list by age in ascending order.
var query = from p in PersonList
order p by p.Age asc
select p;

To collect only Age field
List<Int32> ageList = (from p in PersonList
select p.Age).ToList();

Hello.

Today, I want to tell the absolute beginner how to read a value from a SQLDataReader in C#.

If you are an experienced ADO.NET developer then this article will be a complete bore for you. But, believe it or not, there are people who are trying to learn how to work with databases in C#. So maybe I can help out at least one person!

What is an SQL DataReader? DataReaders are a fast way to pull records from a database when all you want to do is simply READ. You may have heard the term "Firehose Cursor" used to describe a DataReader. A firehose is a good comparison because the water (data) only flows one way and it flows fast. DataReaders can not be used to update data, delete data, or anything else other than reading. A good example of when to use a DataReader would be cities in a state. You may want to read out all cities in New York and since they aren't exactly changing every day, you would want to pull them down as fast as possible.

 

Ok, I promised fast and easy so here goes.

First, you must instantiate (create) a new database connection. Now, I am only working with Microsoft's SQL server today. If you need help converting this article to other database platforms like Oracle or MySQL then please let me know.

 

Make sure you are also using the needed namespaces before you begin.

using System.Data;
using System.Data.SqlClient;

SqlConnection adoConn = new SqlConnection("Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=username;Password=password");
adoConn.Open();

Database is now created and opened. The string that we passed is called the "Connection String". All it does is tell the database how and where to open the connection. Substitute "server", "Initial Catalog", and "User ID/Password" with your database information. Remember, this is ONLY an open connection. The database is sitting there waiting on a command. And that is exactly what we setup next. A command. Think of a command as a direct order you give the server (even though it may or may not listen!).

// new command
string sql = "SELECT CustomerName FROM MyTable";
SqlCommand adoCmd = new SqlCommand(sql, adoConn);

 

The sql string is simply a SQL command we are passing. The adoConn is telling the command which connection to use. Simple, huh?

Ok, now we have an open connection and a command (using the sql string). Our next move is to create the DataReader and display some data.

SqlDataReader adoDR = adoCmd.ExecuteReader();

if (adoDR.HasRows)
{
while (adoDR.Read())
{
Response.Write(adoDR["CustomerName"].ToString());
}
}

The ExecuteReader() method sends the SQL data from the command (our SELECT statement) and if there are records, brings them one at a time down to the DataReader (adoDR).

You'll notice that we first called the .HasRows condition. It's always good to first make sure there is data returned before you do anything with it. The next statement might look a little confusing. This while loop brings each record down one at a time. See, when you call the ExecuteReader and assuming there are rows, you actually start at position "-1". Strange, huh? For example, let's say that SELECT statement returned 50 rows of data. The first record number would be 0, the next would be 1, then so on until record 49. 0-49 records. Everytime you call the .Read() on the DataReader, you advance a record. So, if you started at -1 and advanced a record you would be at the beginning. Record 0. Calling .Read() will continue to return TRUE until you reach the last record. So as you can see, this makes it convenient to cycle through all records. Also I should mention you HAVE to call it at least once to advance to the first record.

The Response.Write command simply sends the data to the web page. This could have been Console.WriteLine, etc. Notice how the "CustomerName" was used. Be careful here because you want to make sure you don't try to call a field in a table that you didn't SELECT.

Ok, the last thing to do is close connections and dispose so that we don't create memory leaks on the server.

 

adoDR.Close();
adoDR.Dispose();
adoCmd.Dispose();
adoConn.Close();
adoConn.Dispose();

Noticed I reversed the order that I used when creating the objects. DataReaders are opened when you call the ExecuteReader() and when you open something, you should close it. Calling .Dispose() on these objects would also close them but closing them myself has always been a habbit of mine. Command objects aren't opened or closed so no Close() is needed. And finally we close/dispose of the database connection.

There. Was that so hard? We created a database connection, opened it, created a command (using a custom SQL query) and executed the DataReader. Then, we looped through the records. Finally, we closed and disposed of all the objects.

 

There you have it. Simple. ADO.NET has made it really easy to display data. This is just a tiny scratch on the Titanic. ADO.NET could fill 50,000 pages!

I hope you enjoyed this article. I have to admit, I'm not much of a writer but I remember the first time I pulled data from a database and I wished I had someone telling me in plain English how to get right to the point.

Obviously, we didn't cover other topics like error trapping, DataGrids, DataSets, etc. Those will come in time!

ASP.NET 3.5 was released in November 2007. It holds features that were build above the ASP.NET 2.0 engine. In a nutshell, the following are the features of ASP.NET 3.5:-
  1. ASP.NET AJAX is integrated with the .net framework.
  2. New powerful controls like the ListView and DataPagers are included.
  3. Use of LINQ - (Language Integrated Query).  A consistent query language used over databases, objects and XML.
  4. Widgets: Widgets are the so called web part of .net 2.0. They are like small pods containing the contents of various different web pages.
  5. WCF - Windows communication foundation
  6. WPF - Windows presentation foundation
  7. WF - Windows workflow
  8. Windows card space

Sometimes you've just got to dance like nobody's watching. (via: thedailywhat )

Watch Video ›


Read this Article

Pok

Someone has an overactive imagination. Poor Harrison got a little bit more than he bargained for with this answer.

View Image ›


Read this Article

Raf Cloud

Powered by RafCloud

Login Form