Tuesday, 30 September 2014

Fun with ExpressionTextBox

After a short hiatus doing other things (a lot of back-end services work) I’m back in the fray with Workflow.

Yesterday, a colleague asked me to help out with an activity he was building that works like a combination of an If and a ForEach. The basic premise is that we have a List<Something>, and want to iterate through that list until we find a match with a Predicate<Something>, in which case we then schedule a child activity.

So, I came up with the following…


Here we have a collection of Noodle’s (as an argument called Stuff), and we’re going to iterate through all elements in the collection until we find the first that matches the predicate (x => x.Name == “Sausages”). When found, we then execute the Body activity, with item as the variable holding the selected Noodle instance.

The activity code is fairly simple…

    public class Find<T> : NativeActivity, IActivityTemplateFactory
public InArgument<IEnumerable<T>> Values { get; set; }

public ActivityAction<T> Body { get; set; }

public InArgument<Predicate<T>> Match { get; set; }

protected override void Execute(NativeActivityContext context)
var match = this.Match.Get(context);

// Iterate through the collection and if we find a match, we're sorted...
foreach(var o in Values.Get(context))
if (match(o))
context.ScheduleAction<T>(this.Body, o);

protected override void CacheMetadata(NativeActivityMetadata metadata)

public Activity Create(DependencyObject target)

The activity contains a collection of type T, a body that is passed the selected value from the collection, and a predicate that matches against the items in the collection. I’ve also overridden CacheMetadata to setup all of the arguments correctly, and in addition implemented IActivityTemplateFactory as there’s some setup that needs to be done when the activity is created in order to get it to work correctly. Full details are in the code download.

In the Execute method I iterate through the elements in the collection and execute the Match function against each. For the first that matches I then schedule the body activity, passing through the selected element. This then terminates the loop (that’s what we wanted, a more standard implementation might iterate though all matching elements in the collection.

The Designer

The important thing about the code is the designer (and that’s why I wrote the post in the first place). It’s fairly rudimentary, but there is something that might trip you up which is why I wrote this post.

The designer XAML contains a couple of ExpressionTextBox’s as shown in the image below…


The first is bound to the Values property on the activity, the second to the Match property. The important thing to note is that in order to get these to work properly you *must* use the ExpressionType property of the ExpressionTextBox…

Expression="{Binding ModelItem.Values, Mode=TwoWay,
Converter={StaticResource argToExpressionConverter}}"

OwnerActivity="{Binding ModelItem, Mode=OneWay}"
ExpressionType="{Binding ListType}"/>

Now, the type of items in the bound List is based on the type of element you choose to fill the list – in my case I have Noodles. So, the ExpressionType for the list would be IEnumerable<Noodle>, and the datatype for the predicate would be Predicate<Noodle>.

If you don’t use the ExpressionType property of the ExpressionTextBox then the text box will essentially be one-way, it will bind to values you set on the property grid, but won’t allow you to push values the other way (even if those values match 1:1 with what you type in the property grid). So, ExpressionType is mandatory, and has to be the right type.

In order to get the right type, I have created two properties on the Designer, and these call down to the underlying activity to get the actual type necessary. As an example here’s the code for the ListType…

    public Type ListType
if (null == _listType)
var findActivity = this.ModelItem.GetCurrentValue();

var valuesProp = findActivity.GetType().GetProperty("Values");

var args = valuesProp.PropertyType.GenericTypeArguments;

_listType = args[0];

return _listType;

private Type _listType;

This code gets the fund activity which is exposed through the ModelItem (which is a proxy object over the activity you are editing). I then lookup the Values property and return the first generic argument – in my example this will be IEnumerable<Noodle>. I have a similar property for the match predicate.

The Code

If you want to have look at the full code please click to download it…


Unknown said...



Richard Majece said...

I had similar task to do at home after classes. Then I found these homework help websites and did it very fast. You can use this info for your homework, too)

studentsassignmenthelp said...

Take professional Homework Help Canada services from the academic experts of StudentsAssignmentHelp.com. Our writers are expert in various academic disciplines such as law, IT, management, nursing, mass communication, economics, English, history, and many others.

meldaresearchusa said...

The vast experience we have in offering nursing writing services has enabled scores of students to score high grades in their assignment since we are known for offering the purchase term paper.

jacklinemelda said...

Why we rank the best in offering professional research papers for sale online is the quality services that are offered to the thousands of clients that contract our organization for the provision of quality custom writing services.

meldaresearch said...

If you have been wondering who will “Affordable Research Paper Writing Service Online”“write my research paper” or “write my paper” choose us today and avoid poor grades.We reliably provide services at the stated price without hidden charges. Contact us and let us help you at any stage of your Affordable Essay Writing Services.

Puremelda said...

Our top-notch writers have access to peer-reviewed articles, Free Essay Writer Services and online databases that are essential in writing Custom Writing Services on any chosen topic.

Assignment Help said...

This is a great article, that I really enjoyed reading. Thanks for sharing
Science Assignment Help

Puremelda said...

In the quest for quality grades, students have realized the need for working with Nursing Paper Writing Service agencies that specialize in various types of essay writing. They are the best company that handles Best Proofreading Service and Affordable Editing Services.

ahmed5987 said...

حتى إذا كنت تستخدم غطاء مرتبة بشكل دينى ، فإن الفرش يجمع الغبار وعث الغبار وتربة الجسم. انزع الغطاء وأغسله بالماء الساخن. لتنظيف المرتبة ، قم بتفريغ الهواء جيدًا في الجزء العلوي والجانبين ولا تنس نوابض الصندوق إذا كان لديك. افحص الفراش بحثًا عن أي بقع واعالجها بمحلول منظف الطبق والماء المعتدلين. استخدم فرشاة ناعمة واعمل من الخارج من البقعة باتجاه المركز لمنع الانتشار. شطف المنطقة بقطعة قماش مغموسة في الماء العادي ثم اتركه حتى يجف تمامًا. لتسريع التجفيف ، استخدم مجفف شعر على مستوى منخفض ولكن تجنب الحرارة الزائدة.
شركة تنظيف
شركة تنسيق حدائق بالرياض
شركة تنظيف منازل بالخرج
شركة تنظيف فلل بالرياض

Ashley said...

Are you looking for Science Assignment help? justquestionanswer.com is providing Science Assignments company in the USA from the qualified expert. Our 3000+ Science experts are available 24x7 to help the USA students and bring forth the peerless Science end of the day without asking an amount that exceeds the budget.

Sam said...

According to reports of survey, it is confirmed now that three out of every four student seek online assignment help from professionals in Australia. It also indicate that students who avail assignment help for their assignment or homework from professionals improve their grade by 20% than those students, who do not take any help. If you are stuck with your research projects, essays, case studies, business reports or need Urgent Assignment Help, then myassignmenthelp is the place to be.

noor said...

مكافحة حشرات بالخبر
مكافحة حشرات بمكة مكافحة حشرات بمكة
مكافحة حشرات بالمدينة المنورة مكافحة حشرات بالمدينة المنورة
مكافحة حشرات بالدمام مكافحة حشرات بالدمام

meldaresearch said...

Online education writing services companies have come up with Online Education Assignment Help for education and teaching studies students in order for them to score straight A’s in their custom education research paper services.

Term Paper Writing Services said...

Political science research paper writing help has become very popular among students seeking Political Science Writing Services and political science essay writing services.

KeiraDoltan said...

Complete Your Assignment From
Financial Planning Assignment Help

Rubel hossen said...

Crypto-currency as a modern form of the digital asset has received a worldwide acclaim for easy and faster financial transactions and its awareness among people have allowed them to take more interest in the field thus opening up new and advanced ways of making payments. Crypto.com Referral Code with the growing demand of this global phenomenon more,new traders and business owners are now willing to invest in this currency platform despite its fluctuating prices however it is quite difficult to choose the best one when the market is full. In the list of crypto-currencies bit-coins is one of the oldest and more popular Crypto.com Referral Code for the last few years. It is basically used for trading goods and services and has become the part of the so-called computerized block-chain system allowing anyone to use it thus increasing the craze among the public, Crypto.com Referral Code.

Common people who are willing to purchase BTC can use an online wallet system for buying them safely in exchange of cash or credit cards and in a comfortable way from the thousands of BTC foundations around the world and keep them as assets for the future. Due to its popularity, many corporate investors are now accepting them as cross-border payments and the rise is unstoppable. With the advent of the internet and mobile devices,information gathering has become quite easy as a result the BTC financial transactions are accessible and its price is set in accordance with people’s choice and preferences thus leading to a profitable investment with Crypto.com Referral Code Code. Recent surveys have also proved that instability is good for BTC exchange as if there is instability and political unrest in the country due to which banks suffer then investing in BTC can surely be a better option. Again bit-coin transaction fees are pretty cheaper and a more convenient technology for making contracts thus attracting the crowd. The BTC can also be converted into different fiat currencies and is used for trading of securities, for land titles, document stamping, public rewards and vice versa.

Another advanced block-chain project is Ethereumor the ETH which has served much more than just a digital form of crypto-currency Crypto.com Referral Code and its popularity in the last few decades have allowed billions of people to hold wallets for them. With the ease of the online world,the ETH have allowed the retailers and business organizations to accept them for trading purposes, therefore, can serve as the future of the financial system.

Nora Pittman said...

Our full Lace Front Wigs are all hand made with a lace cap. They are manufactured with thin lace sewn on top of the cap. Individual hairs are then sewn onto the thin lace. Each lace wig has lace all around the unit which will need to be cut prior to securing the wig to your head. You will need to cut along the hairline around your entire head. By doing so, you will be able to wear your hair anyway you like. You can even style ponytails, up-dos, etc. Once the Lace Wigs is successfully applied, it will appear that all the hair is growing directly from your head!

Lace front wigs are hand-made with lace front cap & machine weft at back. Lace front wigs are manufactured with a thin lace that extends from ear to ear across the hairline. When you receive the wig, the lace will be quite long in the front. Cut and style according to your preference, as you will need to apply adhesive along the front of the wig. Once the wig is applied, you will still have Lace Wigs with a very natural appearance.
TeamWigz Provide the Best Lace Front Wigs and Lace Wigs in Johannesburg and South Africa.

Smart Research said...

Through the services of Public Relations Assignment Help as well as Food Science Homework Writing Help we have helped thousand who are stuck with their assignment. You can also get Top Writing Services Online at an affordable cost.

Smart Research said...

Through the services of Public Relations Assignment Help as well as Food Science Homework Writing Help we have helped thousand who are stuck with their assignment. You can also get Top Writing Services Online at an affordable cost.

how to rank your website or youtube channel (basic) said...

Tongkat Ali ist eine Pflanze beheimatet in Südostasien. Sie gehört zur Gattung der Bittereschengewächse und Ihr botanischer Name lautet “Eurycoma longifolia”.
Maca Kapseln Es gibt noch eine weitere Reihe länderspezifischer Namen
wie z. B. “Pasak Bumi”, wie die Pflanze in Indonesien genannt wird oder “longjack”, die allgemeine Bezeichnung für Tongkat Ali Kaufen in den USA, Kanada und Australien.

Das Ursprungsland von Tongkat Ali Kaufen ist Indonesien, daher findet man auch dort auch die größten Bestände. Weitere Vorkommen gibt es in Ländern wie Thailand, Malaysia, Vietnam und Laos.

Die Einnahme von Tongkat Ali Kaufen empfiehlt sich insbesondere für Leistungssportler, die einen schnellen
Muskelaufbau und Muskelzuwachs anstreben und nicht auf illegale und künstliche Substanzen zurückgreifen möchten um Ihren Testosteronspiegel zu erhöhen.

Generell empfiehlt sich eine Einnahme von Tongkat Ali für alle Männer ab dem 30ten Lebensjahr, da in dieser Phase nachweislich die Produktion von körpereigenem Testosteron zurückgeht. Dies macht sich vor allem dadurch bemerkbar dass die körperliche Leistungsfähigkeit nachlässt, die Lust auf Sex spürbar abnimmt und dadurch allgemein das Selbstwertgefühl negativ beeinflusst wird.

Mit der Einnahme von Tongkat Ali können Sie nachweislich Ihre Libido steigern, Ihr Testosteron erhöhen und Ihre gewohnte Lebensenergie aus den jungen Jahren Ihres Lebens wieder herbeiführen. Hier können Sie übrigens weitere Informationen bekommen zum Thema ‘Libido steigern‘ ganz natürlich. Sollten Sie daran interessiert sein lohnt es sich auch unseren Artikel über Butea Superba zu lesen.

Tongkat Ali wächst als Strauch und kann Höhen von bis zu 12 Metern erreichen. Typischerweise dauert es 10-15 Jahre bis solche Ausmaße erreicht werden. Der Strauch trägt anfangs grüne Blüten die sich im Laufe der Zeit, bis zur Reife, rot färben.

Allerdings sind die Blüten im Hinblick auf die Wirkung der Pflanze weniger interessant. Der wertvolle Teil verbirgt sich unter der Erde.
Im Laufe der Jahre wachsen die Wurzeln teilweise senkrecht und bis zu mehrere Meter tief in den Boden, was die Ernte zu einer schweren und mühsamen Arbeit werden lässt. Je älter die Wurzeln sind, desto höher ist auch die Anzahl der Wirkstoffe Butea Superba.
Von daher gilt es einige Dinge zu beachten sollten Sie Tongkat Ali kaufen wollen.

Rubel hossen said...

Health Experts have proven that regular exercise coupled with a good diet allow you to live longer and healthier. In this busy day and age, not everyone has the time to go to the gym - resulting to a lot of overweight people that desperately need to exercise. A healthy alternative is for you to Buy Home Gym Equipments that you can store in your own home or even at your office. Here are some tips when buying home gym equipment.

First, know your fitness goals and keep these goals in mind when you are buying home gym equipment. One of the biggest mistakes that people make is buying the biggest or trendiest fitness machine simply because they like how it looks. More often than not, these end up gathering dust in your storage rooms or garage because you never end up using them. It is important to take note of what particular type of physical activity you want or enjoy doing before you buy your exercise machine. If you are looking to loose a few pounds and you enjoy walking or hiking, a treadmill is the best option for you. If you are looking to tone your lower body while burning calories a stationary bike is your obvious choice. Similarly, Special Equipments for Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

Second, set aside a budget before Buying Home Gym Equipments. Quality exercise machines do not come cheap. They are constantly exposed to wear and tear when they are used properly. So, pick machines that are built to last and have passed quality certifications to get the most out of your money. If you are operating on a tight budget, think about investing in several weights, We can Provide you High Quality Home Gym Equipments at Very Low Prices for your Complete Uses: Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

Its the Right Time to Buy Home Gym Equipments for you at Very Low Prices.

diyaroy.com said...

I would like to be your pen friend...You can write me email on genuinehotelescorts@gmail.com for
Jaipur Escort
Jaipur Escort
Jaipur Escort
Delhi Escort
Guwahati Escort
Guwahati Escort
Guwahati Escort
Guwahati Escort
Lucknow Escort
Aerocity Escort

freya maya said...

Buy Dank Now began as an idea to create a top-notch delivery service for buy weed online in the US and quickly evolved in much more. Even though California accepted Safe to Buy Marijuana Online in 1996, we felt there was still a major lacking in quality and service. From what once started as a humble, flower-child type movement, evolved into the next California gold rush.

Buy Dank Now Shop is committed to ensuring that your privacy and security is protected at all times, in fact, we care so much that we offer guaranteed stealth delivery to anywhere in the world at no extra cost! Buy Weed Online, Glo Carts, Glo Extracts, Glo Cart, Glo Cartridges, Glo thc Carts, Glo vape, Lions Breath Carts, Big Chief Carts and All orders are fully guaranteed, so whatever happens, nothing will ever stand between you and your weed!

With literally thousands upon thousands of amazing strains from the best breeders in the world, ranging from famous cup-winners to potent, CBD-laden medical strains, High THC powerhouses, Glo Extracts, famous cheese to Buy Marijuana Online and Glo Carts popular white widow strains, all the way through to some of the rarest, hardest-to-find varieties in the world.

Why Is Marijuana Effective for Treating Anxiety? Conventional medicine uses several different kinds of drugs to treat anxiety disorders, including serotonin reuptake inhibitors like Zoloft and tranquilizers like Valium. However, many patients don’t respond well to these medications. One of the non-psychoactive cannabinoids found in marijuana that is commonly used to treat anxiety is cannabidiol (CBD). Various scientists and researchers have experimented with both animals and humans to test the effectiveness of CBD for anxiety treatment.

You can get it all right here at Buy Dank Now! Because we only ever work with breeders who meet our rigorous quality standards, you can be sure that whatever products you get from our Website such as, Glo Carts, Glo Extracts, Glo Cart, Glo Cartridges, Glo thc Carts, Glo vape, Lions Breath Carts, Big Chief Carts, they’ll make exceptional additions to your genetic library!