Shine's corner

How to import an Excel sheet into multiple SQL tables using SSIS

Today we will be looking on how to import an excel sheet into multiple tables. Let’s take as an example the following excel spreadsheet:

Image007

Looking at the excel above we can identify two problems:

1)      We need to split a sheet into three tables

2)      No identifier columns

For this task we will be using SQL Server Integration Services. So let’s run the SQL Server Business Intelligence Development Studio and create a new Integration Services Project:

Image012

Now let’s create our data flow:

Image013

First of all we need to establish a connection to our Excel file. On the bottom , right-click on the Connection Managers and create a New Connection:

Image014

Next we will choose the Excel connection and point to our source file:

Now that we have our connection we need to add a Excel Source to our Data Fow:

Image019

Next double-click on the Excel source to change its settings like so:

Image024

If all is well we should be able to preview the data:

Image025

Now, one of the problems we identified earlier was the lack of a identifier column for both stores and products. So first we need to solve this with the help of the Derived Column Data Flow Transformation:

Image027

First we connect the Excel Source with the Derived Column. Then we double-click the Derived Column and configure it like so:

Image031

Ok, we now have the identifier columns but still the is no value for them. Let’s fill that gap. We need to ensure that every time the Excel is imported the same key is generated. We can do that with the help of MD5. So let’s add a Script Component to our Data Flow, setup and add the c# code for this task:

1)      First we need to connect the Derived Column to our Script Component;

2)      Secondly when we double-click the Script Component we must choose the Transformation Mode;

3)      Next we go to the Input Columns and choose the new Derived Columns and also the STORE and COD Columns;

4)      Finally we add our code to the component:

Image035

And the code:

    public override void Input0_ProcessInputRow(Input0Buffer Row)

    {

        Row.ProductId = Encode(Row.COD.ToLower());

        Row.StoreId = Encode(Row.STORE.ToLower());

    }

    private Guid Encode(string text)

    {

        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();

        byte[] bs = System.Text.Encoding.UTF8.GetBytes(text);

        bs = x.ComputeHash(bs);

        System.Text.StringBuilder s = new System.Text.StringBuilder();

        foreach (byte b in bs)

        {

            s.Append(b.ToString("x2").ToLower());

        }

        text = s.ToString();

        return new Guid(text);

    }

Like I said before, we will be using MD5 crypto to generate our unique columns. Sweet. One problem solved.

Now that we got our final source table we need to execute multiple operations on it. For that we will be using the MultiCast Transformation:

Image039

So, first lets populate the Products Table. We need a way to get the list of distinct products. For that we will use the Sort Transformation:

Image040

We first select the columns that we want to use and most importantly we must select “Remove rows with duplicate sort values” to have our distinct filter.

Let’s try it to see if it works. For that we will be adding a Grid Data Viewer to the connection between the Script Component and the Multicast. We, for test purpose only, will also add a Data Reader Destination and connect the Sort Transformation to the Data Reader Destination. Then will add a new Data Viewer to the connection.

So to add a Data Viewer simple right-click on the connection between components, click Add, select Grid type and click OK twice:

Image042

Notice now that we have a little goggles between our components:

Image052

So let’s run it:

When running we will be presented with a grid for the first Data viewer. Notice that our derived columns are now filled with unique values:

Image053

Cool.

The next Data Viewer is for the distinct products:

Image054

Nice.

Also notice that the data flow show the number of rows returned in each step:

Image055

Ok. The hard part is done. We now pretty much have to do a copy paste to fill the Store table:

Image058

We now have the distinct products and stores. Finally we will add the ADO NET Destination for both:

In the end:

Image067

Hope it helps J

(download)

(download)

ASP.net Webforms and the Passive View Design Pattern

This is more a personal reminder than an article.

With the release of the first bits of the ASP.Net MVC framework, I moved from webforms to the new model. But since I can't always have it my way, some times I need to use webforms. 

"If you can't beat them, join them!"

One of the biggest problems of webforms is that its isn't very testable. Implementing the MVP pattern "handles this by reducing the behavior of the UI components to the absolute minimum by using a controller that not just handles responses to user events, but also does all the updating of the view." [1].
The MVP pattern was splitted in two: The Supervising Controller and the Passive View. Today we will be talking about Passive View.

"Run Forrest, run..."

With this design pattern the view get as dumb as they can. All the logic is in the Controller. The Controller is also responsible for updating the view.

"Hello, World!"

Lets build a simple example. First we create a ASP.Net Web Application.
The objective of our application is simple: The user types his name on the text box. Pressing the Greet button and a nice little message is showed. :)
Let's define our view:

From the view we can get the typed user name and set a message.

Now, let's update our default.aspx to become our view. First we need to add a textbox, named txtUserName, a button, named btnGreetUser and a literal that will hold our greeting message (named litMessage).

Next, in the code-behind file of our default.aspx page, we add the IHomeView and implement its properties:

Notice that:

  • The page_load event of the page initializes a Presenter passing the instance of the view;
  • Our View properties map to both the textbox, for getting the name, and to the literal, for setting the message;
  • The button click handler calls a method of the Presenter.

Now that we've build the View we can't yet run the code: The Presenter is missing.

As I stated before, the Presenter will handle all te responses to user events, in this case, the button click event. So based on the needs of the view, our presenter will look like so:

Taking a closer look at the OnGreetUser() we can see that we take the user name from the view, build a simple greeting message and set back the message to the view thru the Message property of the view.

"That's all folks..."

We're done. If we run our application we can see how everything is hook up and a nice message is shown to the user when we types his name and presses the button.

Since there's a separation of the UI logic from the view implementation we can easly test our code:

 

Goo.gl Url Shortener API Wrapper

Just for the fun, there's a Goo.gl Url Shortener API wrapper on my codeplex corner.

var service = new GooglUrlShortenerService();
GooglErrorResponse error = null;
var url = service.GetShortUrl("www.google.com", out error);
Console.WriteLine(url.Id);

var
details = service.GetShortUrlDetails(url.Id, out error);
Console.WriteLine(details.Created);

Smell you later!

Book review: A Guide to Claims-Based Identity and Access Control

It's been a while since my last book review. Today's book is A Guide to Claims-Based Identity and Access Control cat.gif

 First I would like to say thanks to Eugenio Pace (@eugenio_pace) for sending me the printed version, and to O'Reilly Media (@oreillymedia) for the digital version.

Is it really you?

Claims-based identity is everywhere, all around us (just like the matrix :P). Whenever we go somewhere and we are asked for our identity card, we are providing a claims-based identity. Our word is just not enough.

In the software realm the same workflow happens in many applications. Whenever we use a application that depends on windows authentication, we are using a claim-based access control. The application (relying party) doesn't really trusts you, but instead trust the security token privided by the Active Directory (Identity Provider).

"But this is all very nice, but what I really want is to start using it on my web application..."

And if you, like me, need a guide to jump start, well, look no further, this is the one (Today is all about Matrix references).
This book will take you, whatever role you have (developer, security specialist, architect or IT pro), and guide to the process of moving your applications, from whatever local authentication mechanism, to a claims-based one.

The book is a lightweight read, very easy to understand, with sample code that you can download from the codeplex (where you can also download the PDF version) so that you can see in action what you have just read.
The book focus on migrating both a web (asp.net) application and a WCF service, not forgetting that, since it's a guide, the starting point is the understanding of what is a claims-based identity, nicely explain in the first chapters, so that we don't get lost in all the terminology.

using jQueryUI with Script# and the Script# Contrib project roadmap

Since my last post, I've started a new codeplex project to allow the usage of the jQueryUI in Script#.
At the writing of this post, we already support most of the jQueryUI interactions and some of the widgets available on the 1.8.4 stable version.

We are trying the most to keep lined up with the jQueryUI syntax, so that jQuery users feel comfortable and with low learning curve. In the source code there's a sample project that mimics all the demos available at the jQueryUI site, so that users can see how easy it is to use and also compare results

So let's build a simple example 

First go to the codeplex and download the latest bits and compile. 
Now we can create a new solution for our sample.
Start by adding a new Asp.net MVC 2 Empty Web Application and the a new Script# jQuery Class Library. When prompt, point the deployment path of the Script# project to the Scripts folder of the MVC application.

For this demo we will build a ajax search page:

Search1


Has you can see from the picture above, both the search button and the result table share the same theme. While the themed table is accomplish by applying a class attribute, the button is themed using the Button widget from the jQueryUI. 

If the user press the button, a full search is made, while if the user searches for a non-existing product, a message is showed:
Search2

The dialog showed was build using the Dialog widget.

So what's the code

To build this sample, we go to the Script# project, create a new Scriptlet with the following code:
Search_code

In line 18 with start by finding our html button and applying the Button widget. We also define the click event.
So when the user clicks the button, we will create a variable with the search parameter (line 19). Next we will make a POST to our Search action on the Home Controller, passing the search parameter. We than handle the return result (line 22). First we clear any data already displayed on our results table (line 23), then we cast the result to a strongly-typed array. 
This is the main advantaged of using Script#. We work with strongly-typed variables, and with this we get compile time checks :).
So, if no results are returned, we let the user know be showing a message dialog, has defined in the line 27 to 30.
Notice that, since Script# doesn't yet support extension methods, we had to create our own jQueryObject, in this case, a jQueryUIObject, that contains all the jQueryUI implementation. So when we mix jQueryObject with jQueryUIObject we need to Cast from one to another, as we can see on line 30.
If results are returned, we iterate each and append to the search table, as showed on lines 34 to 37. 
Notice once more the usage of the strongly-type Product variable.

Script# Contrib roadmap

Our plan is to have a full implementation of the jQueryUI in the first release. Next I'm thinking on going with the Google API.

So, what do you think? Any suggestions are highly appreciated.

Click here to download:
ScriptSharpjQueryUISample.zip (428 KB)

Getting started with Script# (ScriptSharp)

If you, like me, develop web applications, you got your hands all dirty with JavaScript.

Writing JavaScript isn't always easy, and with the new client-side features being added to the browsers, allowing rich applications to be developed, JavaScript is taking a great heat.

So we are now writing code in, at least, 3 flavours: C#, Html, and JavaScript.

But what if we could write C# code that generated JavaScript? 

This is where Script# enters the picture:

Script# brings productivity to Ajax and JavaScript development. Script# is a free tool that enables developers to author C# source code and subsequently compile it into regular script that works across all modern browsers, and in doing so, leverage the productivity and power of existing .NET tools as well as the Visual Studio IDE. Script# empowers you with a development methodology and approach that brings software engineering, long term maintainability and scalable development approaches for your Ajax applications, components and frameworks.

Script# is used extensively by developers within Microsoft building Ajax experiences in Windows Live, Office to name just a couple, as well as by a external developers and companies including Facebook. If you’re building Ajax-based RIA applications, you owe it to yourself to try Script# today and see if it can help improve your own Ajax development!

Script# is used by Microsoft, for instance, to generate the MicrosoftMvcAjax scripts that are available when we create a new asp.net MVC project.

scriptsharp1.png

Lets start with a simple example...

...of binding a click event to a button:
Scriptsharp7
The previous code generates the following:

Scriptsharp8

Notice that:
  • The code we made in C# is almost identical to the code generated;
  • All the client-side objects, like Window and Document, are available to C# code, so there is no new learning involved and with the benefit of compile time checks;
  • All the documentation added to the C# code is also added to the JavaScript (on the debug file);
  • We are working on a OO code on the client-side.
So, on our page we can now add the necessary script references:

Scriptsharp6

We even got intellisense and the documentation helper. How cool is this?

Now, lets improve our code a bit by using jQuery. This is for me the best JavaScript framework:

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

So lets create a new ScriptSharp scriptlet:
Scriptsharp10

When we build, our new code will be added to the ScriptLibrary(.debug).js:

Scriptsharp11

In the end...

This is a great tool to build JavaScript.
There are some small issues with this, like the lack of good documentation our closed source code. Although jQuery support was added with the latest drop, there's no support for the jQueryUI.

There are other tools, like http://sharpkit.net/, that has more features but that are not free.

So, what do you think? 
Filed under: script# scriptsharp

Book of the month: Programming Microsoft(R) ASP.NET MVC by Dino Esposito

This is my first post in the "Book of the Month" series. And what a start: Programming Microsoft® ASP.NET MVC by Dino Esposito.
First I would like to thank O'Reilly for kindly sending me a copy of the book.
cat.gif

O'Reilly Description
"Author Dino Esposito leads you through the features, principles, and pillars of the ASP.NET MVC framework, demonstrating how and when to use this model to gain full control of HTML, simplify testing, and design better Web sites and experiences."

My two cents
Moving from the webforms to the MVC framework may not be an easy task, and this is where this book will come in handy.

Dino starts by explaining why did Microsoft saw the need to create a new web development framework.
After we get why, we need to know the how.  The second chapter explains the MVC foundations and the similarities/differences with the webforms.
Above all It's important to understand the MVC pattern. What's a View? What's the role of the Controller? Why do we need a Model? This gets answered on the 3rd chapter.
The next three chapters go deeper on each of these actors. Mastering these chapters is the key to fully get the benefit of the MVC framework.
The seventh chapter delves with how we should handle data: How is data presented, how we handle data editing and saving and how do we perform validation.
Chapter eight goes deeper on MVC infrastructure that we read about on the second chapter and adds some new concepts like localization and dependency injection. 
We live in a Web 2.0 era. And that means Ajax. The nine chapter is all about that.
"Red, Green, Refactor"
This is the concept of the tenth chapter: Testability and Unit Testing and how we can achieve this on the MVC framework.
The last chapter, we learn how to extend the MVC framework: Controller Factory, Action Filters and Results and Rendering.

In the end...
This is a great book to learn MVC. Although its already based on the MVC 2 release, Dino does a great job explaining each aspect of the framework, so that even if you didn't catch the first MVC train, you'll get all the foundations (and more) to start creating well design, based on patterns, professional applications.

Improve your code with NDepend

Although we all try to write the best code ever, we can't be sure unless we have some kind of code analysis software, like NDepend. This  is one of those tools that any developer and architect should have in his toolbelt.

NDepend makes refactoring easier: With a set of standard rules, and the possibility to defines your own, we can exactly pinpoint improvement spots.

Welcome to the Code Query Language (CQL)

NDepend sees our code as a database, so we just need to query to find anything. For instance, querying our code for methods with more that 30 lines of code its as simple as SELECT TOP 10 METHODS WHERE NbLinesOfCode > 30 ORDER BY NbLinesOfCode DESC.

This is one of the more than 80 rules avalilable that run on your assemblies when you use NDepend. But what is great is that you can write your own set of rules using the CQL Query Editor with intellisense:

NDepend CQL Editor

NDepend CQL Editor

Control your dependency

We all know that type coupling can easily go out of control and increase the effort that any change introduces. Using the CQL rules with the Dependency Matrix window, one can spot tight coupling and fix it:

Dependecy Windows
Dependecy Windows

Always keep track

For me, one of the best features of NDepend is the ability to compare analysis, and this way track change evolutions.

New code was added...
New code was added...

Full Report

Everytime that a analysis run, a full report is generated, so that you can, for instance, publish for your team easily understand the what's going on.

Full Report
Full Report

Who are my friends

Besides the standalone UI, NDepend works with Visual Studio and Reflector.

Integration With Reflector and Visual Studio
Integration With Reflector and Visual Studio

What's your flavor?

NDepend is available not only for the .NET, but also for Java and C++. The new v3 fully integrates Visual Studio 2010 and a drastic performance and memory consumption improvement, to avoid slowing down VS. Sweeeet :)

What's next for you...

...is to godownload and become addicted.

Filed under: ndepend software
114
To Posterous, Love Metalab