C#: Generate a Random Sequence of Numbers and Letters in a User Defined Pattern and Characters

Here is a quick little snippet of code which uses allows one to create a sequence of numbers and letters, or any character needed, in a sequence defined by the user. Here is the code

Random rn = new Random();
string charsToUse = "AzByCxDwEvFuGtHsIrJqKpLoMnNmOlPkQjRiShTgUfVeWdXcYbZa1234567890";

MatchEvaluator RandomChar = delegate (Match m)
{
    return charsToUse[rn.Next( charsToUse.Length )].ToString();
};

Console.WriteLine( Regex.Replace( "XXXX-XXXX-XXXX-XXXX-XXXX", "X", RandomChar ) );
// Lv2U-jHsa-TUep-NqKa-jlBx
Console.WriteLine( Regex.Replace( "XXXX", "X", RandomChar ) );
 // 8cPD

What is happening is that in the Regex.Replace we specify a pattern by X’s. Anything which is not an X is ignored and left in the result. We specify what characters to use in the string charsToUse and in this case we have A-Za-z0-9 expressed as written out. When we run the Regex.Replace it returns the pattern we specified with the characters we needed.

VS2010: Not Seeing the Obvious – Named Threads in Profile Reports

iStock_000002461629XSmallCall me crazy but I named my kids, I named my pets and heck, yes I even name my threads. Things which are important to me in life are worth naming; right? Thread names for me can be important in debug situations. When one uses the Performance Wizard and chooses to have a Concurrency Visualization profile report, specifically the Threads section the name of a thread is not used.

Historically and in the latest version of Visual Studio 2010 the profile reports ThreadMedo not show the thread names. Why?

Don’t get me wrong on this, Visual Studio Twenty Ten is a great product and light years ahead of all other versions! I look forward to having it share my cube and work computer for eight plus hours a day when it is finally released. But heck a man can dream can he?

Let us take a look at what inspires me to write this diminutive dissertation on a distilled user suggestion…

Premise

One can name threads, simply by, well naming it. Here is a code snippet below:

Thread T1 = new Thread(ThreadOne);

T1.Name = "Jabberwocky";

T1.Start();

Viola our thread is named. I cannot think of another reason for naming a thread except for debug purposes. Hey did someone mention debug?

Jabberwocky

Yep while debugging the nice little Threads window as shown above displays our named thread. But yet the Profile Performance reports do not show it. Are the two groups at Microsoft not talking to each other and sharing technology. ;-)

Heck I even tried a trick to Trojan Horse a name into the profiler (Reference the Microsoft.VisualStudio.Profiler dll located in the install directory at  \Team Tools \Performance Tools\)

Thread t = new Thread(new ParameterizedThreadStart(threadIndex =>{    Microsoft.VisualStudio.Profiler.DataCollection.NameProfile(        "Jabberwocky",        Microsoft.VisualStudio.Profiler.ProfileLevel.Thread,        Microsoft.VisualStudio.Profiler.DataCollection.CurrentId        );

    Console.WriteLine("Hello from thread " + (int)threadIndex);}));

alas to no avail. The report still only shows the type of thread and its generic ID.

Why?

I feel that named threads might give one an edge in debugging race or deadlock conditions in code. This is a great tool which frankly could be made even better by including the actual thread names, if found in the report.

Connect Suggestion

If you find this little diatribe interesting go and put your two cents into the Microsoft Connect issue which I created:

Named Threads: Missing the Obvious on Profile Reports

Thanks for your time and well; taking a second look.

C#: How to Detect if a Workstation has been Locked and Unlocked

Here is a quick little console program which demonstrates how to detect if a computer has been either locked or unlocked using C#.  We simply subscribe to the SessionSwitchEventHandler Delegate for the lock or unlock reasons.

// using Microsoft.Win32;
public class CheckForWorkstationLocking : IDisposable
{
    private SessionSwitchEventHandler sseh;
    void SysEventsCheck( object sender, SessionSwitchEventArgs e )
    {
        switch ( e.Reason )
        {
            case SessionSwitchReason.SessionLock: Console.WriteLine( "Lock Encountered" ); break;
            case SessionSwitchReason.SessionUnlock: Console.WriteLine( "UnLock Encountered" ); break;
        }
    }

    public void Run()
    {
        sseh = new SessionSwitchEventHandler( SysEventsCheck );
        SystemEvents.SessionSwitch += sseh;
    }

    #region IDisposable Members

    public void Dispose()
    {
        SystemEvents.SessionSwitch -= sseh;
    }

    #endregion
}

Here is a the code in a console application code to run it:

CheckForWorkstationLocking workLock = new CheckForWorkstationLocking();

workLock.Run();

Console.WriteLine("Press ESC to exit...");
while ( true )
{
    ConsoleKeyInfo key = Console.ReadKey( true );
    if ( key.Key == ConsoleKey.Escape )
        break;
};

C# Regex Linq: Extract an Html Node with Attributes of Varying Types

iStock_000008717494XSmall

The premise of this article and subsequent code sample is that one has an html node to parse and needs the parsed node’s attributes accessible in a handy fashion. Using Regular Expressions with Linq  we can achieve our goal and examine all attributes of the html node. I will show the steps to take and pitfalls on using other methodology.

Data

<INPUT onblur=google&&google.fade&&google.fade() class=lst title='Google Search' value=TESTING maxLength=2048 size=55 name=q autocomplete='off' init='true'/>

Why Not Use XElement’s Attributes?

Because of the free-form text found in the html the following code throws an exception on the first attribute encountered:

string test = @"<INPUT onblur=google&&google.fade&&google.fade() class=lst title='Google Search' value=TESTING maxLength=2048 size=55 name=q autocomplete='off' init='true'>";

// Fails saying google is unexpected token!
var input = XElement.Parse( test )
                    .Attributes()
                    .Select( vl => new KeyValuePair<string, string>( vl.Name.ToString(), vl.Value.ToString() ) );

foreach ( KeyValuePair<string, string> item in input )
    Console.WriteLine( "Key: {0,15} Value: {1}", item.Key, item.Value );

Step 1: Regex

Our first step is to create a regular expression which can handle the node and its attributes. What is interesting about the below regex pattern is that it uses an if clause to discriminate if the attribute contains the value in quotes, single or double, and will put them into the captures collection.

(?:<)(?<Tag>[^\s/>]+)       # Extract the tag name.
(?![/>])                    # Stop if /> is found
# -- Extract Attributes Key Value Pairs  --

((?:\s+)             # One to many spaces start the attribute
 (?<Key>[^=]+)       # Name/key of the attribute
 (?:=)               # Equals sign needs to be matched, but not captured.

(?([\x22\x27])              # If quotes are found
  (?:[\x22\x27])
  (?<Value>[^\x22\x27]+)    # Place the value into named Capture
  (?:[\x22\x27])
 |                          # Else no quotes
   (?<Value>[^\s/>]*)       # Place the value into named Capture
 )
)+                  # -- One to many attributes found!

The above will find a match on a node, place the tag into the named capture of Tag. Then each attribute will be in two named capture collections of Key Value

Regex Returns A Match…Now What?

We need to extract the items into a Dictionary of key value pairs. The following code works with the name match captures and its indexed captures and extracts all attributes (Note copy code to clipboard or view to get alignment):

var attributes = ( from Match mt in Regex.Matches( node, pattern, RegexOptions.IgnorePatternWhitespace )
                   select new
                   {
                       Name = mt.Groups["Tag"],
                       Attrs = ( from cpKey in mt.Groups["Key"].Captures.Cast<Capture>().Select( ( a, i ) => new { a.Value, i } )
                                 join cpValue in mt.Groups["Value"].Captures.Cast<Capture>().Select( ( b, i ) => new { b.Value, i } ) on cpKey.i equals cpValue.i
                                 select new KeyValuePair<string, string>( cpKey.Value, cpValue.Value ) ).ToDictionary( kvp => kvp.Key, kvp => kvp.Value )
                   } ).First().Attrs;

What the above is doing is enumerating over all the matches, in this case there is only one. Then we work through all the keys in the “Key” captures array and marry them to the “Value” value in that array on a one-to-one basis. Notice how we can index into a joined array via its index thanks to the specialized select which returns the index value. Finally we express those combined items  into a key value pair.

Full Code and Result

string node = @"<INPUT onblur=google&amp;&amp;google.fade&amp;&amp;google.fade() class=lst title='Google Search' value=TESTING maxLength=2048 size=55 name=q autocomplete='off' init='true'/>";
string pattern =@"
(?:<)(?<Tag>[^\s/>]+)       # Extract the tag name.
(?![/>])                    # Stop if /> is found
                     # -- Extract Attributes Key Value Pairs  --

((?:\s+)             # One to many spaces start the attribute
 (?<Key>[^=]+)       # Name/key of the attribute
 (?:=)               # Equals sign needs to be matched, but not captured.

(?([\x22\x27])              # If quotes are found
  (?:[\x22\x27])
  (?<Value>[^\x22\x27]+)    # Place the value into named Capture
  (?:[\x22\x27])
 |                          # Else no quotes
   (?<Value>[^\s/>]*)       # Place the value into named Capture
 )
)+                  # -- One to many attributes found!";

var attributes = ( from Match mt in Regex.Matches( node, pattern, RegexOptions.IgnorePatternWhitespace )
                   select new
                   {
                       Name = mt.Groups["Tag"],
                       Attrs = ( from cpKey in mt.Groups["Key"].Captures.Cast<Capture>().Select( ( a, i ) => new { a.Value, i } )
                                 join cpValue in mt.Groups["Value"].Captures.Cast<Capture>().Select( ( b, i ) => new { b.Value, i } ) on cpKey.i equals cpValue.i
                                 select new KeyValuePair<string, string>( cpKey.Value, cpValue.Value ) ).ToDictionary( kvp => kvp.Key, kvp => kvp.Value )
                   } ).First().Attrs;

foreach ( KeyValuePair<string, string> kvp in attributes )
    Console.WriteLine( "Key {0,15}    Value: {1}", kvp.Key, kvp.Value );

/* Output:
Key          onblur    Value: google&amp;&amp;google.fade&amp;&amp;google.fade()
Key           class    Value: lst
Key           title    Value: Google Search
Key           value    Value: TESTING
Key       maxLength    Value: 2048
Key            size    Value: 55
Key            name    Value: q
Key    autocomplete    Value: off
Key            init    Value: true
*/

Problems One May Encounter When trying to use the Ajax Control Toolkit for the first time.

 

Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "AjaxControlToolkit.Properties.Resources.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed.

System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure "AjaxControlToolkit.Properties.Resources.resources" was correctly embedded or linked into assembly "AjaxControlToolkit" at compile time, or that all the satellite assemblies required are loadable and fully signed.

AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the AjaxScriptManager in System.Web.Ajax.dll, or use the ToolkitScriptManager in AjaxControlToolkit.dll.

The latest incarnation (3.6.097 as of this writing) of the asp.net Ajax Control Toolkit needs to be setup using its script manager and not the standard asp.net Script Manager.

So one way to avoid the above issues is to drag the ToolkitScriptManager (found in the control toolkit) onto the Form tag and then use any other Ajax Controls. Here is an example of it using the TabContainer:

<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager2" runat="server"/>
<div>
    <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1">
        <asp:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1">
            <ContentTemplate><p>Hello</p></ContentTemplate>
        </asp:TabPanel>
        <asp:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2">
        <ContentTemplate><p>Hello2</p></ContentTemplate>
     </asp:TabPanel>
    </asp:TabContainer>
</div>
</form>

C#: Does the String Have Content – My Newest Favorite Extension Method

Everyone knows that one should do two things before using a string in C#. One is to check to see if it is null and the other is to check to see if it actually has content, not just blank. The primary way of doing that is to use the static method on the stringIsNullOrEmpty such as

string txt;

if (string.IsNullOrEmpty( txt ) == false)
{
   // Valid string do something
}

I have religiously been using that string checking paradigm (see my 2007 rants on it here (Is String.IsNullOrEmpty Hazardous to your Code’s health in .Net 2.0/3.0?)) for awhile now.

Issues

But I had two issues with using string.IsNullOrEmpty:

  1. The negative result of the method call (false) is telling me that the string is OK to use. Every so often I would call it without checking for that false condition. Grrr! I only want to do actions on it if it valid, not invalid.
  2. My way of working/thinking is that I type in the string name first and then think of testing it. Visual Studio’s Intellisense doesn’t help me, for I have already typed in the variable. I have to go back and add string.IsNullOrEmpty.

Solution

With the advent of extension methods I can solve both issues by making an extension method of what I want. By giving it a name which suggests a positive result means that the string is viable, I solve #1. By making it an extension method, I solve #2 above because it now shows up in Intellisense! Here is the code written as an extension

/// <summary>
/// Does the string contains text? Same as (IsNullOrEmpty() == false).
/// </summary>
/// <param name="txt">Text to look at.</param>
/// <returns>True if valid and contains text.</returns>
public static bool ContainsText( this string txt )
{
    return string.IsNullOrEmpty( txt ) == false;
}

Because I name it with a C, it shows up in the first set of selections in intellisense. That is a bonus.

Note this works even if the string is null! Give it a try!

Visual Studio 2008 Database Project: Unable to drag multiple SQL Scripts

I am running into this issue with Visual Studio 2008 Team System SP1 database project. It will allow me to drag one script but not multiple. I am publishing this to my blog to investigate, so let me explain.

Scenario

I have a database project with an active connection to the database and a few scripts. My goal is to drag my scripts as shown below to the active instance (a SQL Server 2008 instance to be exact)

Database Target

If I highlight one sql script and drag it to the instance and I get this message:

Single

It works and the script executed after I select yes. Note the text on the dialog, it clearly talks about multiples queries/scripts. Plural!

Problem

The problem arises when I select multiple scripts and drag them. At that point I am not allowed to drop:

Denial

Does anyone reading provide insight? Thanks!

C# Tribal Knowledge: Use of the Conditional Attribute for Conditional Compilation For Object and and Argument Validation during Development

stockxpertcom_id14589271_jpg_013ced4118ce4854e1935aeaa12684ecThis is another one of of my topics which I deem to be Tribal Knowledge type information. For me it seems that such information seems be known by only the privileged few. In this article I present for your reading perusal details on how to handle different state errors found in classes and arguments during debug/development activities. The premise is that such checks for object or argument correctness is only needed for development and not for production level code. By using the Conditional attribute in ones C# code such checks can be utilized for object and state correctness but not be a burden in a production program or web site.

Development State Errors Checking

For example, and yes its a basic example,  say one is writing a database layer and the requirement is that the connection string be be properly filled with with a database name a user name and a password. You happen to know that this code will be reused by others on the development staff and they will most likely fail to provide such values the first time they hook up the code. So you don’t have to go to their desks to hand hold and debug the error, wouldn’t it be nice if the object checked its own state of correctness?

Once working the checks will really become superfluous and will be removed. This scenario speaks to the fact that the user has two options, or two roads to failure, of loading the values. Say it can be done either during construction or after via the exposed properties. Just ripe for someone to forget to do one or the other.

Code Speaks Conditionally

For the code we will create a connection object which checks for the validity, to the best of its ability, of those values before their use, and if a problem exists throw an application exception during development time only.

Here is our code and the highlight lines are related to the state checking:

using System.Diagnostics;

public class ConnectionManager
{
    public string DatabaseName { get; set; }
    public string UserName     { get; set; }
    public string Password     { get; set; }

    public ConnectionManager() { }

    public ConnectionManager( string databaseName, string userName, string password )
    {
        DatabaseName = databaseName; UserName = userName; Password = password;
    }

    public string GenerateConnectionString()
    {
        // This is only called during debug builds and *not compiled*
        ValidateState(); // during Release builds.

        return string.Format( "{0};User={1};Password={2}", DatabaseName, UserName, Password );
    }

    [Conditional( "Debug" )]
    private void ValidateState()
    {
        if ( string.IsNullOrEmpty( DatabaseName ) )
            throw new ApplicationException( "Development Error: DatabaseName Empty" );

        if ( string.IsNullOrEmpty( UserName ) )
            throw new ApplicationException( "Development Error: UserName Empty" );

        if ( string.IsNullOrEmpty( Password ) )
            throw new ApplicationException( "Development Error: Password Empty" );

    }

}

So if this class is instantiated and the proper variables are not setup an application exception is thrown during debug mode only when a call to generate a connection string occurs. The magic is done by the highlighted lines but the second one with Conditional attribute tells the compiler to only use this in debug builds

Summary

Now this example is a bit contrived, but the idea is that if one has unique business state requirements which may need to be met before an object’s operation can be used, this methodology can be used to catch all actions, but not hamper runtime operations. It obviously shouldn’t be used to catch unique runtime scenarios such as user validation, those should be handled directly and possibly not by generating an exception.

Tribal Knowledge: EWS C# Extract Alternate Email Address’ Mailbox

stockxpertcom_id260320_jpg_7150e45f4e023f0d664c8903434549ef This is what I call a Tribal Knowledge (TK) type of  information. TK is something that is obvious to those who work with it, or have been using it for a long time yet to the new person coming along its a mystery. Accessing a different mailbox using Exchange Web Services (EWS) was such an event for me. I had actually tapped Microsoft Premier Support to get this answer but was able to divine it at the last moment.

Why Is This Confusing?

The reason behind this confusion is how one registers a service with Exchange Web Services. Here is a snippet below:

ExchangeService service = new ExchangeService( ExchangeVersion.Exchange2007_SP1 );

service.AutodiscoverUrl( "Omega.Man@MyCompany.com" );

When we pass the email address to Autodiscover we believe that it is registering the account we want to access. Usually when one is developing against EWS they use their mailbox as the target first and will have no problems. (See my article entitled C#: Getting All Emails From Exchange using Exchange Web Services for how process emails from the inbox.)

Once the developer access the inbox and retrieves emails, the next step is to attempt access to a shared mailbox. That inbox is shown in Outlook and the user’s account has access rights to it. So the developer does this and erroneously uses Autodiscover again:

service.AutodiscoverUrl( "SharedMailboxNotPrimaryAccount@MyCompany.com" );

Well it actually works, sort of… the service doesn’t throw an exception, but when on tries to get email, its the primary email inbox that is gotten and not the specified email! The problem is that autodiscover could frankly care less about the who, its only concerned with the @xxxx.com to facilitate its processing. Very disingenuous eh…

Solution

Get the service with the email address as shown above (either one will work actually), but before EWS mail box processing add these lines:

Mailbox mb = new Mailbox( "SharedMailboxNotPrimaryAddress@MyCompany.com" );

FolderId fid1 = new FolderId( WellKnownFolderName.Inbox, mb );

FindFoldersResults findResults = service.FindFolders(
                fid1, // was WellKnownFolderName.Inbox,
                new FolderView( int.MaxValue ) );

That lets EWS know about which mailbox we want to use. It handles the getting of the folder ID (different from the ID you might use in Outlook Interop programming if you got it that way; btw) and all is well.

HTH

Windows 7: Getting SQL Express to Work with Visual Studio

Here are some of the tips and tricks required to get SQL Express working with Visual Studio 2008 under Windows 7.

SQL Management Studio

Why they don’t supply this with the install of Express is beyond me. But you will need it to solve a problem in a future step so I recommend you download it. Microsoft SQL Server Management Studio Express Note check for a newer version than the one at the time of this writing.

Before you actually install it, do the next section first.

User Account Control Not Just For Vista

This situation actually affects most of the older install programs when it comes to the UAC. The user account control will have an install quietly fail an install and provide no warning to the user that it was the UAC. For example if you run the install for SQL Management Studio with the default UAC settings in Windows 7 this is the error you will get:

The installer has encountered an unexpected error installing this package. This may indicated a problem with this package. The error code is 29506.

The UAC will never come up with any warning either.

So change the UAC settings to be minimal (search for UAC in the start bar and select Control Panel –> Change User Account Control Settings) and set to minimal settings.

Install the Management Studio Now.

Connecting to the Database Complains about .Net…WHAT?

Once you attempt to connect to the sql express database VS2008 will complain such as:

Execution of .NET Framework code is disabled.

Set "clr enabled" configuration option and restart the server.

I love this error because it implies you need change Visual Studio’s setting. Oh no, its the SQL Express Server setting. To add insult to injury one cannot use Visual Studio’s SQL editor to execute the change! It has to be done from management express.

Wow…as a new developer that has to be a challenge. Microsoft gives the tools such as express, but makes it impossible to use out of the gate.

To resolve the problem open up SQL Server Management Studio Express, open up the instance of SQL Express and run this command:

EXEC sp_configure 'CLR ENABLED' , '1'
GO
RECONFIGURE
GO
ALTER DATABASE PutYourDatabaseNameHere SET TRUSTWORTHY ON
GO

Once run find Sql Server Configuration Manager in the start program menu and by right clicking the “SQL Server (SQLEXPRESS)” instance restart the service. At that point you should be able to go back to Studio and run the application. HTH