WCF, Self-Hosted through IIS, RESTFul

April 4, 2011

Looking into WCF for a couple projects I’ve involved with and so far its great. If you are one of those dev teams who need to configure your service for consummation across myriad of technologies. WCF is an extremely powerful technology. Being involved in a primarily microsoft shop though sometimes causes you to pick products through convenience oppose to them being the right tools. I’m in that boat as of right now. Do I need a way to deploy service oriented technologies? Yes. Do I need to configure the same service in terms of its binding/address or can I pretty much just get by with using a HttpWebRequest and hosting through IIS. Yes. With that an aspect of what makes WCF so great is kind of out the door. Additionally with its host of configurable facilities, its difficult to sift through all the tech to find out exactly what you need.

What I need is something hosted through IIS and is RESTFul for simplicity.

Three things you need.

  • 1. Any web application.
  • 2. WebGetAttribute found in System.ServiceModel.Web.
    • Used as follows
      [OperationContract]
      [WebGet(UriTemplate="*")]
      string CheckStatus();
    • So basically in the case where you simply access http://…/Service.svc, it would access CheckStatus()
    • Using the WebInvoke method you can access post requests as well.
    • UriTemplate is also very important as that allows you do define more descriptive routes or requests.
      • Consider the following piece code.[WebGet(UriTemplate="/User/{userName}")]
        string GetUserInfo(string userName)
      • Now accessing the following resource http://…/Service.svc/User/Evan will route to GetUserInfo passing in “Evan” as userName
  • Now so assuming that you can just have httpWebBinding and its hosted through IIS you can skip the web.config changes access the markup in Service.svc and add the attribute Factory=”System.ServiceModel.Activation.WebServiceHostFactory” into node in there. (Note .NET 3.5 intellisense doesn’t appear to acknowledge this attribute)
  • One other note is if you are adding this service into an MVC web application, you’ll might want to tell your app to ignore routes which access your service.svc. public static void RegisterRoutes(RouteCollection routes)
    {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.svc/{*pathInfo}");

Voice Recognition Software Part 1

May 26, 2010

Over the weekend I started looking into voice recognition software and how it was currently implemented by Microsoft. Most of this inspiration was based on avoiding my current depthbuffer Avatar issue with my developing xna game (trying to prevent burnout). The rest of this inspiration is based on Jarvis in the new Iron Man movie. Curious to see how feasible it would be setup a system for recognizing and dispatching commands. I also thought it would be a good way to get caught up with the WCF capabilities.

I started buying a $20 USB Logictech Microphone. This would be in future useful for Skype purposes anyways. Downloaded the recent Microsoft Speech SAPI5. I sat on moving forward and learning whats in these assemblies and perusing code examples. This was kind of a mistake. I instead started from the service side in WCF, my idea was to expose the WCF as a web service thus allowing xml requests from several sources/clients. I can have one particular client make a voice to xml request whereas another client can have a web interface to send an xml request to this service This was a good idea in point however until I discovered the voice recognition and how the functionality worked I had to modify the request and make subtle design changes as well.

My idea for the WCF service was to be able to inspect an incoming request and verify it again against every single rule involved. The rule most likely to be called would be returned and then subsequently invoked its execute command. The rules are very simple and basically just verify a certain type of phrase or semantics in the request and then dispatch the rule which would actually call a library to do something. The libraries are the part which will be invoked by the rule and would the major groundwork. Reason for this is, I intend these rules to do a whole lot of different things so I need the library to be simple to ensure scalability with ease. I also need a central point of intelligence to control this verification of the rules. So I went with a singleton object.

This how WCF is correctly listening…

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class CommunicateAIVE : ICommunicateAIVE
{
public string GetData(string value)
{
ICommandEngine engine = CommandEngine.Instance;
CommandEngineRuleReturn result = engine.FindRequestType(value);
return result.Response;
}
...

This is how I’m currently handling the Command Engine… I’ll probably should make it thread safe.

public class CommandEngine : ICommandEngine
{
static List ruleSet = new List();
static CommandEngine()
{

}

private static CommandEngine _instance;
public static ICommandEngine Instance
{
get
{
if (_instance == null)
{
_instance = new CommandEngine();
InitializeRuleSet();
_instance.InitializeStateInformation();
_instance.InitializeGrammar();
}

return _instance;
}
}

InitializeRuleSet is where I actually load in all the rule based on loading a dll and invoking all the ctor’s via reflection. With this approach I thought it would be cool to branch off and have these rules/library in their own solution and use them as a support library.


private static void InitializeRuleSet()
{

Assembly assembly = Assembly.LoadFile(@"C:\dev\Service\ProjectAIVE\SupportLibraries\CommandEngineRulesLibrary.dll");
Type[] types = assembly.GetInterfacedTypes("ICommandEngineRule");

object[] constructorParameters = { CommandEngine.Instance };
foreach (Type toConstructType in types)
{
//avoid abstract classes
if (!toConstructType.IsAbstract)
{
ConstructorInfo[] ci = toConstructType.GetConstructors();
//find default constructor
foreach (ConstructorInfo c in ci)
{
if (c.GetParameters().Length == 1)
{
ruleSet.Add((ICommandEngineRule)c.Invoke(constructorParameters));
break;
}
}
}
}
}

Also here’s a sample command rule which doesn’t use a library since the functionality just returns something in the response.


public class SayHelloRule : BaseCommandRule
{
public SayHelloRule(ICommandEngine commandEngine) : base(commandEngine) { }

public override CommandEngineRuleReturn PerformActualResponseQuery(string request)
{
if (request.ToUpper().IndexOf("HELLO") != -1)
{
this.CommandEngineRuleReturn.Heuristic = 100;
this.CommandEngineRuleReturn.CommandEngineRuleReturnType = CommandEngineRuleReturnType.RequestSufficient;
this.CommandEngineRuleReturn.Response = string.Format("Hello {0}", this.CommandEngine.StateInfo["CommanderChief"]);
}
return base.PerformActualResponseQuery(request);
}
public override void ExecuteCommand(string request)
{
base.ExecuteCommand(request);
}
}

Based on every request these rules will be traversed and executed based on the following code.


public CommandEngineRuleReturn FindRequestType(string request)
{
foreach (ICommandEngineRule rule in ruleSet)
{
rule.GetResponseInfo(request);
}

ruleSet.Sort();

ICommandEngineRule bestRule = ruleSet.GetFirstElement();
ExecuteBestRuleCommand(bestRule, request);

switch (bestRule.CommandEngineRuleReturn.CommandEngineRuleReturnType)
{
case CommandEngineRuleReturnType.RequestCausedError:
break;
case CommandEngineRuleReturnType.RequestInsufficient:
this.IncompleteRequest = string.Format("{0}!{1}", this.IncompleteRequest, request);
break;
case CommandEngineRuleReturnType.RequestSufficient:
CommandEngineMemoryStruct newMemory = new CommandEngineMemoryStruct();
newMemory.Request = request;
newMemory.Response = bestRule.CommandEngineRuleReturn.Response;
this.Memory.Add(newMemory);
break;
}

I realize now I haven’t yet talked about anything for voice recognition however the post is getting long. But there is one other thing I thought I should mention, so I’m making these a multiple part series. I’ll to the VR in the next part.

So anyways, I’m working on these unit tests when I’m coming up with extension methods and creating new classes and it occurs to me that I might have a better way to verify these request/response from big picture or from the user point of view. Say for instance you execute a dozen voice commands correctly, the application is working like a dream. You then get the idea to add more functionality you do so and it works, all of a sudden certain commands are no longer dispatching correctly? What happened? After scrambling clearly one of your command rules you added recently are picking up the request instead of the old one you intended. Most of your unit tests are written to catch coverage within the class and not based on integration. Also why not based the tests are real “production” data. So I thought to myself, create a Feedback and a FeedbackRegression. Feedback rule would check to see if the user politely said Thanks or Thank you to the WCF Voice Recognition (need a better name). This would take the last request and the response which is now assume to be correct. We would then log this into a data source. The FeedbackRegression would said the logged request/response from the data source and run it through the Command Engine as if it came in from the client and validate that the response is correct.

Thought that was a cool automated integration test, additionally kept the scope I was currently at with regular unit tests.

Next Part creating Voice Client using Speech SAPI5…
For info on WCF there are tons of information on it at Channel9.msdn.com.


Tecmo Bowl Throwback Review

May 9, 2010
Not as impressed as I thought I’d be with the latest to say the least.

Two things which sum up my thoughts on the game.

You will like this game if you haven’t played the original for a long time and want to feel nostalgic and be able to play a wider audience of players.  (NES,SNES)

You will not fall in love with this game if you were looking/expecting for more than just a refresh in graphics.  I’m in this category as after hearing about multiplayer and such I thought I was to be expecting more.  Aside from that I thought it was still worth the 800pts to get.

The game is pretty true to the original aside from the updated graphics.  It was refreshing to see updated cut scenes as well.  Though this additional polish doesn’t avoid the same pitfalls of the original game to which the purist-minded might  appeal.  Based on this I’m going to just focus on what I was expecting to be fixed/added from the originals.  So don’t think I’m won of those “haters” saying the game is terrible as it clearly is not though I agree with some of the IGN ratings point wise.  The following pitfalls include the following bugs/lack of features.

1.  User controlled players are forced to make uncalculated dives to break up catches they have no chance of making. (original ported bug)
- I’m not sure how the game was designed/developed but if this was done as a purely ported process ie (this is how it was coded in this platform so this is how we’d have to code it exactly in this next platform, then solve the inaccuracies/differences), then I guess there is a defense.  However, if they went by trying to port based on actual behaviors in the game (most likely not the case) then I think this is inexcusable to port such a defect.  I was a hard-core player of this game as were my friends and I remember specifically part of the strategy of breaking up plays was to move away from the intended receiver during a pass in some cases.  You didn’t want to be put in a situation where your DB was forced to dive and come up short causing you to have to re-accelerate off the ground (unless you had Darrell Green, LT, etc… didn’t matter then).  Meanwhile the receiver has caught the ball in mid-stride.

2. Faster lineman can easily end non-shotgun pass plays and up-the-middle run plays.
- This one to me is just unavoidable, while playing the computer in the running season mode I was able to dominate in this way 10 plays in a row with what looks in comparison to other teams, an above average nose tackle.  This is done by pushing down-right (or toward the ball) on the control pad while pressing the dive button.  This can only be prevented in a user-to-user game by changing the playbook to have mostly shotgun plays.  If you’re playing with a crappy playbook and a user opponent is aware of this flaw, I can understand why players might be dropping off early.

Features which could have made improved albeit modified the experience

1.  Mid-play player changes.
- Many times while playing another user, you find yourself on the otherside of the field from action.  This takes time to catch up while your fellow AI teammates are being fooled running up and down diagonally trying to catch your seasoned opponent.  I would have implemented the feature to change to the player closest to the ball carrier, however not really changing the control to user-input until the user has initiated control.  This would get around the problem sometimes experienced in older maddens where its like “Darn it, I was still moving my previous player!”

2.  Intended receivers should be have more control
- I haven’t quite figured out when intended receivers will jump, though I know the ball must be somewhat in their line of the route.  Plus a factor between their receiving ability/agility.  Either way, there should always be some inaccuracy from poorer QBs which I think is a great feature, however most NFL receivers should be able to jump/move/adjust accordingly for the ball, allowing the user to do so by  initiating some control plus motion sounds like a relatively simple feature to implement.  I’ve observed  receivers continually do stupid things in this game.  This includes waiting for a ball out-of-bounds territory and also waiting for a ball in triple team coverage.  Clearly, this is just non-implemented AI, which for the most part works however, adding in the ability to control these players after the throw would make these plays more interesting.

3.  Defensive backs should have more control
- To make it fair to the defense and to not disturb the incredible balance created from the game, DBs would have to have the ability to jump as well.  I think this would make it more difficult for Marino/Elway QBs to establish short passing games since these throw so low to the ground so some modifications might have to be made to the QBs passing game or throw in more factors/weights to avoid pass blocks/interceptions.

Aside from these games my only other complaint is that some of the collision detection doesn’t seem to work as crisp as other tecmo bowl games.  I’m not sure based on the new rigged models they have running around, but I felt with playing for an hour the first day that I’ve avoided some tackles and missed some tackles.  This also could just be subtle difference you’ll get with 2D vs 3D.  Important plays on defense, I felt myself switching back to 2D to avoid this subtlety.  This might be something I just need to get used as it seems at least balanced on both offense/defense (neither side has an advantage).

Maybe my version of tecmo bowl I was working on has a life after all.   The door is open a little at least.

For focusing….

April 28, 2010

If you’re anything like me and have difficulties staying focused on tasks at hand.  I’ve been using this site to bleed out any white noise with well white noise.

http://www.simplynoise.com/

I’ve only been sidetracked at this time to writing this post.


NUnit macros for VS2005

June 23, 2008

I’ve been told the most current direction is to use the Unit Test framework, however I see no reason to convert or change my own methodologies since from what I’ve seen so far this new feature seemed a little buggy.  I’ve noticed some minor glitches in the way it works with source control bindings and just in general the NUnit just seems a little more simpler to get running.  I’ve sure Unit Test will get better and probably become the standard for TDD in time to come with VS.

In the meantime, I wrote a couple macros for VS2005 to help my testing workflow.  I like TestDriven.Net as an add-in to the VS IDE, I just don’t like constant checks to check on what needs to be rebuilt.  Generally, I know the dependencies myself and would like to go right into debugging oppose to these checks.  So I created a macro to automatically attach and debug to a current “nunit.exe” process.

Here’s the code below, I think a nice little enhancement would be a listbox asking which one to debug (assuming you have multiple projects currently with NUnit guis up).

Afterwards export the file to where you put all your macros and then you can add them to your IDE.

   1:  Imports System
   2:  Imports EnvDTE
   3:  Imports EnvDTE80
   4:  Imports System.Diagnostics
   5:   
   6:  Public Module AttachToNUnitGui
   7:      Sub AttachToNUnitGui()
   8:          Dim ps As EnvDTE.Processes = DTE.Debugger.LocalProcesses()
   9:          Dim process As EnvDTE.Process
  10:          Dim p As EnvDTE.Process
  11:          Dim found As Boolean = False
  12:   
  13:          For Each p In ps
  14:              If p.Name.EndsWith("nunit.exe") = True Then
  15:                  found = True
  16:                  process = p
  17:              End If
  18:          Next
  19:   
  20:   
  21:          If (found) Then
  22:              p.Attach()
  23:          Else
  24:              MsgBox("No nunit consoles running")
  25:          End If
  26:      End Sub
  27:  End Module
 
 
Currently listening to Tapes N' Tapes - Insistor
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }


Jack Johnson at Blossom Music Center

June 18, 2008

I can officially say that I will never ever see a large act at blossom music center again. You’re probably saying you should have known better to see someone like Jack Johnson with such a large following at Blossom, you’re probably right I should have. I was hoping it would be different.

The last time Jack made it near Cleveland was 2004 when he traveled with G love and Donovan at the Amphitheater. This wasn’t bad as Jack’s following didn’t hit its peak yet. This time around I was pretty much miserable the first hour. Reason because, Blossom sells too many tickets. Yesterday there were just too many people there who figured Jack was just trendy for the week. Alot of annoying uncontrollable underage alcohol-consuming kids having no idea who Jack was. Just kind of annoying. I’m happy for all the successs he has had, definitely well-deserved, however, I miss the grassroots feel to his music. Yesterday, everything around him just felt too commercialized. Also we were so high up the hill, the music wasn’t loud enough to drown out the sound of underage kids scheming on how to get alcohol. (Which I know was probably be 6 years ago)

Maybe I’ll have to travel elsewhere to really enjoy him live again, in the meantime I’ll continue to scour here for his live tapings.

Plus the cold rain sucked, sorry I’m bitter its only been a day.


Zip Studio 2005

June 14, 2008

Now I’m not one of those hardcore version control guys who needs source safe setup up on another box on his personal network with binding attached to all his VS projects.  I think this admin causes more issues and extra work without following through with all the benefits.  Especially, considering source control main advantage is being able to work with concurrent projects.

Though even for personal usage I think source control can be a total advantage in other areas.  Namely prototyping ideas.  It reduces the risk and time to attempt some different design or attempted refactor on the current solution.  Without some type of source management, you run the risk to have a sort “safe” working solution with an opportunity to attempt a “ground-breaking, change the world” design.  Attempting this change is the risk paid in time and chance that you fubar your solution to where you can’t get it back to the glory it once was.

I had the idea of writing a plugin which wouldn’t be as full-blown as a real version control system, all I need is a little snapshot I can get back to.  I wanted to be able to take a specific solution as argument and parse through the projects and zip them with directory to a location, sounds useful?  Too useful that it has already been done? correct again… This plugin saves me weekly.


Tecmo Bowl Update…

February 4, 2007

In lieu of the upcoming super bowl, I figured I’d put out some screenshots of an extremely early beta of one of my side projects which is relevant to the super bowl.

This really had nothing to do with the super bowl, but more to do with my thumb killing me the last week so I chose not to play in a vball tournament this week. Team Haeg-ah still won. But because of this I’ve been shelling out code to this project like crazy. Good code or bad code?… still in the air on that one.

Anyways, this screen shot is technically not “in-game” but more of a performance test of 24-26 guys on the field at once running in place and also swapping in and out sprites assembled into a particular sequence. Looking promising so far, I hit a performance issue when adding the actual field. Field texture was too large and added a large difference in fps. Put in a tiling engine which I found on here by Kurt Jaegers, pretty quality – straightforward. Anyways I’m working on refactoring this into the TecmoBowl solution and looking at the performance differences then, we’ll see this week..

Tecmo Super Bowl Performance Test


C# Express NUnit

January 22, 2007

C# Express does not give you the ability to run through your nunits in debug. To mitigate your test-driven developments hassles, I came across this little workaround gem…. http://nunit.com/blogs/?p=28 . You’ll have to mess around with the arguments after that but you get the point.

Anyways continuing to focus some of the common library functionality for this XNA toy project, getting closer by the day. The design process has been a little backwards at this point (tons of refactoring err… rewriting). Lot of proof of concept projects, testing some ideas, trying to be creative, borrowing others code to see what I can leverage. Can kind of be expected with the concurrent refactoring done with the XNA framework as well. They changed things on their side which have all made great sense, causing me to refactor on my side because of the new way of thinking. I think I’ve ironed out most of the kinks at this point, and have a pretty good understanding for what I’ll be able to work with on the next level up. More to come soon.

Came across this from Carmack on Slashdot interesting read on the differences between the PS3 and 360 SDKs.

I think thats enough random stream of consciousness for one night.


Follow

Get every new post delivered to your Inbox.