Category Archives: C#

Regex in Visual Studio

If you’re a daily user of Visual Studio like i am, then you’ll appreciate this nice feature I recently actually figured out how to use: backreferences in regular expressions built within search and/or search & replace operations.

Let’s say I have the following code from a VB to C# conversion, that incorrectly uses method parentheses ( ) when it should be using index brackets [ ] .


if ((grid.Items(intCounter) is GridDataItem) &&grid.Items(intCounter).Display)
{
CheckBox chkSelectForAction = (CheckBox)grid.Items(intCounter).FindControl("chkVal");
if (chkSelectForAction.Checked & chkSelectForAction.Visible)
{
ReturnedList.Add(grid.DataKeyValues(grid.Items(intCounter).ItemIndex)("BindID"));
}
}

And now  let’s say this construct of “.Items(val)” is all over the place, and i want to change it to the correct “.Items[val]” construct.  The obvious problem is that for each match of “.Items(val)”  the inner value (val) may be completely different.

Here is where the power of regular expressions and backreferences helps us.

In the Visual Studio “Find & Replace” window, type the following into the “Find What:” box:

Items\({[^\)]+}\)

In the “Replace With: box, type:

Items\[\1\]

Now let’s explain.  In the first “find” regex, we tell it to find the literal “Items” then the character “(”  — using an escape character \( since we don’t mean to open a match expression.  Then we open the backreference block { }.  This tells VS that when a match is found, to store it in the first backreference (which is accessed via \1).  Then we tell it to find 1 or more of any character other than a closing parenthesis “)” — via [^\)] . This is so the regex doesn’t overrun the bounds of our indexer.  Then we close it up with closing the backreference block } and the ending parenthesis literal \).

Now, when each match of “Items(xxx)” is found, it will store xxx into the backreference of \1 (since there will be only one occurance of the “xxx” part in each match.

And in the same execution, it will fire the “Replace with” block, which accesses this backreference, replacing the entire match with Items[xxx].

And that’s it!  You can probably see how powerful this be when you consider global search and replace operations.  The only trick is to try out your new regex on a selection or single page prior to executing it within an entire project or solution (since you can’t “undo” that operation).

Happy regexing!

4 Comments

Filed under .NET, ASP.NET, C#, Regular Expressions

Custom FindControl Implementation (C#) — Part II

Part I of this topic dealt with overriding the basic FindControl method found native to objects inheriting from the System.Web.UI.Control object, which most people find severely lacking for uses other than simple pages/applications.

In this part, I will look at a simple extension from the recursive nature of the custom FindControl implementation that will allow us to find controls by another method: by type. Instead of searching for a single control by it’s string ID, we can scour any controls collection recursively for any controls which are of type X.


        public static ArrayList FindControls(Type type, ControlCollection col)
        {
            ArrayList list = new ArrayList();
            foreach(Control c in col)
            {
                if(c.GetType() == type)
                    list.Add(c);
                else
                    FindControlsRecursive(c, type, ref list);
            }
            return list;
        }

        private static void FindControlsRecursive(Control root, Type type, ref ArrayList list)
        {
            if(root.Controls.Count != 0)
            {
                foreach(Control c in root.Controls)
                {
                    if(c.GetType() == type)
                        list.Add(c);
                    else if (c.HasControls())
                        FindControlsRecursive(c, type, ref list);
                }
            }
        }

As you can see, the implementation of the recursive method is slightly different than the previous version for the single control. The only real difference is the presence of a by ref argument which is a data structure (in this case an ArrayList) to keep track of the results found.

7 Comments

Filed under ASP.NET, C#, Programming

Custom FindControl Implementation (C#)

Anyone who has ever used the native FindControl method built into the System.Web.UI.Page or System.Web.UI.Control classes knows that it pretty much stinks. From my experience using it, the only controls that it can find by name are those that are direct children of the container being searched. This isn’t helpful for most real world ASPX pages which may contain dozens of nested controls and/or third party tools.

So, here’s my own custom version of what FindControl should have been from the beginning.

First, override the FindControl method in your derived control and/or webform base class.


        public override Control FindControl(string id)
        {
            Control bc = null;
            try
            {
                bc = base.FindControl(id);
            }
            catch(HttpException)
            {
                bc = null;
            }
            return (bc != null) ? bc : MyUtility.FindControl(id, this.Controls);
        }

Now write the static utility methods to implement the recursive search if the native FindControl didn’t get what you wanted.


    public class MyUtility
    {
        public static Control FindControl(string id, ControlCollection col)
        {
            foreach (Control c in col)
            {
                Control child = FindControlRecursive(c, id);
                if (child != null)
                    return child;
            }
            return null;
        }

        private static Control FindControlRecursive(Control root, string id)
        {
            if (root.ID != null && root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control rc = FindControlRecursive(c, id);
                if (rc != null)
                    return rc;
            }
            return null;
        }
    }

Voila! Now you have the ability to find controls by name that are nested in the hairiest control structure you can come up with.

Check out Part II of this topic to see how to extend this implementation to find multiple controls by Type.

11 Comments

Filed under ASP.NET, C#, Programming

Using ConvertAll to Imitate Native Covariance/Contravariance in C# Generics

A recent project at work required that we port a relatively large solution from the 1.1 to the 2.0 .NET framework. Overall the conversion went fairly smoothly, with most conflicts being namespace issues with classes that we had in our codebase which conflicted with new classes in the System API.

Once the conversion was completed, our methodology was to start implementing 2.0 specific language features like generics, anonymous methods, etc on an as-need basis or when we were implementing new code. It was during one of these attempts to utilize generics at a base level of our data access layer where I found a slight problem.

The problem was that in our 1.1 version of the code we heavily utilized a cached mechanism using reflection to determine parameterization values on all of our stored procedures. Basically at a core base level the DAL code could determine which return values in a SqlDataReader matched up with properties of our inner data classes (using a combination of custom attributes and some reflection), thus eliminating the need to ever write explicit code for input or output parameters on SQL calls. That is highly simplifying how this works, but in a nutshell that’s the context of this example.

Now, here is a simplified call from a DAL class which is specific to a particular class called “DerivedClass”. This business entity object contains an instance of another class called DerivedClassData whose sole purpose is as a transport for the actual data of that class.


        public ArrayList GetDerivedClasses(params object[] a_params)
        {
            return base.ReadMultipleRecords(
                "STORED_PROC", //SP
                typeof(DerivedClassData), //Type to return
                a_params);
        }

        public ArrayList ReadMultipleRecords(string spName,Type type, params object[] parameters)...

Basically the call passes in the SP name, the type of inner data class expected back from the query and a list of search parameters to give to the SP to limit the results. Inside the ReadMultipleRecords are a series of shared base methods which hammer out the details of how to call the SP, with the parameters given, create instances of the type passed in for returning the results and make sure the columns of the results match with the expected properties of the return type.

The downside to this method is the use of an ArrayList to return data. It was selected because it can be ordered, and it doesn’t care what “type” you fill it with. Inside the BuildRead method the instances are created at runtime based on the type passed in, so the code can literally return any number of hundreds if not thousands of types of data class objects in the ArrayList. As most are aware, this is possible by boxing and unboxing the reference types to the variant object type, which incurs a performance penalty. So let’s look at how we can use generics to speed this up a bit.


        public List<DerivedClass> GetDerivedClasses(params object[] a_params)
        {
            return base.ReadMultipleRecords(
            "STORED_PROC", //SP
            typeof(DerivedClassData), //Type to return
            a_params);
        }

While nice looking, unfortunately it isn’t quite as easy as changing the return type to a strongly typed generic implementation of ArrayList in the List<T> class. The problem lies in that we have to have a return type on the ReadMultipleRecords of type List<BaseData>. This is a strongly typed class, however the inner type T is parent class of our return class DerivedClass. Generics don’t allow covariance and contravariance, thus eliminating our ability to have an implicit conversion between the two in this case.

So, in order to solve this issue there is a dandy method which is implemented as part of the List<T> implementation called ConvertAll which will help us out. All we have to do is create a new instance of the Converter generic class, giving it the base and derived types to convert from and to respectively….as well as the address of a method which will actually perform the explicit cast.


        public List<DerivedClass> GetDerivedClasses(params object[] a_params)
        {
             return base.ReadMultipleRecords(
                  “STORED_PROC”, //SP
                  typeof(DerivedClassData), //Type to return
                  a_params).ConvertAll(new Converter<BaseData, DerivedClassData>(FromBase));
        }

        private static DerivedClassData FromBase(BaseData data)
        {
             return data as DerivedClassData;
        }

        public List<BaseData> ReadMultipleRecords(string spName, Type type, params object[] parameters)...

I’d much rather have generics support contra/co-variance inherently, however this work around isn’t all that bad and basically accomplishes the same thing. In this example any number of method calls to differing stored procedures which return the same type can reuse the same static method for casting, however one converter class will be needed per derived type.

5 Comments

Filed under ASP.NET, C#, General, Programming