Mike's Tech Notes for 7/3/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Useful Abstractions Enabled with ContinueWith - .NET Parallel Programming - Site Home
In the June 2008 CTP of Parallel Extensions to the .NET Framework, we introduced the ContinueWith method on both Task and Future<T>.  ContinueWith is, in effect, a callback, very much like events in .NET.  With events, a causal action results in the event being raised, which by default triggers all of the delegates registered with the event to be invoked.  ContinueWith supports this, but rather than just registering the callback, it also provides back a Task or Future<T> that represents the callback; that returned Task or Future<T>'s lifecycle is tied specifically to the callback and won't be marked as IsCompleted until that callback completes.  While at its core this could be considered a relatively simple idea and is useful for general dataflow in applications, it also enables some important patterns and can serve as the building block for a whole host of larger abstractions.
useful abstractions enabled continuewith net parallel programming site homein june 2008 ctp extensions framework introduced method both task future lt gt effect callback very much events causal action results event being raised default triggers delegates registered invoked supports registering provides back represents returned 's lifecycle tied specifically won't marked iscompleted until completes core considered relatively simple idea general dataflow applications enables important patterns serve building block whole host larger example doesn't provide support mulit item continuations something think release create continuation one finishes out box can't multiple complete nevertheless use basic implement additional here's instances resulting scheduled executed provided tasks i've ommitted parameter validation simplify code static continuewhenall params var starter bool countdownevent ce new length whencomplete delegate decrement value true taskcontinuationkind onany taskcreationoptions none return two parameters execute completed supplied those array monitor completion uses workaround started arbitrary time don't directly capability hence we're planning bunch scenarios including created count down number reaches start used register voila now t1 t2 t3 console writeline finished similarly implemented creating set continuewhenany writeonce thecompletedtask trysetvalue implementation similar that's each store first schedule neat pattern starting become popular frameworks ccr asyncenumerator take advantage iterator make writing asynchronous operations bit more sequential primary focus library such limited capacity consider following runasync ienumerable enumerator getenumerator null movenext current dispose accepts retrieves enumerable moves next element recursively sense execution end disposed simply executes imagine wanted asynchronously read file processing follows readfile path filestream fs filemode open fileaccess fileshare 0x1000 enc utf8encoding byte data pendingread createfuturefromapm ac beginread endread yield bytesread break getstring opens stream continually reads wraps usage filestream's methods http blogs msdn com 8272833 aspx yielded returns passing cause thus ending up location allow complicated written wrapping invocations yielding myriad interesting we'd love hear ones come

Task Cancellation
The System.Threading.Tasks.Task and System.Threading.Tasks.Task<TResult> classes support cancellation through the use of cancellation tokens, which are new in the .NET Framework 4. For more information, see Cancellation. In the Task classes, cancellation involves cooperation between the user delegate, which represents a cancelable operation and the code that requested the cancellation. A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating the operation in a timely manner. You can terminate the operation by using one of these options:
task cancellationthe threading tasks lt tresult gt classes support cancellation through use tokens new net frameworkâ 4 more information see involves cooperation between user delegate represents cancelable operation code requested â a successful requesting calling cancellationtokensource cancelâ method terminating timely manner terminate one options simply returning many scenarios sufficient instance canceled way transitions rantocompletion state throwing operationcanceledexception passing token preferred throwifcancellationrequested method verify responded request following example shows basic pattern throws exception note passed itself class program staticvoid var tokensource2 cancellationtoken ct factory startnew already bool moretodo true poll property cleanup before iscancellationrequested clean up here pass same cancel continue thread wait waitall try catch aggregateexception innerexceptions console writeline message readkey complete children observes thrown compares exception's associated api created token's returns interprets acknowledging sets status waiting taskcanceledexception wrapped manufactured indicates instead faulty situation therefore task's null false match treated normal causing transition faulted presence exceptions cause completed possible process items

Cancellation
The implementer of a cancelable operation determines, in the user delegate, how to terminate the operation in response to a cancellation request. In many cases, the user delegate can just perform any required cleanup and then return immediately.
cancellationthe implementer cancelable operation determines user delegate terminate response cancellation request many cases perform required cleanup return immediately more complex necessary notify library code occurred such correct way call throwifcancellationrequested cause operationcanceledexception thrown new overloads exception net framework versionâ 4 take cancellationtoken argument catch thread examine exception's token determine whether indicates cooperative exceptional situation task class handles information see listening pollingfor long running computations loop recurse listen periodically polling value iscancellationrequested property true method clean up quickly possible optimal frequency depends type application developer best given program itself significantly impact performance following example shows one poll staticvoid nestedloops rectangle rect lt columns amp rows simulating work spinwait 5000 console write assume know inner very fast therefore checking once per row sufficient undo here writeline ncancelling press key exit break complete requests registering callbacksome operations become blocked check timely manner register callback unblocks received returns cancellationtokenregistration object used specifically purpose use cancel asynchronous web cancellationtokensource cts webclient wc cancelasync gt starting downloadstringasync uri http www contoso com manages synchronization ensures stop executing precise point time order ensure responsiveness avoid deadlocks guidelines followed callbacks called synchronously until dispose hold lock waiting deadlock free resources manual synchronizationcontext usage run particular threading constructor enables specify target synccontext active current performing wait handlewhen block waits primitive manualresetevent semaphore waithandle enable both event handle signaled waitany throw appropriate eventthatsignaledindex mre timespan 20 targets manualreseteventslim semaphoreslim support methods pass cancellationtokenâ to requested wakes throws try mres responsive alternative item next iteration canceled working 500000 multiple tokens simultaneouslyin listener simultaneously monitor internal addition passed externally parameter accomplish create linked source join two shown publicvoid dowork externaltoken combines external internaltoken internaltokensource linkedcts createlinkedtokensource doworkinternal timed out elseif cancelling notice done

.NET 4 Cancellation Framework - .NET Parallel Programming - Site Home
A very interesting addition to .NET 4 is a set of new types that specifically assist with building cancellation-aware applications and libraries. The new types enable rich scenarios for convenient and safe cancellation, and help simplify situations that used to be be difficult and error-prone and non-composable.
net cancellation framework parallel programming site homea very interesting addition set new types specifically assist building aware applications libraries enable rich scenarios convenient safe help simplify situations used difficult error prone non composable details described below lets begin motivating principles designed support unit work commenced consistent means early termination response request controls various moving pieces conveniently chain requests blocking calls complex operations such movenext plinq enumerator simple comprehensive infrastructure makes back potentially long running user code possible observe respond cooperative fashion obvious part api clean semantics forceful instead many prevailing systems secondary feature rarely gets treated sufficient detail above introduced raise primary concept apis one cleanly easily incorporated previous approachescancellation finds way design necessity classification common approaches herb sutter's article interrupt politely outlines four distinct techniques those distilled down two major first use asynchronous forced thread abort process kill appdomain unload technique trait target caught completely unaware ensure data safety reasons particularly due risk partial updates shared strongly discouraged second general whereby communicated manner observes enacts itself inherently safer require targets fully participating commonly implemented style approach involves potential object tracking state represents whether requested although shall see inherent problems improved follow examples found example backgroundworker class windows forms member called cancellationpending true calling method cancelasync similarly classes based webrequest provide cancel current operation prevent further commencing clear notion canceled active getresponse getrequeststream call more generally single run simultaneously becomes awkward track allows reset before enactment race conditions lead subtle far superior following issues imbued problematic abstraction better model specific occurrences cancelable achieved direct methods groupable chainable necessary perform setting boolean flag enacting standardized ubiquitous callback forward made parent tracks multiple concurrent commence earlier become issue frequently leads bugs identified enacted resulting behaviors return nothing happened throw operationcanceledexception custom exceptions address introduces examine future blog post perfectly suited needs extensions adopted typesthe purpose represent accept explicit parameter inform contrast mechanisms automatically attach themselves ambient stashed local storage involve automatic discovery attachment exact specification rules fleshed out exception type form basis cancellationtoken struct ‘potential cancellation’ passed poll register fired cancellationtokensource provides mechanism initiating token property obtaining associated natural combine key vs observing responding separated particular take initiate iscancellationrequested polling attached via copied around copies simply point original holds actual regarding lists etc throwing communicates finished without completing stated states observed note existing augmented constructors now look shows create pass correctly doesn't need checked statement once per few thousand instructions guideline subject avoiding significant performance impact ct cheap volatile read handful il tested eventhandler externalevent example1 cts sender obj gt wire up external requester try val longrunningfunc catch cleanup required private static total lt 1000 acknowledge demonstrates facility option blockingoperation manualresetevent mre false cancellationtokenregistration registration waitone wake dispose performs deregisteration pattern force whatever condition waiting immediately check reason woken here normal waking occur benign always regardless wait third listen regular waithandle under covers lazily allocated wh waitany finally fourth share example4 startasyncfunc1 startasyncfunc2 startasyncfunc3 listeners same each functions everyone detailsa important understanding transition prevents arise deep inside permitted application level functionality creating replace lightweight includes reference ‘weight’ separate registered thread's executioncontext captured security context capturing synchronization optional overload callbacks normally stored send synchronizationcontext applicable returned light idiposable disposing causes deregistered guarantee subsequently consequence block currently executing hence fast duration advanced patternsto finish introduction briefly patterns usage situation arises wish tokens best linked signaled source createlinkedtokensource registers linkingexample ct1 ct2 linkedcts slowfunc oce linking attaches onto properly otherwise delegates garbage collected until sources available collection achieve explicitly another scenario allow library cooperate consider accepts responds communicate mentions given typically know getting through side channel closure capture passing runquery var query asparallel withcancellation select result notice function case both throws performed thrown arbitrary behaving exactly though seen thinking failed unexpectedly advantage unexpected different mistakenly interpreted tracked confusion being conclusionthe guis manage over time expect migrate reduce variation crop solutions 3rd party interoperate purposes

Ten Things I Hate About Object-Oriented Programming — The JOT Blog
Boy, I some days I really hate object-oriented programming.
ten things hate object oriented programming jot blogboy days really apparently i’m one immortal words edsger dijkstra “object exceptionally bad idea originated california ”well normally complain think time step back take serious look wrong oop spirit prepared modest list paradigmwhat paradigm anyway straight story heard many different versions don’t know myself go origins smalltalk encounter mantra “everything object” except variables packages primitives numbers classes objects clearly essence fundamental peter wegner once proposed inheritance essential languages http doi acm org 10 1145 38807 38823 language supports features differently even support built others argue convincingly encapsulation data abstraction information hiding problem sources tell same concepts three fundamentally subtle ways mid eighties several myths propagated myth reuse makes more productive instead developing code scratch inherit existing extend design implies analysis implementation follow seamlessly another it’s way down obviously candidates oo let’s paradigms offer particular solve problems procedural described programs algorithms logic facts rules functional functions suggest means messages nice try misses point isn’t “for paradigm” modeling2 languagesanother thing everybody loves guy’s divide world curly brackets vs square round here people favorite oopls “c easy shoot yourself foot harder blows away whole leg ”it bjarne stroustrup that’s ok guess “actually made up term ‘object oriented’ mind ” †alan kay“there two initial concept bertrand meyer“within much smaller cleaner struggling out stroustrup“c history repeated tragedy java farce scott mckay“java best argument frank winkler“if true garbage collection delete themselves upon execution robert sewellbut perhaps blanket condemnation following “there kinds ones nobody uses stroustrup3 classesclasses drive crazy seem strange explain great brain excels classifying everything around seems natural classify real exist minds give single example class physical entity didn’t now here’s considered understand well procedures call source shows … calling send inheriting oops complete disconnect between runtime entities tools help ides show probably smalltalkers program debugger lets hands running directly message tool designers please ide methodsto fair methods learned good short sweet lots little development understanding what’s consider actually spend reading writing known productivity spending hours lot add new functionality write few lines trying figure reasons takes long bouncing forth sometimes lost space syndrome reported early quote adele goldberg “in happens somewhere ”i believe view today’s largely blame given accurately reflect application gets helping bridge gap reason develop see communicating guessing test driven popular exposes interactions during broken haven’t figured over 40 years need ask ourselves dominant want jump again demonstration seaside web platform allows navigate editable st typesok admit impatient guy having twice types force sure thinking “oh untyped never correct ”of course such “untyped” statically dynamically typed static prevent certain nothing principle first tend lead false sense security compiles mean errors type second evil systems assume consistent useful especially reflective deal fact change bits complex finally cope notions rule recall pain experienced generics interesting being developed accommodate gilad bracha optional run unhappy pluggable meaning plug multiple parts pluggabletypesposition pdf proposal seriously explore easily adapted diverse change“change inevitable vending machine gallagherwe right everyone hates better degrade incidentally difference hardware software degrades maintain challenge name mechanism those mechanisms restrict control enable fine context managing inconsistency perfectly comfortable adapting expectations behavior daily lives depending find break immediately changes both adapt changing patterns idioms visitors dependency injection simply artifacts lack disappear available construct patternspatterns can’t live ’em without pattern complicated rest case methodologies“all methodologies based fear kent beckevidently students chuck norris school agile “chuck pairs alone ”“chuck doesn’t iterative documentation stares until tells ”9 umlbertrand meyer always wondering diagrammatic modeling day hit “bubbles crash aka “all code” similarly appears something model usually understood generating models analogy fortran invented sold high level generated nowadays grow next thingfinally catchphrase “objects enough …” needed frameworks components aspects services curiously bring odd served conclusion 25 ago expect last “new” phenomenon thought conferences ecoop oopsla fade mainstream soon dismiss part feel passionately interest academic industrial research still continuing suggests deep important going fully taming complexity through mastered possibly difficulty distinguishing accidental make further progress focus facilitate oscar nierstrasz banquet speech 2010 maribor june 24

Mike's Tech Notes for 7/2/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Configuring Enterprise Search in SharePoint 2010
We all have to agree that search plays an integral part of any successful SharePoint deployment and is an area that Microsoft continues to invest in with each new release of SharePoint. Microsoft went as far as acquiring FAST 2 years ago which it now offers as a separate add-on to SharePoint for those willing to invest in high end enterprise search.  In addition to FAST, SharePoint 2010 search comes in a number of flavors each offering their own feature set and capabilities which I have duplicated at the end of this article as an Appendix for convenience.
configuring enterprise search sharepoint 2010we agree plays integral part successful deployment area microsoft continues invest each new release went far acquiring fast years ago now offers separate add those willing high end â in addition 2010 comes number ofâ flavorsâ each offering feature set capabilities duplicated article anâ appendixâ for convenience today introduce server eventually work way up microsoft’s latest greatest near future before deep dive step guide begin listing features come expect â â follows boolean query syntax finally introduced include operators queries suggestions whilst typing running love major engines such google bing integrating windows allowing users utilise box locate content results display refined provide filters document type categories managed properties view browser allows documents within utilising office web apps having rely launching necessary application even need installed local machine â this handy browsing site via kiosks internet cafes suite last improvements people including phonetic name nickname matching improved relevance self taste what’s let’s configuration service learn over past few articles independent services longer tied shared provider ssp 2007 architecture made crawler indexing engine user interface object model greater flexibility expandability design setup multiple servers scale out index instances below logical overview components make applicationas always journey central administration management manage applications click enter select “none” leave account register ensure domain already provisioned active directory created sp_searchapplication pool admin create settings createthe process presented confirmation successfully navigate back notice additional added list typical page similar here crawl rules reset indexes sources etc wss_usageapplication specifically handles usage health data collection analytics rating â more launch clicking default access specified time provisioning sp_searchconfirming permissionsthere couple areas note check acount sp_search provided appropriate permissions first checking profile navigating profiles highlight administrators ribbon newly “retrieve crawlers” selected permission confirm “read” against being crawled again question policy crawling sourceslet’s venture listed quick navigation bar under â you case sites detected albeit without schedule see start addresses located source editing drop down menu â these includes sps3 address easily scrolling toâ crawl schedules initiate full crawls once completed errors encountered during initial usually noted due incorrect assignments creating “basic center” siteif haven’t done top level actions center”enter url provision center “enterprise sitelet’s comparison â the key difference two tabs searching one choice organizations collections relevant title description tab template selection specify ok earlier test centers performing searches contentsearching peoplenow ran issue trying log displayed following warning “this item items owner nocrawl flag prevent searchable”in order fix true host “search offline availability” allow appear yes enabling perform disappeared that’s setting basic form â from expand providing redundancy â scalabilityâ and increased performance â until next happy require assistance needs team gkm2 assist contact info com au 1300 797 288 australia references technet getting started productsappendixsharepoint versions comparisonfeaturesharepoint foundation 2010search expresssearch 2010sharepoint 2010fast sharepointbasic searchyyyyybest betsyyyyvisual best betsysimilar resultsyduplicate resultsysearch scopesyyyysearch enhancement based contextycrawled propertiesyyyy federationyyyyquery suggestionsyyyysort rank profilesyrelevancy tuning promotionsyyyy shallow refinementyyyydeep refinementydocument previewywindows federationyyyypeople searchyysocial searchyytaxonomy integrationyymulti tenant hostingyyrich supporty

Using Messaging and Scheduling for Lock-free Access to Shared State
In a message passing system there may be times when mutable data must be shared amongst many tasks. In traditional programming this would be handled by a read-writer block, which would allow one writer thread to block all other threads while it updates the shared data. With high performance systems one doesn’t want to ever block threads, so an alternate solution is needed.
messaging scheduling lock free access shared statein message passing times mutable data amongst many tasks traditional programming handled read writer block allow one thread threads updates high performance systems doesn’t want alternate solution needed interesting technique use api set task schedulers actions require reading processed scheduler allows concurrent available cores each immediately reused next messages need update separate time known exclusive magic occurs tpl dataflow calls pair object combines two waiting new sent used returned pool more once done processing woken up again resume becomes eliminates problem blocking care still taken correctly reader write prevent being risk something isn’t under control unsafe manner

Parallel Programming: Task Cancellation - C# Frequently Asked Questions - Site Home
In this post, which is the third one in my parallel programming introduction series, I want to show how you can cancel parallel operations when working with the Task Parallel Library (TPL). I’m going to modify the program that I started in the previous posts. By the way, here’s the full list of posts in this series:
parallel programming task cancellation frequently asked questions site homein post third one introduction series want show cancel operations working library tpl i’m going modify program started previous posts way here’s full list end last small application responsive ui easily used both wpf windows forms models stick version add button code work publicpartialclassmainwindow window â â â â public mainwindow â â â â â â â â â â â â initializecomponent â â â â publicstaticdouble sumrootn root â â â â â â â â double result â â â â â â â â for lt 10000000 â â â â â â â â â â â â â â â â â â â â result math exp log â â â â â â â â return â â â â privatevoid start_click object sender routedeventargs â â â â â â â â textblock1 text â â â â â â â â label1 content milliseconds â â â â â â â â var watch stopwatch startnew â â â â â â â â list gt tasks newlist taskscheduler fromcurrentsynchronizationcontext 20 â â â â â â â â â â â â int â â â â â â â â â â â â var compute factory â â â â â â â â â â â â â â â â â â â â â â â â â â â â return â â â â â â â â â â â â tasks display continuewith resulttask â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â textblock1 tostring â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â compute â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â environment newline â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â ui â â â â â â â â task continuewhenall toarray â â â â â â â â â â â â â â â â var time elapsedmilliseconds â â â â â â â â â â â â â â â â label1 cancellationtoken none taskcontinuationoptions cancel_click now let’s refer topic msdn tells need pass special token model new features net framework haven’t heard take look mike liddell several created loop use once i’ll following field class cancellationtokensource tokensource newcancellationtokensource ones results don’t next change codevar â â â â return becomesvar finally event handler simply call method notified print “cancel” block privatevoid â â â â tokensource â â â â textblock1 environment press f5 compile run click start exception aren’t getting aggregateexception throw something goes wrong true name aggregates failures single case calculate canceled successfully failed reasonable short pause here basically it’s enough above real world even deal consequences example options handling first standard try catch thrown delegate within right lambda expression more aggregated iterate through collection inner exceptions see exceptions’ messages var â â â â tryâ â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â compute â â â â â â â â â â â â â â â â â â â â â â â â â â â â environment â â â â catch ae â â â â â â â â foreach innerexceptions â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â message works fine check again provides elegant dealing type issue analyze happened status decide whether displayresults â â â â â â â â â â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â compute â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â environment â â â â â â â â â â â â â â â â â â â â â â â â â cancellationtoken â â â â â â â â â â â â â â â â â â â â â â â â â taskcontinuationoptions onlyonrantocompletion â â â â â â â â â â â â â â â â â â â â â â â â â ui passing two parameters dependent returns purpose choose best solution notoncanceled option fail reason choosing explain “ran completion” concept little bit later inform indeed each printed reported printing same well create convert different displaycancelledtasks â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â cancellationtoken â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â taskcontinuationoptions onlyoncanceled emphasize natural i’d recommend approach whenever possible state turn back “not ” easy line beginning output clicked saw 5th operation roots calculated nonetheless good illustration called already running switched “run mode still waiting queue waste resources stop computations immediately periodically somewhere performs long declared publicdouble â â â â double â â â â for â â â â â â â â tokensource throwifcancellationrequested â â â â â â â â result made changes removed static keyword declaration enable access added checks indicates “cooperative means throws accepted request handled transitions handle visual studio unhandled shows debug you’re ignore times continue ctrl avoid another possibility switch checking “unhandled user code” go tools debugging general clear box makes “swallow” cause side effects routine documentation make sure that’s wanted final surprisingly â â â â cancellationtokensource â â â â publicdouble â â â â â â â â â â â â tokensource â â â â â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â compute â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â environment â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â cancellationtoken â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â taskcontinuationoptions â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â ui â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â textblock1 â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â environment â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â cancellationtoken â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â â taskcontinuationoptions usual links further reading know thanks dmitry lomov michael blome danny shih reviewing providing helpful comments mick alberts editing

Cancellation
The implementer of a cancelable operation determines, in the user delegate, how to terminate the operation in response to a cancellation request. In many cases, the user delegate can just perform any required cleanup and then return immediately.
cancellationthe implementer cancelable operation determines user delegate terminate response cancellation request many cases perform required cleanup return immediately more complex necessary notify library code occurred such correct way call throwifcancellationrequested cause operationcanceledexception thrown new overloads exception net framework versionâ 4 take cancellationtoken argument catch thread examine exception's token determine whether indicates cooperative exceptional situation task class handles information see listening pollingfor long running computations loop recurse listen periodically polling value iscancellationrequested property true method clean up quickly possible optimal frequency depends type application developer best given program itself significantly impact performance following example shows one poll staticvoid nestedloops rectangle rect lt columns amp rows simulating work spinwait 5000 console write assume know inner very fast therefore checking once per row sufficient undo here writeline ncancelling press key exit break complete requests registering callbacksome operations become blocked check timely manner register callback unblocks received returns cancellationtokenregistration object used specifically purpose use cancel asynchronous web cancellationtokensource cts webclient wc cancelasync gt starting downloadstringasync uri http www contoso com manages synchronization ensures stop executing precise point time order ensure responsiveness avoid deadlocks guidelines followed callbacks called synchronously until dispose hold lock waiting deadlock free resources manual synchronizationcontext usage run particular threading constructor enables specify target synccontext active current performing wait handlewhen block waits primitive manualresetevent semaphore waithandle enable both event handle signaled waitany throw appropriate eventthatsignaledindex mre timespan 20 targets manualreseteventslim semaphoreslim support methods pass cancellationtokenâ to requested wakes throws try mres responsive alternative item next iteration canceled working 500000 multiple tokens simultaneouslyin listener simultaneously monitor internal addition passed externally parameter accomplish create linked source join two shown publicvoid dowork externaltoken combines external internaltoken internaltokensource linkedcts createlinkedtokensource doworkinternal timed out elseif cancelling notice done

Task Cancellation
The System.Threading.Tasks.Task and System.Threading.Tasks.Task<TResult> classes support cancellation through the use of cancellation tokens, which are new in the .NET Framework 4. For more information, see Cancellation. In the Task classes, cancellation involves cooperation between the user delegate, which represents a cancelable operation and the code that requested the cancellation. A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating the operation in a timely manner. You can terminate the operation by using one of these options:
task cancellationthe threading tasks lt tresult gt classes support cancellation through use tokens new net frameworkâ 4 more information see involves cooperation between user delegate represents cancelable operation code requested â a successful requesting calling cancellationtokensource cancelâ method terminating timely manner terminate one options simply returning many scenarios sufficient instance canceled way transitions rantocompletion state throwing operationcanceledexception passing token preferred throwifcancellationrequested method verify responded request following example shows basic pattern throws exception note passed itself class program staticvoid var tokensource2 cancellationtoken ct factory startnew already bool moretodo true poll property cleanup before iscancellationrequested clean up here pass same cancel continue thread wait waitall try catch aggregateexception innerexceptions console writeline message readkey complete children observes thrown compares exception's associated api created token's returns interprets acknowledging sets status waiting taskcanceledexception wrapped manufactured indicates instead faulty situation therefore task's null false match treated normal causing transition faulted presence exceptions cause completed possible process items

.NET 4 Cancellation Framework - .NET Parallel Programming - Site Home
A very interesting addition to .NET 4 is a set of new types that specifically assist with building cancellation-aware applications and libraries. The new types enable rich scenarios for convenient and safe cancellation, and help simplify situations that used to be be difficult and error-prone and non-composable.
net cancellation framework parallel programming site homea very interesting addition set new types specifically assist building aware applications libraries enable rich scenarios convenient safe help simplify situations used difficult error prone non composable details described below lets begin motivating principles designed support unit work commenced consistent means early termination response request controls various moving pieces conveniently chain requests blocking calls complex operations such movenext plinq enumerator simple comprehensive infrastructure makes back potentially long running user code possible observe respond cooperative fashion obvious part api clean semantics forceful instead many prevailing systems secondary feature rarely gets treated sufficient detail above introduced raise primary concept apis one cleanly easily incorporated previous approachescancellation finds way design necessity classification common approaches herb sutter's article interrupt politely outlines four distinct techniques those distilled down two major first use asynchronous forced thread abort process kill appdomain unload technique trait target caught completely unaware ensure data safety reasons particularly due risk partial updates shared strongly discouraged second general whereby communicated manner observes enacts itself inherently safer require targets fully participating commonly implemented style approach involves potential object tracking state represents whether requested although shall see inherent problems improved follow examples found example backgroundworker class windows forms member called cancellationpending true calling method cancelasync similarly classes based webrequest provide cancel current operation prevent further commencing clear notion canceled active getresponse getrequeststream call more generally single run simultaneously becomes awkward track allows reset before enactment race conditions lead subtle far superior following issues imbued problematic abstraction better model specific occurrences cancelable achieved direct methods groupable chainable necessary perform setting boolean flag enacting standardized ubiquitous callback forward made parent tracks multiple concurrent commence earlier become issue frequently leads bugs identified enacted resulting behaviors return nothing happened throw operationcanceledexception custom exceptions address introduces examine future blog post perfectly suited needs extensions adopted typesthe purpose represent accept explicit parameter inform contrast mechanisms automatically attach themselves ambient stashed local storage involve automatic discovery attachment exact specification rules fleshed out exception type form basis cancellationtoken struct ‘potential cancellation’ passed poll register fired cancellationtokensource provides mechanism initiating token property obtaining associated natural combine key vs observing responding separated particular take initiate iscancellationrequested polling attached via copied around copies simply point original holds actual regarding lists etc throwing communicates finished without completing stated states observed note existing augmented constructors now look shows create pass correctly doesn't need checked statement once per few thousand instructions guideline subject avoiding significant performance impact ct cheap volatile read handful il tested eventhandler externalevent example1 cts sender obj gt wire up external requester try val longrunningfunc catch cleanup required private static total lt 1000 acknowledge demonstrates facility option blockingoperation manualresetevent mre false cancellationtokenregistration registration waitone wake dispose performs deregisteration pattern force whatever condition waiting immediately check reason woken here normal waking occur benign always regardless wait third listen regular waithandle under covers lazily allocated wh waitany finally fourth share example4 startasyncfunc1 startasyncfunc2 startasyncfunc3 listeners same each functions everyone detailsa important understanding transition prevents arise deep inside permitted application level functionality creating replace lightweight includes reference ‘weight’ separate registered thread's executioncontext captured security context capturing synchronization optional overload callbacks normally stored send synchronizationcontext applicable returned light idiposable disposing causes deregistered guarantee subsequently consequence block currently executing hence fast duration advanced patternsto finish introduction briefly patterns usage situation arises wish tokens best linked signaled source createlinkedtokensource registers linkingexample ct1 ct2 linkedcts slowfunc oce linking attaches onto properly otherwise delegates garbage collected until sources available collection achieve explicitly another scenario allow library cooperate consider accepts responds communicate mentions given typically know getting through side channel closure capture passing runquery var query asparallel withcancellation select result notice function case both throws performed thrown arbitrary behaving exactly though seen thinking failed unexpectedly advantage unexpected different mistakenly interpreted tracked confusion being conclusionthe guis manage over time expect migrate reduce variation crop solutions 3rd party interoperate purposes

Cancellation in Parallel Extensions - .NET Parallel Programming - Site Home
One of the great features that crosses all of Parallel Extensions types is a consistent approach to cancellation (see http://blogs.msdn.com/pfxteam/archive/2009/05/22/9635790.aspx). In this post we explore some of the ways cancellation is used in Parallel Extensions and explain the guidance we developed.
cancellation parallel extensions net programming site homeone great features crosses types consistent approach see http blogs msdn com pfxteam archive 2009 05 22 9635790 aspx post explore ways used explain guidance developed new cooperative based two cancellationtokensource initiates requests cancellationtoken communicates request asynchronous operations long running blocking method calls experimenting keep eye out methods accept test callssome extension introduce example blockingcollection take task wait default overloads block indefinitely condition waiting never occurs one solution apis many others provide timeout overload return duration report occur isn't particularly convenient want stop specific activity such user clicking 'cancel' button possibility amount time 100 milliseconds check pressed go back puts burden call re implemented repeatedly depending frequency polling add unnecessary cost use cause early termination response here examples item manualreseteventslim waitall tasks each case supply signaled via associated cancel wake up throw operationcanceledexception frees need timeouts happy until true both needs accommodated callsthere variety simply complete large amounts data complex processing taking place following even individual dofunc relatively fast 1000000000 gt assist paralleloptions class instance holds machinery inside observes supplied exit sees token more information exiting loops 27 9645023 cts options doslowfunc another thread canceling identical cases signal digression internal cancellationin certain situations systems necessary blocked reasons aren't due explicit collection being empty subsequently completeadding first invalidoperationexception represent incorrect usage way implement things concerns link second external captures essential details lt internalcts public finishadding externaltoken linkedtokensource createlinkedtokensource try internaltake catch oce iscancellationrequested msg fragment linked created passed simplifies implementation still allows woken concurrent throws tokens determine appropriate action note equal actually observed look original minor risk confusion sources simultaneously benign reasonable behave though source responsible particular choose prioritize mechanism over codeboth tpl plinq infrastructure code very useful respond fashion achieve tracking mentions treated acknowledgement means understand suffer catastrophic exceptional conditional responding result constructs aggregating exceptions participating worker threads throwing aggregateexception follows basic plan query single becomes doesn't matter whether delegate exception correctly understood execution engine var resultarray asparallel withcancellation select toarray interesting parameter expected bloated number considerably shown above conveniently accessed closures equivalent techniques normal collated including hence occurred thrown actual failure always queriesplinq offers deep support endeavors ensure enacted swiftly queries involve simple delegates takes care rest involves pattern described preceding section discussed next frequently working rule thumb approximately once per hundred runs 50ms perform checks detect itself seconds significantly affect user’s experience reason recommend called possible good lower bound few thousand il instructions executed upper less 10ms 1ms preferred snappy demonstrates run provides timely negligible performance assume 'token' 1000 simplefunc throwifcancellationrequested update available beta1 appear subsequent releases behavior acheived manual earlier comments mike summarythe rich callbacks made participate process application make same ideas facilities fully supported feature situation

Mike's Tech Notes for 6/28/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

CCR Coordination Primitives
Asynchronous programming is hard because there is no simple method to coordinate between multiple operations, deal with partial failure (one of many operations fail but others succeed) and also define execution behavior of asynchronous callbacks, so they don't violate some concurrency constraint. For example, they don't attempt to do something in parallel. The Concurrency and Coordination Runtime (CCR) enables and promotes concurrency by providing ways to express what coordination should happen. Plus, enforce the high level constraints between different code segments, all run due to some messages being received on ports.
ccr coordination primitivesasynchronous programming hard simple method coordinate between multiple operations deal partial failure one many fail others succeed define execution behavior asynchronous callbacks don't violate concurrency constraint example attempt something parallel runtime enables promotes providing ways express happen plus enforce high level constraints different code segments run due messages being received ports primitive thread spawn handler defined ccrservicebase couple additional overloads accept parameters pass lt t0 gt passes parameter type call times eventually use available threads free running amongst apart themselves it’s important realize relationship loose coupling fast initiation work consistent queues interaction software design scales well dependencies drawbacks mentioned above addressed appropriate model components primitives provided classified based two primary scenarios inbound requests long lived service oriented common web listening http network port post attaching handlers wake up serve each request independent addition uses advanced guarantee never active responses more outstanding possible return types per response waiting success portset associated pending completes item posted execute another scattering once collecting single caring order arrive arbiter described briefly followed detailed explanation context static classthe class provides helper routines creating instances classes discoverable safe manner methods below members exhaustive list arbiters constructed configurations directly constructor following shows created invoking fromtask creates instance taskarbiter choice choicearbiter receive receiverarbiter interleave interleavearbiter joinedreceive joinreceiverarbiter multipleitemreceive joinsingleportreceiverthe reference documentation used necessary extension methodsa concise alternative through new support examples guide extensions create receivers joins etc responseport easy way handle dss services expose portsets contain requested information fault whichever message sent back effectively waits same time executes corresponding delegate receives receivera receiver associates user takes persist option true false un register 7c var activate _taskqueue console writeline notice persisted until garbage collected abbreviated syntax anonymous statement called line print value experienced programmer older style â example 8c alternate version explicitly constructs passing factory persistedreceiver null predicate task exactly effect really thin wrapper around arbiterthe branches atomically step cant interrupted removes nested guarantees branch branching guard against race conditions 9c serviceport simpleservice getstate given found ex delegates note take arbitrary number receiversmultiple come categories known waitformultiple os literature attempts items wait try again right met phase logic deadlock mechanism atomic access resources without fear specified fixed compile fact join over forms typed eagerly remove participating total count satisfied very resource synchronization gathering results scatter gather joinsexample 10c portdouble portstring joined stringvalue tostring updated values matter power 14159 last 10 demonstrates activated posts determines everything needs schedules 11c portint second listen listens share contention intvalue 128 determine first allowing lost 11 previous showing case implementation both soon extracted shared races affect outcome basically traditional locking problem become scheduling dependency resolved guarded concurrent signal triggers requires 12c itemcount 12 dynamic â join stored variable read expected aggregate 13c exception requestcount send set respond failures successes 13 dealing assuming multipleitemreceiver gives arriving combination collections containing mutipleitemreceive discrete underlying multipleitemgather executed yield implicit activation need useâ arbiter inside iterator componentspersisted receiversccr motivated beginning capable efficiently executing process simplest mode whenever 14c summary base defines public serviceoperation stop updatestate state component abstract api _mainport dispatcherqueue _state taskqueue initialize private supplied three concurrently updatehandler getstatehandler external callers cache dispatcher queue schedule tasks demonstrate invalidoperationexception update field result itself 14 implementing pattern definitions interact definition derived accepts derive convenient reuse particular initializes returns communicate attaches talk exist arbiterfor non trivial carefully protected data structure internally requiring updates treated scenario complex multi preempted certain helps think care queueing activations complete declare protection require programmers familiar reader writer lock similar concept biased instead specific object sections avoiding internal manages exclusively 15c servicewithinterleave relation teardownreceivergroup teardown stophandler exclusivereceivergroup runs concurrentreceivergroup merge strings makes stopping 15 extends various parent youâ can concisely intent terms independently know exclusive protect later section steps writing subclass dsspservicebase automatically maininterleave furthermore added start mark servicehandler attribute see

How do you use the ScatterGather function?
The above code will fill resultPort with a bunch of zeroes. if I return i instead, it fills up with 0 through 9. This makes sense to me since the i variable is analagous to a for loop variable, and num appears to be some parameter passed in. I get zero since I didn't pass any in.
use scattergather function var resultport activate dispatcherqueue 10 num gt above code fill bunch zeroes return instead fills up through makes sense variable analagous loop appears parameter passed zero didn't pass expect p0 numbers possibly out order ten example 1144330022is output one execution

TPL Dataflow and async/await vs CCR - part 3 - Being Cellfish - Site Home
While you could use TPL data-flow for scatter/gather patterns in much the same way as CCR async/await is actually enough for you once again. The only thing you need to do is to create a number of tasks and then wait for them all either by using the Task.WaitAll method (or Task.WaitAny if you're only interested in the first result) but if you have a short constant list of tasks to wait for I would just wait for them with the await keyword like this:
tpl dataflow async await vs ccr part being cellfish site homewhile use data flow scatter gather patterns much same way actually enough once again thing need create number tasks wait task waitall method waitany you're interested first result short constant list keyword code formatted http manoli net csharpformat publicstatic lt gt fibonacciasync return var n1 n2 returnawait 10 remember common pattern want large success failure achieved depending report errors exceptions continue throw exception error occurs case returned flows suitable solution very ccrish done post back etc preventive comment technically above execute synchronously threads started real methods called important wanted show simple calling functions awaiting results needed

Mike's Tech Notes for 6/26/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Lucian Wischik - Async Part 1 -
The next release of Visual Studio has a major new language feature in VB/C#, “Async”. It will make for more responsive UIs, better performing web ASP websites, better network coding, and easier use of Phone/Silverlight/Windows APIs. Come to this talk to learn how it works and how to use it effectively. Learn how the .NET framework is changing to adapt to the Task-based Asynchronous Pattern. Learn what you should be doing right now to make your code ready for Async when it gets released.
lucian wischik async part next release visual studio major new language feature vb make more responsive uis better performing web asp websites network coding easier use phone silverlight windows apis come talk learn works effectively net framework changing adapt task based asynchronous pattern doing right now code ready gets released notes audience developers write

Lucian Wischik - Async Part 2 -
The new Async language feature is easy enough to use in common scenarios. But as the software architect or expert in your team, you’ll want to know more -- what are the best design practices? where are the hidden performance bottlenecks? how can you make your own code blend seamlessly with the new ‘await’ keyword? how does it actually work under the hood? how can you stretch it in powerful ways? You’ll leave this talk an expert on async.
lucian wischik async part new language feature easy enough use common scenarios software architect expert team you’ll want know more best design practices hidden performance bottlenecks make code blend seamlessly ‘await’ keyword actually work under hood stretch powerful ways leave talk notes audience advanced programmers architects people written multithreaded

Datavisualization.ch Selected Tools
Datavisualization.ch Selected Tools is a collection of tools that we, the people behind Datavisualization.ch, work with on a daily basis and recommend warmly. This is not a list of everything out there, but instead a thoughtfully curated selection of our favourite tools that will make your life easier creating meaningful and beautiful data visualizations.
datavisualization ch selected tools section_heading collection people behind work daily basis recommend warmly list everything out instead thoughtfully curated selection favourite make life easier creating meaningful beautiful data visualizations

Patent Patrol: Is Microsoft Planning A Robust Mobile Device Future?
patent patrol microsoft planning robust mobile device future paging_filter last week's reveal surface microsoft's bid relevance computing thrown rare spotlight amp turns out few recent patents ms's name suggest bold plans devices persona based login byodone criticism ipad iphone indeed android they're single user products that's very different situation laptops traditional desktop computers multi thus purpose pc environment perhaps configured business use one entertainment adult control protocols child something application 20120159479 designed remedy introduction notes technologies described herein providing experience virtualization provides ability deliver set configurations computer without installation run through virtual having file configuration files way isolation applications thereby avoiding conflicts exist traditionally installed software protocol defining particular time you're logging parent evening example reconfigure itself differently executive office ms points companies permit employees site find used prevent accidental unauthorized access sensitive data means don't carry around multiple purposes explosion bring habits workplace being driven seem onto here evidently aimed enterprise users carrying easy cachet tablet paradigm imagine edition windows allowing trick visual gesture patterns controlling scrolling etc oddity spotted surface's nifty touch keyboard covers trackpad cursor keys think unnecessary given full interface include partly appease legacy who've habituated themselves icons mice help more ui pro version aware better ways elements filed 20120159404 detecting gestural reason little kinect works thinks embedding sensors solve problem showing bigger document portable screen portion displayed view undisplayed navigation command input processing cause scrolled scroll content small display tedious cumbersome solution analyze user's hand waves near tablet's quickly navigate work workspace gesturessimilarly workspaces aspects task attempting spread space realizes getting between great thing enter 20120159401 basically take above make productivity easier touchscreen smartphone remote futuresone successes interact apple's tv product serving advanced intelligent puts remotes shame player game course courtesy xbox systems act media centers company realized tie tablets smartphones super smart 20120159338 specifically presentation via networked consumption initial summary method selecting comprises receiving metadata server network wherein corresponds available viewing further displaying presenting item response sending request rendering dig language you'll see imagining phone interrogate serve up demand information such schedule list stored movies essentially functions interestingly steve jobs famous promises included fact he'd cracked redesigning awkward interfaces really ambitions same direction stay tuned chat news kit eaton twitterandfast

Exploring Topics and Queues by Building a Service Bus Explorer Tool – Part 1
Due to the breaking changes introduced by the production version of the Service Bus Messaging API with respect to the CTP version, this version of the Service Bus Explorer tool doesn’t compile against the API contained in the Windows Azure AppFabric SDK V1.5 and cannot be used to managed entities in a Service Bus namespace in production.  I published a new version of the Service Bus Explorer tool on MSDN and the related code on MSDN Code Gallery.
exploring topics queues building service bus explorer tool part 1warningdue breaking changes introduced production version messaging api respect ctp doesn’t compile against contained windows azure appfabric sdk v1 used managed entities namespace â i published new msdn related code gallery community technology preview released 2011 constitute foundation cloud based integration infrastructure provides reliable message queuing durable publish subscribe capabilities both premises applications microsoft non technologies functionality seamlessly accessed net via brand servicebus wcf thanks binding servicebusmessagingbinding well support http requests rest over https order exploit it’s necessary create management portal latter provide user interface administer delete topic queue accomplish task use style exposed platform reason decided build forms application allows connect given test post first multi article explain functioning implementation details whose source available archive modification developer particular manage testâ whereas second go through approach followed realize following section basic information more see articles enable large heterogeneous class running exchange messages flexible secure fashion network trust boundaries hosted replicated store maximum size during 100mb expected rise 1gb 256kb sessions creating unlimited sequences accessible apis session correlation meaning multiplexed request reply paths easy way delivery patterns such peek lock transactions ensure batches operations send receive committed atomically detection inbound duplicates allowing clients same multiple times without adverse consequences dead letter facility processed expire before being received deferring later processing particularly handy out sequence need safely put side process waits permit further progress set properties define priority aâ traffic peak entity modeled brokeredmessage exposes various messageid sessionid correlationidâ automatic duplicate enabled communications queuedescription object specify metadata models behavior created lockduration property defines duration consumer peeklock mode receiveanddelete deleted soon read conversely hidden receivers until timeout defined expires time receiver invoking complete methodâ requiresduplicatedetection enables disables changed once modifying requires deleting recreating principle applies permits flatten highly variable predictable stream work distribute load worker processes vary dynamically accommodate incoming volume competing consumers scenario publisher writes compete each one question oriented architecture composed systems interactions between autonomous asynchronous loosely coupled context next increase agility scalability flexibility overall helps decreasing loose coupling individual extends features provided addition consists sequential supports up 2000 number subject future concurrent subscriptions relay copies poll subscription rule specifies filter expression pass action modify sqlfilterexpression sql92 condition ordertotal gt 5000 clientpriority 2shipdestinationcountry ‘usa’ shipdestinationstate ‘wa’conversely sqlfilteraction add remove true selected syntax similar clause update sql command auditrequired 1set ‘high’ severity 1each matching generates separate copy potentially generate subscritpion single receives fetch come served basis excellent solution broadcast many sets mentioned introduction today ability offer gui few months ago storage services handle blobs tables therefore undertake project develop picture illustrates remainder i’ll configure series dive technical actual launch existing choosing under file menu operation opens modal dialog shown below enter name want corresponding authentication credentials three different types credential schemes saml shared secret simple web token easily extend retrieve issuer key clicking view button highlighted red selecting certain clipboard note convention default always owner convenience gives possibility configuration connection frequently namespaces xml snippet elements servicepath optional path within issuername field contains above value issuersecret element lt xmlversion configsections sectionname servicebusnamespaces type dictionarysectionhandler culture neutral publickeytoken b77a5c561934e089 diagnostics traceautoflush indentsize listeners clear addname logtracelistener cat windowsazure samples servicebusexplorer initializedata trace addkey northwind adventureworks appsettings debug scheme sb connectionmanagement addaddress maxconnection 50 startup supportedruntimeversion v4 sku netframework give select drop down list fields automatically populated data parts namespacepanel treeview control navigate browse nodes node right click offers access commands depend panel displays current log error comes especially performed tasks deselecting window option edit finally save bar options displayed varies status shows last already june refresh allow change perform actions choose queuefrom custom max bytes integer maxqueuesizeinbytes live timespan defaultmessagetimetolive history duplicatedetectionhistorytimewindow method lettering expiration checkbox boolean enabledeadletteringonmessageexpiration disable feature requiressession don’t explicitly editmenu text sectionmessage fixed datagridview pairs added dictionary sender sectiontask count msg write transaction checked transactionscope sending batch unit commit check uncheck simulate unsuccessful outbound testing logging transmitted sectionuse receiving creates consume seconds content sent keep track performance statistics example eventually saving associated expand illustrated rules strongly encourage download customize better needs invite share feedbacks ideas comments i’ll illustrate

Integrating Push Notifications with SharePoint Data in Windows Phone 7 Applications
The Microsoft Push Notification Service in Windows Phone offers third-party developers a resilient, dedicated, and persistent channel to send data to a Windows Phone application from a web service in a power-efficient way. In this unit you will learn how create push notifications in SharePoint using event handlers.
integrating push notifications sharepoint data windows phone applicationsthe microsoft notification service offers third party developers resilient dedicated persistent channel send application web power efficient way unit learn create event handlers hands labs applications use services notify users custom events alert changes sources lab list handler alow register bind toast tile display count such number

Implementing Push Notifications in Windows Phone 7
This article is written for earlier version of Silverlight for Windows Phone 7 and may not be fully compatible with the latest version.
implementing push notifications windows phone 7this article written earlier version silverlight fully compatible latest multitasking missing hide fact very moment support 3rd party applications lot reasons iphone user agree more decision running different parallel means power consumption memory higher cpu load factors directly lead reduced experience battery goodbye couple hours screen smooth multitouch it’s „lagging changing between really slow matter evolved today’s smartphone hardwares devices pcs performance capabilities expect innovative sci fi interfaces pc want high definition media real time ish connection social networks identity sacrifices compromises made microsoft sacrifice favor end king probably introduced users anna miles definitely two personas created represent target market miss don’t know pretty job lack feature provides workarounds make think many things same something seems notification experienceto uses concepts simulate behavior one okay tell new interesting even application foreground tap comes up shows whatever necessary worksfor consits components custom cloud service provide data client get’s happens dies gets wiped out won’t chance poll consume resources way wp7 opportunity open httpchannel accept lifetime tells built display message arrives returns url now send information identifies pushes down transfers told tapping opens simple messages arrived source packages timely fashion please note guarantee delivery count use scenarios losing critical typeswindows types raw case runs toast run displayed anyway tile pin shell change picture implement notificationpreparing easy step 1you setup httpnotificationchannel pass privatevoid setupchannel crlf null channelname demochannel try debug writeline creating channel uri anytime channeluriupdated eventhandler lt notificationchannelurieventargs gt httpchannel_channeluriupdated bad exceptionoccurred notificationchannelexceptioneventargs httpchannel_exceptionoccurred opening register binding type bindtoshell catch notificationchannelexistsexception exists retrieving existing find can't close reopen channeluri retrieve retrying unbindtoshellentrypoint re return retrieved sure notificationchannelopenexception already privatestaticvoid bindtoshellnotification notificationchannelbindingexistsexception shellentrypoint remoteimageuri http shared live com 7e81kqtseeomzdlpefps8g web images grouplogo png bindtoshellentrypoint object sender dispatcher begininvoke txterror text exception maybe updated 2we kind we’re expecting let’s wasn’t mention need ready exceptions method loves throw kinds before instance calling previous code sections mentioned sent 3so compose received httpwebrequest sendnotificationrequest webrequest create subscriptionuri post indicate you'll contenttype xml headers webheadercollection add notificationclass isnullorempty txtmessage envelope windowsphone '1 0' encoding 'utf 8' wp xmlns 'wpnotification' text1 wrap byte notificationmessage default getbytes set content length contentlength stream requeststream getrequeststream write reponse sending httpwebresponse response getresponse notificationstatus notificationchannelstatus subscriptionstatus deviceconnectionstatus little bit complex personally i’d prefer wrapper classes developer doesn’t header value stands batching intervals next wrapped request wait answer important what’s still connected listening stop 4make wmappmanifest app element publisher attribute constant otherwise nofiticationchannelexistsexception documented summaryso basically complicated work importantly helps active help less expensive doing actual course itself replace solve problem good helping issue happy download here wpf emulator project

Windows Phone + SignalR = Awesome Possibilities!
Real-time communication. Many software applications on variety of platforms & form factors have a genuine need for it. But persistent networks, real-time connectivity & asynchrony continue to challenge us developers in building such applications. Is there a silver lining? Could we have near-real-time communication in our mobile apps? Imagine the possibilities.
windows phone signalr awesome possibilities real time communication many software applications variety platforms amp form factors genuine need persistent networks connectivity asynchrony continue challenge developers building such silver lining near mobile apps imagine live demonow let’s something little fun before crux article demo sample application action works anywhere earth data connection fact more diverse user demographics merrier work emulator better unlocked side load given xap source code download extract solution visual studio build deploy app essentially shares location connects backend server continuous chat go http signalrserver cloudapp net keep open fire up give yourself name chatroom share join see pushpin bing map actual allowed settings you’ll start out mothership seattle feel free use simulator fake position pop dialog box now away want profanity please show phone’s immediately eh exit leave along disappearing result i’m hoping site running pushpins different parts world used zoom accommodate pins having isn’t hosted massive hardware i’ll try issues force down unpack run locally simple mvc3 fine machine change point localhost instead above hope stays folks places introductionsignalr async library client aids multi connected multiple between clients persisted over best possible transport mechanism combination long polling periodic sockets layer abstracted provide seamless ease development making web started damian edwards david fowler asp team oss github https com cool working conversations jabbr rooms easiest way utilize nugets incorporated project nuget manager command based management console one statement gets dependencies technologies tried solve problem socket io html5 websockets few simply support cross platform ios android through mono low level persistenceconnection class control times abstraction called hub implementation easy persistence learn wonderful posts sampleso learnt think absolutely personal device potentially tons ways leverage technology allow two here mapping users globe phones rest imagination serveryou obviously choices default wanted look showing first ready here’s add package know extend make uniquely track define individual crlf publicclass phoneclient publicstring phoneclientid set publicfloat latitude longitude next functionality disconnect broadcast messages messaginghub privatestatic list lt gt phoneclientlist new publicvoid joinfromphone phoneid float phoneclienttoadd 10 11 12 13 14 addclient 15 caller addclients toarray 16 17 18 19 20 null 21 22 existingclient 23 24 25 26 27 break 28 29 30 31 remove 32 removeclient 33 34 35 pushmessagetoclients message 36 37 addchatmessage 38 39 wondering function calls within well that’s magic actually javascript methods defined ui view shoot index home controller left maps right what’s subtle styling included downloadable script charset utf type text src ecn dev virtualearth mapcontrol ashx url content scripts jquery min js hubs div id 'container' 'chat' br input maxlength button value clear ul chatdialog 'map' legend label usercount mapped span page ajax sdk sure developer pass offered bits below manipulate notice joining sending typed appending those received goes var create signalrhub invoke getpushpins centermap html length entities getlength instanceof microsoft getlocation removeat 40 41 chatdialog' append li 42 43 44 click event handler broadcasting 45 broadcast' 46 47 call method 48 message' val 49 50 51 52 53 54 55 showmap 56 57 58 clearing 59 clear' 60 61 'ul li' 62 63 64 65 66 67 68 69 70 'p' 71 push 72 73 74 75 76 mapoptions 77 credentials auogtnp56_kms3ikua0e p_pbx1owjo6wtpw2xfd hzqfsffsh3fhkgxhfhqd52y 78 center 80 98 79 81 document getelementbyid 82 83 84 85 86 87 88 locations 89 90 91 92 setview 93 bounds locationrect fromlocations 94 95 96 97 99 100 101 102 103 104 105 106 107 108 109 110 return 111 112 113 clientnow waiting interaction develop we’ll regular begin adding appropriate launch ask identified brevity skip xaml markup find both uis indicates awareness figure current geo coordinates physical read mock inputs private geocoordinatewatcher gcw privatedouble phonelatitude phonelongitude privatevoid connectbutton_click object sender routedeventargs present gps geopositionaccuracy high movementthreshold statuschanged eventhandler geopositionstatuschangedeventargs gcw_statuschanged once it’s reference connect ihubproxy signalrserverhub hubconnection 49968 status geopositionstatus watcher stop conserve battery proxy createproxy continuewith task isfaulted oopsie error handling server's deviceid wait tell joined username fly tight binding though passing identifying information whatever needs unique qualifier pinged wakes adds incoming internal collection persist reaches back each functions announce invoking enough types hits posted front end achieve background threads hose chatbutton_click chattextbox empty thread post chatmessage trim chatbackgrounddataworker runworkerasync chatbackgrounddataworker_dowork doworkeventargs takes care posting part informs someone update trigger unlike directly reach case interest happens proposition rigged anytime certain surprised instantaneously listen anything local done chit chatting fellow geeks officially take corresponding fired again sign disconnectbutton_click disconnectbackgrounddataworker isenabled false chatbutton disconnectbutton connectbutton true disconnectbackgrounddataworker_dowork send farewell conclusionthat’s functional allows interactions provides means feasible potential benefit leveraging authorsamidip basu samidip technologist gadget lover solutions lead sogeti usa columbus unit strong stack spends much spreading word discover full cloud backed general passionately runs central ohio group cowpug org labors m3 conf m3conf organization found couple hobbyist projects spare travel culinary adventures wife samidipbasu

Asynchronous scalable web applications with real-time persistent long-running connections with SignalR
I've been spending some time exploring asynchrony and scale recently. You may have seen my post about my explorations with node.js and iisnode running node on Windows.
asynchronous scalable web applications real time persistent long running connections signalri've spending exploring asynchrony scale recently seen post explorations node js iisnode windows application different requirements such rules make don't work kind scaling app gets data loops over calls out high latency mainframe needs maintain connection server old adage hammer everything looks nail really holds true programming space more tools knowledge use better that's i'm advocate polyglot going deep languages learn linq example good dynamics becomes much fun expressive language polling common hammering screw trying chat program poll seconds transaction throw up animated gif until eternity friend another way things done basically open keep forcing client browser wait pretending taking return enough control side model allow breaks transparently re opened break hidden both sides future websockets solve problem baked asp netdoing stock ticker hasn't easy net decent abstraction library talk signalr signaling team working help build multi user isn't socket io nowjs javascript talks lets call similar related perspectives same concepts libraries expect certain conventions probably possible look clients want one wanted complete solution back end create kinds github 12 lines code sufficient level indistinguishable magic suppose sure doitbaby lie here's var name prompt what's receive function message messages append send button click distribute text input val public class hub caller maybe depends roll details signalrsignalr broken few package nuget meta brings install components needed endpoints ninject dependeny resolver play small start visual studio 2010 first empty ui console second new default aspx page add textbox references jquery along script

Smoothing Kinect Depth Frames in Real-Time
I've been working with the Microsoft Kinect for Xbox 360 on my PC for a few months now, and overall I find it fantastic! However, one thing that has continued to bug me is the seemingly poor quality of rendered Depth Frame images. There is a lot of noise in a Depth Frame, with missing bits and a pretty serious flickering issue. The frame rate isn't bad from the Kinect, with a maximum of around 30 fps; however, due to the random noise present in the data, it draws your perception to the refresh. In this article, I am going to show you my solution to this problem. I will be smoothing Depth Frames in real-time as they come from the Kinect, and are rendered to the screen. This is accomplished through two combined methods: pixel filtering, and weighted moving average.
smoothing kinect depth frames real timeintroductioni've working microsoft xbox 360 pc few months now overall find fantastic one thing continued bug seemingly poor quality rendered frame images lot noise missing bits pretty serious flickering issue rate isn't bad maximum around 30 fps due random present data draws perception refresh article going show solution problem time come screen accomplished through two combined methods pixel filtering weighted moving average backgroundsome information kinectby assume everyone heard understands basic premise specialized sensor built capable recognizing tracking humans 3d space true cameras accomplish sensing stereo optics technology called light coding makes possible infrared ir projector color rgb camera purposes emits grid front reflects objects path reflected back pattern received decoded determine sent via usb another device further processing incredibly useful computer vision applications part beta sdk used joint locations human body thereby allowing developers up sorts functionality important setup informationbefore download links demo application source executable need prepare development environment use installed machine http www com en kinectforwindows posting commercial released please sure article’s downloads installs couple run before files databefore dive better express below screenshot raw image reference closer lighter away darker you're looking sitting desk i'm middle bookcase left fake christmas tree right already tell even without video feed low resolution 320x240 looks indeed manifests itself white spots continuously popping out picture comes being scattered object it’s hitting shadows wear glasses scattering limitation limit far see current meters giant square behind that's close room actually extends beyond meter handles can't returning zero solutionas mentioned briefly developed uses different separately series produce smoothed output doesn't completely remove make appreciable difference solutions degrade producing results recording filteringthe first step process transform something bit easier privateshort createdeptharray imageframe short returnarray newshort width height byte depthframe parallel 240 depthimagerowindex gt depthimagecolumnindex lt 640 var depthindex index calculatedistancefromdepth return method creates simple value each placed calculated pushes new values second array begin applying actual filter scan entire couldn't properly want many realistically degrading performance reducing features more later considered candidate take look particular neighboring pixels effectively bands search non frequency distribution takes note found band compare arbitrary threshold filtered broken statistical mode applied otherwise alone biggest considerations ensuring surround displayed next code apply follows smoothdeptharray deptharray length widthbound heightbound deptharrayrowindex deptharraycolumnindex 320 filtercollection 24 innerbandcount outerbandcount yi xi xsearch ysearch amp break elseif innerbandthreshold outerbandthreshold changes original posti recently updated accurate compared post thresholds mean matrix assigned changed matter consider previous representing theoretical visually identify probably edge perspective introduce along placing pixel's half way between individual mostly assured assigning matches dominant feature 'mostly' still chance identifying submissive small variances readings negligible effect though involves discretization deserves separate averagenow hands move calculating number arrays reason reduce produced really notice flicker previously tried interlacing technique never looked smooth experimenting settled set queue store recent queue's fifo collection excellent handle discrete sets weight importance highest oldest lowest created weighting chosen blurring averaging motion final rendering stand straight work fine items once start noticeable trail anywhere go effects less averagequeue enqueue checkfordequeue sumdeptharray newint averageddeptharray denominator count item render imagenow both techniques bitmap colorframe newbyte distanceindex intensity calculateintensityfromdistance blueindex greenindex redindex together nownow shown theory let’s terms provided above side comparison experiment settings well recommend general purpose provides good mix stationary try fill much example turn filters down 10 you'll blunt very fingers webbed don't wall points interesti enjoyed playing learning 'one size fits all' same hardware physical intentions drive choice anything encourage open yourself share ideas improvement borrow neighbor kid’s day give whirl point interest seeing calculation works prior calculations removing 'white' providing best guess hope continue types leave brief demonstration sit wave arms gives idea doing combinations 70 seconds audio keep mind impossible change youtube trust night here direct link youtu yz64kj aeg readingif topic interests highly reading research paper kinectfusion dense surface mapping done amazing area don’t think achieve net pubs 155378 ismar2011 pdf historyjanuary 21 2012 version january 22 include suggestion jpmik comments

Razorfish + Emerging Experiences - Microsoft Kinect
razorfish emerging experiences microsoft kinectas approach one year anniversary kinect launch announced pc commercial sdk released early 2012 http majornelson com 2011 10 31 xbox 360 celebrates effect more 200 businesses worldwide including toyota houghton mifflin harcourt involved pilot program explore possibilities until now companies working within constraints research license consequently applications corporations restricted tightly held private projects proof concept visible demo reels internet people aware technology terms relegated being afterthought something understood distance †nice recent announcement timeline implicitly green lights make preparations releasing enabled everyday use over next expect see ubiquitous part daily environments prevalent interactive kiosks today spread beyond living room dramatic proliferation smart phones tablets day knew everyone seemed boardrooms america question longer whether strategy instead becomes lives limitations undergo much closer scrutiny potential offered mass produced device provides video camera infrared depth four microphone array beamforming capabilities vast taken multiple directions computer vision robotics 3d modeling linked devices inexpensive augmented reality hands free speech recognition based store assistance innovative assisted learning microsoft’s visionary designing revolved around loading processing operating building solely hardware means complex scenarios currently supported made viable through improved software power computers cards price constantly falling actually scalable require improving itself simply processes data streamed leads inevitable future second generation going look answer depends takes forward current version beta shows roots gaming visual even acoustical models tied optimizations required work best size begin troubles small apartments seems well standard rooms painstakingly optimized deal surround sound speakers audio reflections furniture appears trouble large spaces strikingly though capable 640 480 resolutions access 320 240 image streams likewise provide information objects 800 mm ⽠feet sensor capture clearly performance reasons setting problem related fact usb connector bottleneck throttled particular controller configuration requirements moves out real world makes sense leave restrictions imposed tying behind running boost shame infrastructure showstopper nowhere clear consider office developer slide chair back away monitor whenever want debug piece code fortunately don’t cubicle open space fortunate wheels routine down pat anyone wanting business application way unlike natural home environment generally cramped close screen enough keyboard between always two half workspace chief places kinects arm movements wave snap fingers order things happen screens minority report writ achieve turn need move skeletal tracking start enabling fine finger along same lines larger full body sitting chairs typically never anything below waist needs modified take account support partial skeleton level allowed travel upcoming release allows developers build cut strong dependence maturing headed up faces

Kinect Fusion Will Turn Gaming (and More) Into a 3D Fun House
It’s true, people are getting very excited about the idea of Kinect coming to desktops and laptops (it’s available now): Imagine being able to control Windows 7 or 8 with a wave of your arm or finger. However, that seems like child’s play when compared to the new level of interaction the MicrosoftKinect Fusion research project could bring to the wildly popular sound and gesture-control gaming interface.
kinect fusion turn gaming more 3d fun houseit’s true people getting very excited idea coming desktops laptops it’s available now imagine being control windows wave arm finger seems child’s play compared new level interaction microsoftkinect research project bring wildly popular sound gesture interface it’s called technology fuses data top room mapping aware sensors 150 device result kind remarkable sees volume volumetrics object build complete three dimensional picture cool applications working information that’s mind blower microsoft gave demo connected pc running special software turns camera scanner resulting live video image interact virtual objects example saw thousands yellow balls rolled over surface images actually model under same person built within seconds soon affixing themselves microsftie’s body†screen see full look during ces 2012 uses envision microsoft’s

C# Library and Code for Amazon S3
: Amazon Web Services has launched an AWS SDK for .NET (
library code amazon s3important web services launched aws sdk net http com sdkfornet supports infrastructure including s3 cloudfront recommend developers migrate earliest convenience longer maintaining threesharp affirma consulting developed example effort simplify empower use client environment decided together hosting codeplex best way share community involvement future development project descriptionan advanced interfacing powerful features full support data streaming need load memory before sending encryption thread safety live statistics perform multiple simultaneous uploads downloads show progress real time unified object model simplifies maintenance extensions eu buckets solution contains four projects wrapper helper wraps basic common procedures single line calls consolesample console application demonstrates describes various available formsample windows forms app multi threaded graphical legal note 3sharp trademark llc rights reserved under license we're endorsed affiliated associated more fully featured gui experience create manage distributions please see manager built specializes sharepoint silverlight scorecard ocs seattle new york los angeles bay area

From CCR interleaving to TPL Dataflow
Hello,
ccr interleaving tpl dataflowhello mi apologies advance english good time ago i programmed tiny http server robotics library works fine the ccr library great solving parallel problems but a bit odd to most programmers now i am thinking program the server using async ctp tpl dataflows question is how get the same effect as achieved ccr’s interleaving class believe the dataflow tpl documentation that corresponds additionally threading tasks dataflow dll includes concurrentexclusiveschedulerpair type exposes concurrent taskscheduler exclusive pair schedulers cooperates ensure number scheduled scheduler run concurrently long executing soon exlusive task provides asynchronous reader writer lock schedules level blocks target one clearly to use the concurrentexclusiveschedulepair but i can't figure out don’t find a coded example although i searched a lot in the tpl documentation find concept defined could someone give simple concurrentexclusivescheduledpair and define the concept of thanks

Mike's Tech Notes for 6/22/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Down the rabbit hole - Inside .NET
Monday, June 11, 2012 9:13 AM
down rabbit hole inside net monday june 11 2012 13 erix99heywith new release candidate visual studio now known 12 explain difference tpl dataflow tdf built data blocks give short description library groups building part talk first group contains unique commons ones execution thing combines those together each time massage inserted one delegate executed exiting block user create exaction needs provide code provided let's look examples hope clearer action lt gt executes given creator posted sample var actionblock newactionblock console writeline created massages type 'string' write common probably simple posting queue entered post hello show second transform execute return value declared transformblock newtransformblock tostring 'int' convert link before linkto result output automatically third transformmanyblock very similar key results more per input out 'type' many gets single number values newtransformmanyblock retlist newlist 100 returns list initial multiply connect remember still connected beginning outout farther processing although really clear delegates see above power haven't talked parallelism high performance greed behaviors hopefully coming weeks buffer another joining stay tuned תגים vs11

Mike's Tech Notes for 6/18/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Microsoft shows off early peek at Excel 2013 | News
With Release Preview, Windows 8 is ready for businesses to try out, says Microsoft. To get the message across corporate vice president Antoine Leblond demonstrated a range of Metro apps designed for business to the audience at this week's TechEd conference, along with a glimpse of the Windows RT version of Excel.
microsoft shows early peek excel 2013 newswith release preview windows ready businesses try out message corporate vice president antoine leblond demonstrated range metro apps designed business audience week's teched conference along glimpse rt version sneak 8some buy sap app seeing deals sales team working sap's prototype pipeline simulation helps see you're going make quarter bubble chart opportunities size each showing much deal worth position happen confident you'll sale drag bubbles screen difference makes numbers happens sooner bigger opportunity good examples line applications build employees catalogue furniture store rooms go salespeople use look up prices take orders patient care doctors nurses records details including consent forms sign pen dutch public prosecutor's office building give prosecutors mobile access case style documents hollandmicrosoft director erwin visser showed techradar demo application expenses insurance claims adjusters used share functionality photos snapped phone synced pc via skydrive filing claim form send charm turn photo claimslightly more fun ultimate beer rangers written new belgian company sonoma partners customer management data dynamics crm dig detail bars sell ranger reps next appointment bar licence they're visiting recent figures tools site survey checking quality appointments buyersvisser told brewery tried devices disappointed looked wanted different tablets before settled real project who's contact updatesthe 2013microsoft included called interface features seen desktop ribbon tab headings capitals program's signature colour green come tabletsthe status view buttons zoom slider quick toolbar sports icon flipping finger friendly slightly larger styleto help trying released versions several key optimization pack now support include betas bitlocker administration monitoring managing encryption keys centrally advanced group policy changes settings covers policies diagnostics recovery toolset dart work what's wrong won't boot repair faster loading image onto works download candidate filling short connect

IBM Emerging Technologies - jStart - Solutions
Massive amounts of unstructured web data just isn't being leveraged properly. Typical BigSheets scenarios for this include:
ibm emerging technologies jstart solutionsbigsheets extension mashup paradigm integrates gigabytes terabytes petabytes unstructured data web based repositories collects wide range stemming user defined seed urls extracts enriches information management architecture choose languageware opencalais etc lets explore visualize specific contexts such manyeyes component infosphere biginsights solutionwhat problems addressed massive amounts isn't being leveraged properly typical bigsheets scenarios include research analytics structured databases result dated guide strategies support decisions reach business intelligence limited enterprise providing one sided view real environment customer preferences website activity captured through pre packaged outsourced way yourself better understand customers competitors diversify supply chains first discover relevant industry trends extend take control customizable rich tool go beyond database seeing whole picture help levels make provides users new approach keep pace escalation taking structure mine without additional storage requirements valuebroader required total amount warehoused enterprises doubling three years source forrester number growing exponentially billion year up 23 2008 internet world stats use frequency continues increase ability capture collect insights people behind becoming more each day already know exactly looking combining internal external queries adequate finding assembling content requires extensive time effort bit luck attempting patterns opportunities especially aren't quite sure you're allows break down consumable situation frames reference enables organizations translate untapped unknown actionable case scenario illustrates bigsheets's capabilities found here mashups organization start leverage returns contact team

Mike's Tech Notes for 6/12/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

TPL Dataflow Tour | Channel 9
Loading User Information from Channel 9
tpl dataflow tour channel 9loading user information 9something went wrong getting msdnsomething msdnloading visual studio achievementssomething achievements

Download: TPL Dataflow - Microsoft Download Center
If your download does not start after 30 seconds, click here: Start download
download tpl dataflow microsoft centerintroduction start 30 seconds click here

http://msdn.microsoft.com/en-us/library/bb905470

Concurrent Affairs: Concurrency and Coordination Runtime
Concurrent Affairs
concurrent affairs concurrency coordination runtimeconcurrent affairsconcurrency runtimejeffrey richtercode download available concurrentaffairs2006_09 exe 154 kb browse code onlinemicrosoft recently announced prerelease new microsoft robotics studio writing applications robots itself interesting see toolkit appeal even beyond those interested programming under hood powering sdk very advanced technologies including lightweight distributed services oriented architecture common language runtime clr based library called ccr makes asynchronous behavior much simpler typical challenge threaded significant benefit robot require handling many processes sensors motors same time note column version both microsoftâ® information subject change today lack responsiveness scalability periodically hang stop responding user input well server respond client requests timely fashion hasn't seen web browser out due quickly enough reason poor always performing operations such file reads writes database queries synchronously application's thread performs synchronous application basically giving up control thread's processing device hard drive network whatever becomes unpredictable furthermore threads suspended waiting complete tends create more attempt accomplish work creating scheduling destroying requires memory actually hurt performance improve two reasons developers tend write instead first easier developer separate concepts initiating request completion real problem here divorcing syntax required second coordinate actions want performed managed dll greatly simplifies tasks programmer offers number classes allowing simple object model use easily express complex patterns dealing completed high pool execute response phenomenal maximize within couple features anonymous methods iterators developer's dream come true easy way responsive scalable describe ccr's show numerous examples demonstrate works compile demo play you'll find end few need become familiar defined core namespace figure shows relationship between please refer 1â ccr class hierarchyâ the dispatcher classwhen initializes construct creates manages set effect clr's call via delegates order public sealed idisposable int32 threadcount threadpoolname threadpriority priority icollection lt dispatcherqueue gt dispatcherqueues members shown pass constructor desire default one cpu computer notice created fixed logic dynamically unlike special runs checking workload trying predict whether added removed streamlines dispatcher's contributes constructing threads' normal tell name give internally sets property specified names used help debugging visual studioâ® debugger's window allows multiple pools objects differing priorities desired dedicated certain kinds classafter you've constructed maintains queue identify ready wait entries appear usually dispatcherqueue's empty therefore wake virtual enqueue itask task enqueuetimer timespan port datetime timerport dispose 000 items queued item processed until extracted pool's another dequeue associated round robin point calling doesn't take argument possible queues during initialization throughout remainder lifetime turn attention short discard arbiter classesa generic represents type think callback method analogous state threadpool's queueuserworkitem result posted explain happens later zero receivertask gets determine process definition follows register unregister yourself arbiter's interfaces post classthe tap lot against static defines bunch factories specifically factory constructs fields applyclick current id figureâ 2â the fromhandler handler fromiteratorhandler receiver receive boolean persist joinsingleportreceiver multipleitemreceive itemcount variableargumenthandler joinreceiver multipleportreceive ports joinedreceive t0 t1 port0 port1 choice params receivers portset resultport handler0 handler1 interleave teardownreceivergroup teardown exclusivereceivergroup exclusive concurrentreceivergroup activate arbiters offered brief description indicating each less scenarios example calls varying data types define feature won't understanding encourage examine namespaces figureâ 3â common descriptionfromhandlerindicates fromiteratorhandlerindicates enumerator enumerated identifies operation receiveindicates single delegate takes parameter port’s multipleitemreceiveindicates array multipleportreceiveindicates per joinedreceiveindicates different parameters ports’ choiceindicates ensures passed non persistent interleaveindicates back various part similar reader writer synchronization lock concurrently addition executes tearâ­downreceivergroup identical teardownreceiverâ­group except once executed again future run conâ­currentreceivergroup value interleave's persistence important working effectively walk through composed active registers tells forget continue never registered send decides ultimately examplesthe best understand several happening program small demonstrates now found ccrdemos cs msdnâ®magazine site shutdown initialize simply uses statement before returns exiting gracefully exit exited caller demos make helper private msg args console threadid currentthread managedthreadid writeline hitenter sleep 250 chance hit enter readline figureâ 4â initialization dq spawndemo portarbiterdemo multipleitemdemo spawn automatically over wraps natively spawning threadpool together contains fifo capable holding references list stringa stringport traverses handle none port's internal placed next thing false indicates words watching third activated needs things registration previously scanned queuing case efficient postarbiterdemo posts stringb passing allowed unregistered displayed currently activating appears loop 10 tostring batches knows strings ten join 50 variety causing five times following output 12 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 demoat pretty good sense pieces fit pull far basic really start quite sophisticated frequently coordinating asyncstreamdemo read asynchronously filestream intend fileoptions flag already perform beginread endread beginwrite endwrite written adapter map translate apm apmtoccradapters accompanies source figureâ 5â asyncstreamdemo fs boot ini filemode open fileaccess fileshare readwrite 1024 byte 10000 bytesreadport null exception failureport length ref bytesread resize bytes environment newline encoding ascii getstring failed error message initiate stream results returning fail indicated variable variables initialized type's reference derived arguments normally stream's buffer offset count starts completes provided invoked checks successfully returned unsuccessfully throws catches anything successfully†displays unsuccessfully†object's designed select respective chosen asyncstreamportsetdemo exact job slightly together†success failure†streamreadportset overload discussed section having twice variations going t19 commonly serialasyncdemo iterator sequentially blocked gives syntactical simplicity sequential scale support hundreds thousands pending figureâ 6â serialasyncdemo savewebsitetofile ienumerator webresponse yield return getresponse webrequest http wintellect com wr break webdata html numbytes getresponsestream emptyvalue ev wrote inside adapters deal activates fails telling done failure closed exits sequence operationsthe asynciocoordination1 issues made proper succeeded c_imageurls webreq requestnum capture webresp contentlength responseuri asynciocoordination2 allow access resource ensure mutual three figureâ 7â coordinating asychnronous responseport requesturi entire soon detected exclusively finally group simultaneously near touch shared monitor mutex around block discourage better move successful aspects powerful experiment bit flexibility asynciocoordination3 introduce timer timeoutport timeout previous milliseconds date figureâ 8â coordinating frommilliseconds 2000 dt seconds responses responseurl expire expires potential race conditions conclusionthe provides consistent framework fcl wrapped existing integrate coded robust reliable concise without blocking os thus enabling scaling sacrificing quietly tucked away potent technology applied availability included msdn channel video development channel9 showpost aspx postid 219308 questions comments jeffrey â mmsync richter cofounder training consulting firm author books press 2006 contributing editor magazine 1990

Using the Concurrency and Coordination Runtime
concurrency coordination runtime posted nick gunn jan 28 2009 architecture amp design developmenttopicsperformance scalability programming net multi threading addthis button begin end introductionthe ccr asynchronous message passing library platform provides set small powerful primitives enable different approach structuring applications effective use result application more responsive scale better robust intriguing aspect deliver benefits same time reducing sometimes removing need explicitly deal threads failures locks mutexes low level synchronization currently single threaded offers possibility increasing responsiveness utilizing available cores whilst retaining conceptual simplicity original code base alternatively already match improve throughput simplifying codebase particular simple high performance implementation extremely lightweight type safe channels connect objects actor oriented view world primitive scheduling constraints really spawn tasks post messages components process declare via called arbiters under results well incoming requests ensure honored before executing model reason failure causalities effectively means propagating context through series related sub such task fails throws exception dealt isolation place without regard thread originally raised utilization future processing power schedule work over existing pool prefer custom cases nevertheless exposure mechanism normally kept minimum easier integration operations key improving individual processes down efficiency bound tend orders magnitude slower compute blocking effect suspending useful resources case preventing being used pending dispatching asynchronously free until completes sequencing separates initiation each operation completion resulting source difficult follow uses novel iterators bring control 'asynchronous passing' mean communicate sending data what's subsequent reply guaranteed temporal relationship sent probably processed point received reality purely intra somewhat stronger guarantees essential models inter computation everywhere makes building block constructing scalable distributed systems fundamental types ccrthere number basic make up arbitrary pieces execute taskqueues dispatcherqueues exact list awaiting execution vanilla clr known dispatcher remove queues ports essentially nothing linked lists producers generic overloads safety provide glue between port define contraints created arrives queue receive various ship many composed form higher constructs concepts mind let's look first console host examples note tie belonging static args var dr newdispatcher taskqueue newdispatcherqueue samples go here call prevent exiting readline although run multiple encouraged round robin amongst registered retrieving starving others enqueue directly simplest way don't even arbiter class contains convenience methods fromhandler creates delegate anonymous one placed executed gt writeline hello common there's involved somewhere next snippet typed handler whose signature takes newport lt activate again things going pays understand possible 'receiver' satisfied soon arrival calls ties specified critical thing once activated receiver consuming few bytes memory important concept defined illustrated below take above example switch last two lines now alter sample slightly put see happens… thrice you'll printed out extension method simplifies equivalent following syntax false parameter boolean passed indicates transient discarded want arrive flip value true occasionally produce surprising order generates relevant unless nested part larger composition scheduled persistent immediately item sufficient concurrently hence differs ways importantly fixed determined construction expects doesn’t typically matter grow shrink dynamically calling default dispatcherqueue constructor constrain behavior ordering preserved perhaps sit loop fortunately very iterative allows express fairly natural exploiting iterator functionality replace newarbiter processmessages schedules new staticienumerator itask yield return loops indefinitely waiting invoked continues wanted empty written lambda handle within bool fdone isnullorempty elseconsole finished tool toolset write sequence non manner close synchronous counterparts follows topleveltask taskyield iterativetask far looked receivers introduce arbitrations nest choice simply chooses waits signal proceeding processchoice portset emptyvalue determine success select wrapper around independent convenient pass entity successfailureport itself derived portsetthe join both illustrates principle port1 port2 joinedreceive throttling access limited resource second service arbitration interleave conceptually similar reader writer lock semantics readers priority running declaration protecting notional 'cache' updateport updatecache queryport querycache stopport shutdown newinterleave newteardownreceivergroup cleardowncache newexclusivereceivergroup onupdatecache newconcurrentreceivergroup onquerycache appropriate groups indicate allowed interleavings concurrentreceivergroup associated conversely exclusivereceivergroup addition placing group posting teardownreceivergroup fair additionally per basis necessarily relative mentioned earlier allow logical sequences style that's closer we'd frequently web request database file enabling come easily opportunity significantly increase pattern bridging apm beginxxx endxxx based observation asynccallback public voidasynccallback iasyncresult ar copy filestream target buffer byte 128 1024 bytesread beginread length null returnarbiter iar endread beginwrite endwrite instructed upon underway proceed step fully potentially thousands notice intent remains clear read repeat done keep handling omitted normal try catch won't cut affinity indeed 'step' previous approaches errors encoding propagate cause considerable bloat caller callee require substantial changes shows required side resultport beginreadtry break endreadyield stop newsuccessresult obvious unwieldy error prone desirable characteristics alone routines cleaner much support remain explicit outlined declared flow paths regardless allowing arbitrarily complex graph causality typical instantiate attach inform exceptionport foregroundcolor consolecolor red caught tostring resetcolor addcausality newcausality having handled routed onto conclusionin conclusion opportunities terms dependencies describing distributes seamlessly simultaneously frees dealing full advantage increasingly core machines software opinions expressed those author employer article against freely 'microsoft robotics developer studio 2008 edition' please check license agreement further details

http://www.promrds.com/Downloads/ProMRDS_Ch02.pdf

.NET Framework 4.0 Task Parallell Library vs. the Concurrency and Coordination Runtime
I really love Concurrency and Coordination Runtime (CCR) and I have a major product built around CCR. Ever since the .NET Framework 4.0 Task Parallel Library (TPL) was released, I've been contemplating moving off of CCR.
net framework task parallell library vs concurrency coordination runtimeintroductioni really love runtime ccr major product built around parallel tpl released i've contemplating moving compelling reasons consider adopting over example part tools microsoft visual studio center therefore standardizing new patterns practices supported better unknown typical developer overkill simply handle asynchronous work unfortunately choosing between building need easy symmetrical solutions much more granular general tailored solving problems typically encountered robotics many fit somewhere inside logical way comparison replace segment functionally code prototype sample developed understand within i'm going walk through replaced functionality constraints caveatsbefore reviewing facts clarify first don't know internals mimics behavior access source accurate focuses replacing accurately performance worse equivalent feature complete limited scope receiver arbiter review things choice interleave multipleportreceive arbiters suspending creation nothing exceptions article assume familiarity introduction beyond you'll find helpful resources end finally goal look extrapolate conversion experience determine whether parts starting point developer's evaluation simple answers mind begin overview took prior extending microsoft's msmq doing assembly classes mimicking here summary based port serves conduit generic class tied carrying message payload containing delegate function accompanying data handles activation dictates pattern stated earlier tie dispatcherqueues dispatcher pulls messages executes set threads allocated creating removed reference ran execution flow mirrors graphic below depicts figure pdc 2008i'll each detail lt gt implementation public internal handler dispatcherqueue queue post classref var invoke invoket enqueue centers packaging execute leverages generics keeping spirit method initiates everything leveraging type safe functions hide specific coordinating interface clean ihandlerinvoker wraps together consumption downstream works conjunction

Patterns for Parallel Programming [Hardcover]
Timothy G. Mattson is Intel's industry manager for life sciences. His research focuses on technologies that simplify parallel computing for general programmers, with an emphasis on computational biology. He holds a Ph.D. in chemistry from the University of California, Santa Cruz.
patterns parallel programming hardcover timothy mattson intel's industry manager life sciences research focuses technologies simplify computing general programmers emphasis computational biology holds ph chemistry university california santa cruz beverly sanders associate professor department computer information science engineering florida gainesville techniques help construct high quality correct programs including formal methods component systems design applied mathematics harvard berna massingill assistant trinity san antonio texas interests include distributed institute technology 0321228111ab08232004 build come built multiprocessor workstations massively supercomputers cluster haven't program wonderful machines oh few love challenge shown types problems force fit onto computers especially professional lives ignore peril going mainstream multithreaded microprocessors multicore cpus pcs clusters game consoles taking over world ready flood market hardware run full speed write old problem even early 1980s killer micros started assault traditional vector worried endlessly attract normal tried everything think level abstractions implicitly languages language extensions portable message passing libraries many years hard work fact matter didn't overwhelming majority invest effort software common view can't teach new tricks solved until fade away generation takes don't buy defeatist attitude remarkable ability adopt look fortran now writing elegant java sophisticated object oriented designs isn't experts way they've create pool capable that's book comes want capture essence expert algorithms communicate essential understanding readily master adopted accomplish task pattern made choice project devotees looking field conquer ways applicable example very effective provided use talk elements extremely helping contains opens couple chapters introduce key concepts focus jargon used opposed being exhaustive introduction itself presented four parts corresponding thefour phases creating finding concurrency programmer works domain identify available expose algorithm structure structures organizing supporting shift source code consider organized manage shared data implementation mechanisms final step specific constructs implementing making up spaces tightly linked start top through time bottom detailed goal need more environment notation expressing within program's confronted large confusing array environments fortunately community converged around three openmp simple extension memory mpi library features standard class readers already familiar one notations completely included discussion appendixes closing working presenting people exciting development see end expect others ideas better assuredly missed important really belong embrace change forward engaging larger iterate update improve truly represents consensus real begin guide creation won't rest day sequential rare 0321228111p08232004

Download: Patterns for Parallel Programming with the .NET Framework - Microsoft Download Center
This document provides a detailed and in-depth tour of support in the Microsoft® .NET Framework 4 for parallel programming. This includes an examination of common parallel patterns and how they’re implemented without and with this new support in the .NET Framework, as well as covering best practices for developing parallel components utilizing parallel patterns.
download patterns parallel programming net framework microsoft centeroverviewthis document provides detailed depth tour support microsoft⮠includes examination common they’re implemented without new well covering best practices developing components utilizing top pagesystem requirementssupported operating systems windows 2000 server 2003 2008 vista xptop pageinstructionsclick 'download' link commence pageadditional informationthis written stephen toub computing platform team based visual studio 2010 two versions available one code samples basic page

http://www.sigsoft.org/phdDissertations/theses/JorgeOrtega.pdf
http://www.eecis.udel.edu/~cavazos/cisc879/Lecture-04.pdf

Word clouds considered harmful » Nieman Journalism Lab
In his 2003 novel Pattern Recognition, William Gibson created a character named Cayce Pollard with an unusual psychosomatic affliction: She was allergic to brands. Even the logos on clothing were enough to make her skin crawl, but her worst reactions were triggered by the Michelin Tire mascot, Bibendum.
word clouds considered harmful nieman journalism labin 2003 novel pattern recognition william gibson created character named cayce pollard unusual psychosomatic affliction allergic brands even logos clothing enough make skin crawl worst reactions triggered michelin tire mascot bibendum although it’s mildly satirical relate condition similar visceral reaction especially those produced data visualization stories fortunate idea cloud here background represents usage document resizing individual words proportionally frequently used jumbling vaguely artistic arrangement technique first originated online 1990s tag famously described mullets internet display popularity keywords bookmarks more recently site wordle made radically simpler generate such ensuring accelerated use filler much personal pain what’s wrong anyway understand helps principles strive new york times strongly believe reporting many same elements traditional story effective narrative pares away extraneous information find context help reader basics subject interviewing flaws sure conclusions prettiness bonus obliterates ability read worth adding wild style strange interface course throw out window here’s example illustrate six months ago privilege giving talk visualized civilian deaths wikileaks war logs meeting city hacks hackers wanted look touch key good better way foil goofus gallant found one please compare two visualizations †derived set differences apparent i’m sorry harp fast company particular i’ve seen news organizations reporters sidestepping limited knowledge material peering patterns reading tea leaves bottom cup you’re left shoddy fails hold time see presented insight die little inside starters support crudest sorts textual analysis figuring protein getting count amino acids wildly misleading party feelings obama largest implausibly policy mainly importuned don’t automatically excluded fair stopwords otherwise dominate phrase thematic reach accurate looking equal sizing car blast indicate large number reports bombs cars explosions relative frequency lesser doesn’t focusing occurrence specific instead concepts themes miss fact different truck vehicle bongo kia very popular iraq biggest problem applied situations appropriate argue sense point specifically analyze though i’d still suggest alternatives ludicrous complex topic describe events confuse signifiers signify readers leave figure themselves know ln local national cop combat outpost police officer interesting requires form translation explanation bring quickly up speed provide nothing regard furthermore chose focus within displayed clear hand require squint stereograms until pops place case occupation involved lot ieds nobody lead astray initially thought saw surprising dramatic rise sectarian violence surge sect appearing soon figured seeing less levels bureaucracy adoption army requirements requiring detainees horrific baghdad something indicated text series each year conclusion hopefully now sadistically inclined piece worry covered jacob harris senior software architect

Prevailing historical winds
A diagram of the prevailing winds at : . The blue diagram at left is a wind rose: the bar length shows the frequency of winds from each direction. In the red diagram at right the bar length shows the average speed of winds when they come from that direction. For more information, see about this site.
prevailing historical winds diagram blue left wind rose bar length shows frequency each direction red right average speed come more information see site history copyright 2011 daedalus bits llc rights reserved

Mike's Tech Notes for 6/8/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Progress Reporting in C# 5 Async
Note: This article was written using the first CTP of TAP ( released 2010-10-28 )
progress reporting asyncnote article written first ctp tap released 2010 10 28 table contentsthis new task based asynchrony pattern concentrates support explain simple program gets text server asynchronously show each layer solution implementation framework assume already know async await work firstly become application developers go under hood explore method really addressed net appears front centre wishful thinking hope methods cancellation hosted page web shows short list trite quotes generated randomly obtained takes seconds generate quote flushed network one per second requirement write consumes service both current percentage soon arrive ether wrote winforms app client here entire code form publicpartialclass form1 public initializecomponent shown gt txtresult downloadasync done lt var wc webclient eventprogress downloadstringtaskasyncexprogress progresschanged progressbar value progresspercentage return downloadstringtaskasyncex http ancillaryasync nickbutler murphy ashx quite lot going piece turn lambda handle event notice use named eventually returns completes handler appends result whole process finished extension class yield control executing url well good object called parameter fudge little bit gloss over uses classes deserves section itself need tell now raised suitable points during execution ui thread eventargs contain information add updates controls fun doesn't exist publicstatic downloadstringtaskasync uri address cancellationtoken iprogress downloadprogresschangedeventargs reports give access stream buffer meet requirements couple right though reads openreadtaskasync readasync source byte offset count used two includes arrives publicint set publicstring staticclass webclientextensions newbyte 1024 bytes empty total int32 tryparse responseheaders httpresponseheader contentlength out len length break encoding getstring null args 100 report happens perfectly correct allowed forms openread read means blocking safe execute interesting detail create instance time call fired synchronizationcontext post tried reuse single race condition between handlers next that's caller creates passes magic few types look signature actually interface defined ctp's asyncctplibrary dll assembly namespace threading publicinterface remember implements passed makes sense yes fortunately publicsealedclass publicevent eventhandler action privatereadonly m_synchronizationcontext edited above highlight bits basically instantiate captures thread's inside raises previous events being handled subsequent calls reused objects instances bug static factory can't definition delegate publicdelegatevoid teventargs sender constraint type derive helps keeps happy debuggerdisplay m_value publicclass ties together wrapped before sort much easier consumers trivial even yourself still patterns keywords anders team great job arduous microsoft implementing versions expect provide overloads users more doing increasingly asynchronous world enjoyed reading thanks history21st november initial

Mike's Tech Notes for 6/6/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Bravewords.com > News > RUSH
RUSH's anxiously-awaited new album Clockwork Angels will be released on June 12th via Anthem/Universal in Canada and their debut for Anthem/Roadrunner Records in the US. Revered BraveWords.com Editor In Chief Martin Popoff has heard the album and provides (as usual) an in-depth, step-by-step, track-by-track synopsis of the magnum opus we are all just dying to wrap our ears around! Check out his massive glowing 10/10 review below:
bravewords com gt news rush rush's anxiously awaited new album clockwork angels released june 12th via anthem universal canada debut roadrunner records revered editor chief martin popoff heard provides usual depth step track synopsis magnum opus dying wrap ears around check out massive glowing 10 review below hard believe first full concept willy wonkas prog metal being complicated oblique angled tale involving less steampunk rumour much more march time wrapped up meaninglessness non believer except sort inner temple building garden candide style vapor trails spirit sound red yellow blue crimson frantic textured high shelf glorious dour apt result ascribing neil’s belief wetton era mixed van der graaf generator victorian weight lead lined box two institutions therein lies one few nods there’s “watchmaker” peter hammill singular triumph results yes before even music really ponder here lyrics light narration visuals exo story kevin anderson best albums alone mostly abstraction further caused demarcation necessary chapters welcome hugely ambitious exclusively dark songs stand soon mouthed crowds wrongness hockey barns nature feels unified purposeful signals pastels †it’s baffling invention old “the future meant be” parlance gone alex’s trinket layering acoustic accompany riff always thought sounded tear woofer logically tinkle production brightness started grace reared head varying degrees enrageable persona throughout save suppose rush’s bassiest quake drums never fat warm powerful geddy alex storm along through blustery many neo maiden death magnetic sodding conventional verse chorus structure redefinition word “break ” boomy resonance captured inside three months brand year studio toronto called revolution recordings approach writing crazy musicks handing neil make sense professor supposed himself pile spontaneity oxymoron until hear exertion album’s 66 minutes literally conducted drumstick producer nick raskulinecz obviously suggest fills singing stooges routine makes fourth stooge grooviest playing groove area necessity rushwriting rarely bothered think he’d admit he’s white man ergo gorgeously falls end bars town helping create hot mess ‘70s type sell fellow english cynics born tyme squelching moors you’ll glad know person thinks balance actually better advance ‘caravan’ ‘bu2b’ both those fit despite recorded half earlier essentially slide rule grunge getting away family farm next surmises faith bashing sets cloud over rapes rest title comes ain’t cool distraction live setting huge swooping finale close show remarkable picture emerges now imagined 120 years ago world lit fire steam contraptions graphically sonically aurally representingly played ragged 21st century schizoid undisputable singularly bright rush… kings 1977 wonders 1971 closer inefficient frump king sure snap permanent waves looking mortality carrying extra 15 pounds geddy’s deteriorating yodel voice probably knees month words worn wisdom guys turn inspired improbable crucible jammy writes perfectly line want ascribe order none layers enigma feast hours reflection back record ‘the anarchist’ aptly named conjures another subtle dimension whole that’s post punk ged angling chords melodies everything sour sweet jamming vibe ringing beatles chord ends brings creep haunting inter song bits evokes shining horror lone trader horne ‘carnies’ hit between eyes lyrically immediately conjured classic noir william lindsay gresham’s nightmare alley ass trip crypt gobs magazine heavy weird bloody ‘ell ‘halo effect’ perpetuates coincidental connection making read again dragging immersion insistent consistent garagey welled wattage claustrophobia mysterious manchestered explosive leads ‘seven cities gold’ influenced cormac mccarthy influences stultifying environs including john barth michael ondaatje joseph conrad come wreckers’ dauphne du maurier switch instruments go serious shipwreck reason fantastical imaginos saga sandy pearlman oyster cult perhaps ‘headlong flight’ true single way done days opens ‘bastille day’ drum quote proceeds eventually passion filled still total weirdly detached bitter life necessarily plays second minute hour hands chronos ‘bu2b2’ clearest indication uneasy use arrangements rock play garden’ real 16 piece section david campbell eno glass contrasts jarringly party rocker ‘wish well’ aggravated bread odd ‘cos rocks forthrightly byrdsy tinge calling ‘stick out’ heaviest becomes lifting under closes journey laughably epic flourish although surge undermined sorta hangover final strained strains chilling give hope aforementioned idea candide’s garden… analysis very zen musical accompaniment oscillates operating room anesthesia drone enticingly sliced shifted strange landscape obscure curmudgeonly piled worthy intellectual ideas grows finer fiction writer curious see received lot exasperation matter response can’t deny purpose focus sad anguished

www.many-eyes.com

Mike's Tech Notes for 5/22/2012

Today I checked out the following sites and found them useful, so I thought I'd post about them for both my are your reference in the future...

Windows Phone Shake Gestures Library
There are more than a few very successful mobile applications that use the accelerometer as the main user input. Most commonly used in driving or flying simulation games, the accelerometer in mobile devices is a very powerful tool. But there are other applications/games that use the accelerometer. You can imagine applications like magic 8 ball, where you need to shake the phone to get the perfect answer to a very hard question, implementation of a casino-like slot machine, where you need shake the phone to start rolling the dice, or many other similar implementations. The UX aspect is clear, simply shake or move your phone to trigger some functionality.
windows phone shake gestures librarythere more few very successful mobile applications use accelerometer user input commonly used driving flying simulation games devices powerful tool imagine magic ball need perfect answer hard question implementation casino slot machine start rolling dice many similar implementations ux aspect clear simply move trigger functionality good support api relatively easy plain vanilla raw way want drive logic recognizing gesture work yourself well lucky came blog means you’ll read library uses detect “shake gesture” 3d space three different axes †now let’s assume “continuous motion one changes direction several times ” shaking vertically axis up down time continues therefore trying look following continuous swings without major “still” periods during isn’t shaken moving meaningful enough register shakethat down… same applies left right back forthfor example take figure visualization captured data green line representing case represents peaks two positive greater negative smaller shakegesturelibrary recognizes valid raises proper events note works real see event soon algorithms simple don’t require lot cpu memory occurs rest post includes short explanation interested welcome recipe page apphub download sample application documentation applicationonce shakegestures dll follow five steps set add reference statement file header shakegesture eventshakegestureshelper instance new eventhandler lt shakegestureeventargs gt instance_shakegesture optional parametersshakegestureshelper minimumrequiredmovesforshake implement handler step privatevoid object sender _lastupdatetime dispatcher begininvoke text datetime tostring currentshaketype shaketype holds property identifies finally activate helper binds phone’s starts listening incoming sensor detection shakegestureshelper active true continue working directly class doesn’t block events†listens arrives thread ui update dispatch code run done method mycontrol control important configuration parameters coding testing found individualized depends nature actual made give plenty properties tweak tune purposes various aspects algorithm changing change application’s sensitivity “force” shakes duration full here examples shakemagnitudewithoutgravitationthreshold vector magnitude force bigger value considered vectorminimumshakevectorsneededforshake determines number vectors needed order recognize segment” timer measure instead depend fact generates 50 per second between each around 20 msec total roughly 100 intervals world clock required segment signal think parameter raise usual feedback comments thank arik poznanski helped announcements twitter wp7devfollow yochay twitterget started free tools training edited barbara alban

Detect Shaking Motion on Windows Phone 7
Download the code
detect shaking motion windows phone 7download codethe day msdn forums one asked i've playing accelerometer lately took great joy answering along providing working implementation question asking left right direction made class detects up down totally ignoring axis together now though extending consider wouldn't hard code detecting abstracted called shakedetector algorithm used few variables constants defined modified tune behaviour classes constructor accepts optional parameter many times shaken before considered acceptable raised lowered control device needs minimumshaketime takes time span defines maximum length overwhich shake sequence occur user moves way meets requirements type wanted shakedetected event raise reduced moving directions north east south west inbetween those kept angle ensured atleast minimum difference between angles thought map make easier understand _accelerometer_readingchanged object sender accelerometerreadingeventargs currenet acceleration vector meet magnitude care gt minimumaccelerationmagnitudesquared prefer work radians sake reading degrees following contain accelerating 180 math atan2 pi degreestodirection detected same last ignore amp _shakerecordlist _shakerecordindex shakedirection none return save list shakerecord record new eventtime datetime _minimumshakes checkforshakes startindex lt endindex subtract onshakeevent example found skydrive account here want see program action video youtube codeproject tags programming

Reactive Extensions responding to UI events
One of the great things about the Reactive Extensions is that they allow you to express rather complex interactions simply. For this example, we’ll consider the mouse drag drop operation in Silverlight. Note: The identical code works in both the web based Silverlight and the Windows 7 phone. If you want to download the phone version of this code, it is available in C# or VB.
reactive extensions responding ui eventsone great things allow express complex interactions simply example we’ll consider mouse drag drop operation silverlight note identical code works both web based windows phone want download version available vb one indicators simplicity explain concept mother go something record start location press button down moving end until up calculate difference between locations move image dragged accordingly now let’s see beauty programming model compose multiple expressions together concise manner here’s accomplish above process dim startlocation mousedown endlocation mousemove takeuntil mouseup select new reads nearly same description gave actually bit more slightly verbose point couple details wrap first need declare variables used rx subscribe events discussed post evt observable fromevent mousebuttoneventargs mouseleftbuttondown eventargs getposition mouseleftbuttonup mouseeventargs we’re here notice grabbing event track form itself use try fast time takes canvas mean movement detected before you’ve tracking drastically increases performance reduces possibility soon last thing sample placed distance recorded query action moves sub value setleft settop wpf samples wp7 page

CS 585 A1: Gesture Recognition
Design and implement a computer vision system that can recognize and distinguish between the following human gestures:
cs 585 a1 gesture recognitionproblem definition design implement computer vision recognize distinguish between following human gestures waving one handwaving both handsopening closing hand regular fast intervalpointing finger order complete first project within prescribed time frame make simplifying assumptions background contain yellow skin tonesno natural light coming windowsonly user interact timeuser's uncovered body parts hands face never overlapuser wear sleeved shirtsuser perform above timeuser invent try trick program such possible extensions useful variety applications interaction method implementation different identify dominant objects interest scene determine each object doing identifying objectsin relevant follows steps detection movement pointing user's therefore ignoring non pixels eliminates lot clutter implemented labeling falling range hue saturation value space smoothing smooths out binary map applying opening eroding mask size dilating distinction identifies areas computing series successive linear projections axes grouping together larger average frequency count projection computed along axis vertical slices slice another horizontal finally third separate close grouped single pass noise elimination very small width height area smaller threshold values considered discarded understanding objectsafter separating several tries action performing techniques allocated memory store information kept over 10 frames attributes velocity inferred 0th 1st moments yielding centroid position properties previous computes distance current centroids identified returns match lowest unless case none score represents fist counterpart used object's assume higher velocities imply greater probability exceed use function form apply stretch push positive waves near ratio ago adjustable parameter compute inverse taken maps template matching stored image index against two templates straight up slightly outward flips accommodate left handed users best re sizes stretches once dimensions bounding box same those found comparing files entire yields accuracy allowing fingers rotated angle high 45 degrees makes false positives easier occur final pseudo probabilities scores averaged exponentially decaying weights decay factor allows factoring still giving weight more recent real adjusted fitted experimental results continuous ranging indicating likelihood performs specified scoresfor set equal maximum category wave second largest 'motion' difference ensures low deemed experiments test performance primarily concerned record recognizable well actually being performed 'ground truth' input examiner recall roc curves visually trade offs true rates note ignore running usage analysis meaningful context observed drop machine moderately powerful workstation undergraduate lab system's computation requirements modest enough run focus instead achieving recognition rate experiment subject sits down front camera initially moving outside camera's view keyboard configured append line containing tab separated text file processing manually inputted calculated runs instructs sit seconds warms requests go simultaneously pushes number key open point hears begins indicated arbitrary period stop presses indicate stops asks times procedure outlined testing three yielded total 2732 reactive display created paint screen draws blue circle circles become darker eventually disappear crowd much allow draw new shapes although probably accurate sketches pencil paper way certainly fun raw data lines formatted lt digit code ground truth gt pr newline confusion matrixtrue class hypothesized 1361 23 19 13 16 240 44 189 125 17 249 36 331 913accuracy 976precision 938recall 979accuracy 970precision 811 929accuracy 918precision 666recall 962accuracy 967precision 883discussionsuccessesour seems four defined good particular excellent particularly important sees longer intervals recognizing couple major problem before provide necessary redundancy even problematic 'broken' drawn limitationshowever detected success weaknesses include comparatively weak attempts looking sudden negative changes surface present fully opened closed change resulting changing compensate averaging entirely robust example fixed fail quickly slowly quite potential plane radial lens appears challenging assumptionsadditionally constraining practical reality people move possibly happens interprets merge incorrectly indicates rapidly painting unfortunately causes overlap recognized settings lighting closer person's color labeled misinterpreted faces reviewing original expectationswe expected foresaw many shortcomings side effects relatively primitive methods employed tracking nevertheless proceeded choices believing sufficient future work extensionsour successful meeting extend remove adaptive currently adapt ranges learn infer closest given conditions sequential regions highest active poses problems items come sometimes rectangles large boundary excludes thinner connected wider ones approach solve algorithm result distinct multiple intertwined overlaid top remedy contour strategy conjunction border appear track begin remember fact occupying susceptible points characterized feature spontaneously extra credit functionality developed game adjusts dimensional virtual world conclusions built reasonably without touching mouse control examined argue serves feasible prototype simplified suggested ways eliminated overall consider product credits bibliography horn berthold klaus paul robot cambridge mit press 1986 li andol opencv mind 27 march 2009 february 2011 http www info hci 830 htm

http://graphics.ethz.ch/Downloads/Publications/Dissertations/Kwo07c.pdf
http://articles.ircam.fr/textes/Francoise11a/index.pdf
http://www.cs.cmu.edu/~dmarg/Papers/Robot-Gestures-AAAI98.pdf

iPhone Development: Detecting a Circle Gesture
In
iphone development detecting circle gesture beginning chapter gestures think covered topic fairly well liked included few more custom point writing already way over page count back didn't good idea become common experiment circles include code book two reasons one reason method really quite long taken lot explanation spare pages second feeling there's much easier efficient go need build certain amount tolerance detection i'm sure decent chance better ways detect google search turn up sample out decided i'd update post please see want means download project right here app very basic traces shape draw tells detected doesn't counts encapsulated re usable technique pretty self contained requiring three instance variables overriding touch handling methods view subclass made drawing work controller class here's description algorithm i've used exact implementation touchesbegan withevent store user first tapped screenin touchesmoved each additional comes storing orderin touchesended final number checks doing computationally cheap ones avoid having expensive ruling obvious non based variance threshold defined constant end far away start operation took seconds okay probably intentional remove check don't stored points can't false positives lingering taps loop through touches determine top bottom left use approximate center average radius order making point's distance within angle formed current flows natural continuously increase decrease sequence complex stated earlier accurate until light functional

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=13&ved=0CFIQFjACOAo&url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.11.847%26rep%3Drep1%26type%3Dpdf&ei=2_W7T4icHY-16AHV3MTjBQ&usg=AFQjCNGmKe8TjW_kKh1RBjovsZ3gf1hD9g

Make Async Your Buddy With Reactive Extensions
For a long time, good folks like Matt Podwysocki have extolled the virtues of Reactive Extensions (aka Rx) to me. It piqued my interest enough for me to write a post about it, but that was the extent of it. It sounded interesting, but it didn’t have any relevance to any projects I had at the time.
make async buddy reactive extensionsfor long time good folks matt podwysocki extolled virtues extensions aka rx piqued interest enough write post extent sounded interesting didn’t relevance projects fortunately now work github pleasure guru paul betts project actively uses man mind blown hits hurricanewhat really blew away allows handle complex interactions declaratively need chain callbacks together worry race conditions easily compose multiple operations it’s powerful way describe think ienumerable ienumerator involved iterating over enumerable take those reverse polarity that’s iobservable iobserver interfaces enumerate existing sequences queries against future events hear sound head asploding again tendency twist contort strange ways complicated hurts first new queryies many here’s simple example helps demonstrate power you’re writing client app such wpf application want save persist window’s position size next starts restored isn’t important curious found saving window location winforms helpful modified two needs replaced settings object asynchronous cache storage placement info changed resized exits crashes won’t forget last handling resize eventsso let’s bit event fired large number times probably don’t one calls performance problem data corruption i’m method possible later call occur before earlier happen close setting there’s pause during operation user stops five seconds traditional code figure out ut it’d ugly perhaps start timer started already each subsequent reset finishes saves turns itself going gnarly place looks observable fromeventpattern lt sizechangedeventhandler sizechangedeventargs gt sizechanged throttle timespan fromseconds rxapp deferredscheduler subscribe saveplacement nice self contained single expression break down part converts sizechangedevent specific type eventpattern analogous reversed having allow stream sequence coming ignore newer arrives within specified span words return item until second lull comes reactiveui framework equivalent dispatcherscheduler current dispatcher indicates scheduler run timers case indicate runs ui thread end takes action actually putting succeeded wait moreok pretty cool imperative slightly hard ok up stakes shall forgot something moved observe still both move occurs restarted passed occurred very shines provides observables we’ll deal created handles locationchanged i’ll intermediate variable clarity exactly you’d expect var locationchanges eventhandler eventargs same sizechanges use merge back analogy different types enumerables wanted combine apply transformation select here care arguments arrive transform unit default calling information returning merged args combined simply subscription various change more familiar easier read tend less variables full idiomatic declarative much crazy logic stuff even apps useful approach available javascript see actioni put rough sample demonstrates concept grab windowplacementrxdemo codehaacks repository infofor recommend following rdf xmlns http www w3 org 1999 02 22 syntax ns dc purl elements trackback madskills com public xml rss module description haacked archive 2012 04 08 aspx identifier title ping services trackbacks 18856 entry

Handling Events with Reactive Extensions - Mike Battista's Blog - Site Home
If you've had a chance to play around with Silverlight for Windows Phone, you've likely realized the importance of asynchronous programming and event handling.  Pushing tasks off thread keeps your UI responsive and allows users to interact with your application while you perform important tasks in the background.
handling events reactive extensions mike battista's blog site homeif you've chance play around silverlight windows phone realized importance asynchronous programming event pushing tasks thread keeps ui responsive allows users interact application perform important background standard handler patterns work well simple scenarios point wished more flexibility way handle maybe you'd filter firing respond subset those based criteria specify listened stream web service responses find user action invalidated ignore stale come back start listening new ones typically solve problems adding boolean flags state artifacts code manage required describe though achievable solutions add bloat distract someone reading primary objective over experience building applications i've encountered several common above implement elegantly net support different model power without requiring much effort resulting succinctly desired behavior same time avoid pitfalls associated deregistering handlerslet example handles pitfall forgotten deregister experienced unpredictable caused handlers unexpected number times happens automatically once accomplished you're interested one instance raised following observable fromevent eventhandler lt eventargs gt ev app initialized take subscribe args searchinprogress false receives discipline enforced declaration another advantage grouped along qualifiers definition making compact unit clearly describes trigger itself improves readability easy extend modify later filtering eventswith triggered requires logic undesirable obscure code's intentions easily define means desirable occurs saving having clean removes risk introducing bugs custom leveraged helper class use phone's current location geopositionstatuschangedeventargs geocoordinatewatcher statuschanged status geopositionstatus ready disabled raisecurrentlocationavailable currentlocationavailableeventargs position raiselocationservicesdisabled stop requestinprocess similar structure previous few additions you'll notice before added clause specifies statuses line doesn't care extraneous deregistered described reached addition here inclusion finalizer second parameter method first contains typical execute interesting cleanup finally block try catch statement opportunity update msdn great article ways emulate data services composing multiple requests feature search page cases single query seed joined presented set results solution track intermediate present entire obtained ideal compose potentially old queries scenario actually called out overview mobile searchresultsavailableeventargs provider searchresultsavailable equals activesearchquery searchresults type var list isearchable addrange typeof type1 type2 type3 raisesearchresultsavailable basic look familiar essentially identical three searches types instances entered passing through property reference compare against returned both comparing active stored processed composed protects overlapping network slow otherwise initiates raise notify listeners available conclusionthe net are powerful tool arsenal examples practical really justice hope shed light elegance expressiveness offer information check rx wiki channel

Writing TrailWithCount and TrailWithTime methods with Reactive Extensions (and incidentally drawing a mouse trail)
I have to confess, the more I play with reactive extensions the more I enjoy the result I get and appreciate their power. With this post I would like to show how it is possible to  take advantage of these extensions to easily obtain something that normally requires a complex code. The example is really simple and probably not so useful by itself but there are lot of uses I can imagine for the trail functions I will show in a few.
writing trailwithcount trailwithtime methods reactive extensions incidentally drawing mouse trail confess more play enjoy result appreciate power post show possible take advantage easily obtain something normally requires complex code example really simple probably useful itself lot uses imagine functions few make very collect manipulate events coming source querying database library define number operate way buffering instance stream groups based count timeout bufferwithcount gives chunks counted bufferwithtime generated specific given sequence 9trailwithcount returns1 9in following extension method creating called previous collection be1 etc publicstatic iobservable lt ienumerable gt observable crlf queue new return select enqueue 10 dequeue 11 toarray 12 13 input returns close ilist preferred use instead need insert remove interface first row create important remember created once time thanks usage lambda expression alive available body each event add ones exceed finally items forwarded next chain same taking od timestamped class timestamp moment received item removing compare current outside defined here timespan datetime now peek 14 15 value 16 17 ok visualize resulting catch mousemove points draw plugin area attach fromevent transform output point calling getposition eventargs call before subscribing mouseeventhandler mouseeventargs ev layoutroot fromseconds subscribe drawline simply assign polyline grow required length shortened end moves try yourself moving attached download find discussed above additional trailwithtimeandcount hybrid behavior combines both working nuget reference project http www silverlightplayground org assets sources slpg trailing silverlight zip kb

Taking advantage of combining different streams using Reactive Extension's:
One interesting feature of Reactive Extensions is the combining of Observables. There are a number of extension methods made to combine two or more streams; Amb, Concat, SelectMany, Merge, Zip, CombineLatest, all these methods are made to take, multiple and non necessarily omogeneous, streams and combine them in a unique resulting stream based on different rules. Here a brief resume of the rules applied from every method
taking advantage combining different streams reactive extension's one interesting feature extensions observables number extension methods made combine two more amb concat selectmany merge zip combinelatest take multiple non necessarily omogeneous unique resulting stream based rules here brief resume applied methodambreturns start providing values firstconcatchain end create single outputselectmanyreturns value second each firstmergereturns merged basing source returns valuezipreturns paired another couple available combinelatestcombine returning always latest both occurrence understanding meaning method really difficult make simple experiment out scope post now show real example little change previous mouse trail give great difference terms functions last used trailwithcount trailwithtime catch mousemove events draw polyline plugin il pointer seen shortens moving stops want shorten zero length achieve result need timer continues record current position purpose use static obsevable interval timespan generate given time lines add observable fromevent lt mouseeventhandler mouseeventargs gt crlf ev new layoutroot frommilliseconds 25 observeondispatcher select eventargs getposition 100 subscribe drawline gets regularly milliseconds selector lambda takes combined expire contain integer intervals event provide replicate taken elapsed feeded visual effect until reaches observeondispatched required implies separate thread marshall back ui trick

About the author

I'm a .NET, XAML, and iOS polyglot that loves playing with new things and making cool and innovative stuff.  I am also a Mac junkie.

I am Principal Technologist for SunGard Global Services in NYC, in their Advanced Technologies practice, and I work extensively with SunGard's energy and financial customers.

Note the the posting on this blog are my own and do not represent the position, strategies or opinions of SGS.

Widget TwitterFeed not found.

The file '/widgets/TwitterFeed/widget.ascx' does not exist.X

Recent Comments

None

Month List