jump to navigation

Custom Attributes with Extension Methods: Resource Key July 4, 2011

Posted by codinglifestyle in C#, CodeProject.
Tags: , , , , ,
add a comment

I picked up this technique in my last job to use a custom attribute to contain a resource key. The biggest benefit was all the enums in the system used this attribute which provided a way to translate that enum to text. Take a look at a sample enum:

public enum Mode
{
    [AttributeResourceKey("lblInvalid")]
    Invalid,
    [AttributeResourceKey("lblReview")]
    Review,
    [AttributeResourceKey("lblCheckout")]
    Checkout,
    [AttributeResourceKey("lblOrdered")]
    Ordered
}

Each enum uses the AttributeResourceKey to specify the resource key defined in the resx file. Combined with an extension method we can extend the enum itself to allow us to execute the following:

public void DoOperation(Mode mode)
{
    Log.Info(GetResourceString(mode.ResourceKey()));
    ...
}

The C++ head in me thinks, “why are we using reflection when a static function in a helper class could contain a switch statement to convert the enum to the resource key?”.  Technically this is sufficient and faster.  However, the C# head in me loves the idea that the enum and the resource key are intimately tied together in the same file. There is no helper function to forget to update.  The penalty of reading an attribute is a small price to pay to keep the enum and resource key together in order to increase overall maintainability.

So the first thing I am going to do is define a simple interface for my custom attributes.

public interface IAttributeValue<T>
{
    T Value { get; }
}

All this interface does is define that the custom attribute class itself will define a property called Value of type T. This will be useful when using the generic method, below, for pulling the attribute. Next we define the custom attribute class itself.

    public sealed class AttributeResourceKey : Attribute, IAttributeValue<string>
    {
        private string _resourceKey;
        public AttributeResourceKey(string resourceKey)
        {
            _resourceKey = resourceKey;
        }

        #region IAttributeValue<string> Members
        public string Value
        {
            get { return _resourceKey; }
        }
        #endregion
    }

Notice how simple the above class is. We have a constructor taking a string and a property called Value which returns said string. Now let’s look at the generic method for pulling the attribute.

    public static class AttributeHelper
    {
        /// <summary>
        /// Given an enum, pull out its attribute (if present)
        /// </summary>
        public static TReturn GetValue<TAttribute, TReturn>(object value)
        where TAttribute: IAttributeValue<TReturn>
        {
            FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
            object[] attribs    = fieldInfo.GetCustomAttributes(typeof(TAttribute), false);
            TReturn returnValue = default(TReturn);

            if (attribs != null && attribs.Length > 0)
                returnValue = ((TAttribute)attribs[0]).Value;

            return returnValue;
        }
    }

The code above is the heart of code. It uses generics so you need only define this code once in a static class. By passing the attribute and return type we can extract our Value defined by IAttributeValue<TReturn>.  Using the where constraint on TAttribute allows the generic method to know this type defines a property called Value of type TReturn.  This exposes the true power of generics as without this constraint the method could only presume TAttribute is nothing more than an object.  This might tempt you to wrongly cast TAttribute in order to access it’s properties inviting an exception only seen at runtime.

Now to define our extension method, to be placed in a common namespace, to extend all enums with the ResourceKey() method.

    public static class EnumerationExtensions
    {
        /// <summary>
        /// Given an enum, pull out its resource key (if present)
        /// </summary>
        public static string ResourceKey(this Enum value)
        {
            return AttributeHelper.GetValue<AttributeResourceKey, string>(value);
        }
    }

Thanks to the generic attribute helper the above extension method looks trivial. We simply use the helper to return the resource key and now we’ve extended all our enums to have this useful property.

Advertisements

Understanding BackgroundWorker and Encapsulating your own Thread Class February 22, 2011

Posted by codinglifestyle in C#, CodeProject, Parallelism.
Tags: , , , , , , ,
add a comment

You may have come across this page if you were searching for any of the following:

  • BackgroundWorker events not firing
  • BackgroundWorker RunWorkerCompleted event not firing
  • BackgroundWorker threads frozen
  • Encapsulate thread class

Yesterday my web page was launching several worker threads and waiting for them to return to amalgamate the results in to a single data set to bind to a grid. Launching several worker threads and waiting for a join is a common pattern. To nicely encapsulate the thread itself I derived a class from BackgroundWorker. BackgroundWorker has many advantages such as using an event model, thread pool, and all the thread plumbing built right in. All you have to do is override OnDoWork and off you go. The RunWorkerCompleted event was used, in conjunction with a lock, to collect the data once the worker thread finished.

Everything looked good but for some reason the event never fired. The problem was that I had gotten myself in to a deadlock scenario. The expectation is that when the event fires the delegate method will run in the context of the thread which fired it. If this were true, this would have allowed my synchronization logic to operate normally and not deadlock. The reality is that BackgroundWorker goes out of its way to run this event in the calling thread’s identity. It did this so when using BackgroundWorker in conjunction with the UI no invoke will be required (an exception will be thrown if a thread tries to touch the UI’s controls requiring you to check InvokeRequired).

When in doubt, use something like this to check the identity of the thread executing the code:

Trace.WriteLine(string.Format(“Thread id {0}”, System.Threading.Thread.CurrentThread.ManagedThreadId));

Once putting the above trace in the code I would clearly see that the identity of my main thread was identical to the thread identity in the RunWorkerCompleted event. Once the code tried to aquire the lock it was all over.

So the solution in my case was not to use the RunWorkerCompleted event. I added an alternative event to my thread class and called that at the end of OnDoWork. The event executed in the context of the thread, as expected, and my synchronization logic worked fine. But I couldn’t help feeling it was a bit of a kludge and pondered whether I should be deriving from BackgroundWorker at all. However, what’s the alternative? There really aren’t other alternatives to BackgroundWorker built in to the framework but it is easy to create your own.  See below:

 /// <summary>
 /// Abstract base class which performs some work and stores it in a data property
 /// </summary>
 /// <typeparam name="T">The type of data this thread will procure</typeparam>
 public abstract class ThreadBase<T>
 {
 #region Public methods
 /// <summary>
 /// Does the work asynchronously and fires the OnComplete event
 /// </summary>
 public void DoWorkAsync()
 {
     DoWorkAsync(null);
 }

 /// <summary>
 /// Does the work asynchronously and fires the OnComplete event
 /// </summary>
 /// <param name="arguement">The arguement object</param>
 public void DoWorkAsync(object arguement)
 {
 ThreadPool.QueueUserWorkItem(DoWorkHelper, arguement);
 }

 /// <summary>
 /// Does the work and populates the Data property
 /// </summary>
 public void DoWork()
 {
 DoWork(null);
 }

 /// <summary>
 /// Does the work and populates the Data property
 /// </summary>
 /// <param name="arguement">The arguement object</param>
 /// <remarks>
 /// Can be called to run syncronously, which doesn't fire the OnComplete event
 /// </remarks>
 public abstract void DoWork(object arguement);
 #endregion

#region Private methods
 private void DoWorkHelper(object arguement)
 {
 DoWork(arguement);
 if (OnComplete != null)
     OnComplete.Invoke(this, Data);
 }
 #endregion

#region Properties
 public T Data { get; protected set; }
 #endregion

#region Events

 /// <summary>
 /// Delegate which is invoked when the thread has completed
 /// </summary>
 /// <param name="thread">The thread.</param>
 /// <param name="data">The data.</param>
 public delegate void ThreadComplete(ThreadBase<T> thread, T data);

 /// <summary>
 /// Occurs when the thread completes.
 /// </summary>
 /// <remarks>This event operates in the context of the thread</remarks>
 public event ThreadComplete OnComplete;
 #endregion
 }

My generic ThreadBase class is a lightweight baseclass substitute for BackgroundWorker providing the flexibility to call it synchronously or asynchronously, a generically typed Data property, and an OnComplete event. The OnComplete will execute in the thread’s context so synchronization of several threads won’t be a problem. Take a look at it in action:

 public class MyThread : ThreadBase<DateTime>
 {
 public override void DoWork(object arguement)
 {
 Trace.WriteLine(string.Format("MyThread thread id {0}", System.Threading.Thread.CurrentThread.ManagedThreadId));

Data = DateTime.Now;
 }
 }

What a nicely encapsulated thread! Below we can see how cleanly a MyThread can be used:

 MyThread thread = new MyThread();
 thread.OnComplete += new ThreadBase<DateTime>.ThreadComplete(thread_OnComplete);
 thread.DoWorkAsync();

 void thread_OnComplete(ThreadBase<DateTime> thread, DateTime data)
 {
 Trace.WriteLine(string.Format("Complete thread id {0}: {1}", Thread.CurrentThread.ManagedThreadId, data));
 }

Then I got to thinking what if I wanted the best of both worlds? Thanks to reflector I found out how BackgroundWorker’s RunWorkerCompleted event executes in the context of the calling thread. My generic ThreadBaseEx class offers two events: OnCompleteByThreadContext and OnCompleteByCallerContext.

 /// <summary>
 /// Abstract base class which performs some work and stores it in a data property
 /// </summary>
 /// <typeparam name="T">The type of data this thread will procure</typeparam>
 public abstract class ThreadBaseEx<T>
 {
 #region Private variables
 private AsyncOperation _asyncOperation;
 private readonly SendOrPostCallback _operationCompleted;
 #endregion

#region Ctor
 public ThreadBaseEx()
 {
 _operationCompleted = new SendOrPostCallback(AsyncOperationCompleted);
 }
 #endregion

#region Public methods
 /// <summary>
 /// Does the work asynchronously and fires the OnComplete event
 /// </summary>
 public void DoWorkAsync()
 {
 DoWorkAsync(null);
 }

 /// <summary>
 /// Does the work asynchronously and fires the OnComplete event
 /// </summary>
 /// <param name="arguement">The arguement object</param>
 public void DoWorkAsync(object arguement)
 {
 _asyncOperation = AsyncOperationManager.CreateOperation(null);
 ThreadPool.QueueUserWorkItem(DoWorkHelper, arguement);
 }

 /// <summary>
 /// Does the work and populates the Data property
 /// </summary>
 public void DoWork()
 {
 DoWork(null);
 }

 /// <summary>
 /// Does the work and populates the Data property
 /// </summary>
 /// <param name="arguement">The arguement object</param>
 /// <remarks>
 /// Can be called to run syncronously, which doesn't fire the OnComplete event
 /// </remarks>
 public abstract void DoWork(object arguement);
 #endregion

#region Private methods
 private void DoWorkHelper(object arguement)
 {
 DoWork(arguement);
 if (OnCompleteByThreadContext != null)
 OnCompleteByThreadContext.Invoke(this, Data);
 _asyncOperation.PostOperationCompleted(this._operationCompleted, arguement);
 }

private void AsyncOperationCompleted(object arg)
 {
 OnCompleteByCallerContext(this, Data);
 }
 #endregion

#region Properties
 public T Data { get; protected set; }
 #endregion

#region Events
 /// <summary>
 /// Delegate which is invoked when the thread has completed
 /// </summary>
 /// <param name="thread">The thread.</param>
 /// <param name="data">The data.</param>
 public delegate void ThreadComplete(ThreadBaseEx<T> thread, T data);

 /// <summary>
 /// Occurs when the thread completes.
 /// </summary>
 /// <remarks>This event operates in the context of the worker thread</remarks>
 public event ThreadComplete OnCompleteByThreadContext;

 /// <summary>
 /// Occurs when the thread completes.
 /// </summary>
 /// <remarks>This event operates in the context of the calling thread</remarks>
public event ThreadComplete OnCompleteByCallerContext;
 #endregion
 }

Your encapsulated thread will be the same as above, but now with two events allowing either scenario, depending on what suits.

ASP.Net Windows Authentication: Authorization by Group January 20, 2011

Posted by codinglifestyle in ASP.NET, C#, CodeProject, Security.
Tags: , , , , , , , ,
4 comments

Often in this line of work it’s the simple things that take the longest time. A seemingly simple question came up yesterday on how to lock access to a customer’s website to a specific Windows group. There are a couple of simple gotchas worth documenting in a relatively simple solution presented below.

First, let’s start with the basics. By default ASP.NET executes code using a fixed account. Assuming you are using IIS 6 or greater, the identity is specified in the application pool. However, if we set impersonation to true ASP.NET assumes the user’s identity. Combined with Windows authentication, our code will run within the context of the user’s Windows identity.

To achieve this, in the web.config we set authentication to Windows and impersonate to true. Now we will have an authenticated Windows user, we next need to focus on authorization or what rights and restrictions apply to that user. Our requirement in this case is simple, if you belong to a specified Windows group you have access, otherwise you do not. When using Windows authentication, roles within ASP.NET translate to Windows groups. To allow a specific Windows group, allow that role within the authorization tag in the web.config. We could add additional lines to allow further roles or users. In this case, we simply want to deny everyone else, so notice the deny users * wildcard below.

Web.config

<system.web>
<authentication mode=Windows/>
<identity impersonate=true/>
<authorization>
<allow roles=BUILTIN\Administrators/>
<deny users=*/>
</authorization>
</system.web>

Here’s a handy tip: When testing use the whoami command. This will show you all the groups the logged in user belongs to which is handy when testing.

If you are making modifications to local or domain groups for the current user (probably your own account for testing) ensure that you see the group information you expect with the whoami /groups command. If you have just added yourself to a test group, remember that you must logout and log back in to see these changes.

Now you could stop here, you’re website is secured. However, if you do the user will get IIS’s rather nasty 401 error page. It would be much nicer to show our own custom error or possibly redirect the user to a registration page of some sort. The problem is we’ve restricted the entire website, so even a harmless error page requires authorization. What we need is an exception, which we can do be adding the snippet below the system.web closing tag.

<location path=AccessDenied.aspx>
<system.web>
<authorization>
<allow users=*/>
</authorization>
</system.web>
</location>

What this has done is specify a specific file to have different authorization requirements to the rest of the website.  Optionally we could have specified a directory where we can place CSS, image files, a masterpage, or other resources we may want to allow access to.  In this example, we are only allowing all users to see the AccessDenied.aspx page.

You might think that using the customErrors section in the web.config would be the last step to redirect the user to the AccessDenied.aspx page. However, IIS has other ideas!  IIS catches the 401 before it ever consults with ASP.Net and therefore ignores your customErrors section for a 401. Use the below workaround in your global.asax.cs to catch the 401 and redirect the user to our error page before IIS has a chance to interfere.

Global.asax.cs

protected void Application_EndRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Response.Status.StartsWith(“401”))
{
HttpContext.Current.Response.ClearContent();
Server.Execute(AccessDenied.aspx);
}
}

If we have further security requirements, we can do further checks any time by getting the IPrincipal from Page.User or HttpContext.Current.User. We could enable a button in our UI with a simple statement such as:

adminButton.Enabled = Page.User.IsInRole(@“domain\domainadmins”);

While the solution seems obvious and elegant, it took a bit of searching and playing to get it to work just right. There are other ways of centrally enforcing security such as Application_AuthenticateRequest in global.asax. However in this case it is far more configurable to take full advantage of the settings available to us in the web.config.

Late binding DataGridView data with BackgroundWorker threads October 18, 2010

Posted by codinglifestyle in C#, Parallelism, Uncategorized, Winform.
Tags: , , ,
1 comment so far

In an increasingly multicore world you may notice your WinForm app never pushes your machine to 100%.  Great, right?  Erm, no.  Winforms are traditionally single threaded applications meaning we typically only tap into 1/2, 1/4, or even 1/8th of our processor’s potential.

I’ve recently been working on a utility containing a DataGridView for displaying work item data from TFS. Some of the column data had to be calculated so when displaying 500+ records the whole app was slowing down considerably. What I wanted was a delayed binding such that the cell would be initially blank, launch a thread, and update itself when the thread returned with the value. It turned out this was pretty easy.

First, use a data entity. You probably don’t have to, but I find having this layer offers an obvious place to add the changes I’ll cover below. The ideal place is in the bound property’s getter. Here you can see that the value is not yet calculated, launch a thread, and return blank or another default value in the meantime.

private int _nWeight = -1;

public int Weight

{

get

{

if (_nWeight < 0)

{

Tfs.GetWeight(Tag, GetWeightComplete);

_nWeight = 0;

}

return _nWeight;

}

}

private void GetWeightComplete(object sender, RunWorkerCompletedEventArgs e)

{

_nWeight = (int)e.Result;

if (Row < FormMain.Instance.Grid.Rows.Count)

FormMain.Instance.Grid.InvalidateRow(Row);

}

The property above represents the weight of the entity to be used in sorting or graphing by importance. Calculating the weight is a time intensive operation and is a great candidate for calculating in a worker thread. Notice a backing store, _nWeight, is used to check if the value has been calculated and also to cache the value. If _nWeight is uncached (-1) we launch the thread and return a default weight of 0 while the thread calculates the actual value. Notice when we call Tfs.GetWeight we pass the delegate, GetWeightComplete, as an argument. This function will ultimately be called when the thread returns.

public static void GetWeight(WorkItem wi, RunWorkerCompletedEventHandler onCompleteEvent)

{

BackgroundWorker worker    = new BackgroundWorker();

worker.DoWork             += new DoWorkEventHandler(GetWeightDoWork);

worker.RunWorkerCompleted += onCompleteEvent;

worker.RunWorkerAsync(wi);

}

private static void GetWeightDoWork(object sender, DoWorkEventArgs e)

{

WorkItem wi = (WorkItem)e.Argument;

int result = 0;

foreach (Revision rev in wi.Revisions)

{

if (rev.Fields[CoreField.ChangedBy].Value.ToString() == wi.Store.TeamFoundationServer.AuthenticatedUserDisplayName)

result += 1;

}

result = Math.Min(result, 10);

e.Result = result;

}

When a call is made to GetWeight you can see it uses the standard System.CompnentModel.BackgroundWorker class to manage the work. This has two main advantages: 1) an easy to use asynchronous event based pattern and 2) uses the thread pool for optimal thread management. Notice the two events, DoWork and RunWorkerCompleted are set before the thread is launched and that we can pass an arguement via RunWorkerAsync. GetWeightDoWork is called when the thread is launched and sets the result to the event arguments.  When we leave this function the RunWorkerCompleted event is called.

Finally, back in the data entity, GetWeightComplete is called when the thread has calculated the value.  The result is taken from the RunWorkercompletedEventArgs and set to the backing store. The form uses the singleton pattern and exposes the grid as a property (see here). This allows the data entity to easily invalidate the row which redraws the row taking the Weight value into account (in my case the weight determined the intensity of a yellow highlight drawn over the row indicating how often the authenticated user appeared in the work item’s revision history).

The user experience when using the above method is truely fantastic.  You get a responsive UI which immediately displays information with calculated information quickly coming in a few seconds later.  The standard binding method of the DataGridView further enhances this experience by only binding the data currently shown to the user.  So if only the first 25 rows are displayed, only those values will be calculated.  As we scroll down to show more rows the DataGridView will calculate only the newly bound rows (saving loads of time for potentially 1000’s of rows never shown).  Good luck unlocking your other cores for a better UI experience.

Welcome Microsoft Delegate! Lambda expressions right this way… July 3, 2010

Posted by codinglifestyle in C#, CodeProject, linq, Uncategorized.
Tags: , , , , ,
add a comment

Delegates are deceptively great.  Without them something as simple as the OnClick event of a button would cease to work.  In a nutshell, they offer a simple way to pass a function as a parameter which in turn can be invoked anywhere, anytime.  Pointers for functions, very useful!

In .NET v2.0 the anonymous delegate was quietly introduced, well at least it slipped my notice.  I read about them at the same time I read about Lambda functions.  I saw them laid bare without the syntactic sugar in all they’re simple glory.  As I was stuck on a .NET v2.0 project I found sugar-free anonymous delegates useful to, say, recursively find all controls of a given Type and execute a function on the matching controls.

More recently, I was working on a robust Windows service responsible for various IO operations.  It was vitally important each file operation (heretofore fileop) had its own comprehensive try/catch block.  As the number of fileops increased the code looked like one huge catch block.

It was clear it would be nice to have just one try/catch block in a static utility class which could catch every IO exception conceivable.  Then I could replace each try/catch block with one-line:

bool isBackedUp = FileUtil.FileOp(_logger, () => File.Copy(latestFilename, backupFilename, true));

Notice the file copy on the other side of the lambda function syntax, () =>, is what is executed in the try block below:

public delegate void FileOperation();

internal static bool FileOp(ILogger logger, FileOperation fileOp)

{

bool success = false;

try

{

fileOp.DynamicInvoke();

success = true;

}

catch (ArgumentException argEx)

{

logger.Error(argEx, “Bad arguement(s) passed”);

}

catch (DirectoryNotFoundException dirEx)

{

logger.Error(dirEx, “The specified path is invalid”);

}

catch (FileNotFoundException fileEx)

{

logger.Error(fileEx, “The specified file was not found”);

}

catch (PathTooLongException pathEx)

{

logger.Error(pathEx, “The specified path, file name, or both exceed the system-defined maximum length”);

}

catch (IOException ioEx)

{

logger.Error(ioEx, “An I/O error has occurred”);

}

catch (NotSupportedException supportEx)

{

logger.Error(supportEx, “The requested operation was not supported”);

}

catch (SecurityException secEx)

{

logger.Error(secEx, “The caller does not have the required permission.”);

}

catch (UnauthorizedAccessException accessEx)

{

logger.Error(accessEx, “The caller does not have the required permission”);

}

catch (Exception ex)

{

logger.Error(ex, “General fileop exception”);

}

return success;

}

Not only was this an elegant way to catch a comprehensive set of exceptions, but the resulting code was much more readable.

Of course we could pass bigger hunks of code and this is fine in moderation.  But the flip-side can mean less readable code when lambda functions (and especially lambda expressions) are used without restraint.  Readability for the whole team is paramount.  After all, too much syntactic sugar will rot your teeth!

The brilliant thing about C# is the mind set of “I’m sure there’s a way to do this” is often rewarded with a little research.

Yet Another VS2010 Overview June 18, 2010

Posted by codinglifestyle in ASP.NET, C#, Parallelism, Visual Studio 2010.
add a comment

Today I attended a mediocre presentation by Paul Fallen which looked stellar compared to the atrocious overview put on at the Galway VS2010 Launch Event.  Paul had the look of a man who had seen these slides many times and glossed over them at speed.  In fairness, he was using the same presentation deck I’ve seen since TechEd 2008.  I think we had all seen several flavours of this overview by this time, so nobody seemed to mind.  Below are the few snippets of information to add to the smorgasbord of other snippets I’ve gleaned from other talks of this nature.

Please click here for more comprehensive posts earlier on VS2010.

Here is the VS2010 Training Kit which was used in the demos.

  • Common Language Runtime
    • Latest version is CLR 4 (to go with .NET 4).
    • Previous version of CLR 2 encompassed .NET 2, 3, 3.5, 3.5SP1
    • Implications
      • App pool .NET Framework version
      • Incompatibilities running CLR frameworks side by side within same process
        • Think 3 COM objects accessing Outlook all using CLR1, 2, and 4
  • Managed Extensibility Framework (MEF)
    • Library in .NET that enables greater reuse of applications and components
  • VS2010 & C# 4.0
    • IDE
      • WPF editor – Ctrl + mouse wheel to zoom.  Handy for presentations
        • Box select (like command prompt selection)
      • Breakpoint labelling, import/export, Intellitrace (covered below)
      • Code navigation improvements (Ctrl + , and Ctrl + – for back)
      • Call Hierarchy
        • Allows you to visualize all calls to and from a selected method, property, or constructor
      • Improved Intellisense
        • Greatly improved javascript intellisense
        • Support for camel case
        • Can toggle (Ctrl + Space) between suggestive and consume first mode (handy for TDD)
      • Test run record, fast forward
      • Better multi-monitor support, docking enhancements
      • Tracking requirements and tasks as work items
    • Better control over ClientID
    • Routing moved out from MVP to general ASP.NET
    • Optional and named parameters
    • Improved website publishing, ClickOnce (see prev. posts)
  • Parallelism
    • Pillars
      • Task Parallel Library (TPL)
        • He didn’t touch at all on the new task concept
      • Parallel LINQ (PLINQ)
        • These are the extension methods to LINQ to turn query operators in to parallel operations.
          • var matches = from person in people.AsParallel()
          •               where person.FirstName == “Bob”
          •               select person;
      • System.Threading significant updates
      • Coordination Data Structures (CDS)
        • Lightweight and scalable thread-safe data structures and synchronization primitives
    • Toolset
      • Debugger: record and visualize threads
      • Visualizer: View multiple stacks
      • IntelliTrace – new capability to record execution, play it backwards and forwards, even email it to another engineer and have them reproduce the problem on their box
    • Other
      • Eventual depreciation of ThreadPool as higher level abstractions layer atop toolkit?
      • Unified cancellation using cancellation token
  • Dynamic Language Runtime (DLR)
    • New feature in CLR 4
    • Major new feature in C# 4 is dynamic type
      • What Linq was to C# 3.5
    • Adds shared dynamic type system, standard hosting model and support to make it easy to generate fast dynamic code
    • Big boost working with COM: type equivalence, embedded interop, managed marshalling
  • Windows Communication Framework (WCF)
    • Service discovery
      • Easier to discover endpoints
      • Imagine an IM chat program or devices that come and go
    • REST support via WCF WebHttp Services
      • Available in the code gallery templates
  •  

    PlaySound: A Better Way to Play Wav Files in C# April 30, 2010

    Posted by codinglifestyle in C#, CodeProject, Uncategorized.
    Tags: , , , , ,
    1 comment so far

    The other day I was whipping up a fun utility which played some wav files.  I was giving this to people who’s desktop us Windows Server 2008 so using the Windows Media Player COM object wasn’t an option and SoundPlayer didn’t seem to work with any of the wav files I had for some reason.

    Back in my C++ days I used to do this all the time with winmm.dll’s PlaySound (and have a piece of freeware which uses this to a great extent).

    Well, once again as a C# programmer I am saved by pinvoke!

    public static class Wav

    {

    [DllImport(“winmm.dll”, SetLastError = true)]

    static extern bool PlaySound(string pszSound, UIntPtr hmod, uint fdwSound);

    [Flags]

    public enum SoundFlags

    {

    /// <summary>play synchronously (default)</summary>

    SND_SYNC = 0x0000,

    /// <summary>play asynchronously</summary>

    SND_ASYNC = 0x0001,

    /// <summary>silence (!default) if sound not found</summary>

    SND_NODEFAULT = 0x0002,

    /// <summary>pszSound points to a memory file</summary>

    SND_MEMORY = 0x0004,

    /// <summary>loop the sound until next sndPlaySound</summary>

    SND_LOOP = 0x0008,

    /// <summary>don’t stop any currently playing sound</summary>

    SND_NOSTOP = 0x0010,

    /// <summary>Stop Playing Wave</summary>

    SND_PURGE = 0x40,

    /// <summary>don’t wait if the driver is busy</summary>

    SND_NOWAIT = 0x00002000,

    /// <summary>name is a registry alias</summary>

    SND_ALIAS = 0x00010000,

    /// <summary>alias is a predefined id</summary>

    SND_ALIAS_ID = 0x00110000,

    /// <summary>name is file name</summary>

    SND_FILENAME = 0x00020000,

    /// <summary>name is resource name or atom</summary>

    SND_RESOURCE = 0x00040004

    }

    public static void Play(string strFileName)

    {

    PlaySound(strFileName, UIntPtr.Zero, (uint)(SoundFlags.SND_FILENAME | SoundFlags.SND_ASYNC));

    }

    }

    Example:

    FileInfo fi = new FileInfo(sFile);

    Wav.Play(fi.FullName);

    CustomValidator and the ValidationSummary Control April 26, 2010

    Posted by codinglifestyle in ASP.NET, jQuery, Uncategorized.
    Tags: ,
    3 comments

    ASP.NET validators can be tricky at times.  What they actually do isn’t particularly hard, but we have all had issues with them or quickly find their limits when they don’t meet our requirements.  The CustomValidator control is very useful for validating outside the constraints of the pre-defined validators: required fields, regular expressions, and the like which all boil down to canned javascript validation.  CustomValidators are brilliant as you can write your own client-side functions and work within the ASP.NET validation framework.  They are also unique in that they allow for server-side validation via an event.

    However, there is a common pitfall when used in combination with the ValidationSummary control.  Normally, I would avoid using ShowMessageBox option as I believe pop-ups are evil.  However, where I work this is the norm and the problem is the CustomValidator’s error isn’t represented in the summary popup. 

    When the ASP.NET validators don’t live up to our requirements we really must not be afraid to poke around Microsoft’s validation javascript.  It contains most of the answers to the questions you read about on the net (to do with ASP.NET validation… it isn’t the new Bible/42).  Quickly we identify the function responsible for showing the pop-up.  ValidationSummaryOnSubmit sounds good, but as the name implies it occurs only on submit.  However my validator failed after submit and now I need the popup to show what errors occurred.  I could see from the script window that this function could be called but programmatically registering the startup script wasn’t working.  So I used a jQuery trick to call the function after the DOM had loaded.

    So drumroll please, there is the information you want to copy and paste in to your CustomValidator event:

    if (!args.IsValid)
    {
    ScriptManager.RegisterStartupScript(this, this.GetType(), “key”, “$(function() { ValidationSummaryOnSubmit(‘MyOptionalValidationGroup’)});”, true);
    }

    Now my server-side validation will bring up the ValidationSummary messagebox.

    Unlock User or Reset Password via Database query – ASP.NET Membership February 13, 2010

    Posted by codinglifestyle in ASP.NET, CodeProject.
    Tags: , , , , , ,
    4 comments

    This morning I was logging in to my website and couldn’t log in.  My personal site uses the out-of-the-box ASP.NET v2 membership and roles.  This took a while to determine what was wrong because my own website didn’t tell me much, using a blanket unsuccessful message for any problem.  This lead me to believe my password was wrong or worse that my site had been hacked and the password changed!

    It turned out I entered the wrong password too many times and locked myself out.  However, my site wasn’t programmed to tell me I was locked out (see here for improvement).  I probably entered the right password loads of times, but couldn’t tell because my account was locked.  Once I figured this out the easiest way to unlock the user was via the SQL query window as my site is deployed on an ISP.  You can unlock programatically, but I wasn’t sure how to via the database directly.  Luckily, a quick look through the sprocs revealed what I was looking for and the day was saved:

    DECLARE @return_value int

    EXEC @return_value = [dbo].[aspnet_Membership_UnlockUser]

    @ApplicationName = N‘applicationName’,

    @UserName = N‘user’

    SELECT ‘Return Value’ = @return_value

    GO

    If you don’t know your application name, the query below can be handy.  If you need to reset your password you can use the information obtained by this query along with the sproc below.  First, create a new user or you can use an existing user with a known password.  Next, execute the query below.

    SELECT au.username, aa.ApplicationName, password, passwordformat, passwordsalt

    FROM aspnet_membership am

    INNER JOIN aspnet_users au

    ON (au.userid = am.userid)

    INNER JOIN aspnet_applications aa

    ON (au.applicationId = aa.applicationid)

    Now that you have a valid password, salt, and password type you can set that password information to the account which needs to be reset.  So take the valid password, salt, and password format and put it in the sproc below along with the application name and user which needs to be reset.

    –Prepare the change date

    DECLARE @changeDate datetime

    set @changeDate = getdate()

    –set the password

    exec aspnet_Membership_setPassword ‘applicationName’,

    ‘user’,

    ‘password’,

    ‘passwordsalt’,

    @changeDate,

    Passwordformat

    Execute.  Now both users have the same password.  Good luck!

    Ref: http://aquesthosting.headtreez.com/doc/b873561c-ab7a-4a8e-9934-cc9366af8a81,http://mitchelsellers.com/Blogs/tabid/54/EntryID/23/Default.aspx, http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.unlockuser.aspx

    Repeaters and Lost Data After Postback (Viewstate) October 8, 2009

    Posted by codinglifestyle in ASP.NET, CodeProject.
    Tags: , ,
    18 comments

    Test question: I have a form which binds data to a Repeater on PageLoad.  The Repeater’s ItemTemplate contains a TextBox and Checkbox.  On postback the data is lost.  What’s wrong?

    You may have found this page if you have been googling the following:

    • repeater postback lost data
    • dynamic control postback viewstate
    • data lost on postback

    The problem is the Repeater is a dynamic control.  If you are binding in the codebehind, which we typically are, you have to realize that the textbox and checkboxes do not existuntil you DataBind().  Keeping that in mind, we should ask ourselves what is the order of execution of ViewState.  I think we can start to formulate our answer to the question above by realizing where I DataBind() and create my controls in relation to the workings of ViewState is why our data is lost on postback.

    So, the answer: PageLoad is the wrong place to bind a Repeater or setup a dynamic control.  It is too late.  ViewState has already tried to resync your controls but they weren’t created yet.

    What about the answer you want?  Stop toying with me and tell me the answer I hear you say.  Try OnInit().  If you bind there you’re controls will exist in time for ViewState to operate normally.

    protected override void OnInit(EventArgs e)

    I would have also accepted Repeaters are the evil frogspawn of Satan and should never be used unless you find peeling off your fingernails with rusty pliers appealing.

    ref: http://weblogs.asp.net/ngur/archive/2004/05/17/133340.aspx, http://aspnet.4guysfromrolla.com/articles/092904-1.aspx