Scott Seely

Unknown's avatar

This user hasn't shared any biographical information

Homepage: https://scottseely.wordpress.com

Article on JSON/XML Went up at InformIT.com

If you develop on ASP.NET MVC and have a need to return the ViewData as JSON and XML as well as HTML, take a look at the article I posted over at InformIT.com today (2/10/10): http://www.informit.com/articles/article.aspx?p=1554970. This is a shortcut to providing REST endpoints without doing a whole lot of extra work. This article doesn’t worry about versioning but does tackle the whole “how do I avoid screen scraping and extra coding” problem. Enjoy!

1 Comment

My first DimeCast is up!

Thanks to Derik Whittaker for bugging me to do one of these. It was fun. Go check it out. It’s a presentation on how to use the WebCam on Silverlight 4.

http://www.dimecasts.net/Casts/CastDetails/162

Leave a comment

Visual Studio 2010 Beta–>RC install and ASP.NET

I installed the VS 2010 RC last night, after uninstalling the VS 2010 Beta. If you see that ASP.NET isn’t coming up/working on your machine, you may need to remap the ASP.NET handlers into IIS. To do that, go to the Microsoft.NET 4.0 folder on your machine (typically C:WindowsMicrosoft.NETFramework64v4.0.30128 on a 64-bit Windows install, C:WindowsMicrosoft.NETFrameworkv4.0.30128 on a 32-bit install). Once in that folder, run the following:

aspnet_regiis.exe -i

After doing this, your ASP.NET applications should start running again. This is the same trick that worked on earlier versions of .NET, but it’s been a while since we had a .NET upgrade. I thought this might help out a few of you out there.

Leave a comment

DataContract, Partial Types and Generated Code

The other day, a friend had an issue with a DataContract. He had an Entity Model that used DataContract serialization. The code, stripped down to its essence, had something like this:

[DataContract]
public partial class SomeClass
{
    [DataMember]
    public int MyInt { get; set; }
}

 

And this was all well and good. When transmitting SomeClass over the wire, the fields on the entity model were transmitted. Now, my friend is really smart, and he knew that his version of serialization had implicit serialization. So, when adding new fields, he relied on implicit field serialization by augmenting SomeClass in a separate file as:

public partial class SomeClass
{
    public string MyString { get; set; }
}

 

Lo and behold, the field MyString didn’t appear on the wire. Why was this? This is because partial classes are a compiler trick that hides itself at the assembly level. The assembly indicated that SomeClass is a type that has the following C# implementation:

[DataContract]
public partial class SomeClass
{
    [DataMember]
    public int MyInt { get; set; }

    public string MyString { get; set; }
}
 

This shows that MyString is not part of the data contract, so the field doesn’t get serialized. At the assembly level, no one knows that you separated the implementation across two files.

So, next time you are wondering why part of your object isn’t being serialized, see if you made any declarations about serialization on the type. If you did, you have turned off the automatic “magic” parts of serialization. Sometimes, wizards will make those decisions for you. One way to recognize that the work was done for you: look to see if the generated type has [DataContract] on the partial class you are augmenting.

Leave a comment

Programmer Productivity

It’s been almost 4 years since I last programmed professionally with C++. C++ was my language of choice from 1994 through the end of 2000. It is a language that, once upon a time, I knew REALLY well. How well? I could read template errors and code the fix based on the build output-if you are a .NET developer, that’s kind of hard to do. Since then, I’ve done a lot of development with three languages: VB.NET, C#, and F#. Most recently, I was doing my hobbyist development in F#. I was impressed by the incremental boost in development productivity in F# over C#. The productivity boost at first was just noticeable and has recently become something where I can express F# algorithms in significantly less time that the C# equivalent.

Since mid November 2009, I started using C++ because a hobby project I wanted to work on required it. The project is a .NET profiler, and you can’t write a .NET profiler in .NET-you have to go to an unmanaged language. I noticed that I’m expressing C++ code at about the same rate as in F# and C#. At first, I was frustrated at the amount of functionality I could code in a few hours of C++ programming versus the same time slice in C#/F#. After talking to some friends, I was reminded that this is a thing that most people know but few people experience: each individual writes code at their own pace. Once they reach a level of expertise across 2 or more languages, they will write more functionality in the language that offers a higher level of abstraction. Unfortunately, not all languages can be used in all situations. The highest level of abstraction I can use for my profiler is C++.

If you do nothing else this year, learn a functional language to compliment the work you do in C#, VB.NET, Java, or C++. F#, Haskell, Clojure, Scala, and LISP all await to increase the amount of functionality you deliver every day. 

Leave a comment

Speaking Calendar: January 26-February 25

I’m going to be assisting the Microsoft office by doing some presentations of the PDC Roadshow.

January 26, 6 PM: Rockford .NET Users Group

February 3rd, 6 PM: Madison .NET Users Group

February 25, 6:30 PM: Lake County .NET Users Group

 

If you have a user group in the Wisconsin/Illinois/Indiana area and want to see this content, let me know. I can either come out to your group or help find a presenter who can deliver the content.

Leave a comment

Incorporating Video into a Silverlight 4 Application

html, body {
height: 100%;
overflow: auto;
}
body {
padding: 0;
margin: 0;
}
#silverlightcontrolhost {
height: 100%;
text-align:center;
}

Over the past week, I spent some time with Silverlight 4. I’m really impressed by how easy it is to incorporate video into an application. This post shows how to capture video from the camera and display the video on the screen. The post also handles grabbing single frames of video. You might use this type of arrangement to allow users to upload images, hold impromptu web casts, and to do video conferencing.

I’ve uploaded a barebones application that turns on video capture and displays the video:

 

To understand how this works, you need to be familiar with the following objects:

CaptureSource

CaptureDeviceConfiguration

VideoBrush

The CaptureSource type encapsulates the methods needed to interact with audio and video devices.

CaptureDeviceConfiguration acts as gatekeeper to the webcam and microphone. CaptureDeviceConfiguration knows how to ask the user for permission to use the webcam or microphone. It also remembers what the user said about using the webcam or microphone during the current session.

VideoBrush knows how to paint using a video as the source.

In order to interact with the camera, you need to know whether the user gave you permission and if not, you have to ask for permission. Once you have permission, you just need to capture video from the default camera, create the brush, and start capturing the video.

private CaptureSource _captureSource = null;
private void btnStartCapture_Click(object sender, RoutedEventArgs e)
{
    if (_captureSource != null && 
        _captureSource.State == CaptureState.Started)
    {
        return;
    }
    if(!CaptureDeviceConfiguration.AllowedDeviceAccess)
    {
        if(!CaptureDeviceConfiguration.RequestDeviceAccess())
        {
            return;
        }
    }

    _captureSource = new CaptureSource {
         VideoCaptureDevice = 
 CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice()
       };
    var brush = new VideoBrush();
    brush.SetSource(_captureSource);
    _captureSource.Start();
    rectVideo.Fill = brush;
}

Later on, when the user wants to capture the current video as an image, you just do something like this to put the current frame into an image control:

 

private void btnGrabImage_Click(object sender, RoutedEventArgs e)
{
    if(_captureSource == null || _captureSource.State != CaptureState.Started)
    {
        return;
    }
    _captureSource.AsyncCaptureImage(
        image => imgCapture.Source = image
        );
}

As someone who spent way too much time in the C++/MFC era writing code to capture video from devices, I am incredibly impressed with the brevity of the code. I think the SL4 team did an awesome job here. Way to go!

 

You can grab the sample project here.

Leave a comment

F# is Changing My Style

Tonight, I was writing some code that made use of transactional WCF bindings. I wanted to do some experimentation with all the bindings available to see which ones support flowing transactions. The pre-built bindings that do this will create a TransactionFlowBindingElement when you ask them to call CreateBindingElements(). The types I’m interested are concrete (no abstract methods) and have a zero-argument constructor. A few years ago, I would have done a bunch of looping constructs to look at each element. However, I’ve been doing a lot more work with F#. While doing this experiment in C# for a project, I wound up writing the following instead:

 

static void Main(string[] args)
{
    var bindings = from bindingType in typeof (MessageContractAttribute).
                       Assembly.GetTypes()
                   where typeof (Binding).IsAssignableFrom(bindingType) &&
                   !bindingType.IsAbstract &&
                   (from constructorInfo in bindingType.GetConstructors()
                           where constructorInfo.GetParameters().Length == 0
                           select constructorInfo).Count() > 0
                   select bindingType;

    var txBindings = from bindingType in bindings
                     where
                         (from bindingElement in
                              ((Binding) Activator.CreateInstance(
                                bindingType)).CreateBindingElements()
                          where bindingElement.GetType() ==
                            typeof (TransactionFlowBindingElement)
                          select bindingElement).Count() > 0
                     select bindingType;
    foreach (var txBinding in txBindings)
        Console.WriteLine(txBinding.FullName);
}

I would’ve loved a Seq.iter for the last 2 lines of the function. I think this is a good reason to learn F# or another functional language. It’ll change how you write code elsewhere. I’m not saying that this code is more readable, but it is interesting.

So, what does the code write out as the transaction supporting bindings?

System.ServiceModel.NetTcpBinding

System.ServiceModel.NetTcpContextBinding

System.ServiceModel.WSHttpBinding

System.ServiceModel.WSHttpContextBinding

System.ServiceModel.NetNamedPipeBinding

System.ServiceModel.WSFederationHttpBinding

System.ServiceModel.WS2007FederationHttpBinding

System.ServiceModel.WS2007HttpBinding

System.ServiceModel.WSDualHttpBinding

Leave a comment

The Sieve of Eratosthenes and F#

There is a problem on the Euler project, www.projecteuler.net, which asks to find the sum of all values under a given number. Problems on the Euler project have a range of solutions, where at least one solution has a runtime of under 1 minute. A popular, time efficient algorithm that finds all primes in a given range is the Sieve of Eratosthenes. The basic algorithm is:

  1. Create an array that contains all values from 2 up to the final maximum value
  2. Starting at 2, For each value in the array, mark all items that have indices of the current value that are multiples and NOT equivalent to the current index as 0 (eg. index mod [current value] == 0).
  3. March forward until you hit a non-zero value in the array, then mark all multiples as 0.
  4. Halt condition: stop when you cross the midpoint of the array (anything remaining that is non-zero is a prime since you already all multiples of 2).

In practice, this gives successive iterations of an array from 2 .. 10 as:

  1. [2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. [2, 3, 0, 5, 0, 7, 0, 9, 0]
  3. [2, 3, 0, 5, 0, 7, 0, 0, 0]
  4. At this point, we reach 5, which is greater than the length of the array (9) divided by 2 (4.5). Any non-zero values in the array are prime.

In C#, one possible implementation is:

private static long SieveOfErastosthenes(long maxvalue)
{
    long[] values = new long[maxvalue];
    // Populate the list for (long i = 0; i < values.LongLength; ++i)
    {
        values[i] = i;
    }
    values[0] = 0;
    values[1] = 0;
    for (long i = 2; i < values.LongLength; ++i)
    {
        if (values[i] != 0)
        {
            for (long j = i * 2; j < values.LongLength; j += i)
            {
                values[j] = 0;
            }
        }
    }

    long retval = 0;
    foreach (long k in values)
    {
        retval += k;
    }
    return retval;
}

Overall computational complexity is O(n). If you aren’t familiar with big O notation, the overall complexity is bound by the size of the dataset times a constant-in this case 3, since we iterate through the complete dataset 3 times:

  1. Populate the dataset
  2. Mark all non primes as 0
  3. Sum the primes

And yes, this works quite well, even for large values of n. My challenge was to get the sieve to work with performance equal to C#, only in F#. At the start of this, I had my first pass of the C# code running in ~600 ms for a value of 5 million. The challenge I set for myself was to achieve a similar timing in F#. The first few passes left me with runtimes of over 15 minutes (I killed the runs prior to completion). The reason why was simple: I wrote an O(n^3) algorithm. My challenge was to get this faster without using mutable values. My first pass looked like this:

let rec sieveofErastosthenes values filterout maxval =
    if (filterout >= (maxval/2)) then values
    else let shouldFilter =
            try let a = values |> List.find(fun x -> x = filterout)
                a <> 0 with | _ as ex -> false if (shouldFilter) then sieveofErastosthenes (values
                |> List.filter(fun x -> (x = filterout) || ((x % filterout) <> 0))) (filterout + 1) maxval
        else sieveofErastosthenes values (values |> List.find(fun x -> x > filterout)) maxval

let max = 5000000let sumofprimes =  sieveofErastosthenes [2 .. max] 2 max |> List.map( fun x -> int64 x) |> List.sum

This code is correct-pass in 10 for the max and the value returned is 17. But the answer just never returned for larger values within reasonable time. Next, I tried using a mutable type: System.Collections.Generic.List<T>. This got the time down to a measureable 4s. That’s still 6.5x longer than the C# version. That next attempt looks like this:

let sieveOfEratosthenes x =
    let retval = new List<int32>()
    retval.AddRange([0 .. x])
    retval.Item(0) <- 0 retval.Item(1) <- 0 for i in 2 .. x do if retval.Item(i) <> 0 then for j in 2 * i .. i .. x do retval.Item(j) <- 0 retval.ToArray()

let max = 5000000let sumofprimes =  sieveOfEratosthenes max |> Seq.map( fun x -> int64 x) |> Seq.sum
printfn "%An" sumofprimes

Notice that this latest iteration executes a lot less code and, frankly, looks pretty close to the C# code. Through some investigation, I found that the call to preload the array consumed 2.6 s. I then switched to a sequence and shrank the execution time to 2300 ms. I was closing in on my goal and learning some stuff about the performance of various F# constructs. Loading using a sequence changed the AddRange call to this:

retval.AddRange([|0 .. x|])

The reason this takes less time is simple. When allocating a List, F# allocates and initializes all values up front. The Seq is created with an iterator and only allocates enough space to store the iterator and not much else. So far, so good. At this point, I did a search on F# implementations of the Sieve of Eratosthenes and found that Chris Smith had one. His implementation keeps track of which numbers AREN’T prime. Performance on his algorithm hits 8600 ms. That wound up being a step in the wrong direction.

Next, I tried, explicitly initializing the list of integers and cut the time down to 1450 ms. The strategy was getting me closer to optimal timing and showed that, for 5 million int32s, I was filling in the list in 46 ms.

let sieveOfEratosthenes x =
    let retval = new List<int32>(x + 1)
    for i in 0 .. x do retval.Add(i)

    retval.Item(0) <- 0 retval.Item(1) <- 0 for i in 2 .. x do if retval.Item(i) <> 0 then for j in 2 * i .. i .. x do retval.Item(j) <- 0 retval |> Seq.filter(fun x -> x <> 0)

This was better, but I’d like to get closer to the C# version. The last thing I tried was moving to Array from System.Collections.Generic.List. This last change cut 250 ms, bringing my times down to 1200 ms. It looks like using lighter weight objects really will speed things up! That version is:

let sieveOfEratosthenes x =
    let retval = Array.zeroCreate(x + 1)
    for i in 0 .. x do retval.[i] <- i
    retval.[0] <- 0 retval.[1] <- 0 for i in 2 .. x do if (i % 2 <> 0) && retval.[i] <> 0 then for j in 2 * i .. i .. x do retval.[j] <- 0 retval |> Seq.filter(fun x -> x <> 0)

let max = 5000000let sumofprimes =  sieveOfEratosthenes max |> Seq.map( fun x -> int64 x) |> Seq.sum

Leave a comment

Greatest Prime Factor in F#

Today I was reading an article in The Onion, Conquerors You May Have Missed,  and noticed that the number for the ant looked like it might be a big old prime, or at least have a large prime divisor. (For reference, the ant is # 43,168,974,563,247.) There are a number of algorithms for finding this answer, but my favorite is a little brute force algorithm that keeps dividing the big number by some other value until the two numbers are equal. Yes, I know I can short circuit a bunch of testing via a square root function, but BigInteger doesn’t have a sqrt function (yet.).

Anyhow, I cobbled this together and it worked right out of the gate:

let rec largestFactor x y =
    if (x = y) then y
    else
        let z = x % y
        if z = 0I then largestFactor (x/y) y
        else largestFactor x (y + 1I)

let LargestPrime x = largestFactor x 2I

let a = LargestPrime 43168974563247I

printf "%A" a

 

Answer: 84,826,177

So, the number isn’t prime, but the largest prime factor is pretty big! And, writing up the code to figure out the answer itself was pretty simple.

Leave a comment