Archive for category Uncategorized
Quiet lately
Posted by Scott Seely in Uncategorized on September 21, 2009
Things have been quiet around here lately because of a large volume of stuff I’ve been handling elsewhere. I recently was forwarded a nice review of the REST book. Feel free to take a gander and see if this pushes you to buy the book!
Solution for Daily WTF Praxis on 8-5-2009
Posted by Scott Seely in Uncategorized on August 5, 2009
Over at The Daily WTF, they’ve started posting programming puzzles. The latest one is a puzzle where a set of locker doors are toggled, starting from the closed state, to the open state. Starting at a step size of 1 and stopping at a step size equal to the number of lockers, one toggles each door. At a step size of 1, all doors are opened, step size of 2, all the even doors are closed. At a step size of 3, door 3 is closed, door 6 opened, and so on.
Many of the solutions observe that only perfect squares remain opened when the algorithm is complete. That option is easy, but I wanted to do one that mimics the jocks effort of brute force solving the problem.
// Init the lockers to the initial state
// and mark all doors as closed (false)
let sw = System.Diagnostics.Stopwatch.StartNew()
let totalLockers = 100
let lockers =
[1..totalLockers]
|> Seq.map( fun e -> (e, false))
// Recursive function to set each door.
let rec openLockers l skip =
let listLength = Seq.length(l)
if (totalLockers < skip) then
// We’ve done our last toggle on the previous iteration.
l
else
// Do the toggling and try again.
let newList =
l |> Seq.map(
fun (e, f : System.Boolean) ->
let modValue = (e % skip)
match modValue with
| 0 -> (e, not(f))
| _ -> (e, f))
openLockers newList (skip + 1)
let remainingOpen =
(openLockers lockers 1) |>
Seq.filter(fun (e, f:System.Boolean) -> f) |>
Seq.map(fun (e, f:System.Boolean) -> e)
sw.Stop()
Seq.iter (printf "%dn") remainingOpen
printf ("%sn") (sw.Elapsed.ToString())
Calling an STA COM Object from a WCF Operation
Posted by Scott Seely in Uncategorized on July 17, 2009
One of the things that many people are still doing is making use of old COM objects that run in STA (single threaded apartment) threads. Back in October, 2006, Jeff Prosise wrote how to do this from ASMX. Not too long after that, I had a chance to teach for Wintellect and Jeff asked me to show him how to do the same in WCF. That information went up on a post for a consulting company that didn’t make it through the latest recession. For better or worse, that post was referenced a fair number of times and now, folks are writing to me, asking for the code again.
In general, any time you receive a message via WCF, the message itself will be processed on a MTA (multi-threaded apartment) thread. Normally, this is just fine. Sometimes, you might be calling out to a COM object. COM objects will not run if the threading model the COM object needs differs from the threading model of the calling thread. MTA COM objects work just fine. But, if you have a bunch of STA COM objects (typically produced by Visual Basic but sometimes coming from C++ applications or other utilities) that you use in your WCF service, you have a problem. To allow things to work, the method needs to be invoked on an STA thread.
In .NET, one creates an STA thread by setting the apartment state of the thread prior to Start()-ing the thread.
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Now, how do we make this happen in WCF? We need to wrap the invocation of the actual method! For this, we resort to an IOperationBehavior. One typically applies a behavior (IServiceBehavior, IContractBehavior, IOperationBehavior) via an attribute. The only exception to this is an IEndpointBehavior, which is applied via manipulation of the EndpointDescription or in the app|web.config file. The IOperationBehavior exposes four methods:
- AddBindingParameters(OperationDescription, BindingParameterCollection): In our case, we will just do nothing with this info.
- ApplyClientBehavior(OperationDescription, ClientOperation): Only called when the contract is used on a client. We will do nothing here since we only care about the service implementation.
- ApplyDispatchBehavior(OperationDescription, DispatchOperation): Only called when the contract is used on the server. We will do our work here and override the IOperationInvoker on the DispatchOperation so that our operation is invoked on an STA thread.
- Validate(OperationDescription): Used to make sure that everything is OK before applying the behavior. Normally, one throws an exception from this method if the environment isn’t right in some way. Our implementation will throw if the method we are calling is being executed asynchronously. If you need an async version of the attribute, that work is left as an exercise for you, dear reader.
Our IOperationBehavior then looks like this:
public class STAOperationBehaviorAttribute: Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription operationDescription,
System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription,
System.ServiceModel.Dispatcher.ClientOperation clientOperation)
{
// If this is applied on the client, well, it just doesn’t make sense.
// Don’t throw in case this attribute was applied on the contract
// instead of the implementation.
}
public void ApplyDispatchBehavior(OperationDescription operationDescription,
System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
// Change the IOperationInvoker for this operation.
dispatchOperation.Invoker = new STAOperationInvoker(dispatchOperation.Invoker);
}
public void Validate(OperationDescription operationDescription)
{
if (operationDescription.SyncMethod == null)
{
throw new InvalidOperationException("The STAOperationBehaviorAttribute " +
"only works for synchronous method invocations.");
}
}
}
So far, so good. Now, we need to write that IOperationInvoker. You’ll note from the ApplyDispatchBehavior above that our STAOperationInvoker takes an IOperationInvoker in the constructor. This is done because, in general, the IOperationInvoker WCF gives us does everything right. It just needs to do its thing on an STA thread. Our implementation will delegate as much work as possible to the provided IOperationInvoker. This is a pattern you will follow in most WCF extensions as most extensions require a slight tweak to existing behavior. We do just that, except for our implementation of Invoke. In that, we will setup an STA thread and then call the contained IOperationInvoker’s Invoke method from the STA thread.
public class STAOperationInvoker : IOperationInvoker
{
IOperationInvoker _innerInvoker;
public STAOperationInvoker(IOperationInvoker invoker){
_innerInvoker = invoker;
}
public object[] AllocateInputs()
{
return _innerInvoker.AllocateInputs();
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
// Create a new, STA thread
object[] staOutputs = null;
object retval = null;
Thread thread = new Thread(
delegate(){
retval = _innerInvoker.Invoke(instance, inputs, out staOutputs);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
outputs = staOutputs;
return retval;
}
public IAsyncResult InvokeBegin(object instance, object[] inputs,
AsyncCallback callback, object state)
{
// We don’t handle async…
throw new NotImplementedException();
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
// We don’t handle async…
throw new NotImplementedException();
}
public bool IsSynchronous
{
get { return true; }
}
}
To test, I wrote the following Service Contract:
[ServiceContract]
public interface ITestService
{
[OperationContract]
string GetApartmentTypeMTA();
[OperationContract]
string GetApartmentTypeSTA();
}
and applied the attribute to this implementation:
class TestService : ITestService
{
public string GetApartmentTypeMTA()
{
return Thread.CurrentThread.GetApartmentState().ToString();
}
[STAOperationBehavior]
public string GetApartmentTypeSTA()
{
return Thread.CurrentThread.GetApartmentState().ToString();
}
}
When calling the service, GetApartmentTypeMTA always returns MTA and GetApartmentTypeSTA always returns STA.
If you want to save some typing time or see the sample application, go here.
Slides and Presentation from CNUG, July 15 meeting
Posted by Scott Seely in Uncategorized on July 16, 2009
The slides and code have been posted for both the back to basics and the REST Server side talk. Click here to get them. I’d like to thank everyone for showing up. I’ll be presenting the same talk again for the Rockford .NET Users Group. You can register for the talk here.
Article on using Google AppEngine + Silverlight
Posted by Scott Seely in Uncategorized on July 6, 2009
I wrote an article on how to integrate Google AppEngine with Silverlight. If you understand how to use REST, this integration is really easy. http://www.informit.com/articles/article.aspx?p=1354698 has the full article!
Speaking at the Madison .NET User Group
Posted by Scott Seely in Uncategorized on July 2, 2009
The Madison, WI .NET User group has asked me to speak at their July 8 meeting. I’ll be talking about the technologies that .NET makes available for writing RESTful .NET Services:
- ASP.NET/IIS
- MVC
- WCF
- ADO.NET Data Services
I’ll be skipping the Azure/Cloud specific choices since I only have an hour to cover things. My feeling is that the audience will be hosting all of their own services for the time being, so the above 4 items will be the most interesting to them. If you are interested in seeing the talk, please sign up here. I hope to see a few of you out there.
On Vacation. Back to posting on 6-23
Posted by Scott Seely in Uncategorized on June 14, 2009
I’m on vacation this week. I’ll be back to posting on June 23, 2009.
Oslo in Chicago? Yes.
Posted by Scott Seely in Uncategorized on June 10, 2009
I recently had an email conversation with a former colleague. He works at an organization that uses some pretty cutting edge technology. My feeling is that the organization firmly understands the value of moving to the latest and greatest is fraught with peril but rewards the early pioneers if these moves happen appropriately. In particular, they are already evaluating Oslo. I’m a big fan of proactive thinking. I have long heard rumors that the Chicago market is too backward or old fashioned, and I just don’t see that. Instead, I hear that a Chicago business is actively hiring and is using the latest and greatest technology to make their business more competitive.
We also have a very active Ruby and Python community which, from what I can tell, is growing every month. I think that the city has already turned itself into a tech hub. We just need that first billion dollar company and the world will know too. I know this will take 7-10 years for the seeds to start bearing fruit, but the process is in motion.
I love this!
Assembly of the day #3: IEExecRemote
Posted by Scott Seely in Uncategorized on June 8, 2009
This is day #3 of my journey through the .NET 4.0 assemblies. I’m planning to split up large assemblies over several days so that I give bigger assemblies proper treatment. Today, that won’t be happening! By the way, this is actually turning out to be pretty neat. .NET ships with a lot of interesting pieces, and the assemblies that sort early in the alphabet (because they don’t start with System) are pretty interesting glimpses into how .NET does things.
Today, we look at IEExecRemote. This assembly contains a single type:
IEExecRemote, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
FullTrust: True
In GAC: True
Number of types: 1
Number of namespaces: 1
Types:
Class IEHost.Execute.IEExecuteRemote
So, what does this IEExecuteRemote do? Reading the docs, we see that this is another class that “supports the .NET Framework infrastructure and is not intended to be used directly from your code.” So what? What does it do? It runs a managed application over the Internet. OK, that’s kind of generic and not very helpful. What is really going on? When you start a .NET application via a URL, Windows fires up an application called IEExec.exe. This KB article describes the process. This part of the discussion is pertinent:
The IEExec.exe application is an undocumented Microsoft .NET Framework application that is included with the .NET Framework. You can use the IEExec.exe application as a host to run other managed applications that you start by using a URL.
For example, when you start a smart client by using a URL, no processes run with the smart client name. Instead, each application that you start by using a URL receives its own copy of the IEExec.exe application. The IEEXEC.exe application sets up the appropriate environment for the application to run in.
Typically, the IEExec.exe application works closely with Microsoft Internet Explorer to help you start the .NET Framework applications. The IEExec.exe application hooks to Internet Explorer version 5.01 and later to listen for assemblies that are requested. During a request, the executable is downloaded to the assembly download cache. Internet Explorer spawns a process for the IEExec.exe application and then passes the raw evidence information of the executable to the IEExec.exe application. The IEExec.exe application then uses the raw evidence information to set up an environment that has constrained-security settings for the executable.
IEExecuteRemote and IEExec work together to host and run assemblies that are stored at URLs (instead of the local file system). IEExec loads the IEExecuteRemote instance in a separate AppDomain and then runs the remote assembly in that domain. The only method that IEExec excecutes on IEExecuteRemote is the ExecuteAsAssembly method.
Bing fighting Google fatigue
Posted by Scott Seely in Uncategorized on June 5, 2009
Over the years, I’ve come to use Google for SOOOOOOO much. Over the past week, I changed my default search engine in Internet Explorer and Firefox over to Bing. From what I think I’m seeing, Bing slightly exceeds Google in effectiveness. It might be that the UI is a little fresher, the results have slightly better relevance, or just that it is something new. Regardless, after several days of really heavy use, I don’t think I’m returning to Google search anytime soon.
FWIW, I tend to type in sentence based queries as opposed to sophisticated boolean logic. Bing likes my questions better than Google does, and that let’s me get my job done faster.
From what I’m seeing, Bing is a little bit better. A little bit is enough for me to switch.
You must be logged in to post a comment.