Drawing Simple Graphics With HTML 5 Canvas


I'm pretty amazed at what HTML 5 Canvas can do. It's truly revolutionizing web graphics and visualizations. It allows web developers to create and display web graphics on the fly dynamically. It can even do animations and games on the web without using Flash. Not only that, it can even draw 3D graphics! I just had a chance of using it with one of my projects which requires dynamic display of graphics based on user-selected criteria. The API is so easy to use, very intuitive and most importantly, all of the major browsers already supported it.

In this post, I'll show you how to draw simple graphics with this API. HTML 5 Canvas is an HTML tag that you can embed inside an HTML document. Here's a sample html document containing the canvas element:
  
    <!DOCTYPE HTML>
     <html>
      <body>
       <canvas id="canvasId" width="578" height="200">
            </canvas>
      </body>
   </html>

With the element declared in the html, you can then create a JavaScript script to retrieve that canvas element and create a 2D or 3D drawing context like this:
  
    window.onload = function(){
       var canvas = document.getElementById("canvasId");
       var context = canvas.getContext("2d");
       // draw anything here 
};

Drawing A Line

To draw a line, you need first to set the lineWidth (line thickness) and strokeStyle (line color). Then you need to tell the drawing context to move from the starting point to the ending point in pixels like so:
  
// set the line thickness to 5 pixels
context.lineWidth = 5;
// set the line color to red
context.strokeStyle = "red";
 // position the drawing cursor
context.moveTo(40, canvas.height - 40);
// draw the line
context.lineTo(canvas.width - 40, 40);
// make the line visible with the stroke function:
context.stroke();
};

Here's the screenshot of the drawn line as being displayed in FireFox:


Drawing An Arc

To draw an arc, you need first to set the lineWidth (line thickness) and strokeStyle (line color). Then you need call the arc function from the drawing context specifying the center location, radius, starting angle, ending angle and draw direction like so:
context.arc(centerX,centerY, radius, startingAngle,
endingAngle,counterclockwise);
  
context.lineWidth = 15;
context.strokeStyle = "red"; // line color
context.arc(canvas.width / 2, canvas.height / 2 + 40, 80, 1.1 *
Math.PI, 1.9 * Math.PI, false);
context.stroke();

};

Here's the screenshot of the drawn arc as being displayed in FireFox:

 


Drawing A Rectangle

To draw a rectangle, you need to call the rect function of the drawing context specifying the center location x and y,width and height. Then you need to specify the fillStyle (rectangle's fill color), lineWidth (line thickness) and strokeStyle (line color). You need to call fill() and stroke() to execute the fill and stroke drawing respectively like so:
context.rect(x,y,width,height);
  
context.rect(canvas.width / 2 - 100, canvas.height / 2 - 50,
200, 100);
context.fillStyle = "green";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "red";
context.stroke();
};

Here's the screenshot of the drawn rectangle as being displayed in FireFox:


Drawing A Circle

To draw a circle, you can use the arc function above with the starting angle set to zero and the ending angle set to 2PI like so:
  
context.arc(canvas.width / 2, canvas.height / 2, 70, 0, 2 *
Math.PI, false);
context.fillStyle = "green";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "red";
context.stroke();
};
};

Here's the screenshot of the drawn circle as being displayed in FireFox:


Drawing An Image

Canvas can be used to draw an image based on an image file from disk. All you need to do is to create an image object, set the source of the image to an image from file. Then you need to create an onload handler for the image that will trigger once the image is loaded. Inside the handler, you tell the context to draw the image and the location x and y in pixels.
  
var imageObj = new Image();
imageObj.onload = function(){
  var destX = canvas.width / 2 - this.width / 2;
  var destY = canvas.height / 2 - this.height / 2;
  context.drawImage(this, destX, destY);
};
imageObj.src = "pitchlocations.jpg";

Here's the screenshot of the drawn image with dynamically generated balls from my project as being displayed in FireFox:


This API is rockin' dude and we're only scratching the surface here. There's still a lot to learn! This topic is so broad it can easily fill a book. Just find other documentations to see how the other graphics are created, and how animations, videos and the fantastic 3D rendering are done. Hope you learn something from here.



Demystifying CSS Selectors

When learning the intricacies of CSS, it's very important that you are familiar with its different CSS Selectors. Mastering CSS Selectors is very useful as you can also use what you've learned in Jquery selection. In this post, I'll tackle all the available CSS selectors including selectors available only in CSS3.


Universal Selector

Pattern: *

Sample:

* {margin: 0px;}
div * {margin: 0px;}
<body>
    <div>
        <p>Hello World!<p>
    </div>
</body>

This selector matches any elements. The 1st css line selects all elements - body,div, and p. The 2nd css line selects the descendant of the div element - p.




Type Selector

Pattern: element1

Sample:

h3{padding: 0px;}
p {font-size: 1em;}
<body>
   <div>
      <h3>My Blog</h3>
      <p>Hello world!</p>
      <p>Im the King!</p>
   </div>
</body>

This selector matches all the elements of the specified type. In the 1st css line, it selects the header3 (h3) element, while in the second css line, it selects the 2 paragraph (p) elements.




Descendant Selector

Pattern: element1 element2

Sample:

body div {font-size: 12em;}
table tr td {color: purple;}
<body>
   <div>
      <table>
          <tbody>
              <tr> <td>Data1</td>  </tr>
               <tr> <td>Data2</td>  </tr>
          </tbody>
      </table>
   </div>
</body>

This selector matches all the descendant elements. A descendant can be a child, grandchild, great-grandchild,etc. In the 1st line, it selects the div element which is a descendant(child) of the body element, while in the second line, it selects all the td elements that are descendants of both the tr element (child) and table element (grandchild).




Child Selector

Pattern: element1 > element2

Sample:

div > span {background-color: blue;}
ul > li {font-size: 1.1em;}
<body>
   <div>
      <h1>My Blogs</h1>
      <span>Blog descriptions...</span>
      <ul>
         <li>Blog <span>item 1</span></li>
         <li>Blog <span>item 2</span></li>
      </ul>
   </div>   
</body>

This selector matches all the child elements. In the 1st line, it selects one span element which is a child of the div element, while in the second line, it selects all the 2 list (li) elements that are children of the unordered list (ul) element.




Adjacent Sibling Selector

Pattern: element1 + element2

Sample:

table + p {margin-left: 2.5em;}
h1 + span {margin-right: 0;}
<body>
   <div>
      <h1>Tables</h1>
      <span>first span</span>
      <table></table>      
      <p>first paragraph</p>
      <div>
         <span>span in div</span>
         <p>p in div</p>
      <div>
      <p>2nd paragraph</p>
      <span>2nd span</span> 
   </div>   
</body>

This selector matches the adjacent sibling element. In the 1st line, it selects the first paragraph (p) element which is an adjacent sibling of the table element, while in the second line, it selects the first span element which is an adjacent sibling of the header1 (hl) element.




General Sibling Selector

Pattern: element1 ~ element2

Sample:

table ~ p {margin-left: 2.5em;}
h1 ~ span {margin-right: 0;}
<body>
   <div>
      <h1>Tables</h1>
      <span>first span</span>
      <table></table>      
      <p>first paragraph</p>
      <div>
         <span>span in div</span>
         <p>p in div</p>
      <div>
      <p>2nd paragraph</p>
      <span>2nd span</span> 
   </div>   
</body>

This selector matches the element that is a sibling of another element. In the 1st line, it selects the first and second paragraphs which are both siblings of the table element, while in the second line, it selects the first and second span elements which are both siblings of the h1 element.




Class Selector

Pattern: element1.classname
element1.classname1.classname2

Sample:

p.important {color: red;}
.example {background: green;}
.note.extreme {background: blue;}
<body class="note extreme">
  <p>paragraph with no class</p>
  <p class="important">paragraph with important class</p> 
  <p class="example">paragraph with example class</p>    
  <span class="example">span with example class</span> 
</body>

This selector matches any element that has a class attribute containing the specified values. In the 1st line, it selects the second paragraph (p) element that has an "important" class attribute. The second line selects the third paragraph (p) element and the span element which both have "example" class attribute. The third line selects the body element because it has a class attribute of "note" and "extreme".




ID Selector

Pattern: element1#idname

Sample:

body#home {background: silver;}
#example {background: lime;}
<body id="home">
  <p>paragraph with no id</p>
  <p id="example">paragraph with id</p> 
</body>

This selector matches an element with the specified id attribute. In the 1st line, it selects the body element which has a "home" id attribute while in the second line, it matches the 2nd paragraph (p) element which has an "example" id attribute.




Simple Attribute Selector

Pattern: element1[attr]

Sample:

a[class] {border: 2px dotted blue;}}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches an element if the specified attribute is present regardless of the attribute's value. In the css line, it selects all except the first anchor (a) element which have a "class" attribute.




Exact Attribute Selector

Pattern: element1[attr="value"]

Sample:

a[class="important"] {color: blue;}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches an element if its complete attribute value corresponds to the specified value. In the css line, it selects the third anchor (a) element as it exactly matches the "important" attribute value.




Partial Attribute Selector

Pattern: element1[attr~="value"]

Sample:

a[class~="important"] {color: blue;}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches an element if a portion of its space-separated attribute values corresponds to the specified value. In the css line, it selects the third and fourth anchor (a) element since both have "important" class attributes.




Beginning Substring Attribute Value Selector

Pattern: element1[attr^="substring"]

Sample:

a[class^="enemy"] {color: blue;}
a[class^="important"] {color: red;}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches any element if its attribute value starts with the specified value. In the 1st css line, it can't select any anchor (a) element because none of the class attributes starts with "enemy". In the second css line, it matches the third and fourth anchor (a) elements.




Ending Substring Attribute Value Selector

Pattern: element1[attr$="substring"]

Sample:

a[class$="enemy"] {color: blue;}
a[class$="important"] {color: red;}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches any element if its attribute value ends with the specified value. In the 1st css line, it selects the last anchor (a) element because its class attribute ends with "enemy". In the second line, it fails to match any element as there are no anchor elements whose class attributes values ends with "important".




Arbitrary Substring Attribute Value Selector

Pattern: element1[attr*="substring"]

Sample:

a[href*="/myblog"] {text-transform: lowercase;}
p[class*="check-"] {background: green;}
<body>
  <a>anchor element with no class attribute</a>
  <a class="any">anchor element with class attribute</a>
  <a class="important">anchor element with important class  attribute</a>
  <a class="important enemy">last anchor element</a>
</body>

This selector matches any element if its attribute value contains the specified value. In the 1st line, it selects any anchor (a) element if its href attribute value contains "/myblog", i.e., it matches "page/myblog" or "/myblog/page" or "page1/myblog/details". In the second line, it matches any paragraph (p) element if its class attribute value contains "check-", i.e., it matches "check-me" or "allcheck-" or "allcheck-me".




Language Attribute Selector

Pattern: element1[lang|="lc"]

Sample:

html[lang|="tr"] {color: red;}
<html lang="tr-en-cs">
  <body>  
  </body>
<html>

This selector matches any element with a lang attribute that contains hyphen-separated list of values and the first value corresponds with the specified value. In the css line, it selects a html element if the html's "lang" attribute contains hyphen-separaed list of values starting with a "tr" value, i.e., it matches 'lang="tr-en-cs"'.




To be continued...

Avoid Cross-Browser Differences with CSS Reset

The number of internet browsers available today are increasing with Internet Explorer, Firefox, Google Chrome, Opera, and Safari as the Big 5 leading the pack. When designing web pages, one needs to make sure that the pages display uniformly on all the browsers. One problem is that these browsers have different default styles. There are no standard default styles for margin, padding, background colors,etc. so each browser naturally displays differently from each other.

One way to correct this problem is to use a CSS Reset. With CSS Reset, you basically create a baseline css styles such that all the browser's different styles will be reset and be uniform to the baseline style. For example, setting margin=0 in your css reset document changes all the browsers' different margin values to 0. This way, all the browsers will have the same margin style initially and you can change the margins later on and you can expect that it will displayed uniformly across all the browsers.

My favorite CSS Reset is created by Eric Meyer. It is currently in version 2.0 and can be used for free in your projects.You can grab a copy of the file here.




/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
 margin: 0;
 padding: 0;
 border: 0;
 font-size: 100%;
 font: inherit;
 vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
 display: block;
}
body {
 line-height: 1;
}
ol, ul {
 list-style: none;
}
blockquote, q {
 quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
 content: '';
 content: none;
}
table {
 border-collapse: collapse;
 border-spacing: 0;
}








How To Determine The Generated SQL Queries In Entity Framework 4

With the help of Entity Framework, you may never write a single SQL Query code in your programming projects. Some of the benefits of Entity framework include:

  1. Visual Studio intellisense
  2. Compile checking
  3. Faster development
  4. Auto generated domain objects
  5. Lazy loading, etc.

However, sometimes you need to know how Entity Framework translates your LINQ Query into a SQL Query. You can't just trust the framework to correctly formulate the Query. If you are concerned about scalability and performance, you need to check and analyze the underlying query and if possible modify or refine it to increase querying speed and performance.

The easiest way to view the generated SQL is to use a profiler tool that's included in database management tools (for instance, SQL Server Manangement Studio). Using this tool, you can monitor all SQL statements executed against the database. But using this tool requires that you have access to the database. Fortunately, with Entity Framework 4, you can use ObjectSet class's ToTraceString method. 

Here's the example code on how to do it in C# and VB.NET: 


C#:

var result = ctx.Orders.Where(o =&gt; o.Date.Year == DateTime.Now.Year);
var SQL = (result as ObjectQuery).ToTraceString();


VB:
Dim result = ctx.Orders.Where(Function(o) o.Date.Year = DateTime.Now.Year)
Dim SQL = TryCast(result, ObjectQuery).ToTraceString() 





Sending Automated SQL Server Notification Emails

One of our clients asked today to be automatically notified through email if a failure in the regularly scheduled jobs in SQL Server occurs. This seems like a pizza cake (yummy!) considering that sending email is common and I'm sure I can find lots of information on the internet on how to achieve this in SQL Server.



The task was simple but unfortunately it took me the whole day to configure the Server. Information was available on the internet and I seem to be following the instructions correctly to the letter. But somehow, the feeling of success and being able to shout Yes! did not occur immediately and the simple task became a nightmare of trial and errors which left me wondering whether working in the office instead of working at home is better.

 
Now to the main course, in order for SQL Server to be able to send emails, the Database Mail must be enabled and configured. The Database Mail is available only for versions higher than the SQL Server Express Editions. First, you need to open SQL Server Management Studio and connect to the SQL Server Database. Once connected, go to the Object Explorer window and under the Management folder, right click Database Mail and select "Configure Database Mail".

When the initial screen shows, click Next.

In the "Select Configuation Task" Window, select "Setup Database Mail" option.


In the "New Profile" window, specify the Profile Name and Description in the designated text boxes and then click "Add".




In the "Add Account To Profile", select an account to add to the Profile you've created earlier or you can click "New Account" to create a new account.



When you create a new account, the "New Database Mail Account" window opens. specify the account name and description, then specify the the Outgoing Mail Server (SMTP) configuration and its authentication. Here, you need to be able to know the SMTP settings that your company uses. Then click OK. You will be taken back to the "New Profile" window earlier but with a new SMTP account specified. Click next.


In the "Manage Profile Security" window, click the Option to make your profile public and available. Click Next.



In the "Configure System Parameters" window, you can leave the default settings and click Next.



Then click Finish.



The Database Mail is now configured. You can check if you've configured it correctly by right-clicking on the Database Mail in Object Explorer and select "Send Test Email". Provide the email of the recipient and click Send. If the email is received, then pat yourself in the back because you're already halfway passed the work to be made.




We need to be able to use Notification Email in SQL Agent. To do that, you need to specify the "Operator" or the list of emails that can be the recipient of the email Notifications.
In the Object Explorer again, under the SQL Server Agent node, right click the folder Operators and select "New Operator".


In the "New Operator" window, specify the name of the Operator. Put the email recipients separated by semicolon in E-mail name text box. Click OK.



Then you need to enable the mail profile in SQL Server Agent properties. After enabling, restart the SQL Server Agent.



And finally, you can use the settings you've configured above in your SQL Server Jobs so that it can send email automatically if a job fails to execute. To do that, in the Jobs properties, under Notifications Tab,check email option and specify the operator you want to receive the email and select the event that can trigger the sending of the notification email.



With the above information in hand, I'm sure configuring another email notifications in SQL Server will be a breeze!

Hope this helps,
Noli











Convert Any Web Page To A PDF Document


There are times when we need a web page to be downloaded and viewed as a PDF document. Web pages display differently based on several factors such as the type and version of browser and size of the computer's screen. To be able to share the web page with other users and ensure that it displays correctly and uniformly regardless of these factors,  you can opt to view it as a PDF document.

If you don't have the software to convert a web page to pdf, you can use the tool I've provided here using a little bit of JavaScript and a service from PDFmyURL.com. Just input the url of the web page that you want to download as pdf and click "Generate PDF" button. Make sure though that the url that you input are not "log-in" protected. 








PDF, or otherwise known as  Portable Document Format, is the de facto standard for printable documents on the web. Most books now are published as a PDF. Ebooks, as they're called, has a few if not many advantages over its HardCover counterpart. To name a few, an Ebook can be searched automatically, you can bring a 5000-page ebook in your pocket, and it can't worn out over time.

A PDF document can be viewed in your PC or Mac using Ebook readers software such as Acrobat Reader, Foxit Reader, Google Chrome,etc. But when you want to read your ebook like a traditional book,  a must have is either Amazon's Kindle or Apple's IPad. Both are great for reading pdf documents.







Convert SQL to LINQ

LINQ (Language Integrated Query) is Microsoft's technology that provides .NET languages the capability to query data of all types. These types include in-memory arrays and collections, databases, XML documents, and more.

LINQ is such a vast topic that you will be better off learning comprehensively by buying a book on this superb technology. I'd highly recommend Steve Eichert's and Fabrice Marguerie's "LINQ in Action" book available in Amazon.




In this post, I'll provide examples for converting SQL queries into LINQ (in VB.NET and C#).
These samples are taken from VB Team's blog: http://blogs.msdn.com/b/vbteam/archive/tags/converting+sql+to+linq/default.aspx. Since all their samples are in VB.NET, I'll include C# for completeness.

SELECT * Query

SQL
SELECT *
FROM CustomerTable
LINQ(VB.NET)
From Contact In CustomerTable
LINQ(C#)
from Contact in CustomerTable
select Contact


SELECT Query

SQL
SELECT Name CustomerName, CustomerID ID
FROM Customers
LINQ(VB.NET)
From cust In Customers _
Select CustomerName = cust.Name, ID = cust.CustomerID _
Order By ID
LINQ(C#)
from cust in Customers
select new(){CustomerName=cust.Name, ID=cust.CustomerID }


SELECT... WHERE Query
SQL
SELECT * FROM CustomerTable
WHERE State = “WA”
LINQ(VB.NET)
From Contact In CustomerTable _
Where Contact.State = “WA”
LINQ(C#)
from Contact in CustomerTable
where Contact.State=="WA"
select Contact



SELECT DISTINCT Query
SQL
SELECT DISTINCT Name, Address
FROM CustomerTable
LINQ(VB.NET)
From Contact In CustomerTable _
Select Contact.Name, Contact.Address _
Distinct
LINQ(C#)
(from Contact in CustomerTable
select new(){Contact.Name,Contact.Address}).Distinct()



AND Operator Query
SQL
SELECT * FROM CustomerTable
WHERE City = “Seattle” AND Zip = “98122”
LINQ(VB.NET)
From Contact In CustomerTable _
Where Contact.City = “Seattle” And Contact.Zip = “98122”
LINQ(C#)
from Contact in CustomerTable
where Contact.City=="Seattle" && Contact.Zip=="98122"
select Contact


BETWEEN Operator Query
SQL
SELECT * FROM OrderTable
WHERE OrderDate BETWEEN ‘Sept-22-2007’ AND ‘Sept-29-2007’
LINQ(VB.NET)
From Shipment In OrderTable _
Where (Shipment.OrderDate > #9/22/2007#) _
    And (Shipment.OrderDate < #9/29/2007#)
LINQ(C#)
from Shipment in OrderTable
where Shipment.OrderDate > new Date(2007,9,22) && 
Shipment.OrderDate <  new Date(2007,9,29)
select Shipment


Order By Query
SQL
SELECT * FROM CustomerTable
ORDER BY Phone
LINQ(VB.NET)
From Contact In CustomerTable _
Order By Contact.Phone
LINQ(C#)
from Contact in CustomerTable
orderby Contact.Phone
select Contact


Order By ASC/DESC Query
SQL
SELECT * FROM CustomerTable
ORDER BY Phone ASC, Name DESC
LINQ(VB.NET)
From Contact In CustomerTable _
Order By Contact.Phone Ascending, Contact.Name Descending
LINQ(C#)
from Contact in CustomerTable
orderby Contact.Phone ascending, Contact.Name descending
select Contact

I'll update this blog later and add more samples...



Import Data From CSV File To SQL Server With Import And Export Wizard

There are many ways to import data from csv files to SQL Server but the easiest is using SQL Server's Import And Export Wizard. The wizard is very very versatile as it can do both import and export from various different sources and destinations such Microsoft Access, Micorosft Excel, Flat File (csv,text files), and SQL Server among others.
Here's the steps to follow to use the Wizard for importing a csv file to SQL Server:


  1. Open SQL Server Management Studio and connect to the destination database. Right Click the database, select Tasks and click  Import Data...

  2.  On the opening screen, click Next.

  3.  On the "Choose A Data Source Screen", select a Data Source in the combobox. In our case, we're going to choose Flat File Source because we're importing from a csv file. Click "Browse" and find the csv file to be imported. Check the checkbox if the csv data contain columns names in the first row.


  4. Click Columns. Here you can specify the row delimiter and column delimiter. Since we're using a csv file, column delimiter is a comma and row delimiter is a new line.

  5. Click Advanced. Here, you can change the data type for each columns of the csv file. The Wizard detects the type of data and automatically set it for you. But if you think the Wizard is incorrect, you can set the data type manually.


  6. Click Preview to see the preview and check if the settings you have made are correct. Then click Next.


  7. In the "Choose A Destination" window, select a destination in the combobox. In our case, since we are importing to a SQL Server database, we're selecting SQL Server Native Client. Enter the Server Name and Authentication credentials needed for accessing the database. Then click Next.


  8. In the "Select Source Tables and Views" window, check the source you want to import and on the right column select a destination table. For the destination table, you can either select an existing table or a new table.

  9. Click "Edit Mapping". In the "Column Mappings" window, there are 3 options available. "Create destination table" option is selected if you're creating a new table as the destination. If you're importing to an existing table, you can choose either to "Delete rows in existing table" or "Append rows to the destination table". You can also enable to insert identity data - this should be enabled if your source csv file contains Identity data that you want inserted as the row ID in the table. Then you need to check and modify accordingly the Column Mappings between the csv file and destination table. Then click OK and click Next.


  10. In the "Review Data Type Mapping", you can check the mapping results and determine if there are problems and inconsistencies so you can always click Back and modify your settings accordingly. When all is OK, click Next.

  11. In the Run Package, check Run immediately. This will execute Import immediately when you click Finished. If you're using SQL Server version that is higher than the Express edition, you can have the other option of saving the Import steps so you can have the luxury of running it again in the future without the need to perform the previous steps again.

  12. Click Next. In the "Complete the Wizard" steps, the import summary steps are displayed. If these steps are correct, then you can proceed to click Finish to begin importing your data



    If you want to be able to save this Import steps, you need to upgrade to a higher version of SQL Server. The saved step is called SSIS package and you can choose to run this package periodically using SQL Server Agent. But that topic is worth another blog page. I'll write about it next time.















Unit Testing With NUnit

Unit Testing is a methodology in computer programming where the smallest unit of software logic is tested to determine if it's correctly doing what the programmer has designed for it to do. Performing unit tests on the programs can effectively reduce and prevent bugs in the program and improve the coding efficiency of the developer.

Unit Testing requires skill and patience. At the start, performing unit tests may seem to just lengthen the time of coding and double your effort since you now need to write additional codes for testing. But in the long run, as you make myriads of changes to the software to cater to customer's unending demands, unit testing can help a lot as it can easily detect if a logic is broken due to the latest changes in your codes.

There are a lot of Frameworks in .NET that can help the developer perform unit testing easily. One that I like is NUnit. I've used NUnit in one of my projects and it's easy to understand and use. NUnit is an open source product so it's free to use. You can download it from http://www.nunit.org/.  When it's installed, it has a Test Runner program that can be used to automatically run your test.

To demonstrate the use of NUnit, I'm going to test the following simple class with its "IsNoteValid" method:

public class Notes
    {       
        public bool IsNoteValid(string note)
        {
            return !string.IsNullOrEmpty(note); 
        }
    }

"IsNoteValid" procedure returns false if its parameter is empty or null and returns true otherwise.

How do we test this code? A unit test usually comprises three main actions: ARRANGE, ACT, and ASSERT.
Arrange is the process of setting up the objects, Act is the processing of calling the procedure under test and Assert is the process of making sure the procedure under test behaves according to its specification. In our case, we are going to test the "IsNoteValid" procedure if it behaves correctly.

Below are the test codes. You can search on the internet for the proper syntax of NUnit but basically in the first Test Procedure, it is just calling the IsNoteValid procedure with a valid parameter and asserting that it must return true. In the second Test Procedure, it is calling the IsNoteValid procedure with an invalid parameter and asserting that it must return false.

       [TestFixture]
        public class NotesTests
        {
            [Test]
            public void IsNoteValid_validNote_ReturnsTrue()
            {
                //arrange
                Notes note = new Notes();
                //act
                bool result = note.IsNoteValid("mynote");
                //assert
                Assert.IsTrue(result, "note should be valid!");
            }

            [Test]
            public void IsNoteValid_invalidNote_ReturnsFalse()
            {
                //arrange
                Notes note = new Notes();
                //act
                bool result = note.IsNoteValid(string.Empty);
                //assert
                Assert.IsFalse(result, "note should be invalid!");
            }
        }

When the Test codes are done, you can run Test Runner, select the assembly .dll of your Test Project and click  Run. The Test Runner  will display how many tests have passed and failed.



So when at a later time, I need to refactor and modify my Notes codes, all I have to do is Run the Test Runner again to see if it has failed a test. This way, bugs can easily be detected.






First Attempt With WPF

The Windows Presentation Foundation (WPF) is the latest graphical display system for Windows. Now with version 4, it's the most radical change to hit Windows user interfaces since Windows 95. The underlying technology behind the power of WPF is DirectX. As a result, you can have rich user interface effects such as transparency, anti-aliasing, 3D graphics and hardware acceleration to name a few.
See below for the screenshots of one of my projects with my first attempt in using WPF. Obviously, it did not look as sophisticated given the vast power of WPF for generating great user interfaces. I've found out that you also need to be good on graphics design (which I'm not) to go hand in hand with WPF to successfully create the user interface of your dreams.