Visual Studio Regular Expressions - Search

I'm sure you've all seen the "Use: Regular expressions" option in the Visual Studio search dialog, but maybe you haven't taken advantage of it. You can use this feature to do some pretty powerful search and replace operations in Visual Studio.

I used this feature today and thought I'd share. I had a situation where I was trying to find every  control (label, textblock, button or tabitem) in the XAML of my WPF UI that did not have a localized string assigned to it. I knew that the controls that were localized looked something like the following:

    <TextBlock Text="{x:Static Member=Strings:UserStringTable.LblDescription}"... />
    <Label Content="{x:Static Member=Strings:UserStringTable.LblDescription}"... />
    <TabItem Header="{x:Static Member=Strings:UserStringTable.LblDescription}"... />

(i.e. that they all referenced a static member called Strings:UserStringTable) and those that didn't looked something like this:

    <TextBlock Text="Description:"... />
    <Label Content="Description:"... />
    <TabItem Header="Description"... />

So how can use Visual Studio to find all of those controls (TextBlock, Label, TabItem, Button, etc) with one search string and exclude the items that have already been localized? The answer is regular expressions in Visual Studio.

I know that most WPF controls have at Text, Content, Header or ToolTip attribute for assigning text that should be shown to the user. I also know that localized strings begin with ="{. Knowing that, I can put together a regular expression to find only those controls that need to be localized.

Here's the Visual Studio Search dialog I used to accomplish that search (the regular expression I used is described below--if you're already familiar with how regular expressions work and their syntax, feel free to skip past my diatribe on the breakdown of my regular expression search string):

clip_image001

So what am I telling the search dialog to look for in this regular expression?

( Content| Text| Header)\=\"[^{]

First let's describe the regular expression tokens we're using in this string:

( )

The parenthesis to execute whatever's inside them as a group. This allows me to put multiple search expressions into a single group.

\=

The equal sign "=" is a reserved token in regular expression syntax, so we have to precede it with a "\" to tell the regular expression we are looking for an equal sign in our text. This is also known as escaping the token.

\"

Same deal here, the quote is a reserved token, so we have to escape it as well.

[ ]

These brackets are used to tell Visual Studio that the stuff inside them is a list, and that I want you to search for each character in that list separately. For example, if I had a string that says "This, that and the other thing" and I had a regular expression search string that looks like this "th[iae]" Visual Studio would find "This", "That", "the", "other" and "thing". It would not return the word "and" in the results.

[^ ]

The caret ^ actually has multiple meanings, but inside square brackets it says NOT, or exclude. So sticking with our example above, if my regular expression was "th[^iae]" nothing would be found.

So now let's break down the regular expression I used in the search above. Here's the regular expression again:

( Content| Text| Header)\=\"[^{]

Here's what it says, piece by piece:

( Content| Text| Header)

Here we say we're looking any string that contains one of these string " Content", " Text" or " Header" in them.

\=\"

Any string found with one of the items in the group above should be followed by an equal sign and a quote. Note that we're escaping them because they are reserved tokens.

[^{]

Finally, we want to ignore any string that has a left curly bracket "{" after the equal sign and quote.

So, if I have XAML that had the following controls in it:

    <TextBlock Text="{x:Static Member=Strings:UserStringTable.LblDescription}"... />
    <Label Content="{x:Static Member=Strings:UserStringTable.LblDescription}"... />
    <TabItem Header="{x:Static Member=Strings:UserStringTable.LblDescription}"... />
    <TextBlock Text="Description: "... />
    <Label Content="Description: "... />
    <TabItem Header="Description"... />

The only strings it should find are:

    <TextBlock Text="Description: "... />
    <Label Content="Description: "... />
    <TabItem Header="Description"... />

You can get pretty powerful with regular expressions in Visual Studio, especially when it comes to search and replace.

More information can be found on the web about how to do this. The MDSN documentation for the Visual Studio regular expression syntax can be found at http://msdn.microsoft.com/en-us/library/2k3te2cs(v=vs.80).aspx. The Visual Studio syntax is a modified version of the standard regular expression syntax that most regular expression engines use, especially when it comes to replacing text, but in most cases if you apply what you already know about regular expressions it should work. Not to worry, if you have something wrong in the syntax Visual Studio will let you know in a hurry.


Posted by: Kyle Libbert
Posted on: 2/3/2012 at 1:15 PM
Categories: Visual Studio
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Async CTP: TPL Dataflow - Buffering and Combining Data

In our previous TPL Dataflow post we introduced the concept of linking TPL Dataflow blocks together in a processing chain. The example we used was effective in illustrating the point. It was a simple, yet not very practical example showing how we can link multiple TBL Dataflow blocks into a network for propagating and processing data to get to an end result.

Let's consider another example that illustrates a more practical scenario where we have data coming in from multiple sources that needs to be combined, transformed and then propagated out to an end point such as user interface. But first we'll need introduce two additional TPL dataflow blocks that will help illustrate these concepts. These two blocks are BufferBlock<T> and JoinBlock<T>.

BufferBlock<T> is a dataflow block for buffering data from a source and propagating it out to a target. It receives incoming data from some source and buffers it up as output to be consumed by some other entity down the propagation chain. JoinBlock<Tin, Tout> accepts two inputs and joins them together into tuples, buffering them as output to be consumed by some other entity in the propagation chain. By themselves, BufferBlock<T> and JoinBlock<Tin, Tout> are not very interesting, but when combined with other TPL Dataflow blocks they can be used to create complex dataflow networks for developing robust messaging based applications that process data in an asynchronous and concurrent fashion.

Let's consider a scenario where we have integer data coming in from two different sources that we need to add together and present to a user input. To accomplish this we'll use two BufferBlock<T> blocks representing the two data sources. We'll combine the inputs from the two data sources into tuples using JoinBlock<Tin, Tout> so that they can be added together further down the chain. We'll use a TransformBlock<Tin, Tout> to add the items in each tuple, and finally we will use ActionBlock<T> will present the sum to the console. The dataflow network for this scenario would look something like the diagram show below.

image

The code for this is very straight forward. We'll configure each block, link them together according to the dataflow graph pictured above and then post the data to each of the BufferBlock<T> blocks which in turn will be propagated through the data network where it will be transformed and presented to the console. Here's the code

 

class Program
{
    static void Main(string[] args)
    {
        var buf1 = new BufferBlock<int>();
        var buf2 = new BufferBlock<int>();
        var join = new JoinBlock<int, int>();
 
        var transform = new TransformBlock<Tuple<int, int>, string>(t =>
        {
            return string.Format("{0} + {1} = {2}", t.Item1, t.Item2, t.Item1 + t.Item2);
        });
 
        var action = new ActionBlock<string>(s =>
        {
            Thread.Sleep(500);
            Console.WriteLine(s);
        });
 
        buf1.LinkTo(join.Target1);
        buf2.LinkTo(join.Target2);
        join.LinkTo(transform);
        transform.LinkTo(action);
 
        for (int i = 0; i < 20; i++)
        {
            if (i % 2 == 0)
                buf1.Post(i);
            else
                buf2.Post(i);
        }
 
        Console.WriteLine("Posting Complete!");
        Console.ReadLine();
    }
}
 

Here's the output:

image

As you can see, the data was posted to the buffer blocks immediately, indicated by the Posting Complete message. Then processing kicked in, are buffered data was combined into tuples, transformed and then presented the result to the console.

In this series of posts we introduced several of the concepts being exposed in the next version of the Visual Studio .NET and the .NET Framework. I personally think these are some pretty cool capabilities that we can look forward to. You can start learning about them today by downloading the Async CTP. The examples in these posts will work with Version 3 of the Async CTP released in October 2011 available at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=9983, as well as the September 2011 release of Visual Studio 11 Developer preview available at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27543.


Posted by: Kyle Libbert
Posted on: 2/3/2012 at 12:17 PM
Categories: .NET | Async | Parallel Computing
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Async CTP: TPL Dataflow - Linking Blocks Together

In our previous posts on TPL Dataflow we talked about ActionBlock<T> and TransformBlock<Tin, Tout>, two dataflow blocks exposed in the TPL Dataflow library that allow you to process message based data asynchronously in a parallel manner. These two blocks, in and of themselves, are quite useful, but there are additional blocks, and additional capabilities available in TPL Dataflow that we can take advantage of that you may want to concern yourself with.

One of the most important aspects of the TPL Dataflow library is the ability to link multiple blocks together. Dataflow blocks can be chained together to form arbitrary dataflow networks where the output from one block can be exposed as inputs to other blocks, or where the output from many different blocks needs to be joined into a single output and exposed to one or more blocks further down in the processing chain. There are many scenarios in which this can be useful, such as a stock hit application where data about stocks is coming in from multiple sources, or when acquiring data from a biometric feedback device where you might be collecting data from multiple channels to analyze and report on different aspects of biometric data from a patient such as blood pressure, heart rate or ECG.

Let's take a look out how we can use TPL Dataflow to solve these types of problems. TPL DataFlow has the ability to link the input of a target block to the output of a source block via the ISourceBlock.LinkTo() method that is available on every source block type. Building on the examples from our previous posts where we described ActionBlock<T> and TransformBlock<Tin, Tout>, we'll take advantage of the ISourceBlock.LinkTo() method to link TransformBlock<Tin, Tout> block's output to ActionBlock<T> block's input.

In this example we'll create an ActionBlock<T> that will accept incoming data, sleep briefly and then output the incoming data to the console. We'll also create a TransformBlock<Tin, Tout> that will accept incoming integer data, transform that data by doubling it and then place the transformed data on the output queue for further processing. Finally we'll link the TransformBlock<Tin, Tout> output to the ActionBlock<T> input using the LinkTo() method of the TransformBlock<Tin, Tout> and then post some data. Here's the code:

 

class Program
{
    static void Main(string[] args)
    {
        var action = new ActionBlock<int>(i =>
        {
            Thread.Sleep(500);
            Console.WriteLine(i);
        });
 
        var transform = new TransformBlock<int, int>(i => i * 2);
 
        transform.LinkTo(action);
 
        for (int i = 0; i < 10; i++) transform.Post(i);
 
        Console.WriteLine("Posting Complete!");
        Console.ReadLine();
    }
}
 

Here's the output:

image

As you can see, the data was posted to TransformBlock<Tin, Tout>, multiplied by 2, and then propagated to ActionBlock<T> via the ISourceBlock.LinkTo link where it was presented to the console.

This was a simple to illustrate the concept of linking the output of one block to the input of another in a processing chain. In our next post we'll take this a step further by showing you how we can buffer our output and consume that buffered output further down in the processing chain using the BufferBlock<T> block. We'll also take a look at out we can consume data from multiple sources and combine them using JoinBlock<Tin, Tout> for further processing later in the processing chain.


Posted by: Kyle Libbert
Posted on: 2/3/2012 at 12:08 PM
Categories: .NET | Async | Parallel Computing
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Some Cloud Computing Benefits (Third in a series)

Cloud computing, like any new technology, should make financial sense.  An example of an ideal cloud application is one with minimal use for months followed by huge spikes (e.g. sites that process taxes, yearly stockholder proxy votes, etc.).  This makes sense because of the ability to “dial up or dial down” resources in the cloud.  While this is a specific example, there’s a more general guiding principal behind moving to the cloud.

Ultimately, cloud computing allows IT staff to focus on strategic business issues and systems vs. base infrastructure.  Because of this, when systems need to be upgraded, it makes sense to consider cloud based solutions.

At Intertech, as we look to renew licenses for on-premise servers, we’re doing a compare, contrast of hosting inside our walls vs. hosted.  For most of the off-the-shelf software we use to run our firm, from CRM to our mail server, we’re finding cloud based solutions are more economical.  As noted, they also allow our IT folks to focus on areas that make our firm strategically different (such as our world-class online classroom training infrastructure/solution).  We’re not alone in this thinking. 

Andrew McAfee, of MIT, states the cloud is ideal for IT groups “stretched thin” and the cloud offers an opportunity to pursue new activities “nimbly” and “cost effectively.” For further insights from Mr. McAfee, check out the November Harvard Business Review.


Posted by: Tom Salonek
Posted on: 2/1/2012 at 2:37 PM
Tags:
Categories: Cloud Computing
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Cloud Computing for the CEO and CIO (Second in a series)

Before diving into cloud-related pros and cons of cloud computing, let’s do a quick summary of the three primary cloud computing service offerings:

IAAS:  INFRASTRUCTURE-AS-A-SERVICE.  This is the simplest.  It’s similar to hosting.  In short, it’s one or more servers in the cloud.  The benefit is flexible storage and bandwidth.  IAAS allows outsourcing of the machines and base technology (OS).  The management of what runs on the IAAS is up to you or your IT provider.

PAAS:  PLATFORM-AS-A-SERVICE:  PAAS allows firms to be up-and-running quickly on a platform like Java, .NET, or Python.  With this platform in place, you can quickly provision an application development space for developers.

SAAS:  SOFTWARE-AS-A-SERVICE:  This is the largest, and most mature, of the offerings.  It’s simple to use.  SAAS is software accessed over the web (think gmail, Microsoft 365, or, the granddaddy of SAAS, Salesforce.com).


Posted by: Tom Salonek
Posted on: 1/24/2012 at 12:32 AM
Tags:
Categories: Cloud Computing
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Visual Studio 11 : The ClassView / Solution Explorer Combo Platter

Like many of you, I?ve been tinkering around with the betas for VS 11.  While one of the *big* changes is the deep XAML designer tools (which are in many ways lifted right from Expression Blend), one of the little features I?d like to point out is the enhanced Solution Explorer perspective.

Recall: This part of the IDE (in any version) will list out the current files in a given project, as well as assembly references. For example, in VS 2010, we might find the following:

image

While seeing your files is useful, often times you are more interested in the assemblies namespaces, types and members. Thus, you would normally flip over to the Class View perspective:

image

Under Visual Studio 11, the Solution Explorer has been updated in such a way, that you can get the best of both worlds. Notice that each file now has an option to expand the file to reveal a tree showing all types in the file, and their members:

image

Again, sometimes the little things mean a lot!


Posted by: Andrew Troelsen
Posted on: 1/19/2012 at 1:58 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

.NET Diagnostics: How and Where to Start | Live Recording | JAN VS UG MTG 2012

 

For more Live-Recordings or to attend an upcoming Visual Studio User Group Meeting visit www.VSTSMN.com


Posted by: Intertech
Posted on: 1/19/2012 at 1:22 PM
Tags:
Categories: Visual Studio
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Cloud Computing for the CEO and CIO (First in a series)

Intertech had a record 2011.  Luckily, we hit or exceeded all of our goals except for one.  The goal was around creating custom cloud-based applications.  With all the hype around cloud computing, it left me asking “Why?”

We believe cloud computing is the future of IT.  From creating Microsoft’s course on Azure to national briefings on cloud computing, we’re working to be the best provider of cloud-based development services.  At first, I thought it was our client base.  Turns out, our clients are not alone in their movement to the cloud.

InformationWeek in a 2011 survey stated only 29% of respondents analyzed the impact of the cloud.  Further, Gartner, a leading research firm, predicts:

  • Cloud computing will grow at 19 percent per annum thru 2015 (sounds like a lot)
  • Cloud computing in 2015 will account for < 5% of worldwide IT spending (yet... seems surprisingly small)

So, given the above, why should companies care about the cloud? 

Here are a couple of reasons and examples… leading thought leaders like MIT scientist Andrew McAfee states the economics of building and running a technology infrastructure favors the cloud vs. on-premise computing.  The CIO for the U.S. called for moving a quarter – or $20 billion – of fed IT spending to the cloud.  That’s a heavy bet for the CIO of our country.  As a CEO, have you given much thought to the implications of the cloud?

  • Do you think the cloud will displace you or your department?
  • Because “cloud” is overused, almost like the word “leadership”, are you unsure what “cloud computing” means?
  • Are you concerned about the benefits vs. risks?

If you answered yes to any of the above, my hope is one of my next posts will help.  In part, it’s information from the article, “What Every CEO Needs to Know about the Cloud” by Andrew McAfee, Harvard Business Review (HBR) November 2011.


Posted by: Tom Salonek
Posted on: 1/15/2012 at 2:41 PM
Tags:
Categories: Business | Cloud Computing
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Portable .NET Class Library

Sometimes the little things mean a lot. For example, if you have downloaded the .NET 4.5 Developer Preview, you might have noticed a new *.dll project type named a Portable Class Library:

image

As the name implies, this project type allows you to build a reusable class library which can be consumed by multiple platforms which support the .NET framework. Specifically, this type of library allows you to build logic which can be consumed by a Windows executable, a Silverlight application, Windows Phone 7 and Microsoft Xbox. 

The key is that when you add references to framework libraries, you are only shown a limited subset of assemblies which are guaranteed to run on each target platform. Consider the following screen shot of the ?Add Reference? dialog:

image

You are also able to control which platforms you wish to target via the project?s Properties editor:

image

So, all things considered, this new class library project should make it much simpler and ?fool proof? to build a library which can easily be used across various .NET aware devices. Nice!


Posted by: Andrew Troelsen
Posted on: 1/3/2012 at 2:18 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed

Windows Workflow 4.0–Cache Those Activities

Earlier this year (2011), our project upgraded its 4 workflow activities from Workflow 3.0 to Workflow 4.0 with the promise of increased speed.  However, when we deployed we noticed how slow things got and we were in panic mode.  Thanks to Ron Jacobs timely blog post (http://blogs.msdn.com/b/rjacobs/archive/2011/02/12/wf4-performance-tip-cache-activities.aspx), we were able to solve the problem.  All of our workflow was being instantiated within a WCF web service on each call to a web method.  As Ron mentions in his article, there is a steep price to pay for this.  We ended up creating static variables for the 4 activities and used those to instantiate the WorkflowApplication object in the workflow helper class we wrote.

Here is the declaration in the helper class:

private static Activity _citationDiagram = new WF_Citation();
private static Activity _complaintDiagram = new WF_Complaint();
private static Activity _dwiFormDiagram = new WF_DWIForm();
private static Activity _incidentDiagram = new WF_IncidentReport();

This is how the WorkflowApplication was instantiated:

switch (_workflowType)
{
    case WorkflowType.Complaint:
        _wfDiagram = _complaintDiagram;
        break;
    case WorkflowType.Citation:
        _wfDiagram = _citationDiagram;
        break;
    case WorkflowType.DWIForm:
        _wfDiagram = _dwiFormDiagram;
        break;
    case WorkflowType.IncidentReport:
        _wfDiagram = _incidentDiagram;
        break;
    default:
        throw new Exception("Workflow type not defined.");
}
 
_wfApplication = new WorkflowApplication(_wfDiagram);

The code for this previous to the change was instantiating the Activity each time and since there was a lot of VB compiling to do in our diagrams (among other things), it was expensive.  Creating static variables for the Activity objects saved our project and my neck.


Posted by: Rich Franzmeier
Posted on: 12/29/2011 at 8:51 PM
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Subscribe to this BlogRSS comment feed
Contact Us 651-994-8558 1-800-866-9884
Home | Training | Curriculum | Course Finder | Schedule | Enroll | Twin Cities Java User Group | Consulting | Foundation | Jobs | About Us | Our Story | Press Room | Instructors | President | Map & Directions | Sitemap

Java Training | JSF / Struts / Spring / Hibernate Training | Java Power Tools Training | .NET 4.0 & Visual Studio 2010 Training | .NET 3.5 and Visual Studio 2008 Training | .NET 2.0 and Visual Studio 2003 Training | Prism / MVVM / MEF Training | Microsoft Web Development Training | Cloud Computing Training | Ajax / Web Services / XML Training | Groovy and Grails Training | SQL Server 2008 Training | SQL Server 2005 Training | Mobile Development Training | SharePoint 2010 Training | SharePoint 2007 Training | Agile, Process, Analysis & Design Training | Arch/Design Patterns Training | Microsoft Official Curriculum Training | Web Development Training | Ruby Training | Rational Application Developer (RAD) Training | WebSphere Application Server Training | WebSphere Portal Training | WebLogic Training | Boot Camp Training | Project Management Training | C++ Training | Metro / WinRT / Windows 8 Development Training | Retired

Intertech delivers training on-site and virtually serving cities including Phoenix, AZ | San Francisco, CA | Los Angeles, CA | San Diego, CA | San Jose, CA | Washington, DC | Chicago, IL | Orlando, FL | Boston, MA | Duluth, MN | Minneapolis St. Paul, MN | Rochester, MN | Raleigh-Durham, NC | New York, NY | Philadelphia, PA | Austin, TX | Dallas, TX | Houston, TX | Seattle, WA.