Asp.net ajax

May 17th, 2008 software

Wow, for the first time in a lot of years I’ve used an API that truly abstracts what it advertises that it does.

 Asp.net ajax is proper software magic, love it.

[?]
Share This Post

Oxymorons and going through the motions

May 15th, 2008 software

It’s been occurring to me more and more lately that there’s an awful lot of guff going about these days surrounding the adoption of agile practices. It’s almost as if people honestly believe that by simply following an ever growing set of written instructions they’ll somehow reach agile nirvana; thus, trading on this naivity are an ever growing army of people trying desperately to nail their name tag on the mast of agile by taking what are essentially a set of very simple ideas and practices and ramming them firmly up their own arses to see what type of ever more complicated book comes out of the other end.

News flash, just coz somebody wrote it down somewhere, doesn’t make it somehow a priori, and that includes this personal opinion by the way!

My most recent daliance with regurgiated dogma involved somebody pulling me up about asking what story to pick up next during a stand up meeting (my motivation being, I have no idea what the relative priorities are, as that particular pactice hadn’t been adopted yet, and yes I do realise that agile planning is about the most simple thing to “get” out of all of it, but that’s a whole other story, so I figured was best to ask, then commit to doing that). Some minutes after the meeting somebody took great glee in telling me that I shouldn’t ask what to do next, I should instead elect to do something as, and get this one, agile teams are self organising and not doing so is a “stand up smell”.

Jebus wept.

Can no one else see the obvious contradiction here?

As far as I’m concerned committing to something is better than simply saying, “so I guess I’ll pick up another story later today”. Uh huh, so whilst we’re all here, any idea which one?

[?]
Share This Post

The joys of the javascript eval function

April 23rd, 2008 software

Eval is such a boon, but today it also reminded me of the reason I prefer working with strongly typed languages (me being someone that doesn’t enjoy chasing my tail dealing with apparently odd type inference issues).

Anyhoo, so as I was taking a substring component out of a string, treating it as an integer and incrementing it I discovered that if you give a string literal number with leading zeros to eval, in some cases it interprets it as Octal.

An example “00:23:12:024″ is a time code literal that I needed to increment to the next frame in a web ui. So I grab the trailing 3 characters and use eval to help me out;

  1. var frames = eval(framesLiteral + ‘+ 1′);

This proved fine whilst I ignorantly happy pathed it through a few ‘001′ to ‘007′ examples but when I ran a few more quick tests on the work I’d done I noticed that the ‘024′ in the example incremented to ‘021′. Eh?

A few moments of confusion and I figured it out. 24 is 20 if you read it as a base 8 number.

So just in case anyone else was as confused as I was, be sure to strip out the leading zeros :)

And writing this has just made me realise my fix is still broken because I just added a replace(’0′, ‘’) on the literal but this will effectively divide any number I have by ten or a hundred if it has trailing zeros.

Oh how I pine for a quick Int32.Parse!! Comeback WPF all is forgiven.

 —-

An update on this, the very helpful Graeme Foster posted a comment with the real solution which (the clue is in my pining for a parse int call over the use eval) is, well, to use parseint and tell it we’re in base 10.  Nice one Graeme, thanks for that;

  1. var frames = parseInt(framesLiteral, 10) + 1;

 

[?]
Share This Post

Code regions are the work of the devil!

February 5th, 2008 software

#rant

If I open just one more open source project and find it litered with more regions than lines of code, I think I may scream, very loudly!

It seems that the masses, not content with merely stating the bleeding obvious in their source code now feel compelled to obfuscate the development process even more by hiding quite literally every single line of code they write with regions.

Now don’t get me wrong, in some cases I appreciate their presence. Certainly if you spend your life trying to avoid very lengthy blocks of tool generated code they can be a godsend. But, come on, I really can tell just by looking that these are all private fields, these are properties, these are public methods etc, and, yes, given a few more seconds I can gather that these methods here are implementations for this interface or virtual method on a base class, you know becuase this type inherits this base and implements this interface, it’s in it’s declaration. No really I honestly can. You know, by simply reading the code.

It’s almost a self fulfilling prophecy that we now need regions simply because everyone seems to insist on hiding their code behind them and thus it’s the only way we can all now find our way around all of this complicated magic code and stuff you know!

Just organise your code better and refactor. If your type is more than 1000 lines long, maybe you should extract some collaborating types rather than hide every single line with regions? We’ll still understand it, honest injun!

#endrant

sample sex moviexxx movies sex starsmovie celebrity sexy clipsmovie scripts short america teenmovie end sim girladult simone movie insinnamon hogtied love moviesmovie sex skinnysnowballing moviesoft wet movies nude hairy

chi bulma dbz and hentai chidrink jap piss girlslezbos chubbygirl asian bondagef spanking f storiesfuck bride interracialhentai xxx bulmaebony ass bangershombres galeria gaygirls nudist peeing

loan credit up no 20000payday loan 31 next 22loan independent hour 24 company finance2500 dollar loanloans 2500 personal risk highloan 3000 personal military forloan personal 5000 check creditcredit bad 5000 loan dollarloan 5000 check easy credit no50000 personal loan

loan 500 pay payday advance 8loans a eaccount sales manager officer loanonline loans accounting calculatorrate adjustable fha loanrate loan mortgage adjustable homeloan cash advance bostoncredit adverse loan uk carloan agricultural landstudent financial education loan aid

loans equity 125loans 203k mortgageagriculture loanshomes a mortgage for loanguide to homeowner a loans directalaska loans studentcalifornia alameda loan officersadjustable mortgage rate loansadvance business cash loan84 loans car month

pics and movies xxx free nakedfull sex length moviemovies full pornosex hardcore cartoon moviesmovies fucking hardcorexxx hentai movieshot movies blonde fuckmovies xxx women hotcock movie hugeindian movies masala

movie clips hentaimovies stripteasebestiality moviesfree rape moviesmovies in nudityxxx movietawnee stone with moviesmovies anime pornsample muscle men moviesclips nude movie

fraud ameriloanalloantibodiesauto loans approval 10025fred home loan aames375000 loan payment calculatoraircraft airone italy loansalabama loans montgomery fhacase alger loan massachusetts student studyofficer alhambra loan californiamortgage and loans ameriquest amc

movie titmus hardcore abimovie examples listening activenaked movies actors inmasala in movies actressmovie free post adult gaysex movies sample asianballs movie deepnaked beach moviesmovie beautiful girlsof movies best 2004

movie guidelines ratingsgifs icon moviewallpaper movie posterrunning poster movie matesmovie juliet soundtrack romeostrip movieslut teacher movietryouts movie2004 moviesfucking movies

movies teen tgpteens masturbating moviesmovie stars female thaititanic soundtrack movietrailer movie park boysthe voyeur movielesbian xxx moviesyoung movies girl Map

ringtones alltea310 usa sch ringtone samsungfree motorola for 007 ringtones t720iharrington chain electric 3 ton hoistnokia ringtone itunes 60107520 ringtone formats g herrington 104 kansasnokia ringtone 2115i free Map

nackt Kiwi Teensanal Europäische dildoPussy haarigen Atkingdomvon Kostenloses Frauen Probeheft verspritzend VideosMaschine Kream verspritzend fucklesbien Schwarz GeschlechtSex Bilder pussey nackten Anker Porno ErwachsenenMädchen nackt Asian minderjährige Map

in tech programs accredited x-ray georgiaamerican union credit federal 1reports credit 3maroc accreditationaiu degree programs accreditationairline cards credit milesamerican military of university accreditationincome 2007 earned credit Map

[?]
Share This Post

WCF – IDisposable and safe WCF Client handling

January 17th, 2008 software

The implementation of the disposable pattern in WCF is something of a mystery to be honest. In C# the presence of the IDisposable interface on any type should invite the developer to take advantage of a using block to ensure any resources are cleaned up even in the event of an unhandled exception in the client code (for any that didn’t know a using block is basically just a C# construct that compiles to try {} … finally{ xxx.Dispose(); }. The trouble with the use of this pattern in WCF is that it’s not correct to call Dispose on a WCF proxy instance if it’s been put into a faulted state else you’ll get a, no doubt now infamous, “The communication object, …., cannot be used for communication because it is in the Faulted state.” exception message.

Regardless of what you’re trying to do in the client code, if you call close on a WCF communication object instance it’ll first try to complete any outstanding work it was doing for you. Clearly if it’s already faulted it’s not going to be able to do this and the internal guard against working on it in this state will always throw an exception.

This can be pretty problematic when you first start using WCF as the communication object faulted exception does a really good job of masking the actual problems that are faulting your channels.

My technical lead and I did a bit of research into this and eventually came up this best practice article from Microsoft on how to deal with using a communication object safely and still be able to deal with exceptions in a more granular fashion depending on what specifically was going wrong.

My problem with this lengthy try {} catch {} statement is the massive duplication it involves (surely the point abstracting safe clean up operations behind a call to Dispose as advertised by the type?).

A solution for us was to create our own SafeProxyHandler that would guarantee clean up and granular exception reporting without the need to repeat ourselves endlessly with the prescribed try catch statements.

The result is below.

  1. <br />
  2. using System;<br />
  3. using System.Diagnostics;<br />
  4. using System.ServiceModel;</p>
  5. <p>namespace Electroholic.Blog.Samples<br />
  6. {<br />
  7.     public delegate void SafeProxyInvocationHandler(out ICommunicationObject proxy);</p>
  8. <p>    public static class SafeProxyHandler<br />
  9.     {<br />
  10.         public static Exception Invoke(SafeProxyInvocationHandler del)<br />
  11.         {<br />
  12.             return Invoke(null, del);<br />
  13.         }</p>
  14. <p>        public static Exception Invoke(string messageTemplate,<br />
  15.                                         SafeProxyInvocationHandler del)<br />
  16.         {<br />
  17.             if (del == null)<br />
  18.                 throw new ArgumentException(“Expected delegate instance for handler to invoke!”);</p>
  19. <p>            ICommunicationObject proxy = null;</p>
  20. <p>            try<br />
  21.             {<br />
  22.                 del(out proxy);<br />
  23.                 HandleClose(proxy);</p>
  24. <p>                return null;<br />
  25.             }<br />
  26.             catch (TimeoutException exception)<br />
  27.             {<br />
  28.                 HandleException(proxy, exception, messageTemplate);<br />
  29.                 return exception;<br />
  30.             }<br />
  31.             catch (FaultException exception)<br />
  32.             {<br />
  33.                 HandleException(proxy, exception, messageTemplate);<br />
  34.                 return exception;<br />
  35.             }<br />
  36.             catch (CommunicationException exception)<br />
  37.             {<br />
  38.                 HandleException(proxy, exception, messageTemplate);<br />
  39.                 return exception;<br />
  40.             }<br />
  41.             catch (Exception exception)<br />
  42.             {<br />
  43.                 HandleException(proxy, exception, messageTemplate);<br />
  44.                 return exception;<br />
  45.             }<br />
  46.         }</p>
  47. <p>        private static void HandleClose(ICommunicationObject proxy)<br />
  48.         {<br />
  49.             if (proxy != null<br />
  50.                 && proxy.State != CommunicationState.Closed<br />
  51.                 && proxy.State != CommunicationState.Closing<br />
  52.                 && proxy.State != CommunicationState.Faulted)<br />
  53.                 proxy.Close();<br />
  54.         }</p>
  55. <p>        private static void HandleException(ICommunicationObject proxy,<br />
  56.                                                           Exception e,<br />
  57.                                                           string messageTemplate)<br />
  58.         {<br />
  59.             AbortClient(proxy);<br />
  60.             ReportException(e, messageTemplate);<br />
  61.         }</p>
  62. <p>        private static void ReportException(Exception e, string template)<br />
  63.         {<br />
  64.             Trace.WriteLine(FormatMessage(template, e.GetType().Name));<br />
  65.         }</p>
  66. <p>        private static string FormatMessage(string message, params string[] args)<br />
  67.         {<br />
  68.             return args == null || args.Length == 0 ? message : string.Format(message, args);<br />
  69.         }<br />
  70.        <br />
  71.         private static void AbortClient(ICommunicationObject proxy)<br />
  72.         {<br />
  73.             if (proxy != null)<br />
  74.                 proxy.Abort();<br />
  75.         }<br />
  76.     }<br />
  77. }<br />

 Example usage scenarios below show how much cleaner it is.

  1. <br />
  2.         public void SimpleWCFServiceCall()<br />
  3.         {<br />
  4.             Exception e = SafeProxyHandler.Invoke(<br />
  5.                 delegate(out ICommunicationObject proxy)<br />
  6.                 {<br />
  7.                     ExampleWCFClient client = proxy = new ExampleWCFClient();<br />
  8.                     client.ExampleCall();<br />
  9.                 });</p>
  10. <p>            if (e != null)<br />
  11.             {<br />
  12.                 //Handle exception<br />
  13.             }<br />
  14.         }</p>
  15. <p>        public void WCFServiceCallWithTraceExceptions()<br />
  16.         {<br />
  17.             Exception e = SafeProxyHandler.Invoke(<br />
  18.                 “Unable to call ExampleWCFService successfully [{0}].”,<br />
  19.                 delegate(out ICommunicationObject proxy)<br />
  20.                     {<br />
  21.                         ExampleWCFClient client = proxy = new ExampleWCFClient();<br />
  22.                         client.ExampleCall();<br />
  23.                     });</p>
  24. <p>            if (e != null)<br />
  25.             {<br />
  26.                 //Handle exception<br />
  27.             }<br />
  28.         }<br />

free movies porn quicktimemovies full length sexmovie hollywood nude scenesinterracial adult moviesstripping movies girls ofgalleries sample moviecast movie scary 3scenes sex movies fromshemale movies funmovies masala south indian

24 term short hour loanslondon 2nd in loans mortgagepersonal high loans 000 3 risk3000 loans autocanadian 56 online 39 loan paydayhome 401k information loan tax401k payment loan back paydeath benefits 401k loans70 loans loan payday 49mortgage personal 500 loan

caculator aacfcu car loankits 12 reloaning ebay gaday 30 loansestate real 1 loansloans advice onpayday advanced loansloan 125 mortgagecar aaa loansadvance no cash loans faxpersonal 2500 loan

peeing moviemovie serenity postersmovie sex extremestars movie fuckingthe deep movietheaters in nh moviefree movie xxxmature movies in ladies pantyhose ofmuscle sample ebony xxx men moviesmovie naked beach

women hot movies ofhuge boobs movieslesbian gallery moviemovies male in nuditydisney movie holesmovie script vocabularymovie watcherpeople having of sex moviesmovies musclemenxxxmale movie naked

movie vintage posterscast movie another teen not2 movie cast scaryporn movies matureparis hilton free moviefree movie bbw clipshentai length movies free fullmovie database adultbdsm movies or or did in vidcapsboob movies free

tramadol all about overdoseviagra gift ambienambien versus xanaxaffects xanax ofmg viagra 200online mg xanax pharmacy 2about tramadol allxanax 3mg Map

men samples movie black gayblowjobs movies freehome dirty moviesmovie dogfartfree fuck fatty moviesfoot fetish free moviesfree movies jizzmovies free latina sex Map

free tdma motorola ringtone 120t cingularnokia 6560 free ringtone gunaudiovox cdm ringtone 8410observer newspaper accringtonwarrington car alamo rentalin clerk jobs payable accounts warringtonringtone t720 alltel1977 barrington fleetwood Map

[?]
Share This Post

Dealing with the opaqueness of WCF MSMQ problems and poison messages.

January 10th, 2008 software

As with a great many software abstraction layers purportedly removing the need to understand the their underlying technology, WCF can be accused of being a wee bit of a leaky abstraction.

Microsoft’s noble intent to distil all interprocess communication into the ABC of WCF endpoints is, in my humble opinion, for the most part a great success and a pleasure to work with. But, as with many abstractions, the devil is always in the detail and in reality you would never really treat any of your endpoints arbitrarily simply as WCF. In my recent experience of working with WCF, an appreciation of their underlying transport mechanisms has actually proved vital in dealing the many and varied idiosyncrasies they exhibit and further that they exhibit when plumbed into the WCF channels you’re using. Most specifically when you need to quickly diagnose issues that have blocked one of your MSMQ queues with a poison message, a means of peering into the WCF channel at runtime has proved invaluable. The problem, as ever, when dealing with such a new technology has been how best to discover these idiosyncrasies.

Adding run time diagnostics to WCF MSMQ exceptions.

WCF comes complete with a great many extension points. Service definitions can be easily extended by adding proprietary Service Behaviour attributes to them (in fact, if you’re using a version of MSMQ prior to 4.0, the only means of moving a poison message onto a poison message queue is by adding a Service Behaviour that reacts to an instance MsmqPoisonMessageException.) In the case of exception handling each of the channel dispatchers in a WCF service can have a collection of ErrorHandlers which behave much like a chain of responsibility.

A generic HanldeException implementation is shown below.

  1. <br />
  2. public bool HandleError(Exception error)<br />
  3. {</p>
  4. <p> //perform custom error handler actions</p>
  5. <p> //indicate that this exception has been handled<br />
  6.  return true;<br />
  7. }<br />

As well as allowing you to add a bespoke handler to your service, by returning false from the HandleError call (indicating to the code managing the exception that it needs to pass it on to the next link of the chain) you can also introduce runtime diagnostics without otherwise interferring with the remaining Service Behaviors (keep in mind that in many cases once the queue has thrown an MsmqPoisonMessageException you will normally have lost any opportunity to delve further into the root cause of the exception).

To take advantage of this we can introdude an ErrorDiagnosticsBehaviourAttribute and ErrorDiagnosticsHandler which can leverage any runtime or simple trace strategy available to us. In the case of this example we had remote trace information available through another WCF based solution that allowed us to inspect trace events in our running applications in real time but even a more simple Debug.WriteLine call coupled wih a running instance of DebugView could suffice.

To put it all together then, you first need to define a concrete WCF error handler by implementing the IErrorHandler interface. For the purposes of diagnostics you need only actually implement the HandleError method.

  1. <br />
  2. using System;<br />
  3. using System.ServiceModel.Channels;<br />
  4. using System.ServiceModel.Dispatcher;<br />
  5. using LU.Diagnostics;</p>
  6. <p>namespace LU.Rti.Library.ServiceModel.ErrorHandlers<br />
  7. {<br />
  8.  public class ErrorDiagnosticsHandler : IErrorHandler<br />
  9.  {<br />
  10.   private static EventSink _eventSink;<br />
  11.   public static EventSink EventSink<br />
  12.   {<br />
  13.         get { return _eventSink; }<br />
  14.         set { _eventSink = value; }<br />
  15.   }</p>
  16. <p>  public void ProvideFault(Exception error, MessageVersion version, ref Message fault)<br />
  17.   {<br />
  18.   }</p>
  19. <p>  /// Trace exception messages inside the WCF framework<br />
  20.   /// to an LU.Diagnostics client<br />
  21.   public bool HandleError(Exception error)<br />
  22.   {<br />
  23.       TraceException(error);</p>
  24. <p>      return false;<br />
  25.   }</p>
  26. <p>  private static void TraceException(Exception error)<br />
  27.   {<br />
  28.        if (_eventSink != null)<br />
  29.           _eventSink.LogEvent(EventSeverity.High, error);<br />
  30.   }<br />
  31.  }<br />
  32. }<br />

Once this is available it can be added into your WCF service by defining a concrete Service Behavior attribute as below.

  1. <br />
  2. using System;<br />
  3. using System.Collections.ObjectModel;<br />
  4. using System.ServiceModel;<br />
  5. using System.ServiceModel.Channels;<br />
  6. using System.ServiceModel.Description;<br />
  7. using System.ServiceModel.Dispatcher;</p>
  8. <p>namespace LU.Rti.Library.ServiceModel.ErrorHandlers<br />
  9. {<br />
  10.  public class ErrorDiagnosticsBehaviourAttribute : Attribute, IServiceBehavior<br />
  11.  {<br />
  12.   private ErrorDiagnosticsHandler _handler = new ErrorDiagnosticsHandler ();</p>
  13. <p>  void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)<br />
  14.   {<br />
  15.   }</p>
  16. <p>  void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,<br />
  17.                                                                  Collection endpoints,<br />
  18.                                                                  BindingParameterCollection bindingParameters)<br />
  19.   {<br />
  20.   }</p>
  21. <p>  void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)<br />
  22.   {<br />
  23.        foreach (ChannelDispatcherBase dispatcher in serviceHostBase.ChannelDispatchers)<br />
  24.          ((ChannelDispatcher) dispatcher).ErrorHandlers.Add(_handler);<br />
  25.   }<br />
  26.  }<br />
  27. }<br />

The main job of this attribute is to allow the running service to inject your custom handler into it’s channel dispatchers exception handling behaviour. This is achieved by adding the attribute to your service definition. Diagnostics can then be made available by adding your new attribute to the definition of any service that you feel may require it.

  1. <br />
  2. [ErrorDiagnosticsBehavior]<br />
  3.  public class ExampleService : IExampleService<br />
  4.  {<br />
  5.       //service implementation<br />
  6.  }<br />

Whilst this strategy doesn’t deal directly with an y of the problems that may occur during your implementation of WCF using MSMQ, I certainly found it helped enormously in discovering the root causes of issues that can block communication in your queues.

serenity firefly movieeducation sex moviessex clip moviemovies porn sexdownloads shaved movie pussyshop girl moviemovies lesbian sinfulsnatch movie quotesporn movies spankingmovie girls spice script for

t290i sonyericsson ringtones alabama120c ringtonescingular ringtone adam feat fsoftware ringtone 3600 composercell lg 4050 ringtone phonecomposable samsung free a300 ringtoneafi polyphonis ringtonestamil nokia 1600 ringtone Map

manager accreditationbad credit loan $5000 withadding to credit website your cardsalaska cards credit airlinescredit alaska airline cardsaccreditation home child care familycredit advantage american cardstolen cards after credit are Map

account allinanchor adult merchant credit cardaustralia hypnosis vic course accreditedfor adresses creditorscredit ammends counselingamba amba accreditation etaccept knuckle card buster creditaccreditation aacsb et aacsbamerican card express credit black titanium Map

[?]
Share This Post

Jack In The Box - an Antipattern?

August 27th, 2007 software

I’m sure we’ve all worked with our fair share of corncobs. Be they motivated by a mix of fear and ignorance, in my experience one of the most common factors influencing disruptive behaviour on a software project, or some other Machiavellian agenda, the corncob is always at least an unwritten management problem, else, in more extreme cases, a major factor that needs to be urgently addressed less the project’s outcome be seriously compromised.

Early symptoms that can unmask a corncob, in the development sense, often seem to stem from a reluctance to veer very far from the known. A corncob might often be seen in early design sessions uttering the famous, “Why can’t we just … [insert any well known xyz software panacea in 24 hours code example here]“ , and, assuming that apart from our corncob, we’ve assembled a team of concerned and motivated professionals, this may well be met by a quick and quiet, “oh .. bugger, how did they slip through”. I’m sure it’s a place we’ve all been, the silent sinking realisation that we may have a corncob here.

Sometimes, however, I’m not sure that the general corncob antipattern can be correctly applied to all disruptive behaviour.

At it’s heart, in my opinion, the corncob is often acting to shield him or herself from factors outside of their current understanding. When faced with a team working in ways they’re not used to and have little knowledge of, they can become a troublesome and belligerent factor that despite the best efforts of their peers to involve and inform them can become a drain.

Another drain can come from the exact opposite. What if you have a team member that far from shy away from areas of responsibility and expertise well outside of their current remit and level of experience and knowledge, actively get involved in everything? What if that person often drains a great deal of everyone’s time effectively hijacking every meeting that they’re involved with? What if that person appeared to be congenitally unable to stop themselves “butting in” to conversations half away across the room, despite having no direct role or responsibility in the topic being discussed?

Is this till a corncob? I’m not sure, and having some direct experience of this currently, I’m also a little inspired by a conversation on the subject whereby project management discussed having to put this particular individual “back in their box”.

So we may have a “Jack In The Box” on our project.

aib calculator loanconnecticut 203k loansacerage loanswebsite student afsa loanamp license testing loan illinoisoriginations aegis loan ceasesdottie loaner quote a rebel moviestudent ak acpe loanloan amone scamfha funding alliance rate nys loan

educational american federal consolidation loan servicesloan tax deduction amortization negativeamortization extra loans schedules auto paymentsguaranteed loan credit personal $100 badpay day loan hour 110 14 payday services loan advance10000 poor credit loansloan 115 income stated Map

home bank america mid loanamerican loan auto generalhome express american equity loanamerican consolidation loanday $1000 pay loanbad loans credit $5000rate 1 july student loan10 day grace on period loans Map

mortgage debt loan 2nd consolidationmortgage home 2nd loan equitypayday 3 week loanpayday loan 44 debt 31payday loan link 35cash 6 cash 4 loan paydayloan link payday 45cash 9 loan 6 online payday Map

payday loan $2000loan expenses accounting accrualproperty loans 0 down commercialamortization loan ofmortgage services loan unit american homeloans amoratization for carloans auto $5000fees loan amortizing Map

hand big moviesblack anal moviesblack lesbian sex moviesblack lesbians moviesblowjobs moviesmovie briana banksmovies used cars inmaker movie cartoon Map

big free movies dickblack gay movies freemovies free enemahot free moviesnude movies free teenmovies free straight sexxxx anime movies freemovies porn xxx free Map

dogfart movieshome movies sexebaumsworld funny jokes celebrity moviesblowjob free moviesmovie lesbian clips freemovie lesbian bestteenie moviesmovies handjob Map

porn african videosamiture sexsouth ocean manalapan 820adult on vod porn video demand2 sexvilla 3dporn links amateurporn al4celebrity 101 sexiest bodies Map

sex age phone play88 pornporn directory adultsex 24 7 latexadult live chat sexmachines toys sex adult fuckingporn men amateur100 porn free hentai Map

dad american cartoon pornteen chat american african roomsadd behavior charts teenagersex photos adolescentporno achat dvdvideo porn amatuer homesexy rai aishwaryasextape american idol Map

[?]
Share This Post

WCF - Extending DataContract types in closed packages

July 21st, 2007 software

Working around the limitations of the new DataContractSerializer inside WCF has been occupying my mind recently. Specifically when moving to a contract based SOA paradigm you seemed to lose a very important capability in object oriented programming, polymorphism. Extending types in closed packages becomes troublesome if you wish the derived types to participate as messages in existing ServiceContracts.

My initial research yielded this excellent article by Sowmy Srinivasan which detailed two possible strategies to solve the problem.

Initially we went with the config section as it offered the most flexability whilst being able to truly close stable packages.

So version 1 of the new PubSub based WCF code we shipped required a config section to support each of the known types such Sowmy’s example below.

  1. <br />
  2. <configuration><br />
  3.   <system.runtime.serialization><br />
  4.     <dataContractSerializer><br />
  5.       <declaredTypes><br />
  6.          <add type=“MyCompany.Library.Shape,<br />
  7.               MyAssembly, Version=2.0.0.0, Culture=neutral,<br />
  8.               PublicKeyToken=XXXXXX, processorArchitecture=MSIL"><br />
  9.             <knownType type=”MyCompany.Library.Circle,<br />
  10.                        MyAssembly, Version=2.0.0.0, Culture=neutral,<br />
  11.                        PublicKeyToken=XXXXXX, processorArchitecture=MSIL"/><br />
  12.          </add><br />
  13.       </declaredTypes><br />
  14.     </dataContractSerializer><br />
  15.   </system.runtime.serialization><br />
  16. </configuration></p>
  17. <p><span />

However, I was still a little dissatisified with the maintainence overhead introduced with having to keep so many config files (at each end of every communication channel) in step with all the latest derived types being introduced and the inherent extra risk of communication stalling at any single point in our ESB if the sections were not correctly defined.

I’d initially dismissed the second solution, being the use of the ServiceKnownType attribute added to the ServiceContract definitions coupled with a helper type to return the array of types the serializer should support, as this seemed to limit extensions to compile time and I felt it was too limited and would introduce a great deal of uneccessary duplication in code to support it. Essentially it still relied on leaving base packages open to allow for supporting extra knowntypes, the exact opposite of what we wanted.

Swomy’s example using a generic servicecontract interface (a slightly different problem being solved as were using deep message envelopes in a common message format, but nice all the same if still, in my opinion, a little too limted for what we needed) is below.

  1. <br />
  2. [ServiceContract]<br />
  3. [ServiceKnownType(Method = “GetKnownTypes”, Type = typeof(KnownTypeProvider))]<br />
  4. public interface IMyServer<br />
  5. {<br />
  6.     [OperationContract]<br />
  7.     bool AddShape(Shape shape);<br />
  8. }<br />
  9.  <br />
  10. static class KnownTypesProvider<br />
  11. {<br />
  12.   static Type[] GetKnownTypes(ICustomAttributeProvider knownTypeAttributeTarget)<br />
  13.   {<br />
  14.     Type contractType = (Type)knownTypeAttributeTarget;</p>
  15. <p>    return new Type[]{contractType.GetGenericArguments()[0]};</p>
  16. <p>  }<br />
  17. }<br />

But thinking it through a little more I realised that using reflection and a single known base message type (which fitted exactly with what we were wanting) you could add runtime knowntype support with zero configuration and support local point to point extensions without the need for amending any of the base packages being used.

It’s much the same idea as the original but rather than relying on the message arguments or any other statically defined data, it scans types at each end at runtime (allowing for multiple matching datacontract definitions if required) for any decorators or other message extensions using reflection. In our case we’ve used this to keep the message assemblies entirely decoupled from the PubSub infrastucture via a single base MessageType defined in a seperate assembly and we don’t have any more huge nasty config sections to worry about.

  1. <br />
  2. [ServiceKnownType(KnownTypesRegister.METHOD_NAME, typeof(KnownTypesRegister))]<br />

  1. <br />
  2. using System;<br />
  3. using System.Collections.Generic;<br />
  4. using System.Diagnostics;<br />
  5. using System.IO;<br />
  6. using System.Reflection;<br />
  7. using System.Runtime.Serialization;<br />
  8. using System.Text.RegularExpressions;<br />
  9. using LU.Rti.Library.Interfaces.ServiceModel.Eventing;</p>
  10. <p>namespace LU.Rti.Library.ServiceModel.Eventing<br />
  11. {<br />
  12.  public abstract class KnownTypesRegister<br />
  13.  {<br />
  14.     public const string METHOD_NAME = “GetKnownTypes”;<br />
  15.     private static readonly string _base = typeof (AbstractMessage).FullName;<br />
  16.     private static readonly Regex _exclusions = new Regex(@“^mscorlib|^system|^nunit”,<br />
  17.                                                        RegexOptions.Compiled |<br />
  18.                                                        RegexOptions.CultureInvariant |<br />
  19.                                                        RegexOptions.IgnoreCase);</p>
  20. <p>    private static readonly object _synchLock = new object();<br />
  21.     private static Dictionary _knownTypes;</p>
  22. <p>    public static Type[] GetKnownTypes(ICustomAttributeProvider provider)<br />
  23.     {<br />
  24.        lock (_synchLock)<br />
  25.        {<br />
  26.           if (_knownTypes == null)<br />
  27.           {<br />
  28.              ScanForDataContracts();<br />
  29.              MonitorAppDomain();<br />
  30.           }</p>
  31. <p>          return new List(_knownTypes.Values).ToArray();<br />
  32.        }<br />
  33.     }</p>
  34. <p>    private static void MonitorAppDomain()<br />
  35.     {<br />
  36.        AppDomain.CurrentDomain.AssemblyLoad  = CurrentDomain_AssemblyLoad;<br />
  37.     }</p>
  38. <p>    private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)<br />
  39.     {<br />
  40.        lock (_synchLock)<br />
  41.        {<br />
  42.           try<br />
  43.           {<br />
  44.              ScanAssembly(args.LoadedAssembly);<br />
  45.           }<br />
  46.           catch(Exception e)<br />
  47.           {<br />
  48.              Trace.WriteLine(string.Format(“Problem Scanning assembly {0}.  Exception: {1}”,<br />
  49.                                            args.LoadedAssembly.FullName, e));<br />
  50.           }<br />
  51.        }<br />
  52.     }</p>
  53. <p>    private static void ScanForDataContracts()<br />
  54.     {<br />
  55.        try<br />
  56.        {<br />
  57.           _knownTypes = new Dictionary();</p>
  58. <p>    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())<br />
  59.              ScanAssembly(assembly);<br />
  60.        }<br />
  61.        catch (Exception e)<br />
  62.        {<br />
  63.           Trace.WriteLine(string.Format(“Failed to fully scan KnownTypes at start up.{0}{1}”,<br />
  64.                                         e.Message,<br />
  65.                                         e.StackTrace));<br />
  66.        }<br />
  67.     }</p>
  68. <p>    private static void ScanAssembly(Assembly assembly)<br />
  69.     {<br />
  70.        if (IsExcluded(assembly.FullName))<br />
  71.           return;<br />
  72.  <br />
  73.        Trace.WriteLine(string.Format(“Scanning assembly {0}”, assembly.FullName));</p>
  74. <p>       foreach (Type type in assembly.GetTypes())<br />
  75.           ScanType(type);<br />
  76.     }</p>
  77. <p>    private static void ScanType(Type type)<br />
  78.     {<br />
  79.        try<br />
  80.        {<br />
  81.           if (type.GetCustomAttributes(typeof (DataContractAttribute), false).Length > 0)<br />
  82.           {<br />
  83.              string name = type.FullName;</p>
  84. <p>             if (name != _base && IsAbstractMessage(type) && !_knownTypes.ContainsKey(name))<br />
  85.              {<br />
  86.                 _knownTypes[name] = type;</p>
  87. <p>                Trace.WriteLine(string.Format(“Adding {0} to KnownTypesRegister”, name));<br />
  88.              }<br />
  89.           }<br />
  90.        }<br />
  91.        catch (IOException)<br />
  92.        {<br />
  93.           Trace.WriteLine(string.Format(“Skipping type {0} as unable to locate it’s assembly.”,<br />
  94.                                         type.Name));<br />
  95.        }<br />
  96.     }</p>
  97. <p>    private static bool IsExcluded(string fullName)<br />
  98.     {<br />
  99.        return _exclusions.IsMatch(fullName);<br />
  100.     }</p>
  101. <p>    private static