Programming

  • Zip File Classes Finally Available in .Net 4.5

    Right now .Net 4.5 is still in beta, but I noticed something that will make developers who must interact with zip files happy: .Net 4.5 will have native support for dealing with zip files. Up until now, the System.IO.Compression namespace only had support for GZipStream and DeflateStream.

    I, like many other developers, have been using the fantastic SharpZipLib library, but I don’t like to have dependencies in my projects if I don’t have to. In order to iterate through a zip file and list its contents while extracting the code looks something like this (SharpZipLib has a lot of one-liners to allow for extracting with events as well, but bear with me):

    private static void ExtractSharp(string zipFile, string extractionLocationSharp)
    {
        Console.WriteLine("Extracting with SharpZipLib");
        Console.WriteLine();
    
        using (var archive = new ZipFile(zipFile))
        {
            int readCount;
            byte[] buffer = new byte[4096];
    
            foreach (ZipEntry entry in archive)
            {
                Console.WriteLine("Name: {0}, Size: {1}", entry.Name, entry.Size);
    
                var extractedPath = Path.Combine(extractionLocationSharp, entry.Name);
                if (entry.IsDirectory)
                {
                    Directory.CreateDirectory(extractedPath);
                }
                else if (entry.IsFile)
                {
                    using (var zipStream = archive.GetInputStream(entry))
                    {
                        using (var outputStream = new FileStream(extractedPath, FileMode.CreateNew))
                        {
                            while ((readCount = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                outputStream.Write(buffer, 0, readCount);
                            }
                        }
                    }
                }
            }
        }
    
        Console.WriteLine();
    }

    I haven’t installed the .Net 4.5 beta on my work machine yet, but according to the MSDN documentation, it should look like this:

    I don’t know if this compiles in .Net 4.5. I don’t have it installed yet.
    private static void ExtractDotNet(string zipFile, string extractionLocationDotNet)
    {
        Console.WriteLine("Extracting with .Net 4.5");
        Console.WriteLine();
    
        using (var archive = ZipFile.OpenRead(zipFile))
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                Console.WriteLine("Name: {0}, Size: {1}", entry.FullName, entry.Length);
    
                var extractedPath = Path.Combine(extractionLocationDotNet, entry.FullName);
    
                // I'm not sure if it will create the directories or not.
                // There does not appear to be an IsDirectory or IsFile like in SharpZipLib
                entry.ExtractToFile(extractedPath);
            }
        }
    
        Console.WriteLine();
    }

    As you can see, it looks a bit cleaner, but the nice part is having it built into the framework instead of relying on yet another assembly.

    As noted in the comments, I’m not sure how .Net 4.5 will handle the directory entries or if it ignores them as separate entries. I may be able to test the beta later, but feel free to comment if you know how this works.


  • Windows Phone Emulator Time Skew When Computer Sleeps

    TLDR: If you put your computer to sleep, the Windows Phone emulator might have the wrong time when you resume. Restart the emulator to get it to have the current time in its clock.

    I was working on my fork of an OAuth library for Windows Phone this weekend, and I ran across a really weird issue. I’m posting this in case someone else Googles this problem, since I couldn’t find anything.

    I have a UNIX epoch timestamp generator (necessary for Twitter) class that looks like this:

        public class TimestampGenerator
        {
            public string Generate()
            {
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0);
                var now = DateTime.UtcNow;
    
                long stamp = ((now.Ticks - unixEpoch.Ticks) / 10000000);
    
                return stamp.ToString();
            }
        }

    I worked for hours on this on my desktop and everything was working fine. Then, when I did a git pull on my laptop, it was suddenly broken. When I’d make a request to the term.ie example OAuth service, it said my timestamp was expired every time. I set breakpoints and compared it to the current epoch timestamp, and it was definitely wrong. I tried many ways of calculating it (that division is to get to seconds from 100 microsecond increments (ticks); I haven’t benchmarked to see which is faster), but nothing made a difference.

    I calculated a time difference of about 102 hours from my current time based on the timestamps. I finally figured out that my emulator could have the wrong time, since I was thinking computer time == emulator time. I killed the emulator, hit F5, and it worked like a charm. Then, I thought about the time difference, and it was about the last time I put my laptop to sleep by closing its lid.

    Apparently, when the computer comes out of sleep, the computer clock stops matching the emulator clock; the emulator clock freezes when the computer sleeps and just resumes from where it left off. I’m not sure if this is a bug or not, or if it happens on a regular basis. I may try to reproduce it later, but probably not.


  • Pretty IPropertyNotifyChanged Declarations for Windows Phone

    The Problem

    I’ve been doing a bit of WPF/Windows Phone development. Usually INotifyPropertyChanged declarations for properties are really ugly. The big problem is that the INotifyPropertyChanged interface relies on strings, which don’t refactor well.

    I’m also using the fantastic MVVM Light Toolkit, which makes life a lot easier when doing Windows Phone development.

    MVVM Light has a snippet that you invoke with the shortcut mvvminpc that produces the following:

    /// <summary>
    /// The <see cref="ScreenName" /> property's name.
    /// </summary>
    public const string ScreenNamePropertyName = "ScreenName";
    
    private string _screenName = String.Empty;
    
    /// <summary>
    /// Sets and gets the ScreenName property.
    /// Changes to that property's value raise the PropertyChanged event. 
    /// </summary>
    public string ScreenName
    {
    	get
    	{
    		return _screenName;
    	}
    
    	set
    	{
    		if (_screenName == value)
    		{
    			return;
    		}
    
    		_screenName = value;
    		RaisePropertyChanged(ScreenNamePropertyName);
    	}
    }

    That saves quite a bit of work, but it’s still ugly. It still doesn’t refactor well because you have to change that property that corresponds to the string. MVVM Light also includes another snippet with the shortcut mvvminpclambda that gets closer to what I want, but it’s still a large declaration with the equality checking, but instead of using ScreenNamePropertyName (and you get to lose that property), that call looks like:

    RaisePropertyChanged(() => ScreenName);

    That’s getting there, but it’s still messy. I found a great solution for this problem from Christian Mosers, but it doesn’t compile in Windows Phone Silverlight due to the lambda compile, and it relies on PropertyChangedEventHandler. Also, Christian’s sets the value after the event handler is called. I’m not sure if that’s a mistake, but it seems like it is, and someone else already pointed that out in his comments.

    I’ve modified it a bit and now it works, gives me an inpcpretty shortcut, and cleans up my declarations a lot. I tried making it an extension method of the delegate I created, but that doesn’t work. In the end, I made it an extension of the value type T.

    The New Code

            private string _screenName = String.Empty;
            public string ScreenName
            {
                get { return _screenName; }
                set { value.ChangeAndNotify(RaisePropertyChanged, ref _screenName, () => ScreenName); }
            }

    The Extension Method

    namespace System
    {
        public static class INotifyPropertyChangedExtensions
        {
            public delegate void OnPropertyNotifyChangedDelegate(string input);
    
            public static bool ChangeAndNotify<T>(this T value, OnPropertyNotifyChangedDelegate handler,
                ref T field, Expression<Func<T>> memberExpression)
            {
                if (memberExpression == null)
                {
                    throw new ArgumentNullException("memberExpression");
                }
                var body = memberExpression.Body as MemberExpression;
                if (body == null)
                {
                    throw new ArgumentException("Lambda must return a property.");
                }
                if (EqualityComparer<T>.Default.Equals(field, value))
                {
                    return false;
                }
    
                var vmExpression = body.Expression as ConstantExpression;
                if (vmExpression != null)
                {
                    field = value;
    
                    if (handler != null)
                    {
                        handler(body.Member.Name);
                    }
                }
                return true;
            }
        }
    }

    The Snippet

    <?xml version="1.0" encoding="utf-8"?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
          <Title>INPC Property</Title>
          <Author>Chris Benard</Author>
          <Description>A property raising PropertyChanged with a string. The class using this property should inherit GalaSoft.MvvmLight.ObservableObject.</Description>
          <HelpUrl>http://www.galasoft.ch/mvvm</HelpUrl>
          <Shortcut>inpcpretty</Shortcut>
        </Header>
        <Snippet>
          <Declarations>
            <Literal Editable="true">
              <ID>Type</ID>
              <ToolTip>Property type</ToolTip>
              <Default>bool</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>AttributeName</ID>
              <ToolTip>Attribute name</ToolTip>
              <Default>_myProperty</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>InitialValue</ID>
              <ToolTip>Initial value</ToolTip>
              <Default>false</Default>
              <Function>
              </Function>
            </Literal>
            <Literal Editable="true">
              <ID>PropertyName</ID>
              <ToolTip>Property name</ToolTip>
              <Default>MyProperty</Default>
              <Function>
              </Function>
            </Literal>
          </Declarations>
          <Code Language="csharp">
            <![CDATA[private $Type$ $AttributeName$ = $InitialValue$;
            public $Type$ $PropertyName$
            {
                get { return $AttributeName$; }
                set { value.ChangeAndNotify(RaisePropertyChanged, ref $AttributeName$, () => $PropertyName$); }
            }]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>

    Conclusion

    There is probably a better way to do this, but I’m not that experienced in WPF/Silverlight/Windows Phone yet. If you know of a better way, please let me know.

    To use this snippet, click the raw button in the code listing (looks like <>), save the contents as inpcpretty.snippet. Then, in Visual Studio, go to Tools -> Code Snippets Manager. Switch the language to C# and select Import. Choose the .snippet file you saved and you should be in business!


  • Speaking at the Dallas PHP User Group

    On January 11, 2011 I spoke at the Dallas PHP User Group on the topic of the Kohana v3 MVC Framework and Facebook integration. The introductory slides are below. To download the sample code yourself, head on over to the GitHub project page. Scroll to the bottom of the GitHub page to see the instructions on how to install it on your own server. An example site is available for you to view the running code on the Internet.


  • Hosting Windows Workflow Foundation in a Console Application without Ugly Code

    I’ve been using Windows Workflow Foundation for a small personal project to learn more about it and see what it can do. It’s pretty powerful and I’m looking forward to delving more into it. For my purposes though, I’m hosting the workflow in a console program.

    If you look around the internet, you’ll see lots of examples of hosting a sequential workflow in a synchronous manner, even though the WorkflowRuntime only support asynchronous operations. That code usually looks like this (example adapted from wf-training-guide.com to add support for input/output arguments):

    static void Main(string[] args)
    {
      Dictionary<string, object> inputArguments = new Dictionary<string, object>();
      inputArguments.Add("Argument1", args[0]);
      Dictionary<string, object> outputArguments;
        
      // Create the WF runtime.
      using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
      {
        // Hook into WorkflowCompleted / WorkflowTerminated events.
        AutoResetEvent waitHandle = new AutoResetEvent(false);
        workflowRuntime.WorkflowCompleted
          += delegate(object sender, WorkflowCompletedEventArgs e)
            {
              outputArguments = e.OutputParameters;
              waitHandle.Set();
            };
    
        workflowRuntime.WorkflowTerminated
          += delegate(object sender, WorkflowTerminatedEventArgs e)
            {
              Console.WriteLine(e.Exception.Message);
              waitHandle.Set();
            };
    
        // Create an instance of the WF to execute and call Start().
        WorkflowInstance instance =
          workflowRuntime.CreateWorkflow(typeof(WorkflowClass));
        instance.Start();
    
        waitHandle.WaitOne();
      }
    }

    Unfortunately, that’s a ton of code to do only a few things:

    1. Take input arguments
    2. Instantiate a WorkflowRuntime
    3. Create a workflow instance
    4. Run the workflow
    5. Handle any exceptions (poorly)
    6. Return output parameters from the workflow
    7. Do all of this in a synchronous manner.

    What if we could just call a method similar to this:

    var outputArguments = RunWorkflow<WorkflowClass>(arguments, completedEvent, terminatedEvent);

    Well, now you can! I’ve written this wrapper class to allow exactly that:

    public class WorkflowManager
    {
      public static Dictionary<string, object> RunWorkflow<T>(
        Dictionary<string, object> arguments,
        EventHandler<WorkflowCompletedEventArgs> completedEvent,
        EventHandler<WorkflowTerminatedEventArgs> terminatedEvent)
        where T : SequentialWorkflowActivity
      {
        using (WorkflowRuntime runtime = new WorkflowRuntime())
        {
          Dictionary<string, object> returnValue = null;
          Exception ex = null;
    
          using (AutoResetEvent waitHandle = new AutoResetEvent(false))
          {
            WorkflowInstance instance = runtime.CreateWorkflow(typeof(T), arguments);
            runtime.WorkflowCompleted += (o, e) =>
            {
              EventHandler<WorkflowCompletedEventArgs> temp = completedEvent;
              if (temp != null)
              {
                temp(o, e);
              }
    
              returnValue = e.OutputParameters;
    
              waitHandle.Set();
            };
    
            runtime.WorkflowTerminated += (o, e) =>
            {
              EventHandler<WorkflowTerminatedEventArgs> temp = terminatedEvent;
              if (temp != null)
              {
                temp(o, e);
              }
    
              ex = e.Exception;
    
              waitHandle.Set();
            };
    
            instance.Start();
            waitHandle.WaitOne();
          }
    
          if (runtime != null)
          {
            runtime.StopRuntime();
          }
    
          if (ex != null)
          {
            throw ex;
          }
    
          return returnValue;
        }
      }
    }

    Now you really can run the above code to execute your workflow in a synchronous manner without all kinds of messy code. Beware creating multiple WorkflowRuntime instances though. If you are managing multiple simultaneous workflows, you’ll need to pass in instance IDs and keep track in the runtime of which one is completing or throwing errors. It’s generally a bad idea to have multiple WorkflowRuntimes.

    Enjoy now being able to write:

    var outputArguments = RunWorkflow<WorkflowClass>(arguments, completedEvent, terminatedEvent);

  • redgate Releases SQL Search for Free

    redgate has released their SQL Search 1.0 for free, and my coworker Stephen sent our team an email letting us know about it. It is a fantastic product that integrates with SSMS and now it’s free. It keeps an index of all the text in every sproc, all the columns in every table, etc, and you can search them all instantly, limiting by type and many other options.

    These are the features they list on their page:

    • Find fragments of SQL text within stored procedures, functions, views and more
    • Quickly navigate to objects wherever they happen to be on your servers
    • Find all references to an object
    • Integrates with SSMS

    And their “Why use SQL Search?”:

    • Impact Analysis
      You want to rename one of your table columns but aren’t sure what stored procedures reference it. Using SQL Search, you can search for the column name and find all the stored procedures where it is used.
    • Work faster
      Finding anything in the SSMS object tree requires a lot of clicking. Using SQL Search, you can press the shortcut combo, start typing the name, and jump right there.
    • Make your life easier
      You need to find stored procedures you’ve not yet finished writing. Using SQL Search, you can search for stored procedures containing the text ‘TODO’.
    • Increase efficiency, reduce errors
      You are a DBA, and developers keep using ‘SELECT *’ in their views and stored procedures. You want to find all these and replace them with a correct list of columns to improve performance and prevent future bugs. Using SQL Search, you can look for ‘SELECT *’ in the text of stored procedures and views.

    If you are a user of SQL Server Management Studio, I highly recommend you check out out. You sure can’t beat the price. Check out the screenshots below as well.


  • A Lesson in How Not to Conduct Website Security

    Louisiana Tech just sent me a “reminder” email with my full username and password in there. That information is everything necessary to logon to the school student portal and get the rest of my personal information, full school transcript, etc.

    Not only do I not like them emailing my password, I don’t like that they even know my password. They should be using hashes instead. They’re doing it incorrectly.

    Here is the full email (user/pass redacted):

    Subject: Reminder
    TO: <[my.school.email]@LaTech.edu>
    Date: Thu, 11 Feb 10 12:35:23 CST    
    From: <[email protected]>
    
    REMINDER:
    
              Your BOSS PIN is: XXXXXX
              Your CWID number is: 100XXXXXX
    
    PROTECT THESE NUMBERS!

    I sure wish they’d protect these numbers for me instead of emailing them to me every quarter.


  • Beyonc□, or How We Can All Learn From Other Developers’ Character Encoding Mistakes

    Picture of Unicode Error, displaying Beyoncé as Beyonc-block

    I’m sure everyone who reads this blog has noticed, at some point, the result of another developer’s mistake in dealing with Unicode or other character encodings. I’ve had a few issues myself. To the left, you can see how my Napster displayed a Beyoncé song as Beyonc□. You may have seen a black diamond symbol with a question mark in it while browsing a web page, or perhaps other strange symbols when interacting with programs or web pages.

    Most, if not all of these, are inconsistencies when dealing with character encoding, with most of them being Unicode. Hazarding a guess, Beyoncé’s is likely stored as Unicode (UTF-16) in Napster’s database, but when output on the screen, it is converted down to UTF-8 or ASCII. Either way, it can’t be converted down, so an entity is displayed. There is even a shirt memorializing the problem in T-shirt form:

    I {entity} Unicode T-shirt

    My issues have been even more low-level than this. I deal with a lot of interaction using EDI with older computer systems running UNIX or or some IBM mainframe OS. None of these are using Unicode for their medical claims adjudication, and are either using ASCII or EBCDIC. Yes, EBCDIC; I have to program using EBCDIC in 2009.

    I have to be very careful when I’m converting to and from Unicode, the native format of the string class in .Net, and other character encodings such as ASCII and EBCDIC, and so should you.



  • Hacked by Chinese

    On our main product, in a branch on which I’m working on a Point of Sale product, something happened in the process of checking files into source control. In our case, we’re using Team Foundation Server. My guess is that the corruption happened on my hard drive for who knows what reason, but this is the beginning of the resulting solution file that ended up in TFS: a bunch of Chinese-looking characters instead of a project name.

    Microsoft Visual Studio Solution File, Format Version 10.00
    # Visual Studio 2008
    Project("{54435603-DBB4-11D2-8724-00A0C9A8B90C}") = "펐!蝀ጢ", "ProductNameFaxServiceSetup\ProductNameFaxServiceSetup.vdproj", "{DDA7A291-A5F6-4FEA-B11E-BBE90848167D}"
    EndProject
    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyName.Claim.Common", "CompanyName.Claim.Common\CompanyName.Claim.Common.csproj", "{11EE0005-87E4-44E0-806A-0BCB382468F0}"
    EndProject
    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompanyName.Claim.Modem", "CompanyName.Claim.Modem\CompanyName.Claim.Modem.csproj", "{FE62F256-5A9C-4212-8EFB-CCD0AC0D59AF}"
    EndProject

    It took a while to track down, because it manifested itself as missing projects, missing dependencies. I kept adding back things one at a time and then ending up with two more dependencies left to add. Finally, I just looked at the raw solution file and saw how it was messed up. I went back to find a file in the source control history that wasn’t messed up, got that specific version by change set, and then added the specific projects that had been added since then back to the solution.

    Thanks to source control, I was back up and running in no time.

    The title is from the phrase with which the Code Red worm defaced web sites it infected. We didn’t really get hacked by the Chinese.


  • Accessing a Control Without Being Able to See It on a Windows Form

    Menu Key Displayed on KeyboardA coworker of mine had a problem and came to me for help. She had a windows form with a control on it that she wanted to edit or delete, but couldn’t see the control. It was listed in the properties box in the list of controls on the form, but when she selected it, she wasn’t able to click it on the form, because it was behind another control.

    I hypothesized a solution, which worked, but requires the use of a less than frequent key on your keyboard, the menu key. Usually this key is two keys to the right of the space bar on windows keyboards, between Alt and Control. A picture of it is on the right.

    Note: As pointed out by Lee, in the comments, you can press Shift + F10 if your keyboard doesn’t contain the Menu Key.

    The Form With a Hidden Label Behind the Filename TextBox) Form with hidden label control

    Properties Window Listing the Hidden Control, HiddenLabel

    Properties window list of controls

    Select the control that you can’t see. It will be highlighted on the form.

    Form with Hidden Control Highlighted

    Label highlighted after selecting from properties windowThe hidden control becomes highlighted. Click into the title bar of the form. Press the menu key on your keyboard to display the context menu.

    Context Menu Being Displayed After Pressing the Menu Key

    bringtofrontSelect “Bring to Front” to display the control. It will now be visible and can be edited or removed.

    Hidden Control Moved

    Label after being brought to front and movedAs you can see, the control that was previously hidden is now visible and has been moved.

    I know this is a basic solution to an easy problem, but I had to figure it out, and I hope that someone searching may find this useful as well. The above example was a new form I was starting; it is not the actual application in question.


Posts navigation