Skip to content

Comparing then Migrating Database Schema Changes from SQL Server 2008/2012 to a Windows Azure Database

18-Aug-12

Today I discovered an absolute gem, a solution I’ve been hunting for a while actually, that being: the ability to migrate my SQL Server 2012 Express database schema changes to a Windows Azure database from within Visual Studio 2012 automatically (This may work in Visual Studio 2010 as well, I am not sure, but no doubt both Standard/Enterprise and Express editions of SQL Server) and I thought those working with Windows Azure and constantly having to migrate database schema changes across might find it helpful too.

As it stands, I believe there is no particular tool or facilitation or guide built by Microsoft in order to migrate schema changes from your local SQL Server database to Windows Azure without doing it manually. I mean Microsoft wrote this guide, but again, it talks really about one-shot database migrations and not subsequent, iterative schema updates.

It should be said, I am aware of the awesome “SQL Azure Migration Wizard” tool built by the community to bridge this shortcoming, I actually used it to initially import my SQL Server 2012 Express database across to Azure; worked a treat. But again, I do not see this as a practical or efficient way of doing things as you have to import a change script each time.

So let’s get on with it – Disclaimer: If you have found an easier way to do this, feel free to leave a comment on the bottom of this post to help myself and others :)

COMPARE & MIGRATE SQL SERVER SCHEMA UPDATES TO WINDOWS AZURE DATABASE:

  1. With your Visual Studio 2012 project open, click the menu SQL -> Schema Compare -> New Schema Comparison… 
  2. In the left hand drop down stating “Select Source” press and enter the database connection settings of the database containing the updated schema you wish to migrate into your Windows Azure SQL Database.
  3. In the right hand drop down stating “Select Target” press and enter your Windows Azure SQL Database connection settings of which you wish to migrate to.
  4. Press “Compare” on the menu strip.
  5. Wait until compared, review the changes by clicking on each row, you may include and exclude certain DB changes by clicking the checkbox. (Note: some changes, typically the stuff of little importance, such as extended property information will not migrate across to Windows Azure and that’s okay.)
  6. Now the all important part, if you pressed “Update” now to migrate changes across to Windows Azure, it would fail with an error something to the effect of: “A project which specifies SQL Server 2012 as the target platform cannot be published to SQL Azure.” So you must enter the “Options” dialog which is represented by the cog icon, then tick “Allow incompatible platform” (it appears you may have to do this each schema comparison, unless you save the comparison file).
  7. Now press “Update” and watch all your glorious changes, and ONLY your changes be migrated to your Azure database! (You may encounter some warnings in your Error List stating “A project which specifies SQL Server 2008 as the target platform may experience compatibility issues with SQL Azure.“, but that’s okay, I had about 5 schema updates on various tables and all mine went through fine, including foreign key re-assignments and additions, and my columns were placed in the right positions!)
  8. No fuss, no mess. A high-automation solution which is what we want.
So enjoy folks, hope it helps speed up an otherwise tedious task; Personally I think it’s crazy that Microsoft hasn’t got a great tool out-of-the-box and advertised to handle this, considering how hard they are endeavouring to push Windows Azure. Oh well!
Credit to the discovery of the “Allow incompatible platform” setting from the fantastic MSFT guys on MSDN forums.
VN:F [1.9.10_1130]
Rating: 4.0/5 (3 votes cast)
VN:F [1.9.10_1130]
Rating: -1 (from 1 vote)

WPF Form Validation Strategy Without Initial Display Errors, Re-callable ValidForm() and Validation on Submit Button

16-Aug-12

Hi Guys,

Well after the last few months of building a commercial WPF app (and learning a lot along the way!) I’ve been generally delighted with the experience. A few things I feel could be a lot more polished, or a lot more thought out, but thems the breaks and we can only hope to see some improvements by Visual Studio 2012.

One of the trickiest and sadly, largest shortcoming of WPF I found was a trivial way to perform WPF form validation. It can get very complicated.

So I thought I might just post quickly some strategies I have implemented over the last few days and hopefully you guys can find some value in it and won’t need to go hunting yourselves.

I mainly illustrate a simple Username/Password TextBox Login validation scenario and to understand a bit more on how to set that up with the PasswordBoxAssistant class see the original post on this StackOverflow.com article: http://stackoverflow.com/questions/8942259/error-handling-in-wpf-passwordbox

My approach uses the standard IDataErrorInfo class.

Firstly, I put a call to a new method called OnDataUpdated() in each setter of my view-bound property, for instance:

        
        private string username;
        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnDataUpdated();
            }
        }

        private string password;
        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnDataUpdated();
            }
        }

Then inside OnDataUpdated() mark a private field boolean as true indicating data has changed for the first time (FormType was only necessary for my business case):

    private void OnDataUpdated()
    {
       dataChanged = true;
       // .. Any other universal RaisePropertyChanged() events you may want to call to get your UI into sync. Eg. RaisePropertyChanged(() => CanConfirm);
    }

Then in my IDataErrorInfo indexer property I do the following (I split it out so ValidForm() can be called manually to perform form validation too.

    public string this[string columnName]
            {
                get
                {
                    string result = null;
                    if (columnName == "Username")
                    {
                        // If other payment amounts have fully paid for balance, and cash amount has been entered, deny
                        if (!ValidForm(FormType.Step1, columnName))
                            result = "Please enter the username field.";
                    }
                    else if (columnName == "Password")
                    {
                        if (!ValidForm(FormType.Step1, columnName))
                            result = "Please enter the password field.";
                    }
                    return result;
                }
            }
        /// summary>
        /// Test if valid form.
        /// /summary>
        /// param name="formType">Specify which form we should validate./param>
        /// param name="columnName">If ommitted, entire form will be validated./param>
        /// returns>
        private bool ValidForm(FormType formType, string columnName = null)
        {
            // This field is used to denote when data has changed on the form.
            // If data has changed, we know we can activate any form validation.
            // We do not activate the form validation until after a user has typed
            // something in at least.
            if (!dataChanged) return true;
            var errors = false;
            if (formType == FormType.Step1 && ((string.IsNullOrEmpty(columnName) || columnName == "Username") && string.IsNullOrEmpty(Username)))
                errors = true;
            if (formType == FormType.Step1 && ((string.IsNullOrEmpty(columnName) || columnName == "Password") && string.IsNullOrEmpty(Password)))
                errors = true;
            return !errors;
        }

Works beautifully. Validation occuring great and most importantly bridges the gap on a large shortcoming — validation styles ONLY appear once the user commences editing the form.

If you want some extra icing on the cake, you can comment in my RaisePropertyChanged(() => CanConfirm); in the OnDataUpdated() method and bind that to your Confirm Button IsEnabled={Binding CanConfirm} with the associated property:

/// summary>
/// Can the user confirm step 1?
/// /summary>
public bool CanConfirm
{
    get { return ValidForm(FormType.Step1); }
}

and your button will only be enabled when your form is valid too. :)

Enjoy! and best of luck with the behemoth that is WPF.

I don’t have time right now, but I can put a working sample project up on request; just leave me a comment.

VN:F [1.9.10_1130]
Rating: 5.0/5 (2 votes cast)
VN:F [1.9.10_1130]
Rating: 0 (from 0 votes)

My New (Aussie!) Discount Daily Deals Accommodation Startup Business Online – Up to 80% Off Stays, yes truly!

16-Jan-12

Hey guys, sorry this blog has been relatively quiet the last six months or so, but for that period I have been knee deep hard at work involved in a startup venture that a few of my friends and myself have started. So unfortunately no real time for blogging, just a slog of actual programming work! :)

So today I’m proud to announce my new business venture Stay Of The Day! Pretty exciting stuff, we’ve just gone live (well live in respects to our “Coming Soon” page) and have an official site launch on 1 Feb.

So what’s it about?

It’s a discount accommodation daily deals site with a twist whereby you only pay for the accommodation when you stay and you can secure deals for up to 80% off around Australia guaranteed and exclusive (yes! that means you won’t find the deal anywhere else) with a lot of fun thrown in the mix on the site.

Currently we have email subscription live for those early birds who want to follow us, plus we are running a $500K social media giveaway campaign! Very exciting. Simply share our website with a few friends and receive $10 credit to use on the site when we go live for each service you share with!

Anyone in the world is welcome to subscribe and share (and we would really appreciate it!) but on launch we will have only Australian accommodation offerings, so if you are from Australia or travelling to Australia I really urge you to check it out! I would really appreciate it :)  Tell your mums, dads, sisters, pets! Share the links to earn credit! It’s that simple :)

Well that’s as “salsey” as my blog is going to get, back to reality and thanks again for reading :)

Graham

www.stayoftheday.com

 

VN:F [1.9.10_1130]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.10_1130]
Rating: 0 (from 0 votes)

ASP.NET MVC / .NET Learning Videos & Tutorial Resources

06-Jul-11

Hi Guys, I feel terrible I cannot blog as frequently now a days, so busy with so many projects on the go at the moment, including a couple of start-ups I’m working on.  But I wanted to quickly share with you probably the most valuable information I could give you in a short space of time; some awesome video resources on ASP.NET MVC and .NET in general from recent events! I find there is no better way to learn than through visual hands-on sometimes.

  • MIX 11 ASP.NET MVC Videos (Las Vegas, Apr 12 – 14 2011) – Great selection of ASP.NET MVC videos and tons of other awesome HD content on .NET in there! Check it out!
  • mvcConf 2 (Feb 2011) – ASP.NET MVC Conference gaining a lot of popularity and has some amazing content, ALL ON ASP.NET MVC!!! Watch them all and you will be an unstoppable MVC ninja!
  • Check out the full selection of videos from recent events here, so much good content up on MSDN Channel9. Pay particular attention to the MIX 11 selection, PDC and TechEd stuff.

As always, if you are new to ASP.NET MVC, a great place to start is nothing other than www.asp.net/mvc.  Loads of great stuff, we’re up to ASP.NET MVC 3 now and it’s pretty darn awesome. Has links to text tutorials, sample projects and a great selection of videos.

If you want to hear about what happens in the ASP.NET MVC world as it happens, you’ll know doubt hear it from one of these blogs:

  • Scott Guthrie (http://weblogs.asp.net/scottgu, VP for Microsoft Developer Division and manages the teams that build core .NET technologies)
  • Phil Haack (http://www.haacked.com, Senior Program Manager at Microsoft on the ASP.NET team and builds ASP.NET MVC)
  • Scott Hanselman (http://www.hanselman.com, Principal Program Manager for Microsoft and has a lot of great stuff to say, and a lot of jokes as well, check out any of his videos from events in the links above, very, very entertaining with some learning as well :P )
VN:F [1.9.10_1130]
Rating: 4.3/5 (23 votes cast)
VN:F [1.9.10_1130]
Rating: +5 (from 9 votes)

Network / Carrier Unlock Guide for Samsung Galaxy Tab

11-Apr-11

Now for something entirely different to my normal pro-Microsoft .NET scriblings…

I had the painful privileged experience of network unlocking my Android powered Australian Samsung Galaxy Tab today and thought due to the number of steps involved and information all over the place on the net that it might be nice to blog about the procedure in clear easy to follow steps in endeavor to help others that wish to do the same and to speak about any hurdles I encountered and how I overcame them.

This guide has been put together through an amalgamation of tutorials I have found across the internet in attempt to make a simple, streamlined guide in the least amount of steps possible that anyone can follow; it may work for other Android-powered devices such as the Samsung Galaxy S but this is unconfirmed (can anyone from the community confirm?).

As I mentioned, worked a treat for me, with no problems and the particular unlocking strategy I selected will retain your Serial number and contains an easy guide with no hex editing which some others require.

However, with that being said.. Use this tutorial for your Galaxy Tab and Galaxy S at your own risk!

TOOLS REQUIRED

STEPS

  1. Check Network Lock:
    1. You can check network lock by dialling *#7465625# on your device.  If Network Lock is present, this will be set to [ON].
  2. Enable root access on your device:
    1. Download SuperOneClick from the location mentioned in the tools (I am using v1.7 at the time of writing this article)
    2. Ensure USB cable is not plugged in to your computer.
    3. On your device go to Settings->Applications->Development->USB debugging and turn it ON.
    4. Connect USB cable to your computer.
    5. Extract SuperOneClick and run SuperOneClick.exe as Administrator.
    6. Once the program has loaded, press “Root”.
    7. Wait for the operation to perform it’s sequence (30secs – 2 minutes) then your device will have root access!

If the program has stalled at “Waiting for Device” or any other process for too long (>2 minutes) you may have an issue with your Android device driver, or may not be running as Administrator.

Try either rebooting your device or more importantly, and the solution that worked for me, is to install the Android device driver which is available on the JuneFabrics PdaNet page (http://junefabrics.com/android/download.php). I actually installed the whole PdaNet package available here not realising first so try that if you still have problems (http://junefabrics.com/android/download.php).

Once you have done this, try re-performing the steps.

  1. Install Busybox Installer and Super Manager from Android Market (this will be used to perform backup in the next step).
  2. Backup /efs folder to sdcard:
    1. Using Super Manager, enable root access (Settings -> Enable ROOT access. If you find Super Manager locking up when pressing this option, try rebooting device first as root access may not have been properly initialised (this worked for me))
    2. On Super Manager home screen press the icon for “File Explorer”.
    3. Go to root directory and then select the tick on /efs folder.
    4. Press “Copy” [Double page] icon.
    5. Open sdcard directory, and press “Paste” [Clipboard] icon.
    6. Disconnect USB cable, disable USB debugging (Settings->Applications->Development->USB debugging) and reconnect USB cable.
    7. Open your Android device folder in My Computer and copy the efs folder to a safe backup location on your local hard drive and do not delete this folder!
    8. Disconnect USB cable, re-enable USB debugging and reconnect USB cable.
    9. Run the network unlock script via adb.exe:
      1. Whilst your USB cable is plugged in to your computer and you are in USB debugging mode, open a command prompt (PowerShell.exe / cmd.exe) and navigate to the SuperOneClick directory or your Android SDK directory where adb.exe is located.
      2. Run the following commands:
adb.exe shell
su

The following can be pasted directly into the shell:

cd /sdcard
echo "this takes about 45 seconds"
if [ ! -f /sdcard/nv_data.bin.orig ]; then
echo "copying file to /sdcard"
cp /efs/nv_data.bin /sdcard/nv_data.bin.orig
fi
echo -en \\x00 > out0
dd if=nv_data.bin.orig of=out1 bs=1 count=1578089
dd if=nv_data.bin.orig of=out2 bs=1 skip=1578090 count=163
dd if=nv_data.bin.orig of=out3 bs=1 skip=1578254
cat out1 out0 out2 out0 out3 > nv_data.bin.unlocked
rm out0 out1 out2 out3
rm /efs/nv_data.bin
cp nv_data.bin.unlocked /efs/nv_data.bin
rm /efs/nv_data.bin.md5
reboot

Your device is now network unlocked and will reboot!

Ensure your new SIM is plugged in and that you now have Internet access. If you don’t, it is most likely because your APN settings for the carrier are not setup correctly.

For the appropriate settings, refer to the wireless broadband guide issued with your SIM from your carrier or Google “APN setting your_carriers_name_here” and enter these settings in Settings->Wireless->Mobile Networks->Access Point Names.  For more information on this process, or help refer to the carrier/SIM unlock thread here (http://forum.xda-developers.com/showthread.php?t=843323).

I have re-written these steps after the fact, and was really aiming for simplicity; so if I have missed anything out, or you feel this guide can be improved, please leave a comment and I will update it.

Credits to the following sources:

Happy unlocking!
Graham

VN:F [1.9.10_1130]
Rating: 3.6/5 (7 votes cast)
VN:F [1.9.10_1130]
Rating: +3 (from 5 votes)

The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type

03-Sep-10

Are you getting this?

System.InvalidOperationException:
The null value cannot be assigned to a member with type System.Int64 which is a non-nullable value type.

On something like this?

var totalSize = query.Sum(x => x.Size);

This occurs because your LINQ property (in my case “Size”) is not nullable, and needs to be nullable because your Sum() operation could potentially iterate over a list which is empty yielding your LINQ property value to be null.
Of course you can’t Sum() null as we know or the universe would explode, so try this instead:

var totalSize = query.Sum(x => (long?) x.Size);

This may very well just be a LINQ to SQL thing, but I am not sure. Maybe somebody else out there in the wide world web can enlighten me!

Best of luck!

VN:F [1.9.10_1130]
Rating: 4.3/5 (8 votes cast)
VN:F [1.9.10_1130]
Rating: -1 (from 3 votes)

Automatically Infer MVC Validation Rules Based on LINQ to SQL Schema – Sweet!

27-Aug-10

Hey gang, just a quickie today. I have been working recently on setting up server side and client side model validation “by the book” in ASP.NET MVC 2 complete with data annotations and the first question that hit me when I was declaring attributes on my LINQ to SQL partial classes to determine model validation was “hold on, surely there is a way to automagically have MVC infer my validation rules based on my database schema…”, it seemed a little silly to me that I would have to re-declare validation rules on my model classes when I have a perfectly, well-decorated set of rules within SQL Server, not to mention within the LINQ to SQL .dbml designer file, against my database objects. I also felt this was going against the DRY principle which is “Don’t Repeat Yourself”.

So, what if you could avoid the monotonous, not to mention need for duplicated code and have your model automatically validation based on your LINQ to SQL schema? (which in turn was resolved from the database.) and what would you expect it to do? Well we know when we declare VarChar‘s, NVarChar‘s and other text types in the database we specify a length in a fashion of VarChar(100) right? Well, this information serves for what our [StringLength] attributes could be.

The other, and probably more pressing check would be if we could automate our [Required] Attribute so we could determine if the field is required by the user for input. Well, thankfully our LINQ to SQL schema reveals that too; Let’s see how this could come together…

Firstly, the main idea and code skeleton for this approach came from Carl over at “Carl On Development” as he displayed quite an ingenious solution to the problem; His approach was to simply check the actual LINQ to SQL data type of the column of the class in question as a pre-validation check to address the field length problem, once having received the value stored in the brackets of VarChar(100) from the LINQ to SQL model, build a standard StringLengthAttribute class returning this newly sought value, the same as if you were to attribute your property as [StringLength(100)] yourself!

Unfortunately, his text editor appeared to have removed the “<” and “>” signs which made it difficult to determine what generic types he was calling upon in his function. However, after a bit of playing, I worked out what was going on and also then thought this could be taken further, and introduced another test for “Is Null” testing.

Enjoy, and tell me what you think (Remember, as this inherits from the AssociatedValidatorProvider class in the System.Web.Mvc namespace, there is no need to decorate any of your model, or partial model classes with any attributes, meaning no more work is required – the thing will just work once it is registered!):

    public class SchemaValidatorProvider : AssociatedValidatorProvider
    {
        public static readonly string[] TextTypes = new string[] { "char", "varchar", "nchar", "nvarchar" };
        public static readonly string LengthRegex = "[" + string.Join("|", TextTypes) + "]\\((.*)\\)";

        public bool IsNotNull(ColumnAttribute column)
        {
            return !column.CanBeNull;
        }

        public int? ExtractLength(ColumnAttribute column)
        {
            var match = Regex.Match(column.DbType.ToLower(), LengthRegex, RegexOptions.Compiled);
            if (match == null || match.Groups.Count != 2) return null;
            return string.Compare(match.Groups[1].Value.ToLower(), "MAX", true) == 0 ? int.MaxValue : int.Parse(match.Groups[1].Value);
        }

        protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
        {
            var columnAttribute = attributes.OfType().FirstOrDefault();

            if (columnAttribute == null || columnAttribute.DbType == null)
                yield break;

            // Determine max length of column and yield the StringLength attribute if found.
            var maxLength = ExtractLength(columnAttribute);
            if (maxLength.HasValue)
                yield return new StringLengthAttributeAdapter(metadata, context, new StringLengthAttribute(maxLength.Value));

            // Determine if state of column is not null, if so yield Required attribute.
            if (IsNotNull(columnAttribute))
                yield return new RequiredAttributeAdapter(metadata, context, new RequiredAttribute());
        }
    }

Then over in your Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
    {
        ....
        protected void Application_Start()
        {
            ModelValidatorProviders.Providers.Add(new SchemaValidatorProvider());
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
            ...
        }
    }

Look Ma! Nothing required on the model, it just works!

    [MetadataType(typeof(ShareMetadata))]
    public partial class User
    {
        private sealed class UserMetadata
        {
            // [Required] [StringLength(50)] - No longer required!
            [DisplayName("The name")]
            public string Name { get; set; }

            [Range(1, 100)] // Still might be required depending on your business requirements!
            [DisplayName("Cost Per Unit ($)")]
            public decimal UnitCost { get; set; }
        }
    }

What this means is you will not have to declare any “typical” validation rules on your model classes at all, required fields and field length will be completely handled for you automatically without the need for any Data Annotation Attributes!

Hopefully this will cover both validation cases I could think of initially using the in-built, and very extensible ASP.NET MVC validation providers. I would be keen to know if this could be extended further for other checks.

VN:F [1.9.10_1130]
Rating: 4.1/5 (8 votes cast)
VN:F [1.9.10_1130]
Rating: +3 (from 3 votes)

New VS Theme Site + Desert Nights 2008 Theme Updated – ReSharper + VS 2010 Support!

30-Apr-10

Just heard news of a sweet new website dedicated to Theming and Styling Visual Studio, called “StudioStyles” now that’s my kinda site.  Go check it out, tons of themes to choose from if your VS IDE is looking kinda drab or you’re sick of looking at that same old blue and white… :)

I also just updated my own Desert Nights theme variation, “Desert Nights Reloaded”; it’s now available for VS 2010 as well as VS 2008 with ReSharper 5 color coding support! Cool! So go get it, officially from my blog or go check it out on StudioStyles! What are you waiting for !?! :)

Not much else happening in blogger-verse right now, but I will let you know if anything exciting happens…

VN:F [1.9.10_1130]
Rating: 3.9/5 (9 votes cast)
VN:F [1.9.10_1130]
Rating: +3 (from 3 votes)

View Contents of HTTP WCF Message with Message Logging & Service Trace Viewer

15-Apr-10

If you would like to see the contents of your WCF message body packet as understood by the server, you can enable WCF message logging via a few adjustments in your WCF Service Web.config file and by then by using the Microsoft Service Trace Viewer application to view it.

I found best results by creating a directory on your system drive, C:\logs\ and storing your WCF messages in there. Everytime I specified the .svclog file to be in the same directory as where my app was, it wasn’t being created, but that could just be my local system permissions at play.

So all you need to do to enable this is in the Web.config of your WCF Service (Host):

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="Default">
            <filter type="" />
          </add>
          <add name="ServiceModelMessageLoggingListener">
            <filter type="" />
          </add>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="c:\logs\web_messages.svclog" type="System.Diagnostics.XmlWriterTraceListener"
       name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
        <filter type="" />
      </add>
    </sharedListeners>
    <trace autoflush="true" />
  </system.diagnostics>
  
  <system.serviceModel>
    <diagnostics>
      <messageLogging logEntireMessage="true" logMalformedMessages="true"
       logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true"
       maxSizeOfMessageToLog="2147483647" />
    </diagnostics>

Then run the client app and perform your WCF call, a new web_messages.svclog file should have been created which can now be opened and viewed.

The most interesting data will be under the XML and Messages tabs once you have clicked a message to view.

The default view is not bad, but by pressing ALT-3 within the trace viewer application you will enter message view which I feel is better suited for messaging viewing (how profound).

<system.diagnostics>
<sources>
<source name=”System.ServiceModel.MessageLogging” switchValue=”Warning, ActivityTracing”>
<listeners>
<add type=”System.Diagnostics.DefaultTraceListener” name=”Default”>
<filter type=”" />
</add>
<add name=”ServiceModelMessageLoggingListener”>
<filter type=”" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData=”c:\logs\web_messages.svclog” type=”System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″
name=”ServiceModelMessageLoggingListener” traceOutputOptions=”Timestamp”>
<filter type=”" />
</add>
</sharedListeners>
<trace autoflush=”true” />
</system.diagnostics>

<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage=”true” logMalformedMessages=”true”
logMessagesAtServiceLevel=”true” logMessagesAtTransportLevel=”true”
maxSizeOfMessageToLog=”2147483647″ />
</diagnostics>

VN:F [1.9.10_1130]
Rating: 4.3/5 (3 votes cast)
VN:F [1.9.10_1130]
Rating: +1 (from 1 vote)

.Net Enum Values As Bit Flags

13-Apr-10

Every now and then I find myself needing to set multiple values to an enum object and test this later on, synonymously I usually find myself also scouring the net on the best practice on how to set, access and test these enum flags :)

So today I thought I would post a definitive reference I found on the net..

Specify flag-annotated enum:

[Flags]
public enum Column
{
None = 0,
Priority = 1 << 0,
Customer = 1 << 1,
Contract = 1 << 2,
Description = 1 << 3,
Tech = 1 << 4,
Created = 1 << 5,
Scheduled = 1 << 6,
DueDate = 1 << 7,
All = int.MaxValue
};

The [Flags] attribute allows you to do this:

Column MyColumns = Column.Customer | Column.Contract;

To check if contains flag:

if ((MyColumns & Column.Customer) != 0)

To check if has flag or higher:

if (MyColumns >= Column.Customer)

To check if has flag or lower:

if (MyColumns <= Column.Customer)

To set a flag:

MyColumns |= Column.Tech;

To clear a flag:

MyColumns &= ~Column.Tech;

To toggle (flip) a flag:

MyColumns ^= Column.Contract;

To clear all flags:

MyColumns = Column.None;

To set all flags:

MyColumns = Column.All;

To set all flags EXCEPT one or more:

MyColumns = Column.All ^ Column.Tech ^ Column.Status;

Credit to Jeremy Lundy for the comprehensive write up.

VN:F [1.9.10_1130]
Rating: 4.7/5 (13 votes cast)
VN:F [1.9.10_1130]
Rating: +4 (from 6 votes)
My name is Graham O'Neale and I'm a software architect from Gold Coast, Australia. I am an overtime thinker, full time coder and awake part time in the real world. I have a keen interest in software development, particularly in the realm of programming (C#, ASP.NET, ASP.NET MVC, LINQ (2 SQL), Entity Framework, Silverlight, Blend, WCF, WPF) and a keen interest in the cutting edge and innovation. I have a new found love for design patterns, ALT.NET practices and well crafted software architecture. The purpose of this blog is to express any thoughts, findings, tips and gripes along my travels in the wonderful world of coding and technology...