Thursday, December 22, 2011

Database connectivity using Entity Framework

Entity framework is a new concept which allows developers to code against a conceptual model (which we create ourselves) rather than coding directly against a relational schema (database). This means that developers can take a slice out of the database cake and eat it rather than having to worry about eating the whole cake as a single piece. To taste this cake, its best to create a simple application that uses entity framework to connect with a database. The following guide will help you do exactly that.

Create a new application (in this example I will be using an MVC3 application) and name it DatabaseProject. Go to the solution explorer and do the following: 

·         right click “Models”,
·         “Add ›”,
·         “New item”,
·         click “data” in the left hand tab then select “ADO.Net entity data model” and click “Add” (this will open a wizard)
·         In the wizard, click “Generate from database” and click next.

You can create a new database connection by clicking on “New connection”. It will start another wizard which will ask you for database related information (which sometimes includes the IP address of server hosting the database) and username/password. Once you have entered this information, click “Ok”.

You will now return to the original wizard where at the bottom you will have a ticked checkbox labelled “Save entity connection settings in web.config as:”. Under this label there will be a default name of “DecisionCentreEntities”. Change this is to NameofConnection for simplification. 

After changing the name click “Next”.

This will retrieve the list of all tables in the database with a checkbox next to each table. Check/tick the tables that you want in your model (or the tables that will be accessed by your code). After this, click “Finish” to exit the wizard. 

You can now see a diagram of selected tables on a white surface which should look like this (I only ticked one table but you can tick as many as you want). This is your data model:




·         In this diagram right click on the white surface and click “Add code generation item”.
·         Click “Code” in the left hand tab then select “ADO.NET Entity Object Generator” and click Add.
·         Build the project. 

Our data model is ready to use.

Go to the controller (or any other class) and run queries on the database tables using the data model you just created.

Add the following using statement on the top “using DatabaseProject.Models”.

In a simple example we will run a query (we will be using a Linq query as an example) which returns all rows from the table “customers”.

using(var db = new NameofConnection())
{
object obj = (from r in db. customers select r).ToList();
}

This code will perform the query “select * from customers” and return the result. The result will then be converted into a list which will be copied on to the object “obj”.

In another example we will run a query which will add a new row to the table “customers”.

using(var db = new NameofConnection())
{
db. customers.AddObject(row);
       db.SaveChanges();
}

With this we have now successfully tasted the cake and can use similar codes to perform other functions with our database.

Monday, October 31, 2011

RSS

RSS or Really Simple Syndication is a format used to organise content which can then be published or sent to different data consumers. For simplicity we will assume our content to be an article. When converting our article into RSS 2.0 format (which is what we will focus on) we have to create an XML file (XML version 1.0) and add certain elements to it. Once this is done, our document is ready.

There are two main components of an RSS file, the channel and item. To understand these components we have to consider an example of a newspaper. It has several articles, some grouped under the sports section, some grouped under finance section and so on.

The RSS feed which publishes these news articles will have a channel named sports and each sport article will be an item under this channel and we will have a similar channel for finance and all other sections.

With this scenario in mind, lets create our very own RSS feed to publish articles. In the example below we will be publishing two articles under the sports section and one under finance by a magazine called Magazine100. This is how our overall RSS feed would look like:

<rss version="2.0">

<channel>                         
<title>Sports</title>
<link>http://www.magazine100.com/sports</link>
<description>Sports news by magazine100</description>

<item>                
<title>cricket updates</title>
<description>Here you can paste the entire article</description>                           
</item>

<item>                
<title>football updates</title>
<description>Here you can paste the entire article</description>                           
</item>              

</channel>

<channel>         
<title>Finance</title>
<link>http://www.magazine100.com/finance</link>
<description>Finance news by magazine100</description>
               
<item>                
<title>wall street updates</title>
<description>Here you can paste the entire article</description>                           
</item>

</channel>

</rss>

As you can see at the top level we have <rss version="2.0">. This is a mandatory attribute that specifies the version that this document conforms to.

We then have a channel which is described by the tags <title>, <link> and <description>. These tags are mandatory for each channel, however if we feel the need to describe our channel further, there are several additional tags that we can use. You can get a list of these tags from here.

After channel, we have an item tag which uses <title> and <description> to publish the content of an article. For an item, it is mandatory to have at least one of these two fields (title and description), and similar to a channel, an item can also be further described using optional tags. You can get a list of these tags from here.

The problem with an item is that you do not have a tag to attach pictures. However this can be done if we use the following html within the content of the "description" tag:

<img src="[location of image]" alt="[alternate text]" title="[title of image]" />.

This code will place the image within the content of our article and solve our biggest headache (at least for me it was).

Monday, October 17, 2011

CSS for beginners

If we want to style any control in an html page (by control I mean textboxes, labels and all other html elements that can be displayed in an html page), we can easily do it using the style property. For example if we have the following heading:

<h2> Heading </h2>

And we wish to change its colour to green and make it italic, we can easily do so using the style property as shown below:

<h2 style="color: green; font-style: italic;"> Heading </h2>

Similarly, we can use a range of properties to stylize any control we want. However, this is not a very good programming practise. If we want to stylise our controls in a way that makes our styles more re-useable, we need to do it in the following way:

On top of the page we need to write the following code to make a style class with any name we want (in this example I have used the name MyHeading).

<style>
        .MyHeading
        {
            color: Green;  
            font-style: italic;
        }
</style>

Then in our html we can write the following code:

<h2 class="MyHeading"> Heading </h2>

With this code we will be achieving exactly the same result as above with the added benefit of code re-use in other places such as:

<p class="Myheading">This is a paragraph</p>

In this approach, we are using a style class to style our page. This can be a good approach to style a page; however we can go one step further by using a cascading style sheet.

Cascading style sheets (or CSS) allow us to create a “.css” file containing many style classes. This css file can then be attached with any webpage giving it access to all its style classes.

 To attach a css file to an html page, we need to write the following line on top of the webpage (above its html code):

<link rel="Stylesheet" type="text/css" href="/Location/File.css" />

In the css file, we need to write the following code to create a style class:

.MyHeading
{
      color: Green;  
      font-style: italic;
}

After this, we can use any class from the css file to style the controls of our page. The benefit of using this approach is that css files allow us to use the same style sheet throughout our website, and ensure a consistent layout across all pages, thus allowing maximum code re-use.

Tuesday, October 11, 2011

Returning XML from MVC Controller Action

To return xml from a mvc controller action we can use the following code:

public XmlElement name_of_function()
{
      XmlDocument Feed = new XmlDocument();
      XmlWriter Write = Feed.CreateNavigator().AppendChild();

      Write.WriteStartDocument();
      Write.WriteStartElement("head");
      Write.WriteElementString("name_of_tag", "value");
      Write.WriteEndElement();
      Write.WriteEndDocument();

      Write.Flush();
      Write.Close()

      return Feed.DocumentElement;
}

Monday, September 5, 2011

Using ASP.NET Webform in an MVC controller

In ASP.NET MVC we use controller actions to call views using the following code:

public ActionResult NameOfView()
{
return View();
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View(ViewModel);
}

Through this code, the view "NameOfView", placed in the folder "Views", will be displayed (in the second instance the view model will be passed to it as an input parameter).
However if we want to work with an ASP.NET view which is NOT in the folder "Views" but is instead located at "Abc/Def/page.aspx", we can change our controller slightly to accommodate this view. To do this, we can use the following code:

public ActionResult NameOfView()
{
return View("~Abc/Def/page.aspx");
}

or if we want to pass a view model to it:

public ActionResult NameOfView(model ViewModel)
{
return View("~Abc/Def/page.aspx", ViewModel);
}

Adding jQuery to an MVC view

To add jQuery code in an MVC view, we need to write its code in the head section of the view. The example below shows simple jQuery code written in an MVC view.

<head>
<script type="text/javascript">
$(document).ready(function ()
{

// here we can write any javascript code that will be executed as soon as the page loads  

// If we have a dropdown in our page, named as "xyz", and need to write code that executes when it's value is changed to "1", we could do the following:

$('#xyz').change(function ()
{
if ($('#xyz').val() == "1")
{

// over here we can write code that will execute when the value "1" is selected in the dropdown "xyz"

}
else if ($('#xyz').val() == "2")
{


// over here we can write code that will execute when the value "2" is selected in the dropdown "xyz"                

}

});
});
</script>

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

</head>

Sunday, July 31, 2011

MVC Multiple Post buttons in one page

Anyone who has worked in MVC knows how clicking a post button will submit the page, and invoke the action method. It can get a bit annoying if you want to do different things based on different buttons being clicked. However, thanks to html there is a way around it.


To do this, we have to figure out which button was clicked. This can be done in the following way:

Make two buttons with the same “name” but different “value”
e.g

<input type="submit" id="GetResults" name="SubmitButton" value="Apply" />
<input type="submit" id="UpdateResults" name="SubmitButton" value="Inform" />

In the controller action, add the following input parameter (string SubmitButton)
Inside the controller action, the value of the variable “SubmitButton” will either be “Apply” or “Inform” depending upon which submit button was clicked.

After this, a simple “if” condition such as the one given below will do the job:

If(SubmitButton == "Apply")
{
                Do this
}
Else if (SubmitButton == "Inform")
{
                Do that
}

Saturday, July 30, 2011

Typical problems with WatiN

In my last post I discussed about creating a Hello World application in WatiN. In this post I will focus on typical problems that can entail the usage of WatiN.

WatiN Not Executing

If your application gives a strange error message and does not execute, go to references and see if you have the reference "Interop.SHDocVw" added. If it is added, then it is no co-incidence that your code is not running, delete it and try again, it should work now.

If you are using a 64-bit machine with .NET Framework 4, you have to change the properties of your project in order to make your application work. As discussed in this blog (from step 7 onwards), you need to go to the properties of your project (by right clicking on your project in solution explorer) and under the text "target framework", change the value of dropdown to ".NET Framework 4". Recompile and it should work now.

Working with Firefox instead of Internet Explorer

Just like you use the code "IE browser = new IE()", you could also use "Firefox browser = new Firefox()" and start working with Firefox rather than Internet Explorer. However, this will come with its own share of problems.

To the best of my knowledge, to date WatiN is incompatible with Firefox 4, so you need to revert to Firefox 3.6 (or any other version of Firefox 3) in order to let WatiN work successfully with Firefox.

Sometimes the problems do not end here, and you get a JSSH error. There is nothing alarming about this error, and if you get it, all you need to do is download JSSH Firefox extension, which could also be downloaded manually from here, and your problem will end.

If your problems do not end here, feel free to inform me of your problems in the comment box below.

Advice for WatiN-Firefox users

As an alternate to Internet Explorer's development tools, Firefox has an add-on called Firebug, which is very easy to use and extremely powerful. While using it you just need to right click on any part of the webpage and click on Firebug to get all the information you need.

Test application for a web project

Once we have a fully functional website it is very common to add features to it without testing it thoroughly enough and getting on with the release. This can leave some bugs unnoticed which could prove to be embarrassing for a developer. However with applications that perform automated testing for you, you can sit back and relax while your application does the testing and gives you the results.
Thanks to WatiN it is not only possible but very easy as well. For an introduction to WatiN you could go to WatiN Home and learn more about it.

Anyways, to create a Hello World application in WatiN you need to create a new console application in .NET.
In that application right click on References (which can be found in the Solution Explorer), and click add Library package reference, over there you can search for WatiN and download it. If you do not have the option of adding a library package reference, you can download it manually from here and add it to your project.
Once this is done, you can use the following code to create a basic application that will go to Google, search for "Hello World" and click the search button to get results.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;


namespace WatiNTest
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            IE browser = new IE("http://www.google.com");
            browser.TextField(Find.ByName("q")).TypeText("Hello World");
            browser.Button(Find.ByName("btnG")).Click();
        }           
    }
}

In this code, there is a keyword [STAThread] on top of void main, this is essential for our application to successfully communicate with Internet Explorer.
In the first line of code, I created a new instance of Internet Explorer (browser), and opened google in it.
In the second line of code, I used WatiN's built in function to find the text box named "q", and type "Hello World" in it. The question here is how I found out the name of google's search textbox. Simple, if you open google on Internet Explorer and press F12, you will open Internet Explorer's development tools. The page should now look like this:

 


In developer tools, there is an icon under the tab "HTML" that looks like a cursor of a mouse. If you click on it, and then click on the google search textbox, it will give you a lot of information about that textbox like this:

 

Notice here that the information about that textbox is highlighted in blue. If you go through this, you can see that the name of this textbox is "q".

Once you have done this, you can now insert anything in the search box, which in the example given above is "Hello World". After that if you follow the same technique, you can find the name of the button "google search" and click it (as done in the example).
 
There you go, your hello world testing application is now complete. You can add more things to it, such as after the code you can add a line of code that clicks the button "next page" and shows page 2 of results. (WatiN has been designed in a way that if you click "google search" and in the next line you write the code to click "results page 2" button, it will click "google search" wait for the page to load and once it is loaded click on page 2 button).

I hope it works without any problems, however, you do not need to worry if you face problems doing it. My next post will focus more on them.