Powershell fun

Today I´d like to share some of the “fun” facts that I´ve learned after a couple of months developing on Powershell:

  1. A function returns something even if it does not have the “return”.
    For example, the following three methods are equivalent:

    function Hello()
    {
       $test = "Hello World"
       return $test
    }
    
    function Hello()
    {
       $test = "Hello World"
       $test
       return
    }
    function Hello()
    {
       $test = "Hello World"
       $test
    }
    
  2. Be careful when calling another method that returns something if you are not using it, since it will go into the pipe and get retuned as well.

    For example, the following code will return an array with two values, “3” and “Hello world”.

    function Sum([int]$a, [int]$b)
    {
       return $a + $b
    }
    
    function Main()
    {
       Sum 1 2
       return "Hello World"
    }
    
    Main
    
    

    To avoid this, we can either send the output to null (Sum 1 2 | Out-Null) or assign it to some variable ($a = Sum 1 2)

  3. $array -eq $null IS DIFFERENT THAN $null -eq $array
    So yes, that’s right. If we want to check if the variable is $null, we have to do $null -eq $array, otherwise, if the input is a collection of values, it will return the matching values (empty if there are not matching values).

    i.e.:

    
    $array = $null
    $null -eq $array # it returns True
    $array -eq $null # returns nothing
    
    $array = @(1,2,3)
    $array -eq @(1,2,5) # returns @(1,2)
    

More “interesting” things about Powershell coming soon!

Search the content of stored procedures (TSQL)

This is a simple and useful query that I use very frequently. Sometimes it might be interesting to know all the sprocs where a specific field or table is being used, so this query could help us with that.

SELECT name, Object_definition(object_id)
FROM   sys.procedures
WHERE  Object_definition(object_id) LIKE '%text%'

For this example, It will return all the sprocs containing the word “text”.

I also recommend the free tool from RedGate (SQL Search) that allows us to search on sprocs, tables, views, etc. from a nice and visual way.

Thanks!

Associating Enums with strings in C#

How many times have you needed to associate a specific Enum with a different string? How have you solved this? Let’s see an example:

public enum Status
{
    New,
    Pending,
    FileNotFound,
    Processed
}

if we use the ToString() method, it will display “FileNotFound” instead of a nicer “File Not Found”.

One solution could be using reflection! We can just add a Description attribute to those enums that we want to have a different text:

public enum Status
{
    New,
    Pending,
    [Description("File Not Found")]
    FileNotFound,
    Processed
}

And then we would need to add a new method to get the new attribute (I would also recommend to use the extension method for this, read my post Extension Methods in C# for more information)

public static string GetEnumDescription(this Enum value)
{
   var fi = value.GetType().GetField(value.ToString());
   var attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

   if (attributes != null && attributes.Length > 0)
      return attributes[0].Description;

   //if no attribute was specified, then we will return the regular enum.ToString()
   return value.ToString();
}

You would only need to add this method somewhere on your project and that’s it! we could use the description attribute and the method Status.FileNotFound.GetEnumDescription() to get the description, and if there is not description specified, then it will return the string of the enum. Also, we could use the same idea if we support multi-language (indicating the key here instead).

Extension Methods in C#

Today I would like to talk about Extension methods. They allow you to add methods to existing types without having to create a derived class or modifying the original one, but they are called like if they were instance methods.

For example, let’s say you are creating multiple rows into a table in different parts of your code, looking something like this:

var table = new Table();
var row = new Row();
var cell = new Cell { Text = "test1" };
row.Cells.Add(cell);
cell = new Cell { Text = "test2" };
row.Cells.Add(cell);
table.Rows.Add(row);

Wouldn’t be nice to have a simpler method into the Table class, allowing us to do this in a nicer way? However, Table is coming with the .NET framework so how can we add our own method into an existing type? Extension methods would help us with this.

public static class MyExtensionMethods
{
   public static void CreateAndAddCell(this TableRow row, string text)
   {
      row.Cells.Add(new TableCell { Text = text });
   }
} 

Notice the “this” on the first parameter. This is indicating that any object TableRow type will now have the CreateAndAddCell (remember to include “using MyExtensionMethods” in the class where you are going to use it)

Doing this, we would simplify the code we had above to have instead:

var table = new Table();
var row = new Row();
row.CreateAndAddCell("test1");
row.CreateAndAddCell("test2");
table.Rows.Add(row);

This looks nicer than before, but we could still improve it a little bit if we would also add an extension to the Table class using params.

public static class MyExtensionMethods
{
   public static void CreateRowWithColumns(this Table table, params string[] texts)
   {
      var row = new TableRow();
      foreach (var text in texts)
      {
         row.CreateAndAddCell(text);
      }
      table.Rows.Add(row);
   }

   public static void CreateAndAddCell(this TableRow row, string text)
   {
      row.Cells.Add(new TableCell { Text = text });
   }
} 

Doing this, we could change our previous code to a cleaner one:

var table = new Table();
table.CreateRowWithColumns("test1", "test2");

Great difference, isn’t it? Now we could re-use this code any time that we need to create a Table with text columns! I hope you found it interesting!

Here you have the fiddle in case you want to play around:

For more information: https://msdn.microsoft.com/en-CA/library/bb383977.aspx

Angular JS

Lately I’ve been working with AngularJS and .NET Web API, and I found it has a great potential so I thought about sharing something about it.

For those who doesn’t know what AngularJS is, It is an open-source Javascript framework maintained by Google that it is becoming very popular due to its flexibility to create pages very quickly, easier to test and with a more object-oriented design.

In case you want to learn about it, there is a great webpage to learn AngularJS that will also allow you to practice and solve the exercises throw the course. Enjoy!

http://campus.codeschool.com/courses/shaping-up-with-angular-js/contents

C# Conversion Operators

First of all, sorry I haven¬¥t be able to write any post for a while. Today I am going to talk about the implicit and explicit operators. I cannot believe that I’ve been using C# for so many years and I had not idea about those operators until a few months ago, so I thought that someone could find them useful as well.

We know that C# has simple type conversions (convert int to decimal, int to string, etc.), but, what If we want to convert our own class to another type? Then we could use the operators, allowing us to have simple casts (or not even using casts at all) between different objects.

Below you can find an example with the explicit operator. In case we change the word “explicit” with “implicit”, then we would also be able to convert our object using:
MyNumber number = text; //no cast needed.

Anyway, go to the fiddle and feel free to play around and see what you could do!

[iframe src=”https://dotnetfiddle.net/Widget/lV3mlx” width=”100%” height=”900″]
More Info at: http://msdn.microsoft.com/en-us/library/85w54y0a.aspx
Also, in case the fiddle didn’t load you can also find it here: https://dotnetfiddle.net/lV3mlx

LeetCode OJ

http://oj.leetcode.com/

This is another cool webpage that I have been using for a couple of weeks. It helps you to be prepared for technical interviews but I do it for fun, I like the challenge about solving some of the problems and then discuss about them on the forum and try to find the most efficient way, and it keeps my mind active!!

The cool thing about this is that you can program on C++, Java or Phyton and just submit your code into the web so it will be compiled and it will run some tests that will verify that your solution is correct (and also the time that it took to run it). It has more than 140 problems, try it and pick one!

http://oj.leetcode.com/

CHECK constraint does not work if using UDF

We were having a bug a few days ago at work. It looked like somehow, we had some values in the database that they shouldn’t have been there at all due to our CHECK. After a while trying to find out what happened and how the values could be introduced, I started debugging the CHECK. When inserting, the ‘error’ would be displayed, however, when I tried to UPDATE the row… wow!! it looks like the row was perfectly updated, even though the CHECK shouldn’t allow it.

I fixed it using one of the workarounds, passing by parameter ALL the fields that we will need to check, even if they are not being used in the UDF. This could have been also fixed using a trigger. However, passing the column worked ok for me.

Example about how I fixed my code: Continue reading to see the example!

Coalesce

Yesterday, while I was answering some questions on “stackoverflow.com”, someone talked about ‘coalesce’ and I had not idea about it. I was always using ISNULL, however, after reading about it, it looks like it can have some advantages.

COALESCE is a shortcut for the CASE expression, but only when we compare it with NOT NULL.

CASE
   WHEN (expression1 IS NOT NULL) THEN expression1
   WHEN (expression2 IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END

NULL is also a shortcut, but it will only allow one expression instead.
The other difference is the type of data that returns. ISNULL will return the type of the first data type, however COALESCE will return the highest data type precedence.

It has some other differences that are very well explained on this webpage http://sqlmag.com/t-sql/coalesce-vs-isnull.

Practice. Continue reading for some practice

MaxLength Multiline textbox

When using in ASP a textbox in mode multiline, the MaxLenght property will not work.

<asp:TextBox id="myTextBox" TextMode="multiline" runat="server" MaxLenght="250" />

So if we need to delimiter the number of characters, we can do it using different ways.

  • We can create a new web control inheriting from the Textbox class, and add some code to the render.
    namespace MyApp.Controls
    {
       public class MyTextBox : TextBox
       {
          protected override void Render(HtmlTextWriter writer) {     
             if (this.TextMode == TextBoxMode.MultiLine  && this.MaxLength > 0)     
             {        
                writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this.MaxLength.ToString());     
             }      
             base.Render(writer); 
          }
       }
    }
    
    
    <%@ Register TagPrefix="M" Namespace="MyApp.Controls" Assembly="MyApp" %>
    <M:MyTextBox id="myTextBox" TextMode="multiline" runat="server" MaxLenght="250" />

    It worked great. I started testing it in different browsers and also copying-pasting some text into the multiline textbox to be sure that it was also working for that case. However, it didn’t work for IE (when pasting the text it would allow more characters).

  • This is the option that I finally used because it worked for all the browsers (IE, Firefox and Chrome were the ones I tested it), and it also worked when pasting text or introducing text manually.
    For my case, I used it from .cs so I could add my variables and render it, however, you might be able to use it in your .js or .ascx file instead (with jquery)

    1. Add your javascript class anywhere you want to (your .js file or .ascx)

    <script>
    function TextAreaCountDown(obj, maxChars, charCount) {
       charCount++;
       chars = $(obj).val().length;
    
       //if lenght is greater than the maximum, we will take only the first maxChar characters.
       if (chars > maxChars) {
           $(obj).val($(obj).val().substring(0, maxChars));
       }
    };
    </script>
    

    2. Call to the previous method in the keyup and change events. we Will also need to include some attributes to keep the count and the maximum.

    $(document).ready(function(){
       $("[id*='myTextBox']").attr('maxChars','" + myTextBox.MaxLength + "');
       $("[id*='myTextBox']").attr('charCount','0');
    			
       $("[id*='myTextBox']").keyup(function(e) { 
          TextAreaCountDown(this, $(this).attr('maxChars'), $(this).attr('charCount')); 
       });
       $("[id*='myTextBox']").change(function(e) { 
          TextAreaCountDown(this, $(this).attr('maxChars'), $(this).attr('charCount')); 
       });
    });
    
    

NOTE: I haven’t tested this code so let me know if it’s not compiling…