Code Improvement

Welcome to my blog!

Saturday, 13 February 2010

Creating a CSV file and dealing with special characters.

Last week, I created a web page that allowed some users to download a list of name with their email addresses as a CSV file. However, some characters were not exported correctly.

Here is a sample of the code I used :

StringBuilder sb = new StringBuilder();
IList<Subscriber> subscribers = Subscriber.GetAll();
foreach (Subscriber subscriber in subscribers)
{
    sb.AppendLine(string.Format("{0},{1}", subscriber.Email, subscriber.Name.Replace(",", "")));
}

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"subscribers.csv\"");
Response.Write(sb.ToString());
Response.End();

And some name looked like this when opened in Excel : sébastien lachance. Not really the expected results.

Why is this occurring?

The default encoding for the response stream is UTF-8 (8-bit UCS/Unicode Transformation Format) and Excel will not detect it due to the lack of BOM (Byte Order Mark). Instead, it will try to open the file using the ASCII encoding. It appear to be a known bug and the fix for it is easy.

 

Response.ContentEncoding = Encoding.Unicode;

 

or

Response.Write("\uFEFF");

 

Just before writing to the stream.


Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Wednesday, 26 August 2009

Process.GetProcesses common errors

Here is a list of common errors I had while working with the System.Diagnostics.Process class. I listed all solutions that worked for me.

Couldn't connect to remote machine.

Solution 1 : Open MMC (Start/Run/mmc), add the Services snap-in and enter the name of the machine you are trying to connect to. This should give the exact reason it’s failing.

Solution 2 : The inner exception could give you more information.

Solution 3 : You need server permission.

Solution 4 : Common on Windows 7 and Vista, start the Remote Registry service.

The RPC server is unavailable

Solution : Turn on File and printer sharing and make sure the firewall is configured to allow access.

Access Is Denied

Solution : In case nothing worked out of Google, try this : Open Local Security Policy and make sure the “Set Network access: Sharing and security model for local accounts” to Classic.

Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Monday, 10 August 2009

NDepend - Small review

I have been using NDepend on various project I am working on and there is so much to say that I can’t wait to do a full review because I will make you wait too long. I got a free license and wanted you to know what the tool can do and what were my impression.

First of all NDepend is a tool that analyse your code. It’s huge! Definitely not a tool you can learn in an hour or two. Simply give the tool a solution or project file and start analyzing. You are first presented with a a complete map of your application. By default it shows all your code sorted by the number of lines but you can quickly switch by different kinds of metrics (LOC, Cyclomatic Complexity, IL instructions, Efferent coupling, etc.).

ndependcomplete

The best part is that you can write query against your code. This feature is called CQL (custom query language). Need to know which method have more than 200 lines of code? No problem. Really. It looks like SQL and is easy to write (I haven’t written any yet, but I’m sure it will prove useful later).

Take a look at this :

// <Name>Methods with too many local variables (NbVariables)</Name>
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE NbVariables > 15 ORDER BY NbVariables DESC

Out of the box, NDepend provide around 200 CQL queries. It has queries to find unused or dead code, find which method are not test covered, naming convention not respected, types with too many methods, ect. Each rules has a short description on what it does and even provide links to more complete documentation if needed. It also has intellisence as if this wasn’t enough.

A cool feature is the dependency matrix. It’s easy to see where is your dependencies.

ndependmatrix

The tools itself is beautiful, it make us want to play more with it (it does not use WPF, but it appears to).

A lot of features that I haven’t used yet are :

  • Compare assemblies
  • Code Coverage
  • Writing complex  custom rules

I recently came across this post entry by Patrick Smacchia (creator of NDepend) that used the tools to spot bugs in an existing code base (http://codebetter.com/blogs/patricksmacchia/archive/2009/06/21/agile-behavior-nurture-knowledge-database.aspx). I don’t know why but this has really struck me and kept it in my favourites. I could write custom query to spot bad practices and potential bugs.

But there is a downside. On a project I worked last year. Every query that has been executed had a warning on it, almost every single one. That’s sad. I almost cried. But I’m fine now. NDepend will help me.

There is so much to say, that it’s almost impossible to cover it all in one single post. I’ll continue to use it and post any relevant information and features that I really enjoyed in the next couple of weeks.

Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Monday, 11 May 2009

'The install location for prerequisites has not been set' error

I think I needed to make this post since I was struck by this problem 2 times in the last year. And I didn’t learn from the first time, so here is the error message I got along with 50+ others that looked the same when building a setup from Visual Studio 2008.

The install location for prerequisites has not been set to 'component vendor's web site' and the file 'dotNetFx35setup.exe' in item 'Microsoft.Net.Framework.3.5.SP1' cannot be located on disk.

At fist, I was thinking that I haven’t downloaded the right version of the framework so, I have gone mad trying to find one that was entitled “redistributable”. Can’t find. Humm maybe something has to do with Visual Studio not looking for the right folder (Program Files vs Program Files (x86)). No.

After a lot of questions and no answer, I found a lost notes in Evernote stating that I should read the VS 2008 SP 1 readme file…

Section 2.3.1.1 : Enable Samesite for the .NET Framework 3.5 SP1 bootstrapper package

Here is the section content for those who don’t want to search for their readme file.

Update the Package Data

  1. Open the [Program Files]\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 folder or %ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 on x64 operating systems
  2. Edit the Product.xml file in Notepad.
  3. Paste the following into the < PackageFiles > element:
    < PackageFile Name="TOOLS\clwireg.exe" />
    < PackageFile Name="TOOLS\clwireg_x64.exe" />
    < PackageFile Name="TOOLS\clwireg_ia64.exe" />
  4. Find the element for < PackageFile Name="dotNetFX30\XPSEPSC-x86-en-US.exe" and change the PublicKey value to: 3082010A0282010100A2DB0A8DCFC2C1499BCDAA3A34AD23596BDB6CBE2122B794C8EAAEBFC
    6D526C232118BBCDA5D2CFB36561E152BAE8F0DDD14A36E284C7F163F41AC8D40B146880DD9
    8194AD9706D05744765CEAF1FC0EE27F74A333CB74E5EFE361A17E03B745FFD53E12D5B0CA5E0DD
    07BF2B7130DFC606A2885758CB7ADBC85E817B490BEF516B662
    5DED11DF3AEE215B8BAF8073C345E3958977609BE 7AD77C1
    378D33142F13DB62C9AE1AA94F9867ADD420393071E08D6746E2C61CF40D5074412FE8052
    46A216B49B092C4B239C742A56D5C184AAB8FD78E833E780A47D8A4B28423C3E2F27B66B14A74B
    D26414B9C6114604E30C882F3D00B707CEE554D77D2085576810203010001 (REMOVE LINE BREAKS!)
  5. Find the element for < PackageFile Name="dotNetFX30\XPSEPSC-amd64-en-US.exe" and change the PublicKey value to the same as in step 4 above
  6. Save the product.xml file
Download and Extract the Core Installation Files
  1. Navigate to the following URL: http://go.microsoft.com/fwlink?LinkID=118080
  2. Download the dotNetFx35.exe file to your local disk.
  3. Open a Command Prompt window and change to the directory to which you downloaded dotNetFx35.exe.
  4. At the command prompt, type:
    dotNetFx35.exe /x:.
    This will extract the Framework files to a folder named “WCU” in the current directory.
  5. Copy the contents of the WCU\dotNetFramework folder and paste them in the %Program Files%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 folder (%ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\DotNetFx35SP1 on x64 operating systems). Note: Do not copy the WCU\dotNetFramework folder itself. There should be 5 folders under the WCU folder, and each of these should now appear in the DotNetFx35SP1 folder. The folder structure should resemble the following:
    o DotNetFx35SP1 (folder)
    • dotNetFX20 (folder
    • dotNetFX30 (folder)
    • dotNetFX35 (folder)
    • dotNetMSP (folder)
    • TOOLS folder)
    • en (or some other localized folder)
    • dotNetFx35setup.exe (file)
      You may now delete the files and folders you downloaded and extracted in steps 2 and 4.
Del.icio.usDigg It!DZone It!StumbleUponTechnorati
Tags: | Categories: .NET
E-mail | Permalink | Comments (3) | Post RSSRSS comment feed


Tuesday, 28 April 2009

Subtle deadly bug

I almost never give my opinion about code I see, but I felt this one was interesting and educative. It all started while working on a legacy project (an ASP.NET web application), I found out that most connections were not closed. So I fixed them all and making sure every connection was closed once the I finished with it, should an error occurred or not.

try
{
    using (IDataReader reader = SqlHelper.ExecuteReader(Sql.MainConnection, "sp_name", paramter1, parameter2))
    {
        while (dr.Read())
        {
            //do something
        }
    }
}
finally
{
    Sql.MainConnection.Close();
}

 

Pretty basic stuff. Today I deployed the application to a server for some testing. After two or  three users getting in, Boumm! SQL Server is dead. I check the activity monitor and found out that a hundred connections were still open. The reason is : I have wrongly assumed that a static class in the project was providing me with a connection that was shared between all data access class.

I was sure I was closing all the connection, but I ended up closing nothing.  Let’s take a look at the MainConnection property of the Sql class :

public static SqlConnection GetMainConnection
{
    get { return new SqlConnection("connectionstring"); }
}

Each time I was accessing the database, and it was accessed a lot (20 times per request), I ended up with a lot of open connections. Enough to make SQL Server unavailable for some time. You could argue that it was my mistake and I shouldn’t be assuming things like this. But in my opinion, it’s a case of bad naming. The choice of name for the property that return me a connection was inconstant. If I access a property, I assumed that if I call it five times in a row, I would have five times the same result. The best choice would have been to create a method that return a new connection and name it accordingly.

public void SqlConnection GetNewSqlConnection()
{
    return new SqlConnection("connectionString");
}

It would have reduced the ambiguity and would have been a lot more easy to read. Good naming is very important and can greatly enhance productivity on a project. Good code should be easy to read and you should not ask yourself if a calling a method would cause side-effects or not doing what it said it should.

 

Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Thursday, 05 March 2009

Top 5 shortcuts you need to know to be a ReSharper Padawan

Important note  : I am using ReSharper 2.x / IDEA keyboard mapping.

This is the last post about shortcuts, next one will be about creating Live Templates.

Alt-F7

Find usage of anything, everywhere it is used.compact_keyboard

Ctrl-J

Browse the list live templates and allow you to select one.

Alt-F12/Shift-Alt-F12

Respectively move to the next and previous error in your solution. Forget about the error windows.

Ctrl-Alt-M

Refactoring shortcut. Extract a piece of code and make a method with it.

F2

Rename anything your cursor is one. And it's an intelligent renaming, meaning it will search for every usages of it and rename accordingly.

Technorati Tags: ,,
Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Tuesday, 03 March 2009

Top 5 ReSharper's shortcuts you need to know after some time

Important note  : I am using ReSharper 2.x / IDEA keyboard mapping.2037992_1a3b63a3ce

CTRL-F12

With this shortcut you can navigate and search the list of methods of the class you are presently in.

CtrlF12

 

ALT-Down Arrow / ALT-Up Arrow

Gives you the possibility of going to the next or previous member or method in your class.

 

CTRL-P

Parameter info. It's over now. Over the time when you had to hit the backspace key and retype some characters to see the list of parameters the method will take poping up. Hit this shortcut and code with less keystrokes.

CtrlP

CTRL-E

I have recently discovered this neat shortcut. It gives you a list of recent files you have edited and the possibility to quickly switch to any of it.

 

Ctrl+Shift+Alt+Backspace

Another recent discovery. It basically does the same thing as CTRL-E (Recent files you have edited), but with a small difference. You can navigate the list of changes you have made to your code. That's right, you can quickly go to any piece of code you have edited recently.

CtrlShiftAltBackspace

 

Technorati Tags: ,,
Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Wednesday, 25 February 2009

Top 5 ReSharper's shortcuts you need to know at first

Important note  : I am using ReSharper 2.x / IDEA keyboard mapping.

Alt-Enter smallkeyboard

Whenever you navigate your code and see a bulb shaped icon at the left side of your code, hit the Alt-Enter key combination that will provide you with a set of actions you can do on the selected code block.

bulb

Alt-R/R

Open the refactor menu. This will present you with a list of possible refactoring you can do.  This is the easiest way to start learning every refactoring's shortcut.

refactormenu

Ctrl-N

Find a class by it's type name. You can quickly navigate without the mouse to get you anywhere you want within your solution. This one will quickly become one of your most used shortcut.

Ctrl-Shift-G

At first you will need to know this one, but, when you'll become a ReSharper Jedi,  you will forget everything about it's existence. Place your keyboard cursor on anything and hit those keys. You will then be able to move to it's declaration, inheritors, usages, unit tests, etc.

Alt-Insert

When you are navigating your solution (Ctrl-Alt-L), press the Alt-Insert key combination and you can create new folders, add classes an even add a file that you previously created with the template editor of ReSharper.

 

Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Monday, 23 February 2009

Top 5 reasons not to use ReSharper

I have been bouncing on various project on various editor and it this has made me think... What so good about ReSharper? And this has lead me to find five reasons not to use it.

 

five

Reason #1 : I am not using Visual Studio.

Reason #2 : I did not possess or will never have a license.

Reason #3 : I will loose my job if I am too productive.

Reason #4 : I am not programming..

Reason #5 : Because you don't know it existed or your network administrator does not want you to install any third-party tools!

 

I'm sorry to have been misleading you with the title, but I have a profound respect for ReSharper. And if you sincerely doubt it will provide you any value, just try it for a couple of days(http://www.jetbrains.com/resharper/download/) and give me some news.

Del.icio.usDigg It!DZone It!StumbleUponTechnorati


Thursday, 29 January 2009

Set a value on an Textbox with his TextMode set to Password

I have a basic scenario which i'm required to display a page where an user can change his user information, including his password. I decided to use an ASP.NET Textbox control which have a TextMode of password. But,  when I put the password in the Text property, nothing will be displayed. The value will also be cleared after a postback event.

There is an easy workaround, you can add the "value" attribute with the password as your value.

txtPassword.Attributes.Add("value", "strongPassword");

But why can't we just set the value the normal way? Basically, it's for security reasons. The password will be set as clear text in the HTML and malicious user could have access to it. This is why you need to stay away from this method if you store sensitive information.

Del.icio.usDigg It!DZone It!StumbleUponTechnorati
Tags: | Categories: .NET | ASP.NET
E-mail | Permalink | Comments (1) | Post RSSRSS comment feed