jump to navigation

Nullable data types in Visual Basic 9.0 November 17, 2008

Posted by fofo in LINQ, VB 9.0, Visual Studio 2008.
Tags: , ,
4 comments

In this post I would like to talk about language improvements in visual basic 9.0 and more specifically about nullable data types.

The largest improvement in Visual basic 9.0 is LINQ. So all these enhancements that were made in the VB 9.0 language (the same goes for c# 3.0 enhancements) had LINQ in mind and how LINQ will be able to work.

Nullable data types enable us to create data types e.g integers and set them-initialise them to the value nothing, null.

In our database design we often have tables where fields are allowed to have NULL.

Prior to Visual Basic 9.0 one should turn the null value from the database into a zero value in the application
Nullable data types help us to avoid this mismatch in LINQ to SQL.

The problem is that representing a null (nothing) value with zero is wrong, because null means something that is uknown and by setting it to zero, well you set it to something that is known….

In order to demonstrate this enhancement-new feature I will create a simple Asp.Net application using VB and Visual Studio 2008.

1) Launch Visual Studio 2008

2) Create a new project (ASP.NET web application)  and choose VB as the project’s language

3) Name it “nullabledata” or any other name you want

4) Add a button in the default.aspx page

5) Double click in the button

6) In the event handling routine that is created just type the following

Dim mynum As Integer? = 4
Dim myothernum As Integer? = Nothing
Dim myres As Integer = 0

myres = mynum + myothernum

Response.Write(IsNothing(myres).ToString())

by adding the ? operator after the data type, we indicate that the variable mynum can be set to nothing.

We declare another variable in this statement

Dim myothernum As Integer? = Nothing

This can only be valid in VB 9.0

Try and run your application by hitting F5.

Click on the button. You will receive an error – exception.

the problem is that the variable with the name myres is not nullable.

When you add 4 with an uknown value you do not get 4. You get an uknown value.

The solution to this problem is to create another variable that is nullable this time.

Dim myfinalres As Integer?

comment out these lines

myres = mynum + myothernum

Response.Write(IsNothing(myres).ToString())

and type these lines

myfinalres = mynum + myothernum

Response.Write(IsNothing(myfinalres).ToString())

Now if you run the application again and press the button you will receive the value of Nothing.

Hope it helps!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

LINQ ordering and grouping keywords August 26, 2008

Posted by fofo in c# 3.0, LINQ, Visual Studio 2008.
Tags: , ,
add a comment

In this post I will look into ordering and grouping keywords in LINQ.  I will try to explain C# keywords such as orderby, descending, group by .

It is always useful in order to better follow what is going on to have a good understanding what LINQ is, what problems came to address and what are extension methods, anonymous types and in general the C# 3.0 enhancements. I will try to explain everything with a detailed LINQ to SQL (instead of writing sql queries against the db we will do the same with c#) example in C#.

We will need a database for our project so please go and grab the Pubs database. You can download the database from this website.

Click here if you need help with installing the database.

1) Launch Visual Studio 2008

2) Create an ASP.NET Web application project in C#.

3) In the Default.aspx page drag and place on it two web server controls:  a button and just below it a Gridview.

4) From your Server Explorer Window connect to the Pubs database so you can see the database objects like its tables, views e.t.c

5) Add a new item to your project LINQ to SQL Classes and give it the name Pubs.dbml

6) From your Server Explorer Window drag and drop the “Authors” table into the Pubs.dbml surface area. Behind the scenes a C# wrapper maps my database table into a class, I can later reference and use.

7) If you visit the pubs.designer.cs file in your Solution Explorer you will see this line of code

(public partial class pubsDataContext ….).

The database object is now a class with this specific name so I can create an instance of the class and query the database

8) Double click on the button in the Default.aspx page and in the button click event handler add this code

   

pubsDataContext mydb = new pubsDataContext();

 var myauthors = from a in mydb.authors
 select a;

GridView1.DataSource = myauthors;

            GridView1.DataBind();

9) Run your application by hitting F5 from your keyboard. In the gridview you will see all the records from the authors table.

10) Let’s examine the ordering keywords I mentioned above. How can I get the results ordered by the author’s last name?

Replace these two lines of code

var myauthors = from a in mydb.authors
 select a;

 

with these

 var myauthors = from a in mydb.authors
                            orderby a.au_fname
                            select a;

Run your Project again and see the results.

11) If you want to order your authors by their last name in descending order just change this line of code

orderby a.au_fname

with this one

orderby a.au_fname descending

and run your application again.

12) If we wanted to order our results that we take back from the LINQ query by state first and then by author lastname we will write this snippet of code

 var myauthors = from a in mydb.authors
                            orderby a.state ,a.au_fname descending
                            select a;

13) To demonstrate the group keywords we will add new .aspx page in our project.

Name it Default1.aspx. Make this page the Start page by right-clicking on it and selecting the appropriate option

14) Drag the sales table from the Server Explorer in the pubs.dbml surface. We want to group the sales table by order date (ord_date=table field) and see what quantities (qty=table field) for all the book titles were ordered on that day.

15) Add a button to this page.Double click on it. In the event handler add this code

 pubsDataContext mydb = new pubsDataContext();

            var mysales = from s in mydb.sales
                          group s by s.ord_date;

            foreach (var salesgroup in mysales)
            {

                Response.Write(salesgroup.Key.ToShortDateString());
               Response.Write(“<br/>”);
               Response.Write(“<br/>”);

                foreach (var thesale in salesgroup)
                   Response.Write(“–” + thesale.qty);

                Response.Write(“<br/>”);
                Response.Write(“<br/>”);

            }

In the first foreach statement I loop throgh a set of sales(mysales) and print the Key to the salesgroup which in our case is the order date.

In the second foreach statement I want to print on the screen all the sales (thesale) from the salesgroup displaying the quantity.

Run your application and see the results.By any given date we can see the quantities for each book title that has been sold on that date.

In one of my next posts, I will cover the extension methods such as OrderBy(), ThenBy(), OrderByDescending(), ThenByDescending() and GroupBy()

Hope it helps!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Extension methods in C# 3.0 July 8, 2008

Posted by fofo in c# 3.0, LINQ, Visual Studio 2008.
Tags: ,
add a comment

In this post I would like to talk about a new feature in C# 3.0 that is called extension methods.

Extension methods are used extensively with LINQ, so it is of vital importance that we get a good understanding of extension methods. The reason why extension methods are so important is because this is how LINQ methods like Select,Where methods operate and work.

We can define them as static methods that extend existing classes without having to rely on inheritance or having to change the class’s source code or recompile the class. In the past to achieve the same thing we had to inherit from the selected class and extend it with new methods, if it was not sealed….

In order to better understand extension methods we will create a project in visual studio.

1) Launch Visual studio 2008

2) Create an asp.net web application in C# and call it “extensionmethods”

3) Add a new item to your application, a class file, and name it “myveryusefulextensionmethods.cs

4) Inside your class file you have somehing like this

namespace extension_methods
{
    public class myveryusefulextensionmethods

change the public class myveryusefulextensionmethods with 

static class myveryusefulextensionmethods

basically what we need to understand is that we must have a static class.Inside this static class we can add static methods.

5) We will create a static method inside our static class that just reverses a string. Please note that i use the keyword “this”. Whatever the input parameters are they must be prefixed with the “this” keyword. The code follows

 public static string strReverse(this string theString)
        {
            char[] strArray = theString.ToCharArray();
            Array.Reverse(strArray);
            string strReversed = new string(strArray);
            theString = strReversed;
            return theString;
        }

6) Now we can use this method from our default.aspx page to reverse a string. We will call this extension method from the page load event handler. The code follows

 protected void Page_Load(object sender, EventArgs e)
        {
            string s = “extensionmethods”;
       
            Response.Write(s.strReverse());
        }

When we type Response.Write(s.) we see something like the following picture in our code editor window.

 

 

 

 

 

 

 

 

 

Did you spot the new extension method “strReverse” among the other methods? This extension method is highlighted with a blue arrow icon facing down.

7) Run your application by hitting F5. You will get a new web page with “sdohtemnoisnetxe” on it. This is the reverse of “extensionmethods”

We can add more static methods to our static class.

Things to note when using extension methods

  • Use them when you really need them
  • Of course you cannot use extension methods to override existing methods
  • They are called extension methods for a a reason, so no you cannot apply this concept to fields and properties

If you want to learn more about extension methods click here

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

LINQ set operations(extension methods) on arrays July 7, 2008

Posted by fofo in .NET, asp.net, C#, LINQ.
Tags: ,
1 comment so far

In this post, which is another post for LINQ, I will try to explain how we can use LINQ set operators on arrays.Basically set operators are extension methods that allows to filter,merge arrays.We are going to examine these methods in detail. We will examine them by creating a project in visual studio.

Basically we are going to use two arrays of strings, countries and favcountries.

1) Launch Visual studio 2008 and create an ASP.net web application in C# in your filesystem

2) In the page load event of the default.aspx type the following

 //create 2 string arrays
 

string[] countries = { “Britain”, “France”, “Croatia”, “Argentina”, “Australia”, “Mexico”, “Finland”, “Spain”, “Italy”, “Greece” };
 

string[] favcountries={“Britain”,”Argentina”,”Greece”,”Brazil”};

//cocatenate the string arrays with the Concat method
var thecountries = countries.Concat(favcountries);

foreach (var c in thecountries)
             
Response.Write(c);

if you hit F5 and run your application you will all the countries listed in both arrays

3) If we need to get only the unique values from the arrays we must comment out this line in the code above

var thecountries = countries.Concat(favcountries);

and type this

 // only the unique countries appear with the union method
  var thecountries = countries.Union(favcountries);

if you hit F5 you will see in your browser the number of the countries in those lists without duplicate values.

you can achieve the exact same thing if you do not type the line above , but this one

var thecountries = countries.Concat(favcountries).Distinct();

4) If you want to see only the values that are in both arrays, comment out the following line

var thecountries = countries.Union(favcountries);

and type this new line that uses the Intersect method

 // countries that appear in both arrays
            var thecountries = countries.Intersect(favcountries);

If you run your application only the dublicate countries will appear.

5) If you want to get the items that appear in the first array but not in the second array(not common items in the arrays, all the items in the first array that do not match with anything from the second array), you comment out this line of code

var thecountries = countries.Intersect(favcountries);

and type this

var thecountries = countries.Except(favcountries);

All these extension methods  that enable us to filter, merge sequences live in the System.Collections.Generic namespace.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

LINQ to SQL – Querying the Pubs Database July 1, 2008

Posted by fofo in general .net, LINQ.
Tags:
5 comments

In this post I will demonstrate how to query a sql server database with c# 3.0 and LINQ. When you finish this post you will realise how all these previous posts in C# 3.0 language enhancements relate with LINQ. 

I assume that you are a little bit familiar with what LINQ is. In a nutshell LINQ stand for Language-Integrated Query and is now available as an integral part of Visual Studio 2008 (code name Orcas). We (developers) have native syntax in the form LINQ to C# and VB.Net for accessing data from any repository. The repository could be a memory object, database and XML files. What Microsoft wanted to do with LINQ was to address the current development model as we know it and create a new paradigm where we can think databases in the context of Object Oriented Programming.With LINQ we can query any source of data.
We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft divides LINQ into three areas.

LINQ to Object (Queries performed against the in-memory data)
LINQ to ADO.Net
     LINQ to SQL (Queries performed against SQL Server databases)
     LINQ to DataSet (Supports queries by using ADO.NET data sets and data tables)
     LINQ to Entities
LINQ to XML (Queries performed against an XML source)

To follow this example you must have Visual Studio 2008 and SQL server 2005.I am going to use the Pubs database. You can download the installation scripts of the Pubs database from here. But you can still read on and enrich your knowledge of LINQ to SQL without typing all that code.

1) Create an ASP.NET web application with C# in your filesystem.Add a gridview web server control to the default.aspx page. Add 4 buttons to the default.aspx page. Name them “Select”, “Insert”, “Update”, “Delete”

2) I assume you have installed the Pubs database in your local sql server

3) Add a new item to your project.In the window that fires up select Data and from the templates choose LINQ to SQL classes. Save it with the name Pubs.dbml

4) When you click Add you will see the Object Relational Designer surface.

5) Connect to your Pubs database from Server Explorer.Drag and drop some tables (author,titleauthor,title) from the Server Explorer to the designer area (see the picture below) . You can add as many tables you want. You can add views and stored procedures. For our example these 3 tables suffice.

 

 

 

 

 

 

 

 

 

 

6) If you notice you will see that a new file is added automatically to our poject. It is called Pubs.designer.cs.

7) If you open this file you will see lots of code. In the first few lines PubsDataContext class. In this class all our database objects are scripted – mapped to objects. We will use an instance of this class to create an object and query(select,insert,update,delete) our database by using native c# code.

8) Go to your default.aspx page and double click the select button.In the button event click handler, you can type this code. You can write any select query you want. I will give you some examples. In this example we just want to return all the rows from titleauthors table.

PubsDataContext db = new PubsDataContext();
var tauthors = from ta in db.titleauthors
select ta;

GridView1.DataSource=tauthors;

GridView1.DataBind();

I will try to explain the code above. We create an instance of our PubsDataContext.

In order to query the database we need to have a variable to store the result set and we do that by creating the implicitly typed local variable called tauthors. Then we just assign the Gridview datasource to our variable and then we just use the Databind method of the Gridview object.Run the application and see the results. We see in our browser when we click the select button the whole result set for the titleauthors table.

We can have a more sophisticated example. Comment out all the above lines and type the code below.

PubsDataContext db = new PubsDataContext();

var tauthors = from ta in db.titleauthors
where ta.au_id==”172-32-1176″
select ta;

GridView1.DataSource=tauthors;

GridView1.DataBind();

We see here we can select a single record from our database through the where clause.

Comment out the code above and type the following code in the select button event click handler.

We can use in our query properties(table fields) that are not part of our table but in the background we can access these properties if they are linked through a relationship with our main table. In this instance we access the au_fname field of the author table because this table is linked with the titleauthors table through foreign keys.

PubsDataContext db = new PubsDataContext();

var tauthors = from ta in db.titleauthors

where ta.author.au_fname == “Marjorie”

select ta;

GridView1.DataSource=tauthors;

GridView1.DataBind();
 

Comment out the code above and type the following code. I am not doing anything fancy here. I merely point out the various options we have when we query our database and how they are associated with SQL statements. We can view our results in desceding order.

PubsDataContext db = new PubsDataContext();

var tauthors = from ta in db.titleauthors
                        
where ta.author.au_fname == “Marjorie”
orderby ta.royaltyper descending

select ta;

GridView1.DataSource=tauthors;

GridView1.DataBind();

We can shape our query to return only the fields from titleauthors table that we want(in this case royaltyper).

PubsDataContext db = new PubsDataContext();

var tauthors = from ta in db.titleauthors
where ta.author.au_fname == “Marjorie”
orderby ta.royaltyper descendin

select new { ta.royaltyper };

GridView1.DataSource=tauthors;

GridView1.DataBind();

Now we need to show how to insert an item in the database and in our titleauthors table.

First create a method showauthors and place the code that gives us all the rows from the titleauthors table.

private void showauthors()
        {

PubsDataContext db = new PubsDataContext();

var tauthors = from ta in db.titleauthors
select ta;
GridView1.DataSource = tauthors;
GridView1.DataBind();
        }

9) Double click the Insert button and in the click event hander type this. If your run the application you will see a new record added in our table.

 PubsDataContext db = new PubsDataContext();

//new c# 3.0 feature called object initialiser

titleauthor ta = new titleauthor { au_id = “998-72-3567″, title_id = “BU1111″, au_ord = 6, royaltyper = 400 };

db.titleauthors.InsertOnSubmit(ta);
db.SubmitChanges();
showauthors();

10) Double click the Update button and in the event click handler type the following code. We try to update a value based on an author’s first name.Run the application and click the update button. The new value of 1000 will be updated.

PubsDataContext db = new PubsDataContext();

titleauthor titleauthor = db.titleauthors.First(ta => ta.author.au_fname.StartsWith(“Michael”));
           

titleauthor.royaltyper=1000;
db.SubmitChanges();
showauthors();

11) Double click the Delete button in the .aspx page and type the code below.In this example we just delete the record we updated before.We call the DeleteOnSubmit method and then submit the changes and show the update version of the table again.Run the application to see for yourself.

PubsDataContext db = new PubsDataContext();
titleauthor titleauthor = db.titleauthors.First(ta => ta.author.au_fname.StartsWith(“Michael”));
db.titleauthors.DeleteOnSubmit(titleauthor);
db.SubmitChanges();
showauthors();
 

Hope this post helped you to understand what LINQ is and how we can use it to query a SQL Server database.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Follow

Get every new post delivered to your Inbox.

Join 1,793 other followers