Search This Blog

Tuesday, July 21, 2015

Valuable Tools When Working With Regular Expressions

Update: This tool works well for testing Javascript's Regular Expression implementation. 
Check here for a list of tools for other implementations.

I am posting here links to some highly valuable tools I found for when you are working with regular expressions:

One is a playground/tester where you can literally play with regular expressions, in an extremely user-friendly manner.

The other is a tool for generating string samples based on a regular expression input. This is very handy when need to deal with all sorts of complex regular expressions you did not create, and you are trying to test if they are working or not. (Ex: when testing .xsd schema validations).

The playground/tester is located at http://www.regexr.com.

Features I like the most:
  1. You can hover over any part of the expression and get its meaning/understand what it does - on the fly.
  2. You can save whatever expression you have been playing with, and share them.
  3. It contains a summarized yet easy-to-understand reference for regular expression syntax components.
  4. You can type as many test strings you want, and it automatically highlights every match. It also colors every syntax component, making it easy to identify them in the pattern.
It has been really very handy. Thanks to the developer team for making it available for public use!

The samples generator resides at http://uttool.com/text/regexstr/default.aspx.

If you are interested in a C# implementation of such string samples generator, https://github.com/moodmosaic/Fare can be useful.

There is also a generator from microsoftRex

Regexplained offers a visual explanation of the regular expression. Try it!

Monday, July 20, 2015

Difference between explicit casting and using the "as" operator in C#

He who does not ask, will not learn. I would not learn this, if I did not ask - something else.
Upon raising the following question in StackOverflow, I started devising the ideal solution I would like to see for the problem (in an ideal world, a place I have been inhabiting for the past 30 years, alone).

Then, the person who offered an answer to the question - made a side remark.
Well, it then quickly had me building up a fresh new question :-)
He suggested instead of performing a cast using the "as" operator, I should do it simply with (T).

Example: say x is variable of type "object", and some type T, then I had var z = x as T;
He stated I should have var z = (T) x;

At first I noted, with the characteristic stubbornness - "it's a matter of taste. I think "as" makes the intent clearer". Minutes later, after playing with the solution, I needed to cast a double type. And thus... thankfully, I learned something new :-)
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GenericCaster<string>(12345));
            Console.WriteLine(GenericCaster<object>(new { a = 100, b = "string" }) ?? "null");
            Console.WriteLine(GenericCaster<double>(20.4));
            
            //prints:
            //12345
            //null
            //20.4

            Console.WriteLine(GenericCaster2<string>(12345));
            Console.WriteLine(GenericCaster2<object>(new { a = 100, b = "string" }) ?? "null");
            
            //will not compile -> 20.4 does not comply to the type constraint "T : class"
            //Console.WriteLine(GenericCaster2<double>(20.4));
        }

        static T GenericCaster<T>(object value, T defaultValue = default(T))
        {
            T castedValue;
            try
            {
                castedValue = (T) Convert.ChangeType(value, typeof(T));
            }
            catch (Exception)
            {
                castedValue = defaultValue;
            }

            return castedValue;
        }

        static T GenericCaster2<T>(object value, T defaultValue = default(T)) where T : class
        {
            T castedValue;
            try
            {
                castedValue = Convert.ChangeType(value, typeof(T)) as T;
            }
            catch (Exception)
            {
                castedValue = defaultValue;
            }

            return castedValue;
        }
    }
 
Bottom line: GenericCaster2 will not work with struct types. GenericCaster will.

Wednesday, July 8, 2015

Accessing AppSettings in "unconventional" ways

I just learned 2 things about accessing the AppSettings node in a configuration file in a VS project:
  1. The framework provides a AppSettingsReader, not widespread in the community, that retrieves settings from the AppSettings configuration node, with some fluffing-behind-the-scenes (which I do not know what) Well, about the "fluffing"... question is what sort of fluffing is being done there, indeed... if you are wondering what's the use of a method that asks for the type of a value and nevertheless returns an object instead of a type-casted value... I raised this question here.
  2. Seems you can store app setting keys in whatever language you want. I tried storing in Hebrew and they are all retrieved without problems.
In the end, here is my version of the AppSettingsReader I think the framework should provide:

    public class Utils
    {
        AppSettingsReader _appSettingsReader;

        public Utils()
        {
            _appSettingsReader = new AppSettingsReader();
        }

        public T GetAppSettingValue<T>(string key, T defaultValue = default(T))
        {
            object value = _appSettingsReader.GetValue(key, typeof(T));
            T castedValue;
            try
            {
                castedValue = (T) Convert.ChangeType(value, typeof(T));
            }

            catch (Exception)
            {
                castedValue = defaultValue;
            }

            return castedValue;
        }

        public string GetAppSetting(string key)
        {
            return GetAppSettingValue<string>(key);
        }
    }

Monday, July 6, 2015

Software Architectures Patterns and Styles - Where is the observable pattern implemented in ASP.NET MVC implementation ?

The following material may be a bit out-dated, but I find it thoroughly essential for any developer to understand/be familiar with: Microsoft Architecture Guide.
After studying section Architectural Patterns and Styles, an interesting realization came out of it, that I believe most ASP.NET MVC developers have not thought about it (or are not aware of it):
The MVC pattern, although it relies in the Observable Pattern, in its ASP.NET implementation, does not implement any observable, publish/subscribe behaviors. This asp.net form question and answer summarize the topic.

Thursday, July 2, 2015

.NET Built-In Logging Capabilities

I just learned something nice for when you are writing some logging utilities (if you are stubborn as I am to write your own instead of using out-of-the-box frameworks such as NLog, log4net, etc). Instead of playing with exceptions trace searching for "line number" (that's what I was up to doing...) You can accomplish the same thing in a much more easy and elegant way: From MSDN:
public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output: 
//  message: Something happened. 
//  member name: DoProcessing 
//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs 
//  source line number: 31

Israeli ID Validation Attribute in ASP.NET

ID validation code extracted from Code Oasis
From this site, I learned the algorithm is based on the Luhn Algorithm
public class IsraeliIDAttribute : ValidationAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(name);
        }
 
        public override bool IsValid(object value)
        {
            string id = value as string;
 
            if (!Regex.IsMatch(id, @"^\d{5,9}$"))
                return false;
 
            // number is too short - add leading 0000
            if (id.Length < 9)
            {
                while (id.Length < 9)
                {
                    id = '0' + id;
                }
            }
 
            //validate
            int mone = 0;
            int incNum;
            for (int i = 0; i < 9; i++)
            {
                incNum = Convert.ToInt32(id[i].ToString());
                incNum *= (i % 2) + 1;
                if (incNum > 9)
                    incNum -= 9;
                mone += incNum;
            }
            if (mone % 10 == 0)
                return true;
            else
                return false;
        }
    }
Usage:
public class MyModel
{
    [IsraeliIDAttribute(ErrorMessageResourceName = "InvalidId", ErrorMessageResourceType = typeof(Validations))]
        public String ID { get; set; }
}