Prabir's Blog

where the tech matters...

Hidden C# feature - string.Format Width

April 13
by prabir 13. April 2010 20:50

If you had written console applications before, you most probably would have spent quite an amount of time formatting the output with Console.Write(“some string”). Its pretty cumbersome to type “\t” or add couple of space “   “ in order to neatly present the output.

Well you don’t need to worry much with C#. It has a method called Format which easily allows to change the format of the string. A HelloWorld example for string.Format would be:

string.Format("Hello {0}", "Prabir");

That’s something most of you already know. But there is more cool feature than to just add a number inside the curly braces - {no}.

One could even add a comma and another number – minimum width to it.

string.Format("Price: {0,5}",price);

The above code would right align the price with width of 5. (If you want to left align you could use a negative number.)

Console.WriteLine("Product: {0,-7} Price: {1,5}", product1, price1);
Console.WriteLine("Product: {0,-7} Price: {1,5}", product2, price2);

The above sample would produce the following output. Notice the negative (-) sign for Product? Its left aligned, while the price is positive signed and is right aligned.

image

string.Format-width.zip (11.30 kb) [Downloads: 135]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

C#

Visual Studio Tips and Tricks - X

April 11
by prabir 11. April 2010 23:14

(This is a part of my series Visual Studio Tips and Tricks – X)

There at times when we write long nested codes in the same file. To organize our codes we split the logic in different classes and files, and yet we still need to organize it further down. With the introduction of C# region directives, it helped us organize pieces of statements to form a collapsible region as show below.

image

image

This is a pretty good solution to organize the codes. But as we keep adding them, it soon turns out to be more messy than ever before. Sometimes we might even prefer to temporarily collapse a particular block. This is not a problem for classes or methods. But what if we want the same for any arbitrary statements or piece of code? Wouldn’t that be great?

No worries. VS already has a solution for us. Its always been there in front of us and yet we failed to discover.

stop it … and show me how?

Ok. First of all select the the code you want to collapse then right click the editor and click Outlining > Hide Selection.

image

Did you notice something weird? I actually selected only the condition inside the if statement and hid the selection. It would then look as below.

imageIsn’t that cool?

Now try closing that file and reopen. VS is smart enough to remember the old collapsible selection.

image

So, the shortcut of the day would be Ctrl + M, Ctrl + H to hide the current selection.

(This is a part of my series Visual Studio Tips and Tricks – X)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Visual Studio

Visual Studio Tips and Tricks - IX

March 11
by prabir 11. March 2010 09:56

(This is a part of my series Visual Studio Tips and Tricks – IX)

Do you find your code messy, especially in the using directives section? When adding a new .cs file, by default certain namespaces are automatically added, but there are times when you will not use them. Following is the screenshot if you are using Resharper plugin in Visual Studio.

image

Note any differences? You will see that I only make use of one namespace which is System (System.Console) while the rest of the namespaces are not in use. Resharper being intelligent dims the unused namespaces as shown above.

imageHovering at the using directives sections, Resharper prompts me with a red bulb and asking me whether to remove the unused directives in file. Clicking it will remove the unused directives.

The same can be accomplished without using any plugins in Visual Studio by right clicking the code editor and choosing Organize Using > Remove and Sort.

image For me both way seems to be tedious as i need to go with too many mouse clicks to get something done. Why not create a Visual Studio Keyboard shortcut key. This will save a lot of your time.

Open Tools > Options menu. Select show all settings. Select Environment > Keyboard. Then type Organize to filter the commands in Show commands containing.

image

Then choose EditorContextMenu.CodeWindow.OrganizeUsing.RemoveAndSort and press Ctrl + U in Press shortcut keys text box. You will see that Edit.MakeLowercase already makes use of that shortcut key. Since I never use that keyboard shortcut, I prefer to replace it. Search again for Edit.MakeLowercase and click the remove button to remove the Edit.MakeLowercase keyboard shortcut.

Search back again for Organize and choose RemoveAndSort and assign Ctrl + U. Next time you want to organize using directives its as simple and as fast as pressing Ctrl + U.

If you would like to see more Visual Studio tips and tricks page. Please visit Visual Studio Tips and Tricks.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Visual Studio Tips and Tricks - VIII

August 18
by prabir 18. August 2009 18:37

(This is a part of my series Visual Studio Tips and Tricks – VIII)

Have you ever been working on a visual studio project with lots of tabs open and find it difficult to navigate around even with ctrl + tab. Well I hope this tip is going to help you.

Let’s say I have a bunch of tabs opened.

image

I could use ctrl + tab (similar to alt + tab for normal windows applications) and get the following result. which would allow me to navigate with live preview.

image

Even though it still gives me a great UI, it still isn’t productive especially when you need to submit your code to boss by evening. So you are telling me there is much better solution?

Yeah and simple one. Just Ctrl + Alt + down arrow key.

image

That instruction would tell Visual Studio to show a list of open tabs. You can then use arrow keys or mouse to click on one of those files. What is more cool is that if you actually know the name of a file, you can also type it and it tries to match up with it. It doesn’t match the file name if you enter it from the middle. It has to be left to right.

If you still want another solution. You can check about my previous visual studio tips and tricks at http://blog.prabir.me/post/Visual-Studio-Tips-and-Tricks-IV.aspx.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

Visual Studio

Alternative Method of Throwing Exception

August 05
by prabir 5. August 2009 11:44

Most of us use Exceptional Handling mechanism to prevent our programs from crashing and then debug the program by understanding the message thrown.

Traditional way to use would be to use try..catch..finally block to handle the exceptions thrown using throw. How do you throw exceptions? There are basically two ways to throw exception.

throw new Exception();

Or simply,

throw;

Most of us would be using the first method to throw. But sometimes, it might not contain enough information that is required to solve our problems (bug). In that case, the second method would be more useful.

Below is an example of the c# code that would help to distinguish between the two types of errors.

There are two methods defined in the Program class under ConsoleApplication1 namespace. (I’m assuming the file named a.txt doesn’t exist in c drive)

The first method uses throw ex;

 

private void LoadFile()
{
    try
    {
        using (FileStream fs = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read))
        {
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

 

The second method uses only throw; (You can enter this only in the catch block).

 

private void LoadFile2()
{
    try
    {
        using (FileStream fs = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read))
        {
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}

 

The program is as follows:

using System;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();

            try
            {
                p.LoadFile();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            Console.WriteLine();

            try
            {
                p.LoadFile2();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);

            }
        }

        private void LoadFile()
        {
            // code omitied.
        }


        private void LoadFile2()
        {
            // code omited.
        }
    }
}

When you run the program you will get the following output.

image

The error message printed to the console is as follows:

   at ConsoleApplication1.Program.LoadFile() in D:\Prabir\Documents\Visual Studi
o 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 47
   at ConsoleApplication1.Program.Main(String[] args) in D:\Prabir\Documents\Vis
ual Studio 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at ConsoleApplication1.Program.LoadFile2() in D:\Prabir\Documents\Visual Stud
io 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 62
   at ConsoleApplication1.Program.Main(String[] args) in D:\Prabir\Documents\Vis
ual Studio 2008\ConsoleApplication1\ConsoleApplication1\Program.cs:line 28
Press any key to continue . . .

 

 

As you might have noticed the second information is in more details. This allows you to know your stack trace in more details.

So how is it different?

In the first method, the stack trace is initialized at throw ex statement. The second method rethrows the exception meaning that the previous stack trace is kept along with more information where they occurred.

ThrowRethrowExample_CSCode.zip (538.00 bytes) [Downloads: 178]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

.NET Framework | ASP.NET

Visual Studio Tips and Tricks - VII

June 28
by prabir 28. June 2009 16:29

(This is a part of my series Visual Studio Tips and Tricks – VII)

In my previous post I had explained how to use the shortcut Alt W, L to close all open documents in Visual Studio. This post will be taking the same situation one step further.

Rather than pressing a series of keys, you will need to install the Visual Studio addin – PowerCommands. After that you can close all the documents using the normal menu style as shown below.

image 

For more articles on tips and tricks refer here. Or you can also access the page from the right menu under Page List heading.

 PowerCommandsSetup.msi (275.50 kb) [Downloads: 256]

To download the source code, you can go to the official site of PowerCommands at http://code.msdn.microsoft.com/PowerCommands.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

Visual Studio

Visual Studio Tips and Tricks - VI

June 23
by prabir 23. June 2009 12:24

(This is a part of my series Visual Studio Tips and Tricks – VI)

One of the most important feature which I think is lacking in the the Visual Studio shell, is allowing us to close all documents. They do have the feature to close all other documents beside the current one, but it still doesn’t full fill all my requirements.

image

Thus it requires me to execute a series of commands to close all the open documents which is really a waste of time. In order to solve this solution you can press Alt W, L to Close All Documents.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

Visual Studio

Save Team Foundation Server Password

June 14
by prabir 14. June 2009 17:02

(This is a part of my series Visual Studio Tips and Tricks – V )

Have you ever be tired of entering your password every time you access your Team Foundation Server (TFS) project. Don’t worry.There’s a way to bypass the login my storing your passwords in a secure vault.

image

For Windows 7 users:
  • Start Menu>Control Panel
  • User Accounts and Family Safety > Credential Manager
  • Add A Windows Credential>
  • Type in your internet/network address as your TFS server address, and username and password of your TFS account.
    image

For Windows Vista users:

  • Start Menu>Control Panel
  • User Accounts> Manage your Network Passwords
  • Click Add
  • Enter TFS server address
  • Enter your TFS username and password

For Windows XP users:

  • Start > Settings > Control Panel
  • User Accounts > Advanced> Manage Passwords > Add
  • Enter TFS server address
  • enter your TFS username and password.

Try it now to see if it works. It works with codeplex accounts too.

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

Visual Studio

Remove Annoying Yahoo Mail Ads.

June 07
by prabir 7. June 2009 16:02

Have you ever been sick of Yahoo Mail Ads. specially when you have a small screen where every pixel on your screen does matter. Well, great news for you guys. There is actually a solution to remove those annoying ads from Yahoo mail.

First of all you need to login in to your Yahoo mail and click My Account, which is basically at the top. You will be redirected to another page where you will be allowed to change quite a lot of important Yahoo Account settings. Then click edit in your Member Information, where you will be transferred to change your member details. Click your current Preferred Content and then you will be redirected to another page again to change the settings. And in the new settings drop down, choose Yahoo! Singapore. Congratulations you just removed the ads. Now go to you yahoo mail (www.yahoomail.com) and login, you will now see that the ads have been removed except the one at the Home tab (its a small one).

Note: If you are using Yahoo US and also use Yahoo Connections, your yahoo connections will not be shown in Inbox or the home page when you migrate it to Singapore. I don’t recommend to do this if you are a frequent user of Yahoo Connections.

I have also shown below the screenshots for you to have a glance at how it feels.

Yahoo Mail With Ads:
image

Yahoo Mail Without Ads:
image

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

Custom web.config Intellisense

May 27
by prabir 27. May 2009 01:28

(This is a part of my series Visual Studio Tips and Tricks – III )

Intellisense ExampleThere are at times when you would like to have intellisense support for you custom providers like the ones Microsoft provides.

In this post, I will be guiding you on the way how to create a basic intellisense for your BlogEngine.NET provider model for web.config.

You can open your BlogEngine.NET sourcecode or any of your websites to try it. But in this tutorial I will be sticking with BlogEngine.NET source code.

  1. To make stuffs clean I like to put all my Intellisense files (XSD schemas) in a folder called schemas. Please go ahead and create the folder. Add a new image item to your schemas folder. You can name it anything. Out here for simplicity I will name it blogengine.xsd.
  2. Change the target namespace to something meaning full. I prefer to have it like http://schemas.[company name]/product/year/month but its your choice. For now lets stick to http://schemas.prabir.me/blogengine/2009/5.
  3. Lets first have a look at our web.config file, and try to understand the schema.
<BlogEngine>
    <blogProvider defaultProvider="XmlBlogProvider">
        <providers>
  <add name="XmlBlogProvider" type="BlogEngine.Core.Providers.XmlBlogProvider, BlogEngine.Core"/>
  <add name="DbBlogProvider" type="BlogEngine.Core.Providers.DbBlogProvider, BlogEngine.Core" connectionStringName="BlogEngine"/>
        </providers>
    </blogProvider>
</BlogEngine>
  1. I will not be teaching you how to write XSD schemas. There is a good article at W3schools out here where you can learn more. For now just paste the code to your xsd schema file you created earlier. (Just looking at my code you can already learn a lot about xsd schemas – I would recommend you to download the code files at the end of the article for better formatting and readability).
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="blogengine"
targetNamespace=
"http://schemas.prabir.me/blogengine/2009/5"
elementFormDefault="qualified"
xmlns="http://tempuri.org/blogengine.xsd"
xmlns:mstns="http://tempuri.org/blogengine.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="BlogEngine">
<xs:complexType>
<xs:sequence>
<xs:element name="blogProvider" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="providers" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="add" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="type" type="xs:string" use="required" />

<xs:attribute name="connectionStringName" type="xs:string" use="optional" />

</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="defaultProvider" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
  1. Finally to make your schema work, you will have to add the xmlns attribute to your web.config file which looks like below.
<BlogEngine xmlns="http://schemas.prabir.me/blogengine/2009/5">

custom_webconfig_intellisense.zip (3.65 kb) [Downloads: 203]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

BlogEngine.NET | Visual Studio