.Net, Visual Studio, VS2017

VS 2017 Structure Visualizer

After installation of Visual Studio 2017, you probably noticed some vertical dotted lines.  Many people find them annoying and want to remove them.  At the end at this article I’ll show you how you can disable this feature but first I’d like to tell you how this new feature can be beneficial to you.

It’s not hard to figure out that these lines are lining up with structured code blocks.  It allows you quickly figure out the code scopes.  The biggest benefit you get when you hover over the line.  It allows you easily see namespace, class, method, and other code blocks without the need to scroll.  I’ve been using a lot Ctrl+] to jump between difference braces in Visual Studio.  Now I just need to hover over the line and see the scope of the code at a glance.

StructureVisualizer

If you think you like this feature but don’t use VS 2017 yet, you can install Productivity Power Tools for VS 2015 or VS 2013.

Ideally, you write your code in such manner that each code block can be easily seen on a single screen.  Even if you succeed to write the code nice and concise, the need to read someone else code will arise in your career and this feature might be helpful you.

Disable this feature.

If you still believe that this new feature is not going to help you, then you can disable it by going to Tools > Options > Text Editor and uncheck “Show structure guide lines”.

Disable structure guilde lines

In case you like this feature but you want the guide lines to be less or more prominent you can go Tools > Options > Environment > Fonts and Colors.  In “Display items” select box choose “Structure Guide Lines” option and pick the color that suits you best.

Modify structure guilde lines

I hope you find this article and this new feature useful.

.Net, C#, C# 7

Out Parameters

I’m so happy to see this new, very simple improvement in C# 7.  You probably have to write the code similar to the one below many times:

   int outNum;
   var tryParse = int.TryParse("5", out outNum);

In C# 6 and earlier versions, we had to use two statements.  One to declare a variable and then to call int..TryParse method.  I take pride of having my classes and methods as small as possible. I can save a line with this new feature, no need to declare a variable.

   var tryParse = int.TryParse("5", out int outNum);

In some cases you don’t care about the out variable at all. You just want to know if you can parse string to int or not. In this case, use a single underscore instead the variable name to create a discard.

   if (int.TryParse("5", out _))
   {
      // Some logic
   }

Because we don’t need the declaration of the variable, we can implement a method with an expression body:

   static int ParseOrMyDefalt(string text) =>
      int.TryParse(text, out int value) ? value : 5;

That’s basically it about new out parameter feature. Once again I’m very happy that I don’t need to deal with annoying variable declaration statement.

.Net, C#, C# 7

Underscore Separators

Another new feature of C# 7 is underscore separators.  Now you can put underscore anywhere inside any numeric literal to make long numbers more readable.  And I mean any, you can put it inside regular integer, binary, hex, decimal and many other numeric literal.

In the statement bellow it’s hard to see how many millions / billions the numeric value has.

int milesFromEarthToSun = 92960000;

We can improve it by putting some separators.

int milesFromEarthToSun = 92_960_000;

With new syntax we can clearly see how many million miles from Earth to Sun.

However, you also can misuse this feature and make code less readable. Unfortunately this example is valid:

int loooooongTen = 1___________0;

This new feature plays nicely with another C# 7 feature (binary literal)

   int readableBits = 0b0010_1111_0000_1111;

When using this feature, you need to be aware of some restrictions.  All examples below are invalid:

  • You can’t prepend the literal with an underscore
    int invalidNumber = _2;
  • You can’t add an underscore to the end of the literal
    int invalidNumber = 2_;
  • You can’t insert an underscore before or after the period in a floating point literal
    
   float invalidFloatNumber = 23_.15f;
   decimal invalidDecimalNumber = 23._15m;
  • You can’t put an underscore after the base specifier (0x or 0b) or before the literal suffix
    
   byte invalidHexByte = 0x_A;
   byte invalidBitByte = 0b_1010;
   decimal invalidDecimalNumber = 23.15_m;

I disagree that we are not allowed to put underscore after the base specifier. I wish I could use something like this:

   int whishToBeValidBits = 0b_0010_1111_0000_1111;
.Net, C#, C# 7

Binary Literals

One of the new feature that comes with C# 7 is binary literals.  We had hex digit literal for a long time 0x or 0X prefix.

int hexNum = 0xA; // Prints 10

With C# 7 we now can represent a number in binary format.  To represent number in binary (bit) format you just need to prefix it with 0b or 0B.

int bitNum = 0b1010; // Prints 10

So why do need to know about this syntactic sugar?

  • If you read a code where this syntax is used, you need to understand it.
  • For bitmasks.
  • When implementing protocol with specific bit patterns.

We also can use it in enum.  Some people might agree that it’s more readable. Before C#7 our enum Colors would looks something like that:

enum Colors
{
   Black = 1,
   Red = 2,
   Blue = 4,
   Green = 128
}

That’s how it looks using binary literals:

enum Colors
{
   Black = 0b0001,
   Red = 0b0010,
   Blue = 0b0100,
   Green = 0b10000000
}

I myself probably would use binary literals only if I have to work with bitmask. However, it’s nice to have an extra option.

byte decByte = 60;
byte hexByte = 0x3C;
byte bitByte = 0b00111100;

The last thing I want to mention is that using binary literals doesn’t affect performance at all.

C#

Capitalize only first character. (C#)

Once in a while, you may need need to capitalize only the first character of a word. Like everything else in programming, there’s more than one way to solve this problem. In this post, I’m going to explore three different ways to capitalize the first letter of a word, and then let you know which one I prefer.

1. String manipulation solution.
private string UpperFirst(string text)
{
return char.ToUpper(text[0]) +
((text.Length > 1) ? text.Substring(1).ToLower() : string.Empty);
}

 

This solution is straightforward. First, capitalize the initial character of the text, and then append the rest. Next, we test if our text has more than 1 character. If this is text with multiple characters, we convert the rest of the text to lowercase, in case there are any uppercase letters.

2. LINQ solution.
private string UpperFirst(string format)
{
return format.First().ToString().ToUpper() +
String.Join("", format.Skip(1)).ToLower();
}

 

LINQ solution is also easy to follow and understand. We get the first character, and then we convert it to String (because the char type doesn’t have instance implementation of ToUpper()). Then, like in the previous solution, we append the rest of text.

3. TextInfo.ToTitleCase solution.
private string UpperFirst(string text)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
}

 

This solution is taking advantage of the ToTitleCase method. It looks simple, but it’s not exactly like our two previous solutions. The problem with this solution is that it’s going to capitalize every word in the text.  For example: if your text has the value “hello world”, the result of this solution will be “Hello World” and not “Hello world” as in the two earlier examples. If you need to capitalize every word in your text, use this solution. Otherwise, use one of the earlier solutions.

The best solution for me.

Personally, the 1st solution looks the best. There are two reasons why I think solution #1 is the best:

  1. I believe it’s easier to read, but readability is very subjective.
  2. It performs better. I iterated each solution 1,000,000 times, and the first solution performed the fastest.

Below is the table of my performance test, in case you’re interested. It shows the time in milliseconds for 1,000,000 iterations.

Solution Time
String manipulation

201

LINQ

511

TextInfo.ToTitleCase

361

 

Please let me know if you can think up other implementations for capitalizing letters.

Technorati Tags: ,,,
SystemWrapper

Corrected problem with SystemWrapper in NuGet gallery.

Yesterday, I told the world that SystemWrapper is in NuGet gallery.  However, I didn’t realized that I publish the wrong version that does absolutely nothing.

I just want to let you know that I re-publish the correct version and everything should work fine. 

I originally tested the package on my local machine but I’ve never tested the published one.  It taught me AGAIN that I should not to assume anything.

I hope you’ll forgive for this embarrassing, rookie mistake.

Miscellaneous

From hobbies to a professional.

Most people have hobbies, at least I hope that most people have some other interests beside their primary job.  Some lucky folks can make money doing things they like.  I consider myself a lucky one because if I wasn’t a computer programmer, I would do it in my spare time.  Actually I’m still doing coding in my spare time working on some personal projects which probably will never make me a penny.  However, besides writing computer code I have other hobbies.  I enjoy photography, road cycling, tennis and some other activities at which I always will be just an amateur.

I always admire people who takes their hobbies to the next level and became professional at what they love to do.  One of mine co-workers tremendously enjoys nature photography.  He is making a next step to see if he is good enough to become a pro.  He created a site where people can admire and buy his pictures on canvas.  On his site JustCanvasPrints.com visitors can view beautiful, unique photos from Yosemite National Park, Yellowstone National Park, Death Valley National Park and many other beautiful places.  All photos on his website can be printed on canvas and are available either in color o black and white.

What is missing on his website is a space where people could leave a comment for each picture.  As an artist you probably want to see feedback from others.  Well, may be he’ll add it later.  You cannot do everything at once.

Let’s wish him luck and go check out his site.

MbUnit

Gallio v.3.2.2 resolves problem with CS1685 warning.

I was very pleased when I saw a Yann Trevin’s post about new version of Gallio and MbUnit.  What made me happy about this release is that the team resolved issue with CS1685 warning.  After I downloaded Gallio v3.2.2 and remove my temporary fix that deals with CS1685 warning, I was able to confirm the problem is gone.  If you’re using Gallio / MbUnit, go to Downloads page and get the msi for your system.

.Net, ASP.NET, C#

Detect when another site is unavailable. (404 detection)

A long time ago we used to store our code on punched cards.  Since that time, our development tools improved a lot.  Thanks to more powerful languages and tools, it became easier for us to write code, and as a result, our applications became more and more complex.  In 1986 Fred Brooks predicted exactly that in his article “No Silver Bullet”.  Today, any modern application uses third party libraries or components.  Our web apps need to integrate with other sites to use their services. But what do you do if the third party site is down?

At first, the problem doesn’t seem that difficult, but then I realized that it’s impossible to detect with JavaScript when another site is unavailable. (Please let me know if I’m wrong.)  If it would be possible to do this with client scripting, it would be huge security hole.  Since the release of Netscape Navigator 2.0 in 1996, browsers prevent access to most methods and properties across pages on different sites.  Today, this policy is known as Same Origin Policy.

The solution I came up with is to ping the third party host on the server side before JavaScript is loaded.  If I get a good response, then I proceed with my JavaScript; otherwise, it’s redirected to my error page.

Here’s a sample how you can check if the host available with ASP.NET:

protected void Page_Load(object sender, EventArgs e)
{
    HttpWebResponse response;
    try
    {
        var request = 
            (HttpWebRequest)WebRequest.Create("http://www.someSite.com/camdsa");
        response = request.GetResponse() as HttpWebResponse;
    }
    catch (WebException webException)
    {
        Response.Redirect("ErrorPage.aspx?status=" + webException.Status);
        return;
    }
}

If GetResponse() throws a WebException, it means that something went wrong with our request.  We can figure out what’s wrong by analyzing the WebException Status and Response properties.

kick it on DotNetKicks.com