Showing posts with label Microsoft. Show all posts
Showing posts with label Microsoft. Show all posts

NPOI 2.0 series of posts scheduled

NPOI logoWhat’s NPOI you may ask. So here it goes:

NPOI is the .NET version of POI Java project. POI is an open source project which can help you read/write Office 2003/2007 files.

NPOI advantages
a. It's totally free to use
b. Cover most Excel features (cell styles, data formats, formulas and so on)
c. Supports .xls, .xlsx, .docx
d. Designed to be interface-oriented (in NPOI.SS namespace)
e. Supports not only export but also import
f. .NET 2.0 based even for xlsx and docx (but it also supports .NET 4.0)
g. Successful use cases all over the world
h. Great amount of basic and to the point samples
i. Professional service support (even 24*7) directly from NPOI team (not free)

My dear friend Tony Qu from China (the guy behind NPOI development) approached me and asked me to help him share NPOI 2.0 news with the English speakers. I’m always glad to help spread the word about this amazing open source project that has served me in many situations.

The most seen and shared post of this humble blog as of now has almost 9000 shares and was published on 7/02/2009 – oh God that’s exactly 4.5 years ago… its title is Creating Excel spreadsheets .XLS and .XLSX in C#. This huge amount of shares shows that a tool that does what NPOI does is highly demanded in the market. No doubt!

You know: when I wrote that post I had no idea it would be so useful to so many people. My intention with this blog is really to share useful things with the world giving back a bit of what I find/learn/improve from the great minds spread throughout this big planet earth. This is a continuous\infinite process for sure.

OK dude: that’s enough of food for thought. Let me show you what’s going on with NPOI. Here you go…

NPOI 2.0 release
The release is planned for this January. We agreed to publish posts discussing major features/enhancements that’s arriving.

Here they are:

1 - WorkbookFactory can help make HSSF and XSSF transparent for users

2 - Excel 2007 and Word 2007 support

3 - Cell, Row, Sheet copying and Workbook merging

4 - Converting Excel XLS documents to HTML format

5 - isRightToLeft and setRightToLeft in XSSF and HSSF

6 - Diagonal line in cells for both Excel 2003 and Excel 2007

7 - Excel 2007 chart support

8 - New excel functions added in formula calculation

9 - NPOI tag added to files generated with NPOI

10 - XSSFWorkbook implements IEnumerator

Keep an eye on this blog for the next posts.

NPOI source code 
https://github.com/tonyqus/npoi

NPOI NuGet package
https://www.nuget.org/packages/NPOI/2.0.6

SQL UPDATE statement with SELECT and SQL Server Image data type column

In a SQL Server database I have a table called users which has a column named signature. This column is of type Image.

My production SQL Server is located in a shared hosting environment.

One problem I’ve been facing lately is that I need permission to execute an UPDATE statement to insert a signature image for a given user. This problem occurs because to insert a signature image for a given user I have to execute a BULK statement like this for example:

--Update existing user
UPDATE users SET [signature] =(SELECT MyImage.* from Openrowset
Bulk 'C:\MyProject\trunk\MyCompany.Product\MyCompany.Product.Web\
Images\Signature.jpg'
, Single_Blob) MyImage) where Id
= '1111aaaa-1111-11aa-a111-111111a1a1a1'

The query above works fine in my local machine but when I tried to execute it on the remote/production server, I got this beautiful message:You do not have permission to use the bulk load statement.

In the shared hosting environment the execution of Bulk command is disabled by default for security reasons. This is annoying but totally understandable!

Using Bulk load - allows the user to populate a database from a file. It’s not available in shared environment because it is necessary to insert client files on SQL server locally (the production server).

So… great! I need a way to bypass this limitation because I won’t spend tubes of money paying a dedicated server… it’d make sense if and only if I needed a dedicated server.

1st try: import a specific user row from my local SQL Server to the remote instance using SQL Server Management Studio Import task. I got an error about constraint key violation because I already had the same row (for that user) on both databases. It’s just a matter of updating the signature column in the production database. This seemed to be a pain path.

2nd try: consider a dedicated server? Smiley pensativo No thanks… hehehe

3rd try and solution: a few days later I found myself thinking about this problem again (this signature column updating thing is a recurring task) and so I decided to find another way and it came to light - link the remote server to my local SQL Server Express instance and write a beautiful SQL query that does the job.

First I stopped in this excellent blog post with a step by step guide written by jen: Create Linked Server SQL Server 2008
This post provided everything I needed to link both SQL Server instances.

To make sure you have linked your server correctly, you can execute this query in your local server:

select server_id, name, product, provider, data_source, [catalog], is_linked
from sys.servers

The above query gave me this result:

Linked servers linked to my local SQL Server Express instance
Figure 1 - Linked servers linked to my local SQL Server Express instance

Then I Googled about Update with Select + SQL Server or something like that and found this StackOverflow question: Updating a table with multiple values from a select statement where the date matches. Lieven’s answer helped. I just had to adapt it to my case. This is the SQL code that does the dirty work:

UPDATE  U
SET     U.[signature] = users.[signature]
FROM    [LOCAWEB].[laudotech].[dbo].[users] U INNER JOIN users
ON users.id = U.id AND U.id = '1234aaaa-5678-90aa-b123-456789a0a1a2'

The above query must be executed within the context of the local SQL Server instance of course. Where the linked server resides.

To give you a view… this is how all this is configured inside SQL Server Management Studio (SSMS):

SSMS Object Explorer and the Linked Server LOCAWEB in my local SQL Server Express instanceFigure 2 - SSMS Object Explorer and the Linked Server LOCAWEB in my local SQL Server Express instance

There’s so many things one can do with SSMS that I feel really happy in learning one more of those things. Last week I blogged about Import/Export SQL Server database data with SSMS. Take a look at it.

Man! Have I said that I Iike working with databases!?

Hope it helps.

Import/Export SQL Server database data with SSMS

This post is a visual guide about one of the most powerful features of Microsoft SQL Server Management Studio (SSMS) 2008: Import/Export database data.

These tasks are useful for example when you need to debug an application with real world/production data to find possible bugs in your code. You can import the production database data to your local development database and find what’s causing problems. These tasks can be used to create a protection layer because you won’t be working “directly” with production data.

As you see, if I right click a database in SSMS I get access to this rich menu full of interesting options that deserve a careful study:

SSMS 2008 Import Export Database Tasks

Looking at the above picture you see in Object Explorer that I’m connected to two SQL database servers. The first one is a remote SQL Server (version 10.0.2775) and the other one is my local SQL Server Express (version 10.50.1617) instance.

With this configuration I have the perfect scenario to visually show you how the Import/Export Data… menu options work.

In this blog post I’ll execute the Export Data task. This allows me to test my web application using my local SQL Server instance with real world/production data.
The Import Data… task does practically the same thing but in reverse, logically. I’ll let the execution of the Import task to you dear reader!

OK… If I proceed and select the Export Data… menu option I’ll be able to bring new data to the database that is located on my machine. Data comes from the remote/production server to my local copy of the same database.

After clicking Export Data…, SQL Server Import and Export Wizard pops up. I then select the Data source/Server name (from which Data source type and Server I want to get the data to be imported). In this case, the data comes from the remote SQL server. I use SQL Server Authentication, fill the user name and password and select the Database that’ll provide the data. In Server name field I used the IP address of my remote server.

SQL Server Import and Export Wizard - Choose a Data Source

Now is the time to choose the Destination. In this case it’s my local SQL Server instance. LENIEL-PC is my Windows 7 machine name. SQLEXPRESS is the default SQL Express server name. I also selected the Database I want to receive the imported data. As you see both databases (source and destination) have the same name to make things easy.

SQL Server Import and Export Wizard - Choose a Destination

The wizard then asks if I want to copy data directly from table to table or if I want to write a custom SQL query to shape the data according to specific needs. I’ll select the first option to keep things simple.

SQL Server Import and Export Wizard - Specify Table Copy or Query

In the next screen we get a beautiful list of available tables and views. I’ve selected two tables that I want to copy.

SQL Server Import and Export Wizard - Select Source Table and Views

If you click the Edit Mappings… button (which applies to each table selected in the grid), I can also specify if I want to delete rows before importing data or if I want to append rows to the destination table. I’ll append rows because I have already erased both tables (exams and files) on my local database.

Apontando para cima Table files is linked to table exams through a foreign key. I disabled this foreign key constraint in my local database to avoid conflicts/errors during the import process. Beware because conflicts do appear most of the time. Conflicts are generally related to key violation/duplication.

SQL Server Import and Export Wizard - Column Mappings

As I’m using the free SQL Server Express Edition, the following screen has an interesting information:

In SQL Server Express, Web, or Workgroup, you can run the package that the Import and Export Wizard creates, but cannot save it. To save packages that the wizard creates, you must upgrade to SQL Server Standard, Enterprise, Developer or Evaluation.

This is telling me that I’ll have to go over the wizard (#7 steps) again if I happen to execute this very import process. Really annoying… Irritado … but that’s the price you must pay when using free tools.

SQL Server Import and Export Wizard - Run Package

Next button once more (the last one hallelujah) and we’re ready to go. It’s just a matter of reviewing what’ll be done and pressing the finish button.

SQL Server Import and Export Wizard - Complete the Wizard

After clicking Finish I got this last window:

SQL Server Import and Export Wizard - Execution Successful

Hope this simple and visual guide helps you understand how the data Import and Export processes work when dealing with a SQL Server database inside SSMS.

Free tools
Microsoft SQL Server Express Edition
Microsoft SQL Server 2008 Management Studio Express (SSMSE)

Testing Windows 7 beta and RC versions

Windows is the piece of software that underlies everything on my computer so that I thought it would be a great opportunity to write about it since we’re on the verge of its new version, namely, Windows 7.

I’ve been testing Windows 7 for the last two months. It’s been my operating system since then.

Firstly I got the 32-bit Beta release on March, 15th and today I’m downloading the 64-bit RC (release candidate) version. I plan to install it this weekend and as soon as I have it installed and configured I’ll update this post.

What I have to write about this operating system? Numbered from 1 to 7 in an unordered relevance fashion…

1 - It is fast.
2 - I risk to say it is faster than Windows XP.
3 - It is beautiful! Take a look at the new taskbar.
4 - It simplifies a lot of tasks.
5 - It has more native programs.
6 - Previous Windows’s native programs got a refresh and were optimized.
7 - It adds more security points to your day to day tasks.

My Windows 7 Beta taskbar:

Windows 7 Beta Taskbar

I moved directly from Windows XP to Windows 7. I didn’t use Windows Vista because it was too bloated for my computer in the beginning of 2006 when I also tested it in the beta period. At that time I had an AMD Athlon XP 2400+ with 512 MB RAM memory and an onboard video card which didn’t allow me to get the so famous Aero interface. I didn’t have a plan to upgrade my hardware. That was the big impediment. I think that Windows Vista arrived in a time in which the majority of computers didn’t have a proper hardware configuration yet.

Now the landscape is different. Windows 7 appears in a time that it’s much cheaper to buy a 2-core computer with GBs of RAM memory; Computer prices went down during the past years even here in Brazil where hardware prices double if compared with US $. Today $ 1 = R$ 2.07. This price is still attractive. Believe it or not! :)

The following picture shows my current computer configuration:

 Windows 7 System configuration

This is the Windows Experience Index score I got - a low score given the fact that I still use an onboard video card and that the score is determined by the lowest subscore:

 Windows 7 Windows Experience Index

Even with a 3.2 score I have the windows Aero enabled. Take a look at the Windows Experience Index: An In-Depth Look post that describes the score levels and what system’s features are enabled or disabled based on them.

From the Engineering the Windows 7 “Windows Experience Index” post we have the following:

The Vista-era general guidelines for systems in the 1.0, 2.0, 3.0, 4.0 and 5.0 ranges still apply to Windows 7. But, Windows 7 has added levels 6.0 and 7.0; meaning 7.9 is the maximum score possible.

While using Windows 7 beta I installed all the software I work with as the Microsoft Visual Studio 2008 Professional, Oracle Database, PL/SQL Developer, TortoiseSVN, etc - a typical developer box.

Windows 7 didn’t crash and was a well behaved operating system during this beta period in which I did everything I used to do in Windows XP.

The only hardware problem I had was with a Creative Audigy sound card (model number SB0090). There was no driver available for Windows 7. So I had to install a driver that wasn’t full compatible. The sound didn’t sound as good as it should be. I experienced a lot of noise.
Creative Labs has a Windows 7 - Driver Availability Chart in case you’re interested.

All in all you’ll get a great experience with such a robust operating system. After all Windows is ubiquitous and the more you can do with it the better you get at work.

Updated on 6/6/2009 05:48:00 PM

I’ve installed Windows 7 64-bit version but I didn’t use it because for the sake of my work I thought Win 7 wouldn’t play as expected.

Firstly we should consider that Windows 7 64-bit has a default Program Files (x86) folder where it puts all applications that are made to run on a 32-bit operating system. This particularly broke my way because the software that I develop rely on an Oracle database connection. There is a known bug with Oracle that prevents an application hosted in a folder that has parenthesis in its name to access an Oracle database.

I didn’t notice any performance gains while running the 64-bit OS.

Today I finally installed the Windows 7 RC 32-bit. I upgraded from the 32-bit Beta version to the RC version. The upgrade is only possible from 32-bit to 32-bit versions and not from a 64-bit Beta to 32-bit RC and vice versa.

The upgrade took 1 hour and 40 minutes to complete and ran flawlessly. You may ask why this took so long? This is because in a upgrade it is necessary to copy a lot of files from the old OS to the new one.

I downloaded the ISO file and extracted its content to a temp folder. I changed the file cversion.ini as described in the post Delivering a quality upgrade experience from the Engineering Windows 7 blog so that I could go through the upgrade. I then clicked setup.exe while running the Windows 7 beta version and the installation started.

I got the following report:

Upgrading Windows will affect the following devices and/or programs:

          These programs might not work properly after the upgrade. We recommend uninstalling these programs before upgrading. Cancel the upgrade, open Control Panel, and search for "uninstall a program". (Note: Programs marked as * can be safely reinstalled after the upgrade.)
          • Microsoft SQL Server 2008
          • Microsoft SQL Server 2005

        I then decided to ignore the report and proceeded with the installation.

        Windows 7 - Upgrading from 32-bit Beta to RC

        The above image shows the early stages of the upgrade. In fact there were more than 400000 files to be gathered. I already had an extensive list of apps installed on the beta OS as for example Microsoft Office 2007 that in itself is a big suite of apps.

        Windows 7 then restarted sometimes and installed the new OS bits that were refined from Beta to RC. The last step was to transfer files, settings and programs to the new OS. It transferred a total of 524490 files.

        My Windows 7 RC taskbar:

        Windows 7 RC Taskbar

        From this what I have to say now that I’m using the RC to write this blog post using Windows Live Writer is that the upgrade was successful. I didn’t need to reinstall anything (including Windows Live Writer). Everything is the way they were before installing the RC version.

        I had a pleasant experience while upgrading from Beta to RC.

        Congratulations to the Microsoft Windows 7 Team for providing this must have feature, that is, making upgrades possible! :-)

        A last note: I described above the problem I had while configuring my Creative Audigy sound card in Windows 7 Beta. With the RC version the Creative Audigy soundcard is functioning as expected. One of the first things Windows 7 did was to install the sound card driver!

        Updated on 2/22/2010

        On February, 17 I made the change to Windows 7 RTM version. After almost a year of constant use the RC version proved to be really stable.

        Now let’s use Windows 7 till Windows 8 comes.

        References
        Engineering Windows 7 blog
        http://blogs.msdn.com/e7

        Windows 7 Team blog
        http://windowsteamblog.com/blogs/windows7

        Microsoft official Windows 7 site
        http://www.microsoft.com/windows/windows-7/default.aspx

        Windows 7 @ Paul Thurrott's SuperSite for Windows
        http://www.winsupersite.com/win7

        Windows 7 article at Wikipedia
        http://en.wikipedia.org/wiki/Windows_7

        List of features new to Windows 7
        http://en.wikipedia.org/wiki/Features_new_to_Windows_7

        C# Word Permuter-Shifter

        On April 23rd I had a job phone interview. The talk was about a Software Development Engineer in Test (SDET) position at Microsoft.

        I already blogged about a C# Thread Safe Circular Queue, which was one of the questions of a screen test (prior to a phone interview) I completed on January for the same Microsoft job position.

        On this last interview we (me and the Microsoft employee-interviewer) would talk a little bit and then get to the coding questions. It didn't happen as expected. Firstly the Microsoft interviewer tried to call me on my cellphone. I just couldn't hear a word of what he was saying. The sound was very low. Then we decided to start with the coding questions and then on the phone land line we would talk so that he could explain more about the position, etc.

        We started a meeting on Microsoft Office Live Meeting. I was asked about a simple and easy question.

        The question:

        Write a program that changes the position of the words of a given sentence. For example, given the sentence "How are you going" as input, the output should be "are How going you".

        Simple, isn't it? I thought that too at the moment.

        As you can see, the first and second words change of position and then the third and forth words change of position and so forth.

        The interviewer explained that I could write any code. It didn't need to be written with the syntax of a programming language, it could be a pseudocode.

        I'm so used to code using code auto-completion (IntelliSense) and the debugger that I just didn't write any good code to solve the question. It was really frustrating. All what I needed to do was clear in my mind but I just couldn't express it. Was that the case of me being nervous? Beats me.

        Today I decided about writing a post with a possible solution to this simple programming question. I opened Microsoft Visual Studio C# Express and wrote some code. In just 5 minutes I had a working code that did the job.

        There are things in life that are really weird. I passed more than 45 minutes trying to write a pseudocode and then with the help of IntelliSense and debugger catching my mistakes, things flowed flawlessly and rapidly. Why that faster? I don't know how to explain it, maybe because of IntelliSense and the presence of a handy debugger!

        For sure the solution I present here isn't the better, but it's a solution and that's what was asked.

        Bellow is the code I wrote:

        namespace WordPermuter
        {
          class Program
          {
            static void Main(string[] args)
            {
              List<string> sentences = new List<string>()
              {
                { "How are you going my dear?" }, // are How going you dear? my
                { "I am going fine honey." } // am I fine going honey
              };
              DoPermutation(sentences);
            }
            static void DoPermutation(List<string> sentences)
            {
              foreach(string sentence in sentences)
              {
                // Split the sentence when it reaches a white space
                var splitted = sentence.Split(' ');
                // Increment the counter on a scale of 2
                for(int i = 0; i < splitted.Length; i = i + 2)
                {
                  if(i < splitted.Length - 1)
                  {
                    var aux = splitted[i];
                    splitted[i] = splitted[i + 1];
                    splitted[i + 1] = aux;
                  }
                }
                foreach(var str in splitted)
                  Console.Write(str + " ");
                Console.WriteLine();
              }
            }
          }
        }

        What's the purpose of this code? Aha... It isn't the code itself but what approach you took to get to a solution. The interviewer wants to see how is your thinking process. No matter if you coded it wrong, but at least you should show something. As the recruiters always say: "Think it loud so that we can help you."

        After a solution has been presented, the interviewer will probably ask you what if questions. What if I did this way? What If I did that way? What is the breach? What are the possible bugs?... The list of possible questions is innumerable.

        I think my solution is OK! If you find any bug, please tell me.

        Thread Safe Circular Queue in C#

        While completing a screen for a Software Development Engineer in Test (SDTE) position for Microsoft I had to implement a thread safe circular queue.

        The question was the following:

        Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe. A really good observation was: Please do not to use existing class libraries for this question. Thanks!

        My first attempt was obviously get more information about a circular queue and bring it back to my mind. That's because I had studied it a long time ago when I was in the beginning of the computer engineering course. If you don't use it you forget it. That's the truth.

        This post aims to present an implementation of a thread safe circular queue in C#. I won't deal with theory. For theory, I advise you to read the Wikipedia article about circular queue (buffer) to get started.

        I reused some code from the links I present in the references section at the end of this post.

        I'll break down the code I implemented so that you can go through the functions that were asked in the problem statement.

        class ThreadSafeCircularQueue
        {
          private int[] queue;
          private int head;
          private int tail;
          private int length;
        
          static Object thisLock = new Object();
        
          public CircularQueue()
          {
             Initialize();
          }
        
          ...
        }

        The class ThreadSafeCircularQueue has five properties: an integer array (the queue) and the queue's head, tail and length. A static object thisLock is used to make the queue thread safe.

        private void Initialize()
        {
          head = tail = -1;
        
          Console.Write("Circular Queue size: ");
        
          string length = Console.ReadLine();
        
          this.length = int.Parse(length);
        
          queue = new int[this.length];
        }

        The function Initialize() does what its name means. The queue's head and tail are set to appropriate values and the user has the opportunity of specifying the queue's size (length) by entering an integer value. A new queue is then created and has the user specified size.

        The Enqueue() and Dequeue() functions shown bellow do the hard work, that is, they control all the circular queue functionality.

        The Enqueue() function receives an integer value to be enqueued. Note the use of the thisLock variable. It is used so that we get thread safety, that is, all the code section inside the lock statement can't be executed by two threads at the same time. This avoids the problem of two concurrent threads trying to access the queue data structure simultaneously. If it's not controlled in the source code level we can get invalid values in the queue what could lend to a corrupted queue. That's not what is expected. When the code section that is inside the lock statement is being executed by a thread and other thread reaches the same section of code, this second thread waits till the first thread exits such code section. This way the queue has a valid set of values and its data is maintained secure.

        Firstly is checked if the queue is full. It is full when it's head points to index 0 and its tail points to length - 1 or when its tail + 1 equals the same value of head. Remember that it is a circular queue.

        In case the queue is full a message is shown to the user. If it still has room we check if the "end" of the queue (tail) that points to the last element has an index of length minus 1. If it is then the tail will now point to the the "start" of the queue. The other possibility is to increment the tail variable. The position referenced by the tail variable is then used to enqueue the value parameter into the queue. Then the just enqueued value is printed in the screen. A check is done to verify if the head variable has a value of -1. If it's the case then head will point to index 0.

        private void Enqueue(int value)
        {
          lock(thisLock)
          {
            if((head == 0 && tail == length - 1)  (tail + 1 == head))
            {
              Console.WriteLine("Circular queue is full.");
        
              return;
            }
            else
            {
              if(tail == length - 1)
                tail = 0;
              else
                tail++;
        
              queue[tail] = value;
        
              Console.WriteLine("In -> {0}", value);
            }
        
            if(head == -1)
              head = 0;
          }
        }

        The Dequeue() function also uses the lock statement because it must be a thread safe function.

        Firstly is checked if the queue's head points to -1. Remember that in the Initialize() function when the queue is initialized its head and tail variables are set to -1. If head has a value of -1 then the queue is empty and the user is informed about that. A value of -1 is returned to conform with the function signature that needs to return an integer value.

        If the queue is not empty the integer variable v receives the value that is indexed in the queue's head position. The value 0 is then assigned to the position that was just dequeued.

        Now it's necessary to update the head position inside the queue. To accomplish that it's checked if head is equal tail, if it is, then head = tail = -1. This last operation states that the queue is empty after the dequeue operation. Else it's checked if head is equal length - 1. If it is the case then head receives 0. The last possible condition increments the value of head. In the end the value being dequeued (v) is printed in the screen.

        Printing the values in the screen is a good way of keeping track of what is going on while the program is running.

        private void Dequeue()
        {
          lock(thisLock)
          {
            int value;
        
            if(head == -1)
            {
              Console.WriteLine("Circular queue is empty.");
        
              value = -1;
            }
            else
            {
              value = queue[head];
              queue[head] = 0;
        
              if(head == tail)
                head = tail = -1;
              else
                if(head == length - 1)
                  head = 0;
                else
                  head++;
            }
        
            Console.WriteLine("Out -> {0}", value);
          }
        }

        Now take a look at the Show() function bellow. Again the lock is present. Why? In an instant you'll get to the point. Hold your horses! :-)

        A check is done to verify if the queue is empty. If it is the case the callee function just returns to the caller function. If it is not the case we proceed to show the values already present in the queue. If tail is less than head a for loop starting in 0 and ending in length - 1 iterates the queue and each value is written in the screen. Otherwise a for loop starting in 0 end ending in tail iterates the queue and each value is written in the screen.

        private void Show()
        {
          lock(thisLock)
          {
            int i;
        
            if(head == -1)
            {
              Console.WriteLine("Circular queue is empty.");
        
              return;
            }
            else
            {
              if(tail < head)
              {
                //for(i = head; i <= size - 1; i++)
                for(i = 0; i <= length - 1; i++)
                  Console.Write("{0} ", queue[i]);
              }
              else
                //for(i = head; i <= tail; i++)
                for(i = 0; i <= tail; i++)
                  Console.Write("{0} ", queue[i]);
        
              Console.WriteLine();
            }
          }
        }

        The following is the EnqueueDequeue() function responsible for calling the Queue(), Dequeue() and Show() functions. In this function I execute a simple test case and comment the operations being carried out.

        public void EnqueueDequeue()
        {
          Enqueue(1);
          Enqueue(2);
          Enqueue(3);
          Enqueue(4);
          Show();
          Enqueue(5); // Circular queue is full!
          Dequeue();
          Dequeue();
          Dequeue();
          Dequeue();
          Dequeue(); // Circular queue is empty!
          Dequeue(); // Circular queue is empty!
          Show();
          Enqueue(6);
          Show();
          Enqueue(7);
          Show();
          Dequeue();
          Dequeue();
          Enqueue(8);
          Enqueue(9);
          Show();
        
          // Supposing a 4 size queue:  0 ¦ 0 ¦ 0 ¦ 0
          //
          //                            1 ¦ 0 ¦ 0 ¦ 0  <- Enqueue 1
          //
          //                            1 ¦ 2 ¦ 0 ¦ 0  <- Enqueue 2
          //
          //                            1 ¦ 2 ¦ 3 ¦ 0  <- Enqueue 3
          //
          //                            1 ¦ 2 ¦ 3 ¦ 4  <- Enqueue 4
          //              
          //                            1 ¦ 2 ¦ 3 ¦ 4  <- Circular queue is full when trying to enqueue 5.
          //
          //                            0 ¦ 2 ¦ 3 ¦ 4  <- Dequeue 1
          //
          //                            0 ¦ 0 ¦ 3 ¦ 4  <- Dequeue 2
          //
          //                            0 ¦ 0 ¦ 0 ¦ 4  <- Dequeue 3
          //                   
          //                            0 ¦ 0 ¦ 0 ¦ 0  <- Dequeue 4
          //
          //                            0 ¦ 0 ¦ 0 ¦ 0  <- Circular queue is empty when trying to dequeue.
          //
          //                            0 ¦ 0 ¦ 0 ¦ 0  <- Circular queue is empty when trying to dequeue.
          //
          //                            6 ¦ 0 ¦ 0 ¦ 0  <- Enqueue 6
          //
          //                            6 ¦ 7 ¦ 0 ¦ 0  <- Enqueue 7
          //
          //                            0 ¦ 7 ¦ 0 ¦ 0  <- Dequeue 6
          //
          //                            0 ¦ 0 ¦ 0 ¦ 0  <- Dequeue 7
          //
          //                            8 ¦ 0 ¦ 0 ¦ 0  <- Enqueue 8
          //
          //                            8 ¦ 9 ¦ 0 ¦ 0  <- Enqueue 9
          //
          // * 0 is set in a position when dequeueing so that it's easier to watch the queue variable.
        }

        Now the main start thread:

        class Program
        {
          static void Main(string[] args)
          {
            ThreadSafeCircularQueue circularQueue = new ThreadSafeCircularQueue();
        
            Thread[] threads = new Thread[10];
        
            for(int i = 0; i < threads.Length; i++)
            {
              threads[i] = new Thread(new ThreadStart(circularQueue.EnqueueDequeue));
            }
        
            for(int i = 0; i < threads.Length; i++)
            {
              threads[i].Start();
            }
        
            Console.ReadLine();
          }
        }

        As you can see above I declare an object of type ThreadSafeCircularQueue. An array of 10 objects of type Thread is then created. In a for loop I instantiate each Thread passing to it a delegate that represents the method that'll be invoked when the thread begins executing.

        In the subsequent for loop I call the Start() method of each thread and they start executing simultaneously, tough they won't concur when accessing the functions Enqueue(), Dequeue() and Show().

        Visual Studio C# Console Application
        You can get the Microsoft Visual Studio Project and the app executable at: http://leniel.googlepages.com/ThreadSafeCircularQueueCSharp.zip

        References
        During the research phase of this implementation I recurred to some sites to get more information regarding the circular queue data structure. The following list can provide you a better understanding of such a data structure.

        Thread Safety articles
        [1] Venners, Bill. Designing for Thread Safety: Using Synchronization, Immutable Objects, and Thread-Safe Wrappers. 1998. Available at <http://www.artima.com/designtechniques/threadsafety.html>. Accessed on April 29, 2008.

        [2] Suess, Michael. A Short Guide to Mastering Thread-Safety. 2006. Available at <http://www.thinkingparallel.com/2006/10/15/a-short-guide-to-mastering-thread-safety/>. Accessed on April 29, 2008.

        [3] Allen, K. Scott. Statics & Thread Safety: Part II. 2004. Available at <http://www.odetocode.com/Articles/314.aspx>. Accessed on April 29, 2008.

        Circular Queue sample code
        [4] Kumar, Nunna Santhosh. Circular Queue Implementation using Arrays in C++. Available at <http://www.sourcecodesworld.com/source/show.asp?ScriptID=887>. Accessed on April 29, 2008.

        Thread material
        [5] Albahari, Joseph. Threading in C#. 2007. Available at <http://www.albahari.com/threading/>. Accessed on April 29, 2008.

        Translating ScottGu's Blog to Portuguese

        Joe Stagner from Microsoft wrote a post in which he calls people to volunteer for translating Scott Guthrie's Blog posts originally written in English to Portuguese. I immediately contacted Joe emphasizing that I would like to help. Since then I've translated three posts and I really expect to translate many more.

        You can access the new blog created especially for the Portuguese community at http://weblogs.asp.net/scottguportuguese

        Other great news for the Brazilian community is that the Developer Division, more precisely the Community Localization Team from Microsoft has released the Brazilian Localization of Visual Studio 2008 and .NET FX 3.5. More details can be found on this post at Somasegar's WebLog.

        Again, I volunteered to participate in these community localization projects assisting with translating into my native language: Portuguese.

        I think it's a good idea to participate in such projects. You can learn a lot more. As Joe stated in the title of his post "Do you translate ScottGu's blog in your head?"; my answer is YES, I do. I always do that. Besides, it's worth it to help others that still don't know the English language.

        PivotTable and PivotChart with Microsoft Excel

        In this post I use a sample spreadsheet that stores the grades of a college student to show how to create a pivot table and a pivot chart using Microsoft Excel 2007.

        Note: Although I use Microsoft Excel 2007 to illustrate the creation process, I provide at the end of this post a spreadsheet compatible with Microsoft Excel 2003.

        Pivot Table
        A pivot table is extremely helpful when we want to summarize data through different forms. It gives us the possibility of arranging what data we want summarized and in what shape we want them.

        The following is the sample spreadsheet I'm going to use throughout this post:

        The above spreadsheet has just one sheet named Grades.

        To create a pivot table go to the Insert tab on Microsoft Excel 2007 and select PivotTable.

        You'll be asked about the range. In the case of this sample spreadsheet just type B2:I72.

        You then can choose where to place the PivotTable. I selected New Worksheet.

        After doing this, you'll have the following screen:

        Note that the column headers of the sheet named Grades are included in the PivotTable Field List on the right of the screen.

        Just for the sake of organization, let's rename this new sheet PivotTable.

        OK. Now we can start summarizing the data as we want. To accomplish this we must choose what fields/columns to add to the report.

        What I want to do in this sample case is a simple task: to average the student grades by terms.

        I start by selecting the field Term and then I drag and drop it on the the Row Labels area:

        It's clear that what I'm doing is to represent each term by a row in my report.

        Now I'll repeat the drag and drop action but this time with the Average field. I'll put this field on the ∑ Values area.

        After doing this last action, we get something like this:

        At this point we start getting some results; but wait, we're getting the sum of the student's grades for each term. That is not what we want to do. To correct this we must left click the Average field on the ∑ Values area and change its settings:

        On the new screen that is shown just select Average:

        Now we have the average grade for each term as we wanted. Look at the final result:

        The value we get in Grand Total is congruous with the already calculated GPA we have inside the Grades sheet.

        Pivot Chart
        A pivot chart can be used to display a pivot table's summarized data through different charting types and any changes you make to the pivot table's summarized data will be reflected on the pivot chart.

        To create a pivot chart you just have to follow the above steps we used to create a pivot table, but this time instead of selecting a PivotTable you must select PivotChart on the Insert tab.

        Bellow is the pivot chart after being formatted:

        Instead of Row Labels we have Axis Fields (Categories) inside the PivotTable Field List. I rearranged the pivot table report so that the terms are sorted accordingly. I also renamed the fields to reflect more precisely what the report data is about.

        Summary
        The possibilities for summarizing the data are innumerable and that's what makes a pivot table a so powerful resource.

        A pivot chart is simply a chart that uses a pivot table to do data binding.

        Get the sample spreadsheet at:

        Microsoft Excel 2007 version - http://leniel.googlepages.com/PivotTableSpreadsheet.xlsx

        Microsoft Excel 2003 version - http://leniel.googlepages.com/PivotTableSpreadsheet.xls

        IT giants: IBM, Google and Microsoft

        This year was a remarkably great one and I'd like to mention why I think so.

        IBM logoOn January 14th I received an e-mail from IBM that stated that my resume had been chosen and that they were inviting me to participate in the first stage of the recruiting process in Rio de Janeiro. The first stage was composed of a logical reasoning test, an English test and a composition. The estimated duration of the stage was about 2.5 hours. OK, I went there on January 19th at 3:00 P.M. and I did all the tests. On January 23rd I received an e-mail confirming that I had been approved in the first stage (tests) of the IBM passport (as they call the whole process). They stated that they’d schedule the second stage (group dynamics) as soon as possible. I received other e-mail on the same day and I was greeted with the following phrase: “You’ve been approved in the first stage and we’d like to invite you to the second stage (group dynamics) of the IBM recruiting process.” Again I went to the same place Botafogo, Rio de Janeiro on January 24th at 9:00 A.M. to take part in the second phase. In a timespan of just two days I received a message stating the following: “We thank you for your participation in the second stage (group dynamics) of the IBM passport internship program and we inform that your profile doesn’t fit in any of the open opportunities we have at the moment. We emphasize that this result doesn’t eliminate the possibility of a new entry in the next IBM internship program after a period of 12 months from this participation. Respectfully, IBM Brazil (Recruiting and Selection).”

        From the above experience I have good memories. In the first stage I went to Rio de Janeiro with my dad. That was a great trip and an unforgettable one. My dad sad at the time: I think you’re going to succeed in it. But it wasn’t the time yet. I remember of a moment in which I was in the hall of IBM’s building right before the first stage and for sure I knew that was just the beginning of a great journey. At that time I was heading to the last two terms of the computer engineering course. This year I had to develop the final project too.

        By the end of the year I realized it was time to start searching for a place to work. So I created a LinkedIn account and sent my resume to some places.

        Google logo One of the messages was sent to a contact I got at LinkedIn site on December 13th. The message title was Job Opportunity and the recipient was Kerry Xin, a software engineering recruiter that works for Google. He replied my email asking me what's my phone number and confirming that he would call me. I then replied the e-mail writing: "There is only a problem: here in Brazil not everyone has access to broadband internet. So, I still use a dial-up internet connection. This way, my phone will be occupied while I'm on the internet. If you can, set a time for us to get connected on the phone." He then replied with the following: "I would like to call you at 8pm Brazil time, which is in half an hour. Is that ok?" Of course it was OK. I was going to talk with someone from Google. That was above my expectations. I just replied that message stating that he could call me at 8:00 PM. And so I talked to him on the phone. That was my first English phone call. We talked for about 15 minutes. The talk was about the available locations to work at Google and the specific area to direct three technical questions. I answered the first two questions but wasn't sure about the last one. In a later e-mail I sent him my resume and wrote that I can read and write almost everything in English, but to talk is still really strange (I'm not in the right environment). I need an opportunity to practice. I know I can master the English language if I'm in the right place. After a week I received a message from Kerry with the result of the preliminary phone interview. The hiring committee's feedback for the Google/SRE position wasn't positive. He thanked me for my time and interest in Google. According to them my background and experience was carefully reviewed and unfortunately they couldn't find a position that is a strong match with my qualifications at the time. He then affirmed that he would keep my resume active in their system and try to match my profile with new opportunities and would reach out to me if they find an opening for which I may be qualified. I then replied the "Thank you from Google" e-mail with the following: "Thank you for considering me. It was a pleasure to talk to you on the phone (my first English phone call). For sure I'll remain enthusiastic about Google. It's a splendid company! I use Google's services everyday and it plays a great role in my life." I think it was a good FIRST experience with Google.

        More to come...