Guilherme Cardoso, Blog EN

.NET geek

  Home  |   Contact  |   Syndication    |   Login
  21 Posts | 0 Stories | 15 Comments | 0 Trackbacks

News

Name: Guilherme Cardoso
Age: 19
Country: Portugal


pontonetpt

NetPonto

xaml pt

Twitter





Archives

Saturday, October 15, 2011 #

I've wrote this article a few months ago but in Portuguese: http://pontonetpt.org/blogs/guilhermecardoso/archive/2011/06/03/qunit-testes-unit-225-rios-em-javascript.aspx
I've decided to translate it to engish. The sample project is hostead at GitHub but it's in Portuguese (the same as my first article).

Link Github: https://github.com/guilhermegeek/QUnitSample

I've been progamming with unit testing and test-driven developement in use for server-side for 2 years. On the last months i've been working more with javascript, so i decided to try this concepts in cliente-side!
Of all the frameworks i've seen for unit tests, the QUnit was my favourite. It's also used by jQuery team.
For this article i use the scenario where you need to write a method that validate some student code, and you test your code with unit tests.

jQuery (required by QUnit): http://docs.jquery.com/Downloading_jQuery
QUnit: https://github.com/jquery/qunit

First lets start by declare our scripts in the head of page.
You can use the default theme (.css). It's quite simple and clean.

<link href="/Styles/qunit.css" rel="Stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="/Scripts/qunit.js" type="text/javascript"></script>

Now we're going to declare an object to handler the erros details. This is optional of course.

function OutputJS() {
      this.Msg = null;
      this.Code = null;
}

Use the follow html elements in your page:

<h1 id="qunit-header">Unit Tests</h1>  
<h2 id="qunit-banner"></h2>  
<h2 id="qunit-userAgent"></h2>  
<ol id="qunit-tests">

Now it's time for us to write the first test!
For this we'll follow TDD. First we write the test and it should give an error. Then we start writing the code that will be tested, and we run the test to see if the code is already doing what we want (you can check some scenarious using tests like massing requests and bots that are greate!).

function Should_Validate_StudentCode(studentCode) {
        result.Code = false;
        result.Msg = "The minimum length of Code should be 4.";
        return result;
}

As we already except, the test will fail. This is what we want.
As we're using javascript code, the best option for you to run your tests it's in $(document).ready() of a page. But if you want you can execute the tests from some plugin or even an server side application.

<script type="text/javascript">
    $(document).ready(function () {
        module("Validate");
        test("Validate Student Code", function () {
            var result = Should_Validate_StudentCode("AAAAA");
            ok(result.Code, result.Msg);
        });
    }); 
</script>

module: acts like a category (you can group your tests in modules)
test: name of the test
ok: one of QUnit assertions.
ok excepts the first parameter as a true boolean, and if we passe a false boolean, then the test failes and display the message "result.Msg". That's why i use an object for this (;

The Should_Validate_StudentCode() is returning the OutputJS with the results of the test (code and message). If you write your tests using this design you can easily check the tests details.
Now open the HTML page and the result is this:

That screenshot is from this article in Portuguese, but as you can see the test fails.
Now that we've writed the test, let's start writing the code to test the student code.

function Should_Validate_StudentCode(studentCode) {
    var result = new OutputJS();
    if (studentCode.length < 4) {
        result.Code = false;
        result.Msg = "The minimum length of Code should be 4.";
    }
    else {
        result.Code = true;
        result.Msg= "Code s valid.";
    }
    return result;
}

Now run the test again (open the html page)


And there it's, passed!
QUnit documentation can be found in jQuery website. Here you can check more assertions types and other fun stuff like async requests! http://docs.jquery.com/Qunit
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Wednesday, July 13, 2011 #

This tip is really simple but usefull if we're concatenating strings to write a Where clause.
For example:

DECLARE NVARCHAR @SQL = 'SELECT ... FROM ...'

IF(@IDAluno IS NOT NULL)
SET @SQL = @SQL + '' WHERE [IDAluno] = ' + CAST(@IDAluno AS NVARCHAR)

A better solution would be something like this:

SELECT ...
FROM ...
WHERE ([IDAluno] = @IDAluno OR @IDAluno IS NULL)

A special thanks to Paulo Moreira for the advice ;)

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Wednesday, March 30, 2011 #

I've seen a few guys asking on stack overflow and forums how to order randomly using LINQ.
Here's a simple solution using Guid:

OrderBy(x => System.Guid.NewGuid())
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Thursday, February 24, 2011 #

Database .NET is an awesome tool that allow us manage several database in simultaneous (SQL Server, MySQL, Oracle, etc).

What lead me to install this tool was an problem that must be shared by must developers. Tools like SQL Server Management Studio consume to many resources, and if you don't have a decent computer you'll get problems in performance, and that's my case!

With Database .NET we can access an SQL Server for example, and make several actions to database (crud operations, manage procedures, etc).
Of course that this tool can replace the use of SQL Server Management Studio for example!  But it's really usefull if  you just need to perform small operations because it consumes many fewer resources.

This tool don't need to be installed (it can be used as an portable application).

One tip: if you are using SQL Server Express for example, don't forget to check the server name in Database .NET connection. In my case i've to change from GUILHERM-196634 to GUILHERM-196634\SQLExpress.

Project: http://fishcodelib.com/Database.htm

Download: http://fishcodelib.com/files/DatabaseNet3.zip 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Thursday, February 10, 2011 #

Channel9 already provided 4 vídeos from mvcConf, and more will be published on the nexts hours.

http://channel9.msdn.com/Series/mvcConf
http://www.mvcconf.com/

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Wednesday, February 09, 2011 #

In this article i'm gonna show you how i do when i have to update some content with AJAX and i have to change the URL.

First, let's see an example to understand it better.

If the user is reading a News with Id 1 and he clicked on another News with Id 2, if we update the content with AJAX the user is now reading the News Id 2 but the URL remains the same, for example: http://localhost/News/Read/1

Now let's see another example from Facebook. If i'm reading my profile and i click on Photos, Facebook updates it with AJAX and the URL switch to:
http://www.facebook.com/guilhermegeek#!/guilhermegeek?sk=photos

If we enter on that URL, it's mapped to: http://www.facebook.com/guilhermegeek?sk=photos

The trick here is the parameters that we use after the #!. Those parameters are never sent to the server side, so we handle them on the client side (javascript).
In the example of Facebook, he receives my profile name (guilhermegeek) and the action is to read photos.

A few time ago i've written an article in my Portuguese blog explaining how to use an alternative to clients with javascript disabled. Like this:

<a onclick="javascript:ReadNews(id);" href="#!News/Read/@id/">Title</a>

When the user enter the link of that news, my function Read(); fills the News in the page. Then, i add the #!News/Read/@id/ to my URL. It's gonna stay something like this:

http://localhost/News/Read/1#!News/Read/2

As i explained before, the News that the user is reading has the Id 2.
The next step is to use javascript to check if the URL that the user typed has other News Id, because if we enter on the above URL our controller will get the Id 1 (everything after to the # isn't sent to the server side).

$(document).ready(function () {

            var h = window.location.hash;

            if (h != null) {

                var parts = window.location.href.split('#!');

                if (parts.length > 1) {

                    window.location.replace("http://localhost/" + parts[1]);

                }

            }

   });

It's pretty simple. I'm cutting everything after the #!, then i redirect the user to a new page. So, it's gonna stay:
http://localhost/News/Read/2

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Thursday, January 27, 2011 #

I've decide to write about unit testing in the next weeks.
If we decide to develop with Test-Driven Developement pattern, it's important to not forget the routes.

This article shows how to test routes. I'm importing my routes from my RegisterRoutes method from the Global.asax of Project.Web created by default (in SetUp).
I'm using ShouldMapTp() from MvcContrib: http://mvccontrib.codeplex.com/
The controller is specified in the ShouldMapTo() signature, and we use lambda expressions for the action and parameters that are passed to that controller.

       [SetUp]
        public void Setup()
        {
            Project.Web.MvcApplication.RegisterRoutes(RouteTable.Routes);
        }

        [Test]
        public void Should_Route_HomeController()
        {
            "~/Home"
                .ShouldMapTo<HomeController>(action => action.Index());
        }
        [Test]
        public void Should_Route_EventsController()
        {
            "~/Events"
                .ShouldMapTo<EventsController>(action => action.Index());
            "~/Events/View/44/Concert-DevaMatri-22-January-"
                .ShouldMapTo<EventosController>(action => action.Read(1, "Title")); // In this example,44 is the Id for my Event and "Concert-DevaMatri-22-January" is the title for that Event
        }
        [TearDown]
        public void teardown()
        {
            RouteTable.Routes.Clear();
        }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Logo
Developers that use unit testing are familiar with Resharper and his plugin for Unit Testing.
For those that like me, don't have a great pc hardware (Pentium 4, 3ghz, 1GB ram) the Resharper can be really slow, and affect the performance of pc. That's why i use TestDriven.NET

TestDriven.NET is a freeware license tool (there are others licenses for this product) that gives us the possibility to run unit tests with this plugin, that's integrated with Visual Studio.
You can check some screenshots here: http://www.testdriven.net/Screenshots.aspx
It's compatible with: NUnit, MbUnit, MSTest, NCover, Reflector, TypeMock, dotTrace and MSBee.

More information and free download here: http://www.testdriven.net
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Tuesday, October 19, 2010 #

A few time ago i've write an article explaining how to use iTextSharp. Check it here:

http://geekswithblogs.net/guilhermecardoso/archive/2010/09/22/itextsharp---create-a-.pdf-document-with-a-gridview-table.aspx

In this article, i'll show how to use headers.

You just should follow this article if you're using iTextSharp 5.x or above. Other versions uses the object HeaderFooter.
The last releases, instead of using an object to create the header, uses events.

There's a list of existing events in iTextSharp: OnChapter, OnChapterEnd, OnCloseDocument, OnEndPage, OnGenericTag, OnOpenDocument, OnParagraph, OnParapraphEnd, OnSection, OnSectionEnd e OnStartPage.
If you want, read more about PdfPageEventHelper  class here: http://api.itextpdf.com/com/itextpdf/text/pdf/PdfPageEventHelper.html

To create the headers in all pages, we'll use the event OnStartPage

public class PdfHandlerEvents : PdfPageEventHelper
    {
        public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        { 
                Image logo = Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/logo.gif"));
                document.Add(logo);
                document.Add(new Phrase(Environment.NewLine));
                document.Add(new Phrase(Environment.NewLine)); 
        }
} 

I'm adding two new lines for the content have a little space between header.
We're creating the class PdfHandlerEvents, but it's important to use PdfPageEventHelper as parent..

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Monday, October 18, 2010 #

In this article i will show how to read feeds rss.
In this example i will show it for MVC architecture but it's very easy to use it in webforms. (use the SyndicationFeed object as a datasource for an repeater for example).

Let's declare our SyndicationFeed object in Model:

 public class BlogModel
    {
        public SyndicationFeed BlogFeed { get; set; }
    }

In Controller we'll get the feeds. But first, we need to add new references to our project:  System.ServiceModel.Syndication e System.Xml

public ActionResult Index()
        {
            var model = new BlogModel();
            string strFeed = "http://pontonetpt.com/blogs/guilhermecardoso/rss.aspx";
            using (XmlReader reader = XmlReader.Create(strFeed))
            {
                SyndicationFeed rssData = SyndicationFeed.Load(reader);
                model.BlogFeed = rssData;;
            }
            return View(model);
        }

Now we will read the feeds in View, through a foreach cicle. In this example, i'm only displaying the last 5 entries from my blog.

 <% if(Model.BlogFeed!=null) { %>
        <ul>
        <% foreach (var post in Model.BlogFeed.Items.ToList().Take(5)) { %>
        <li>» <a href="<%=post.Links.First().Uri%>" target="_blank"><%=post.Title.Text %></a></li>
 <% } %>

Yoi can see more details about SyndicationFeed class here.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati