Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, May 22, 2010

Substring Extension Method that does not give exception

One of the limitations of the .Net Substring(start,[length]) method is it expects the arguments to be within range otherwise we get ArgumentOutOfRange. This is by design as strings are immutable, a member function doesn't exist. String manipulation is one of the most common activity, and it becomes huge annoyance when your truncate or some other method fails at runtime. You may have to write additional code to guard against range "overreach".

Here is a wonderful extension method (IMHO) that solves your substring overreach issue once for all -- instead of runtime exception, it instead returns the most logical substring based on parameters and substitutes nulls for anything beyond that range -- including an empty string if the whole thing is beyond the range.

Substring(startIndex, handleIndexException)
and Substring(startIndex, length, handleIndexException)

"startIndex" and "length" work just like the original substring. But with handleIndexException enabled(set to TRUE) is where the behavior gets interesting:


  • "startIndex" can be negative or can exceed length of string.
  • "length": when negative is interpreted as take characters from the left. Therefore, Substring(2,-1,true) means start from third position (remember C# count is zero-based), and take one character from the left. See extensive examples below.

    Note, I created another extension method to show nulls. Also I tested it with all possible boundary conditions. Attached are the test results.

         /// 
         /// String Extension for Substring with startIndex, that intelligently handles out of bounds without returning exception
         /// see http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html
         /// 
         /// 
         /// 
         /// 
         /// if set to "true" handles intelligently handles the exception, otherwise works like regular Substring
         public static String Substring(this String val, int startIndex, bool handleIndexException)
         {
             if (handleIndexException)
             {
                 if (string.IsNullOrEmpty(val))
                 {
                     return val;
                 }
                 int instrlength = val.Length;
                 return val.Substring(startIndex < 0 ? 0 : startIndex > (instrlength - 1) ? instrlength : startIndex);
             }
             // ELSE handleIndexException is false so call the base method
             return val.Substring(startIndex);
         }
    
    
    
    /// /// String Extension for Substring with startIndex and Length, that intelligently handles out of bounds without returning exception /// see http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html /// /// /// /// /// /// if set to "true" handles intelligently handles the exception, otherwise works like regular Substring public static String Substring(this String val, int startIndex, int length, bool handleIndexException) { if (handleIndexException) { if (string.IsNullOrEmpty(val)) { return val; } int newfrom, newlth, instrlength = val.Length; if (length < 0) //length is negative { newfrom = startIndex + length; newlth = -1 * length; } else //length is positive { newfrom = startIndex; newlth = length; } if (newfrom + newlth < 0 || newfrom > instrlength - 1) { return string.Empty; } if (newfrom < 0) { newlth = newfrom + newlth; newfrom = 0; } return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom)); } // ELSE handleIndexException is false so call the base method return val.Substring(startIndex, length); } //TEST IT: //Console.WriteLine("-1,3 : " + "abcde".Substring(-1, 3, true).ShowNull()); //....etc... RESULTS from a suite of tests for the string "abcde":
    start,length:result
    ===================
    -1 : abcde
    -0 : abcde
    2 : cde
    4 : e
    5 : <<null>>
    12 : <<null>>
    -1,-1: <<null>>
    -1, 0: <<null>>
    -1, 1: <<null>>
    -1, 3: ab
    -1, 9: abcde
    0,-1: <<null>>
    0,-0: <<null>>
    0, 3: abc
    0, 9: abcde
    2,-3: ab
    2,-2: ab
    2,-1: b
    2,-0: <<null>>
    2, 2: cd
    2, 6: cde
    4,-9: abcd
    4,-4: abcd
    4,-0: <<null>>
    4, 1: e
    4, 4: e
    5,-9: abcde
    5,-5: abcde
    5,-4: bcde
    5,-0: <<null>>
    5, 1: <<null>>
    I hope this helps. I spent several hours first browsing the web, then writing/testing the code. This can be a great time saver!
  • Sunday, April 4, 2010

    ASP.net MVC 2.0 Attribute-based Validations using metadata

    I have been meaning to publish this for a while. This is a terrific shortcut to quickly create the metadata scaffolding from the Data Access Layer (DAL) created from LINQ2SQL. You will need to download and install Expresso, and be a little familiar with the tool, as well as it will help if you know a bit about regular expressions.

    1. Regenerate DAL (I recommend you use SQLMetal).
    2. Copy required tables from designer.cs into Expresso regex editor (Test Mode) "test area"
    3. Simple find "public (?!e|E|.*\().*" (without the quotes). Then Run Match
    (this gets rid of all junk except class name and properties)
    4. Take the Match Results and copy-to-clipboard, them paste back into the "sample text" area (REPLACING the existing text from step 2).

    5. Now we do a regex find/replace in Expresso.
    Go into Design Mode:
    Search String: "public (?!partial)[^ ]+ (.+)"
    Replace String: (copy the entire string without the quotes, but include the carriage return at the end)
    "public object $1 { get; set; }
    "
    Back to Test Mode and click "Replace"

    6. Copy the replaced-text area back into the sample-text (same as step 4)

    7. Finally decorate the class and add braces:
    Go into Design Mode:
    Search String: "public partial class (\w+).*"
    Replace String: (copy and paste the entire block below exactly as shown, without the quotes, and including the carriage return at the end.
    "}
    [Bind(Exclude = "Id")]
    [MetadataType(typeof($1MetaData))]
    public partial class $1{}
    public class $1MetaData
    {
    "
    Back to Test Mode and click "Replace"

    8. That's it! copy the final text into a new visual studio "metadata.cs" in the models. You have nice clean scaffolding to add your validation attributes. The [Bind] attribute is a placeholder.

    Monday, November 16, 2009

    c# LinQ SelectMany

    I was brushing up on my Linq and reading up on "SelectMany", and created an example that I thought I'd share with you. This uses all the 3.5 new features: Lambda expressions, LINQ, implicitly typed arrays and anon types - declared, instantiated and populated on the fly! It can make for an amazingly compact code!
    
    static void Main(string[] args)
    {
        // declare products array which includes categories for each product
        var products = new[] {
                new {name="salon shampoo", price=15.99d, categories = new[]{
                                                     new {name="bath"},
                                                     new {name="luxury"}
                                                    }
                    },
                new {name="soap", price=1.33d, categories = new[]{
                                                     new {name="bath"}
                                                    }
                    },
                new {name="asiago bread", price=5.99d, categories = new[]{
                                                     new {name="luxury"},
                                                     new {name="grocery"}
                                                    }
                    },
                new {name="sugar 1kg", price=1.99d, categories = new[]{
                                                     new {name="grocery"}
                                                    }
                    }
            };
    
    
        // linq query to extract products less than $10 and of category "grocery"
        var groceries = from p in products
                     where p.price < 10D && p.categories.Any(c => c.name == "grocery")
                     select p;
        // Alternatively: "Fluent" syntax is more condensed:
        // var groceries = products.Where(p => p.price < 10D && 
           p.categories.Any(c => c.name == "grocery"));
    
        //now iterate the result to display the selected product    foreach (var product in result)
        {
            Console.Write(string.Format("\r\nProd:{0}, Price:{1} Categories:", product.name, product.price));
            foreach (var category in product.categories)
            {
                Console.Write(category.name + " ");
            }
        }
    
        //however SELECTMANY, can show the collection in a "flattened" list, while repeating parent items
        var allProducts = products.SelectMany(p => p.categories, (p, c) =>
                p.name + ", $" + p.price.ToString() + ", cat=" + c.name);
        Console.WriteLine("All Products:" + string.Join("\r\n", allProducts.ToArray()));
        var grocFlattened = groceries.SelectMany(p=>
          p.categories,(p,c)=>p.name + ", $" + p.price.ToString() + ", cat=" + c.name);
        Console.WriteLine("Groceries:" + string.Join("\r\n", grocFlattened.ToArray()));
      //Groceries:
      // asiago bread, $5.99, cat=luxury
      // asiago bread, $5.99, cat=grocery
      // sugar 1kg, $1.99, cat=grocery
    }
    

    SelectMany is very powerful and cool as it can "flatten" a collection, but otherwise works just like a Select statement.

    Tuesday, June 24, 2008

    Part 1. Power of a Regular Expressions

    Rather than just posting the slides, I decided to do a series of blog posts on the subject - consider it as a intro or tutorial to Regular Expressions.

    What are Regular Expressions?

    Regular Expressions (or RegEx for short) is a technique to shorten coding by using bunch of letters and symbols (metacharacters). Most modern languages support regular expressions. You can use it in code. But where they are really useful is data cleanup, extraction, converting legacy data, grabbing data from the internet, etc. Regular Expressions can be considered as the SQL for freeform text.

    RegExs are avoided by most people (even experienced programmers shy away from it), because they either don't understand it, haven't taken the time to learn it -- or they think that it is sediment left over from the Unix era.

    At the end of this tutorial you will see that, regular expressions can actually be easier and quicker to code. Once you understand how it works, and some of the tools and techniques, you will see how dramatically it can shorten code, and save you a time with coding and debugging. Also, maintenance can actually be easier!

    Here is a terrific example. Today, I was browsing through the prep book for MCTS Exam 70-528, and came across this example for asp.net custom validator control to validate passwords. The password rules are:

    • 6-14 characters,
    • at least one lowercase letter,
    • at least one uppercase letter
    • at least one number

    Here is the conventional method. (Code directly copied from the book, pg 469 with misspelled "argument" and all)

    <script language="javascript" type="text/javascript">
    function ValidatePassword(source, arguements)
    {
    var data = arguements.Value.split('');
    //start by setting false
    arguements.IsValid=false;
    //check length
    if(data.length < 6 || data.length > 14) return;
    //check for uppercase
    var uc = false;
    for(var c in data)
    {
    if(data[c] >= 'A' && data[c] <= 'Z')
    {
    uc=true; break;
    }
    }
    if(!uc) return;
    //check for lowercase
    var lc = false;
    for(var c in data)
    {
    if(data[c] >= 'a' && data[c] <= 'z')
    {
    lc=true; break;
    }
    }
    if(!lc) return;
    //check for numeric
    var num = false;
    for(var c in data)
    {
    if(data[c] >= '0' && data[c] <= '9')
    {
    num=true; break;
    }
    }
    if(!num) return;
    //must be valid
    arguements.IsValid=true;
    }
    </script>

    Now, with the use of regular expressions, we can shorten this into just ONE line of code:
    <script language="javascript" type="text/javascript">
    function ValidatePassword(src, args)
    {
    args.IsValid =
    args.Value.length>=6 && args.Value.length<=14
    && /[a-z]/.test(args.Value) //find a lowercase
    && /[A-Z]/.test(args.Value) //find a uppercase
    && /\d/.test(args.Value) //find a digit
    }
    </script>

    You've got to love the elegance and compactness of this code. I believe it is actually easier to understand and debug - no messy loops and "if" constructs. And it reads exactly like the password rules specification above. Such is the amazing power of regular expressions. Note: "\d" is the character class for identifying a single digit. We could have just as well said "[0-9]".

    In my next post we will look at a few more easy examples and examine the metacharacters.