Skip to content

Blogs

Ruby - If Ternary, Until, While

Yet another bloody blog - Mark Crowther - Tue, 07/22/2014 - 01:58
We’re making good progress getting some of the key basics of Ruby understood. Variables are of course central, Arrays allow a more complete way of data handling, Case and If statements are the building blocks of ‘flow control’ in our program.
In looking at these, we’ve also learned a few tricks with getting, printing, chomping and interpolating data and a few neat tricks to present and evaluate data in different ways, to get a True or False state so we know what to do next. That’s quite a bit in a few hours, congratulations if you’ve followed along so far!
YouTube Channel: [WATCH, RATE, SUBSCRIBE]

http://www.youtube.com/user/Cyreath
With this stuff understood, let’s loop back on ourselves somewhat and add in more detail on a couple of things. To start with, let’s finish off a few more aspects of flow control.The if statement as we saw it before also has a shorter version, called the ternary or base three operator. Here’s an example:
a = 2a == 1 ? (puts "Banana") : (puts "Cheese")
Here we set the value of our variable a to 2, in the next line we ask does a equal 1? If True then puts Banana, else puts “Cheese”. In the brackets we could include whatever code we wish to, just like the longer form If statement. However, the ternary or base three version easily gets difficult to read and should only be used for small tasks. This might be concatenating two string or doing a quick piece of math.
In addition to Case and If statements, we also have Until and While loops available to us. These allow us to execute a block of code until a certain condition is trueor false.

·         For Until, the code executes so long as a condition is evaluated to false·         For While, the code executes so long as a condition evaluates to true
First, here’s an example of Untilin action:
c = 1
 until c == 6
   puts "C = #{c}"
   c +=1
end 
 
We’ll see five lines printed to screen, stopping when c evaluates to 6, as the condition is now true. Note in the last line how we increment the value of our variable.Let’s look at an example ofWhile in use:
d = 1
 while d < 5 do
   puts "D = #{d}"
   d +=1
end
 
As with the Until, here we’ll see five lines printed and the code will stop executing once the condition is false. The do keyword is optional. However, it’s more correct to use it, just like adding then in our If statements.
Mark
Read Morehttp://cyreath.blogspot.co.uk/2014/07/ruby-nested-if-statements.htmlhttp://cyreath.blogspot.co.uk/2014/07/ruby-if-statements.htmlhttp://cyreath.blogspot.co.uk/2014/07/ruby-case-statements.htmlhttp://cyreath.blogspot.co.uk/2014/05/ruby-w-vs-w-secrets-revealed.html
http://cyreath.blogspot.co.uk/2014/05/ruby-variables-and-overview-of-w-or-w.html
http://cyreath.blogspot.co.uk/2014/02/ruby-constants.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-global-variables.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-local-variables.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-variables-categories-and-scope.htmlhttp://cyreath.blogspot.co.uk/2014/01/ruby-variables-part-1.htmlhttp://cyreath.blogspot.co.uk/2014/01/ruby-getting-and-using-user-input.htmlhttp://cyreath.blogspot.co.uk/2014/01/download-and-install-ruby.html



YouTube Channel: [WATCH, RATE, SUBSCRIBE]http://www.youtube.com/user/Cyreath

Categories: Blogs

The Journey to a Software Testing Center of Excellence

Testing TV - Mon, 07/21/2014 - 23:39
What happens when the company that has engaged you as some kind of process expert has no clue how to test its applications & systems consistently or thoroughly? Where do you start? Where do you lead them, with what software testing best practices, tools, technologies? This will be a little personal journey through this rocky […]
Categories: Blogs

How Models Change

DevelopSense Blog - Sat, 07/19/2014 - 21:38
Like software products, models change as we test them, gain experience with them, find bugs in them, realize that features are missing. We see opportunities for improving them, and revise them. A product coverage outline, in Rapid Testing parlance, is an artifact (a map, or list, or table…) that identifies the dimensions or elements of […]
Categories: Blogs

5 Secrets to Professional Service on Client Engagements

Yet another bloody blog - Mark Crowther - Thu, 07/17/2014 - 21:55
If you think contracting and client work is about billing hours and F*&k all else, stop reading, there's nothing for you to see here. If you feel there's something more to it, that engagements are a precious slice of interaction to be valued, read on.

Still here? Good!

As often happens, I had a interesting and unexpected conversation with a colleague in work today - about professional service on a client engagements.

Every engagement has it's good and bad parts, its ups and downs. At all times though, you need to stay professional, but what does that look like?

Here's my attempt to capture some of what was said and add in a few thoughts of my own.


1. Serve the Client
The single most important thing to remember, is that you are being paid to provide service. Not necessarily 'a' service, even though a Statement of Work may say that. Service can be defined as 'acts of helpful activity'. In any engagement, you'll always be performing acts (see what I did there...)

Therefore, as you are a servant, drop any pretense or arrogance, borne of imagined technical or professional  superiority, and humbly serve your client to the best of your ability, by executing helpful acts as best you can.

That service may come in many forms. Working a little earlier or later. Listening attentively to what is and isn't said, perhaps coaching and mentoring. Speaking well of them in front of colleagues and customers. Producing a good report in time for an important meeting. Apologising for being late... the list goes on, enjoy expanding it. Service is not subjugation.


2. Deliver the best work you can, right to the very end
When we first engage with a Client, there's a lot of positive high energy and excitement about what's to come. We do our best work and give or all, thinking of the positive outcomes it will bring. What comes is often success in a shape we didn't imagine, coupled with a lot of frustration and all too often a slow winding down of a project, where it doesn't have a defined done-done.

It's essential that every engagement, good or bad, successful or not, finishes on a crescendo. Make sure you stay strong to the end. I'll claim there's good science behind this, it's called the Peak End Rule. Clients remember the most intense thing you do and then the final thing you do, then forgetting most of the stuff in between, form a view of what you were like. As time passes the peak levels off and the end is what they remember most.

I implore you, for the security of your reputation and future employ-ability, finish strong!


3. Help the Client succeed
Your glory and success must always be a by-product of the success you bring the Client. You succeed if the Client succeeds. If they fail, you fail. No exceptions. Your reward is getting paid, everything else is a by-product for you.

Constantly look for what is hampering the Client's success and seek ways to resolve it. That could be a lot of things, related to the specifics of the engagement or not. As in 1. above, you might need to step out of the engagement's remit and give that 10% extra on the 100% you're already doing.

Some of helping them succeed will call on your professional skills, maybe technical skills, your network, your ability to coach, heck maybe even just to listen. Ask yourself, is the Client looking good, winning, growing, succeeding? If not, figure out what you can do about it.


4. The Client isn't always right, but they're never wrong
Like a good Barrister, you'll take your instructions and look to follow them as best you can. However, on occasion, your Client will be misguided, ill informed, limited in their understanding, shallow in their perspective, inexperienced in approaches - they will never be wrong.

Don't like the test approach? Think the automation used is rubbish? Seeing sub-optimal management practices? Dislike the organisational structure? Feel the project is hampered by bad supplier relationships?

Great, well done on noticing! It's your job as a professional to offer your insights, experience, training, etc. to highlight ways that things could be improved so that you help the client succeed and deliver the best work you can. It's not your job to belittle the Client and make them feel wrong wrong wrong! That's not how we server the client is it?

Coach and guide, but ultimately if they don't want to follow your guidance, they're not wrong and you'll have to perform your acts of helpful activity in support of what they've asked for. Hey, no one said it would be plain sailing all the time!


5. It's not over until... well never
How long is your career going to be? I'll make up a figure and say on average 15 to 20 years. Where is your work going to come from? Again I'll guess and say people you know (certainly as a consultant) or people that know the people you know. That means anytime you have an engagement it never really ends, as the continuation is that (Linkedin) connection back in time to them through the community and your reputation.

As an example, assuming I make it to the end of 2014 in the current engagement, my network will have directly come to me with engagements for 4 years straight. No looking around, no interviews, just a journey through the bullet points in this post.



Bonus!

6. Have fun with them, sometimes!
Given Clients are so important, as customers, people and fellow professionals. Given you're hoping to engage with them for months on end, that they are people just like you, with hobbies, interests, families, hopes and dreams. It's OK to just leave work in work sometimes and go do something fun.

That might be a few beers after work, inviting them to a corporate do or just demanding they let you buy them lunch as a thank you once during the engagement. (Clients of mine are now thinking of the Spanish meats and wine they've be loaded up with from time time... yum).


The real bonus secret...

... is that it's all about professional relationships. Build it through service, maintain it through reliability and secure it through trust. Sprinkle it with a little fun along the way!

Mark.





Liked this post?Say thanks by Following the blog or subscribing to the YouTube Channel!

Categories: Blogs

Conventional HTML in ASP.NET MVC: Baseline behavior

Jimmy Bogard - Thu, 07/17/2014 - 16:11

Other posts in this series:

Now that we’ve got the pieces in place for building input/display/label conventions, it’s time to circle back and figure out what exactly we want our default behaviors to be for each of these components. Because it’s so easy to modify the tags generated programmatically, we can establish some pretty decent site-wide behavior for our system.

First, in order to establish a baseline, we need to examine what our current implicit standards are. Right now I’m solely focused on only the input/label/display elements, and not how these elements are typically composed together (label + input etc.). Looking at several of our inputs, we see a prevalent pattern. All of the input elements (ALL of them) have a CSS class appended to them for Bootstrap, “form-control”. Appending this in our normal method of the MVC templated helpers is actually quite difficult and esoteric. For us, it’s a snap.

First, let’s create our own HtmlConventions class that inherits from the default:

public class OverrideHtmlConventions 
    : DefaultHtmlConventions {
}

We’ll then redirect our container configuration to use this convention library instead:

public class FubuRegistry : Registry
{
    public FubuRegistry()
    {
        var htmlConventionLibrary 
             = new HtmlConventionLibrary();
        var conventions
             = new OverrideHtmlConventions();
        htmlConventionLibrary.Import(.Library);
        For<HtmlConventionLibrary>().Use(htmlConventionLibrary);

The OverrideHtmlConventions class is where we’ll apply our own conventions on top of the existing ones. The base conventions class lets us apply conventions to several classes of items:

  • Displays
  • Editors
  • Labels

And a couple of things I won’t cover as I’ve never used them:

  • Forms
  • Templates

There’s no real difference between the Displays/Editors/Templates conventions – it’s just a way to segregate strategies and conventions for building different kinds of HTML elements.

Conventions work by pairing a filter and a behavior. The filter is “whom to apply” and the behavior is “what to do”. You have many different levels of applying filters:

  • Always (global)
  • Attribute existence (w/ filtering on value)
  • Property metadata

The last one is interesting – you have the entire member metadata to work with. You can look at the property name, the property type and so on.

From there, your behaviors can be as simple or complex as you need. You can:

  • Add/remove CSS classes
  • Add/remove HTML attributes
  • Add/remove data attributes
  • Replace the entire HTML tag with a new, ground-up version
  • Modify the HTML tag and its children

You have a lot of information to work with, the original value, new value, containing model and more. It’s pretty crazy, and a lot easier to work with than the MVC metadata (which goes through this ModelMetadata abstraction).

I want to set up our “Always” conventions first, which means really only adding CSS classes. The input elements are easy:

Editors.Always.AddClass("form-control");

Our input elements become a bit simpler now:

@*Before*@
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@*After*@
@Html.Input(m => m.Email)

Our labels are a bit more interesting. Looking across the app, it appears that all labels have two CSS classes applied, one pertaining to styling a label, and one pertaining to width. At this point we need to make a judgment call. Do we standardize that all labels are a certain width? Or do we force all of our views to explicitly set this class?

Luckily, we can still adopt a site-wide convention and replace this CSS class as necessary. Personally, I’d rather standardize on how screens should look rather than each new screen becoming a point of discussion on how wide/narrow things are. Standardize, but allow deviation. Our label configuration now becomes:

Editors.Always.AddClass("form-control");
Labels.Always.AddClass("control-label");
Labels.Always.AddClass("col-md-2");

Then in our HTML, we can replace our labels with our convention-based version:

<div class="form-group">
    @Html.Label(m => m.Email)
    <div class="col-md-10">
        @Html.Input(m => m.Email)
    </div>
</div>
<div class="form-group">
    @Html.Label(m => m.Password)
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.Label(m => m.ConfirmPassword)
    <div class="col-md-10">
        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
    </div>
</div>

It turns out in this app so far we’re not using display elements, but we could go a similar path (surrounding the element with a span tag etc).

So what about those other methods, the “PasswordFor” and so on? In the next article, we’ll look at replacing all of the form helpers with our version, based solely on metadata that already exists on our view models.

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

Categories: Blogs

How to conduct a good phone interview

The Social Tester - Wed, 07/16/2014 - 18:01
A phone interview is an excellent interview activity to include when you’re recruiting. I believe the phone interview is a really important step in the hiring process as it is an effective way for both parties (hiring manager and candidate) to speak to each other before a fully fledged face-to-face interview. The phone interview is... Read More
Categories: Blogs

Full Stack Behaviour Driven Development

Testing TV - Tue, 07/15/2014 - 22:33
This talk presents the adoption of BDD from the back-end (with the likes of Behat and phpspec) through to the front-end (with Mocha.js and Cucumber.js) and how you can align these processes to make all your development consistent. It also discusses how this approach suits an Agile process. Video producer: http://greenroomlondon.com
Categories: Blogs

Indians and their Indian'isms - Top 10 List

Yet another bloody blog - Mark Crowther - Tue, 07/15/2014 - 22:16
Hey All,

For those of us who've had the pleasure of working with Indian off-shore companies, you'll no doubt have been charmed by their good looks, refined manners and quirky phrases. Yes, on top of everything, our Indian colleagues bring with them some amusing and colourful turns of phrase.

Here's my Top 10 List, have anymore? 

OK... OK, Top 8 list... Have any more to make a Top 10?

8) Test Suit (instead of suite)^
7) Updation
6) Prepone
5) Greetings! (at the start of emails)
4) Please do the needful (at the end of emails)
3) What all...
2) Prepend

and the No. 1 most amusing thing I like to hear...

1) Devleper

Oh yeh! Because all developers should be treated like lepers! ;p

Hey, love you guys!

Mark.

^ An Indian colleague stated that if you say suite, then people will just think of sweets ;)
Unfortunately ladies, whoever this bloke is...we confirmed he is NOT a software tester.
(sorry about that ;])


Liked this post?Say thanks by Following the blog or subscribing to the YouTube Channel!
Categories: Blogs

Very Short Blog Posts (20): More About Testability

DevelopSense Blog - Mon, 07/14/2014 - 23:30
A few weeks ago, I posted a Very Short Blog Post on the bare-bones basics of testability. Today, I saw a very good post from Adam Knight talking about telling the testability story. Adam focused, as I did, on intrinsic testability—things in the product itself that it more testable. But testability isn’t just a product […]
Categories: Blogs

Measuring Coverage at Google

Google Testing Blog - Mon, 07/14/2014 - 21:45
By Marko Ivanković, Google Zürich

Introduction
Code coverage is a very interesting metric, covered by a large body of research that reaches somewhat contradictory results. Some people think it is an extremely useful metric and that a certain percentage of coverage should be enforced on all code. Some think it is a useful tool to identify areas that need more testing but don’t necessarily trust that covered code is truly well tested. Others yet think that measuring coverage is actively harmful because it provides a false sense of security.

Our team’s mission was to collect coverage related data then develop and champion code coverage practices across Google. We designed an opt-in system where engineers could enable two different types of coverage measurements for their projects: daily and per-commit. With daily coverage, we run all tests for their project, where as with per-commit coverage we run only the tests affected by the commit. The two measurements are independent and many projects opted into both.

While we did experiment with branch, function and statement coverage, we ended up focusing mostly on statement coverage because of its relative simplicity and ease of visualization.

How we measured
Our job was made significantly easier by the wonderful Google build system whose parallelism and flexibility allowed us to simply scale our measurements to Google scale. The build system had integrated various language-specific open source coverage measurement tools like Gcov (C++), Emma / JaCoCo (Java) and Coverage.py (Python), and we provided a central system where teams could sign up for coverage measurement.

For daily whole project coverage measurements, each team was provided with a simple cronjob that would run all tests across the project’s codebase. The results of these runs were available to the teams in a centralized dashboard that displays charts showing coverage over time and allows daily / weekly / quarterly / yearly aggregations and per-language slicing. On this dashboard teams can also compare their project (or projects) with any other project, or Google as a whole.

For per-commit measurement, we hook into the Google code review process (briefly explained in this article) and display the data visually to both the commit author and the reviewers. We display the data on two levels: color coded lines right next to the color coded diff and a total aggregate number for the entire commit.


Displayed above is a screenshot of the code review tool. The green line coloring is the standard diff coloring for added lines. The orange and lighter green coloring on the line numbers is the coverage information. We use light green for covered lines, orange for non-covered lines and white for non-instrumented lines.

It’s important to note that we surface the coverage information before the commit is submitted to the codebase, because this is the time when engineers are most likely to be interested in improving it.

Results
One of the main benefits of working at Google is the scale at which we operate. We have been running the coverage measurement system for some time now and we have collected data for more than 650 different projects, spanning 100,000+ commits. We have a significant amount of data for C++, Java, Python, Go and JavaScript code.

I am happy to say that we can share some preliminary results with you today:


The chart above is the histogram of average values of measured absolute coverage across Google. The median (50th percentile) code coverage is 78%, the 75th percentile 85% and 90th percentile 90%. We believe that these numbers represent a very healthy codebase.

We have also found it very interesting that there are significant differences between languages:

C++JavaGoJavaScriptPython56.6%61.2%63.0%76.9%84.2%

The table above shows the total coverage of all analyzed code for each language, averaged over the past quarter. We believe that the large difference is due to structural, paradigm and best practice differences between languages and the more precise ability to measure coverage in certain languages.

Note that these numbers should not be interpreted as guidelines for a particular language, the aggregation method used is too simple for that. Instead this finding is simply a data point for any future research that analyzes samples from a single programming language.

The feedback from our fellow engineers was overwhelmingly positive. The most loved feature was surfacing the coverage information during code review time. This early surfacing of coverage had a statistically significant impact: our initial analysis suggests that it increased coverage by 10% (averaged across all commits).

Future work
We are aware that there are a few problems with the dataset we collected. In particular, the individual tools we use to measure coverage are not perfect. Large integration tests, end to end tests and UI tests are difficult to instrument, so large parts of code exercised by such tests can be misreported as non-covered.

We are working on improving the tools, but also analyzing the impact of unit tests, integration tests and other types of tests individually.

In addition to languages, we will also investigate other factors that might influence coverage, such as platforms and frameworks, to allow all future research to account for their effect.

We will be publishing more of our findings in the future, so stay tuned.

And if this sounds like something you would like to work on, why not apply on our job site?

Categories: Blogs

Struggles getting sign-off

Yet another bloody blog - Mark Crowther - Mon, 07/14/2014 - 20:39
On most projects there will be some kind of document produced that states what work will be undertaken, how and when. As always they take different forms, it might be a Statement of Work, Test Plan or Charter. Once the testing work is being defined in terms of implementation specifics and then executed, there could be other documents such as a Technical Definition, Schedule or at the end a Test Summary Report.

At each stage, especially in consultancy deliveries, you're going to need sign-off at some point. This sign-off is often defined as a milestone delivery.

- Commence Analysis
- Signed-off, proceed to Planning
- Signed-off, proceed to Execution
- Signed off, proceed to Wrap-up
- Signed-off. job done!

As much as we'd love this step-wise, gated approach not to be the case, it often is due to the nature of the engagement and the tie-in with delivery milestones and payment milestones. There needs to be a way to recognise work delivered is 'done' and an invoice can be sent in. In my experience, whatever shape the Test Plan takes will need to be signed-off.
Now, sign-off is notoriously hard to get even for internal test teams, in client vendor engagements it can prove even harder. So what do we typically see when chasing sign-off?
Excluding no sign-off at all, I'd say there are three common scenarios:

   * Complete and full sign-off
   * Partial sign-off
   * Sign-off by silence


Complete and full sign-off is of course the easiest to work with. All stakeholders required to review and sign-off do so in the time requested. The next stage of work commences with a common agreement in place and the document is archived for future reference, This is a rarity (...he said cynically).

Partial sign-off is more common. In any project team, there are those that will engage more than others. What can happen is the same few review the documents, send in their comments and then provide sign-off. The remainder are never heard from or appear to partially engage and/or never get around to giving clear sign-off by the date requested.

Sign-off by silence is the more complex. This in essence is where sign-off is assumed, as the stakeholders had sufficient time to raise issues, yet failed to do so. In law you would say you have sign-off by acquiescence. The silence and lack of objection being taken as approval.

It goes without saying that complete and full sign-off is what's best and in some cases you'll have no wriggle-room and have to push for it. In this case the situation is simpler, though no less frustrating. If you don't get sign-off, you don't proceed with the next step. Whomever is not giving sign-off is then the bottle-neck and the one pushing the project time scales and costs out. Escalate, make it clear, point the finger, whatever you need to do to get things moving again. Be careful with your due diligence and awareness of your blind-spots.They may have legitimate reasons for not signing-off in which case you need to address them quickly and well, so you're not the one pushing time and costs up!

However, what can you do when you can't get sign-off, despite all you good natured badgering and gentle escalation? My recommendation is to work to get agreement for following a combination of Partial and Acquiesced sign-off. But getting that established is a two step process and not something you can just impose yourself. 

Establishing the sign-off Process 
First step, make sure you take the time to explain to the project group, especially those who you need to get a sign-off from, the issues you're having and why sign-off is important. Assuming you've had this conversation before the project commenced, they should all be aware now of the original need and that it's been an issue. As with all process changes, you need to take people with you, not do it to them.

Secondly, get agreement on the idea that all stakeholders have a responsibility to review the documents and give feedback. These documents and other artefacts are statements of intent or reports of what's been done. As such they are of importance to the stakeholders because the testing work will impact them. If they deny this, stating the work you're doing has no impact on them, allow them to leave the room and take their name off the signatories list. Now the only people left in the room are those that do care, reiterate again the need for them to sign off.

With buy-in achieved you'll need to agree the process for sign-off. I suggest the following can be used as a template, tweak it to your own needs:


1.  The test team complete the artifact as fully as possible, clearly highlighting any areas needing more information or clarity

2.  A first issue is sent to all stakeholders and the missing information requested
3.  Feedback and corrections are added to the document, then a final issue is sent out for approval
4.  If not all feedback is received by the date set, call a 2 hour* document review meeting
Issue the final version and set a date for sign-off
5.  If about half way to the sign-off date there's anyone not done so, invite them to a 2 hour* document walk-through and sign-off meeting
6.  Get sign-off and issue the artifact out!

    Wow, heavy-weight... but what's your options if everyone has to sign-off? Well, you can change at step 4 at least:

    4. If not all feedback is received by the date set, assume acquiescence and the document is signed-off and issued

    You will of course need senior management agreement on this!

    People are busy, lazy, confused and a whole bunch of other things you'll need to deal with. If you have a contractual need to get sign-off you have no choice but to define, publish and follow a process. It would be great to be more agile and silence equals sign-off is the least best way of continuing with the schedule in the event of no feedback. Don't under estimate the power of 2 hour document review meetings. No sane person wants to be in these meetings and it often prompts feedback. If they attend and give so much feedback it can't be incorporated before the planned sign off date, then a) you did a crap job on the initial copy or b) you need to ask why, if there were so many problems, did they not come to you before the meeting? Hey, some people like to look smart in these meetings and 'cause problems', don't let them get away with it. Likewise, most people feel sign-off via acquiescence undermines their authority and/or view and will get feedback to you before the cut-off date. If anyone goes for the silence as sign-off approach, ask why you need them on the sign-off list.

    All too often, what should be a simple and beneficial activity can all too easily turn into a frustrating time sink. Whatever the needs of your environment and engagement; define the approach, communicate it out, get senior management buy-in and then stick to it!

    Mark



    "FINAL FINAL FINAL WALKTHROUGH. ARE WE READY TO FLY?"(src: http://www.edcheung.com/job/sm4/wfpc/wfpc.htm)


    Liked this post?Say thanks by Following the blog or subscribing to the YouTube Channel!

    Categories: Blogs

    Ruby - Nested If statements

    Yet another bloody blog - Mark Crowther - Mon, 07/14/2014 - 02:59
    Hey All!
    Now that we have an idea of how to use If statements in our code, let’s look at how we might use multiple If statements together via nesting.
    YouTube Channel: [WATCH, RATE, SUBSCRIBE]

    http://www.youtube.com/user/Cyreath
    It’s very likely you’ll have a condition you evaluate that won’t be the last nuance of the question. For example, you might ask what team someone is in but then need to know what business area they are assigned to. They could be in the testing team, but more specifically in the UI testing team. Knowing that could make a whole bunch of difference as to who knows… what tools they have access to, the SharePoint site they can use, etc.
    Putting an If statement inside an If statement is the easiest way. Though caveat number 1 is they look messy (hey, pretty code is important!) and worse they can start to look confusing. Take the approach then when using nested If statements, keep them simple and limited. As we’ll discover, Ruby and other languages have tidier ways of doing things like Methods, Classes and even Arrays.
    Let’s start with a straight forward If statement in the style we saw previously. In this example we use a mix of the evaluation styles we have available and a single then as a reminder from the last post. In your code, keep it consistent!
    puts "Where are you from?"location = gets.chomp.downcase
    if location =~ /\A(london|f)\z/ then  puts "OK, a big city..."    elsif location == "scotland"    puts "ach the noo!"
      elsif location == "pen y bont" or location == "bridge end"    puts "A fun town, haven't been there in years"      else    puts "Aha, I thought you came from somewhere strange..."  end
    The above locations are a bit broad, what if we wanted to respond differently given a person’s location? Say, having Pen Y Bont as a second question after asking if the user comes from Wales? Let’s change the above to ask about Wales first.
    elsif ["Wales","wales"].include? location then
    Now we’ll put the Pen y Bont part back in, using a nested If.
    elsif ["Wales","wales"].include? location then    puts "Which part? of Wales"    country_part = gets.chomp.downcase
          if country_part == "pen y bont" or country_part == "bridge end"        puts "A fun town, haven't been there in years"
          end
    In this way we have a nested If statement that will only be called if the user comes from Wales. If so, we have another variable called country_part to capture which part of Wales, Bridegend in this case. Just like our ‘outer’ if, it’s an if-code-end format and yes you could add elsif and else in there too.
    puts "Where are you from?"location = gets.chomp.downcase
    if location =~ /\A(london|f)\z/ then  puts "OK, a big city..."    elsif ["Scotland","scotland"].include? location    puts "ach the noo!"
      elsif ["Wales","wales"].include? location then    puts "Which part? of Wales"    country_part = gets.chomp.downcase          if country_part == "pen y bont" or country_part == "bridge end"        puts "A fun town, haven't been there in years"              elsif country_part =~ /\A(cardif)\z/        puts "Nice Castle there..."            else puts "Hmm... never been there! Ydych chi'n siarad Cymraeg?"            #watch Google translate get that wrong...                        end        else    puts "Aha, I thought you came from somewhere strange..."  end
    Not bad, covers quite a bit and is still fairly readable. However, you’re probably already getting a sense of how a larger nested If statement will easily become difficult to read. Use with caution. Even with our current limited knowledge of Ruby we could be combining Arrays for data, with Case for control and sprinkling some If statements for a little decision making and it would be neater.
    Bonus question: Can you spot the bug in the above code? It won’t fail as such, it’ll just give an  undesired response for an ‘odd’ input.
    ---------------------------------------------------------------------------------------------------Spoiler:  if location =~ /\A(london|f)\z/ thenThe f is an alternate that shouldn’t be there, copy and paste error! Was (flee|f), the user can type Flee or f and it will mean the same. Woops. Can you think of a way to use this feature?----------------------------------------------------------------------------------------------------- 


    Mark.
    Read Morehttp://cyreath.blogspot.co.uk/2014/07/ruby-if-statements.htmlhttp://cyreath.blogspot.co.uk/2014/07/ruby-case-statements.htmlhttp://cyreath.blogspot.co.uk/2014/05/ruby-w-vs-w-secrets-revealed.html
    http://cyreath.blogspot.co.uk/2014/05/ruby-variables-and-overview-of-w-or-w.html
    http://cyreath.blogspot.co.uk/2014/02/ruby-constants.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-global-variables.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-local-variables.htmlhttp://cyreath.blogspot.co.uk/2014/02/ruby-variables-categories-and-scope.htmlhttp://cyreath.blogspot.co.uk/2014/01/ruby-variables-part-1.htmlhttp://cyreath.blogspot.co.uk/2014/01/ruby-getting-and-using-user-input.htmlhttp://cyreath.blogspot.co.uk/2014/01/download-and-install-ruby.html



    YouTube Channel: [WATCH, RATE, SUBSCRIBE]http://www.youtube.com/user/Cyreath



    Categories: Blogs

    I am a Tester

    Hiccupps - James Thomas - Sun, 07/13/2014 - 11:47
    I'm wary of drawing parallels between managing and parenting, of analogising my team with my children (in a forum that I know some of them read, at least) but I find the proposition in “Helping” Versus “Being a Helper”: Invoking the Self to Increase Helping in Young Children very appealing. Essentially it suggests that subtle differences in language used to describe behaviour can have an effect on observed behaviour.

    In the paper, the authors run experiments where they ask children to "be a helper" or "to help" and find that the former results in significantly more helpful actions. Even when the children are doing something else that they regard as enjoyable, they're more likely to stop it and help if they were asked to be a helper.

    There's similar research in adults linking the noun version of a behaviour more strongly to a sense of self than the verb version, both positively and negatively. For instance people are less likely to cheat when asked to "be a cheater" than when asked "to cheat" because (it is hypothesized) the nominal reflects how people (want to) see themselves.

    My team are testers. (And my kids could be more helpful.)
    Image: https://flic.kr/p/zA4D1
    Categories: Blogs

    Lessons Learned When Designing Products for Smartwatches & Wearables

    Jonathan Kohl - Sat, 07/12/2014 - 18:46

    Lately, I have been doing a bit of work designing products for smartwatches and wearables. It’s a challenge, but it is also a lot of fun. I’m just getting started, but I’ll try to describe what I have learned so far.

    Designing for these devices has required a shift in my thinking. Here’s why: we have a long and rich history in User Experience (UX) and User Interface (UI) design for programs written for computers with screens. When we made the leap from a command line interface to graphical interface, this movement exploded. For years we have benefitted from the UX community. Whenever I am faced with a design problem when I’m working on a program or web site, I have tons of material to reach for to help design a great user interface.

    That isn’t the case with wearables because they are fundamentally different when it comes to user interaction. For example, a smartwatch may have a small, low-fidelity screen, while an exercise bracelet may have no screen at all. It might just have a vibration motor inside and a blinking light on the outside to provide live feedback to the end user.

    So where do you start when you are designing software experiences that integrate with wearables? The first thing I did was look at APIs for popular wearables, and for their guidance on how to interact with end users. I did what I always do, I tried to find similarities with computers or mobile devices and designed the experiences the way I would with them.

    Trouble was, when we tested these software experiences on real devices, in the real world, they were sometimes really annoying. There were unintended consequences with the devices vibrating, blinking, and interrupting real world activities.
    “AHHHH! Turn it off! TURN IT OFF!!”

    Ok, back to the drawing board. What did we miss?

    One big insight I learned from this experience sounds simple, but it required a big adjustment in my design approach. I have been working on software systems that tried to make a virtual experience on a computer relatable to a real-world experience. With wearables devices that we literally embed into our physical lives, that model reverses. It can mess with your mind a bit, but it is actually very obvious once it clicks in your brain.

    Simply put, when I don’t have a UI on a device, the world becomes my UI.

    Let me expand on my emerging wearable design approach to help explain why.

    Understand the Core Value Proposition of Your Product

    If you’ve been developing software for computers and mobile devices already, this may sound simple, but it can actually be a difficult concept to nail down.

    One approach I take is to reduce the current features. If we cut this feature, does the app still work? Does it prevent the end user from solving problems or being entertained? If we can cut it, it might be a supporting feature, not a core feature. Remember, wearables have less power and screen real estate, so we’ll have to reduce. When I had a group of core features remaining, now it is time to summarize. Can we describe what these features do together to create value and a great experience for users?

    Another approach I use is to abstract our application away from computing technology altogether. I map out common user goals and workflows and try to repeat them away from the PC with a paper and pen. With an enterprise productivity application that involved a lot of sharing and collaboration, I was able to do this with different coloured paper (to represent different classes of information), folders (to represent private or shared files), post-its and different coloured pens for labelling, personalization.

    In a video game context, I did this by reducing the game and mechanics down to a paper, pen, rule book and dice. I then started adding technology back until I had enough for the wearable design.

    Now, how do you describe how you are different? Have you researched other players in this market? Who are your competitors, or who has an offering that is quite similar? How are you different? What sets you apart in a sea of apps and devices? This is vital to understand and express clearly.

    How do I know if I am done, or close enough? As a team, we should be able to express what our product is and what it does in a sentence or two. Then, that should be relatable to people outside of our team, preferably people we know who aren’t technologists. If they understand the core offering, and express interest with a level of excitement, then we are on our way.
    If you are starting out new, this can be a little simpler since it is often easier to create something new than to change what is established. However, even with a fresh, new product, it is easy to bloat it up with unneeded features, so have the courage to be ruthless about keeping things simple, at least at first.

    Research and Understand the Device

    With wearables and mobile devices in general, the technology is very different than what we are used to with PCs. I call them “sensor-based devices” since the sensors are a core differentiator from PCs and enable them to be so powerful and engaging to users. The technical capabilities of these devices are incredibly important to understand because it helps frame our world of possibilities when we decide what features to implement on wearables and smart watches. Some people prefer to do blue-sky feature generation without these restrictions in place, but I prefer to work with what is actually appropriate and possible with the technology. Also, if you understand the technology and what it was designed for, you can exploit its strengths rather than try to get it to do something it can’t do, or does very poorly.

    This is what I do when I am researching a new device:

    • Read any media reviews I can find. PR firms will send out prototypes or early designs, so even if the device hasn’t been released yet, there are often some information and impressions out there already.
    • Read or at least skim the API documentation. Development teams work very hard to create app development or integration ecosystems for their devices. If you aren’t technical, get a friendly neighbourhood developer on your team to study it and summarize the device capabilities and how it is composed. You need to understand what sensors it has, how they are used, and any wireless integration that it uses to communicate to other devices and systems.
    • If they have provide it, thoroughly read the device’s design/UX/HCI guidelines. If they don’t, read others that are offering similar. For example, Pebble smart watches have a simple but useful Pebble UX Guide for UI development. It also refers to the Android and Apple design guidelines and talks about their design philosophy. Pebble currently emphasize a minimalist design, and recommend creating apps for monitoring, notifications and remote control. That is incredibly helpful for narrowing your focus.
    • Search the web – look for dev forums, etc. for information about what people are doing. You can pick up on chatter about popular features or affordances, common problems, and other ideas that are useful to digest. Dev forums are also full of announcements and advice from the technical teams delivering the devices as well, which is useful to review.
    Determine Key Features by Creating an Impact Story

    Now we can put together our core value proposition and the device’s capabilities. However, it’s important to understand our target market of users, and where they will use these devices, and why. I’ve been calling these types of stories different things over the years: technical fables, usage narratives, expanded scenarios and others, but nothing felt quite right. Then I took the course User Experience Done Right by Jasvir Shukla and Meghan Armstrong and I was delighted to find out that they use this approach as well. They had a better name: impact stories, so that is what I have adopted as well.

    What I do is create an impact story that describe situations where this sort of technology might help. However, I frame them according to people going about their regular everyday lives. Remember that stories have a beginning, middle and end, and they have a scene, protagonists, antagonists, and things don’t always go well. I add in pressures and bad weather conditions that make the user uncomfortable, making sure they are things that actually occur in life, trying to create as realistic situations as I can. Ideally, I have already created some personas on the project and I can use them as the main characters.

    Most people aren’t technology-driven – they have goals and tasks and ideas that they want to explore in their everyday lives and technology needs to enable them. I try to leave the technology we are developing out of the picture for the first story. Instead, I describe something related to what our technology might solve, and I explore the positives, negatives, pressures, harmonies and conflicts that inevitably arise. From this story, we can then look at gaps that our technology might fill. Remember that core value proposition we figured out above? Now we use this to figure out how we can use our technology platforms to address any needs or gaps in the story.

    Next, we filter those ideas through the technical capabilities of the device(s) we are targeting for development. This is how we can start to generate useful features.

    Once we get an idea on some core features, I then write three more short stories: a happy ending story (what we aspire to), a bad ending story (the technology fails them, and we want to make sure we avoid that) and a story that ends unresolved (to help us brainstorm about good and bad user experience outcomes.)

    Impact stories and personas are great tools for creating and maintaining alignment with both business and technical stakeholders on teams. Stories have great hooks, they are memorable, and they are relatable. With experienced people, they remind them of good and bad project outcomes in the past, which help spur on the motivation for a great user experience. No one wants their solution to be as crappy as the mobile app that let you down last night at the restaurant and cost you a parking ticket.

    Use the Real World as Your User Interface

    UX experts will tell you that concrete imagery and wording works better than abstract concepts. That means if you have a virtual folder, create an icon that looks like a folder to represent what it is by using a cue from the physical world. What do we do if we have no user interface on a device to put any imagery on it at all? Or maybe it is just very small and limited, what then? It turns out the physical world around us is full of concrete imagery, so with a bit of awareness of a user’s context, we can use the real world as our UI, and enhance those experiences with a wearable device.

    Alternate Reality Games (ARGs) are a great source of inspiration and ideas for this sort of approach. For a game development project I was working on, I also looked at Geocaching mechanics. Looking to older cellular or location-based technology and how they solved problems with less powerful devices is an enormous source of information when you are looking at new devices that share some similarities.

    I talked to a couple of friends who used to build location-based games for cell phones in the pre-smartphone era, and they told me that one trick with this approach pick things that are universal (roads, trees, bodies of water, etc.) and add a virtual significance to them in your app experience. If I am using an exercise wearable, my exercise path and items in my path that I pass by might trigger events or significance to the data I am creating. If you run past significant points of interest on a path, information notifications to help cheer you on can be incredibly rewarding and engaging.

    Enhance situational activities

    One thing that bugs me about my smartphone is that it rarely has situational awareness. I have to stop what I am doing and inform it of the context I am in and go through all these steps to get what I want at that moment. I want it to just know. Yesterday I was on my way to a meeting in a part of town I am bit unfamiliar with. I had the destination on my smartphone map, without turn by turn directions turned on. I had to take a detour because of construction, so I needed to start a trip and get turn-by turn directions from the detoured area I was on. I pulled over to the side of the road, pulled out my smartphone, and I spent far too long trying to get it to plan out a trip. I had to re-enter the destination address, get the current location I was at and mess around with it before I could activate it. A better experience would be a maps app that would help and suggest once it senses you have stopped, and allow you to quickly get an adjusted trip going. While you have a an active trip, these devices are quite good at adjusting on the fly, but it would be even better if they knew what I was doing and suggested things that would make sense for me right now, in that particular situation.

    It is easy to get irritating and over suggest and bug people to death about inconsequential things, but imagine you are walking past your favorite local restaurant, and a social app tells you your friends are there. Or on the day you usually stop in after work, your smartwatch or wearable alerts you to today’s special. If I leave my doctor’s office and walk to the front counter, a summary of my calendar might be a useful thing to have displayed for me. There are many ways that devices can use sensors and location services to help enhance an existing situation, and I see a massive amount of opportunity for this. Most of the experience takes place in real life, away from a machine, but the machine pops up briefly to help enhance the real life experience.

    Rely on the Brain and the Imagination of Your User

    If we create or extend a narrative that can make real world activities also have virtual meaning, that can be a powerful engagement tool. One mobile app I like is a jogging app that creates a zombie game overlay on your exercise routine. Zombies, Run! is a fantastic example of framing one activity into a context of another. This app can make my exercise more interesting, and gets your brain involved to help focus on what might become a mundane activity.

    With a wearable, we can do this too! You just extend the narrative of what you created on your job and delay telling you what happened until you are complete, and have logged in to your account on a PC or smartphone/tablet. You have to reinforce the imagery and narrative a bit more on the supporting apps on devices with a screen.

    ARGs really got me thinking about persisting a narrative. It is one thing to apply virtual significance to real-world objects, but what happens if we have no user interface at all? What are we left with? The most powerful tool we have access to is our human brains, so why not use those too? Sometimes as software designers I think we forget about how powerful this can be, and we almost talk down to our users. We dumb everything down and over praise them rather than respecting that they might have different interpretations or alternative ways of creating value for themselves with our software. Just because we didn’t think of it doesn’t mean it has no merit. It does require a shift towards encouraging overall experiences rather than a set of steps that have to be followed, which can be challenging at first.

    Wearable Integration – Data Conversion

    If you are working with a wearable that doesn’t have a screen or UI, and is essentially a measuring device, one option to tie in your app experience is to think of converting the data from one context into another. This can be done by tying into APIs for popular wearables. You don’t have an app on the device, but your device ties into the data that is gathered by it and used for something else. For example, convert effort from an exercise wearable into something else in your app. One example of this is Virgin Pulse, an employee engagement application that has a wearable that tracks exercise. Exercise with the wearable can be converted into various rewards within their system. The opportunities for this sort of conversion of data that is measured for one purpose to another experience altogether are endless.

    One app I designed extended data generation activities to a narrative in an app. We extended the our app concepts to the physical activity and tapped into the creative minds and vivid imaginations of the humans using the devices with a few well placed cues. This was initially the most difficult app for me to design, but it turned out that this was the overwhelming favourite from a “fun to use” perspective. The delay between generating the data out in the real world, and then coming home and using your PC or tablet to discover what your data measured by the wearable had created in our app was powerful. Anticipation is a powerful thing.

    However, be careful when you do this. Here are a couple of things to be aware of:

    • Make sure the conversion rules are completely transparent and communicated to the users. Users need to feel like the system is fair, and if they feel taken advantage of, they will stop using your app. Furthermore, many consumer protection groups and laws could be broken in different jurisdictions if you don’t publish it, and change it without user consent.
    • Study currency conversion for ideas on how to do this well. Many games use the US dollar as a baseline for virtual currencies in-game, mirroring the real world markets. These are sophisticated systems with a long history, so you don’t have to re-invent the wheel, you can build on knowledge and systems that are already there.
    • Add Variability Design Mechanics to Combat Boredom

      It can be really boring to use a device that just does the same things over and over. Eventually, it can just fade into the background and users don’t notice it anymore, which causes you to lose them. If they are filtering out your app, they won’t engage with it. Now, this is a tricky area to address because the last thing you want to do is harass people or irritate them. I get angry if an app nags me too much to use it like some needy ex, or try hard salesman. However, a bit of design work here can help add some interest without being bothersome, and in many cases, add to the positive experience.

      Here are some simple ideas on adding variation:

    • Easter Eggs: add in navigation time savers that will be discovered by more savvy users and shared with friends to surprise and delight
    • Variable Results: don’t do the same thing every time. Add in different screen designs for slightly different events. One trick is to use time and seasons as cues to update a screen with themes that fit daytime, night time, and seasons. Another is to use the current context of use to change the application behaviour or look. There are lots of things you can do here.
    • Game Mechanics: levelling and progression can help people feel a sense of progress and accomplishment, and if there are rewards or features that get unlocked at different levels, it can be a powerful motivator. It also adds dimensions to something repetitive that changes the user’s perspective and keeps it from getting stale.
    Provide for User Control and Error Correction

    As we learned when designing notifications for a smartwatch, it can be incredibly irritating if it is going off all the time and buzzing on your wrist. Since wearables are integrated with our clothing, or worn directly next to our bodies, it is incredibly important to provide options and control for users. If your app is irritating, people will stop using it. However, one person’s irritating is another person’s delight, so be sure to allow for notifications and vibrations and similar affordances in your product to be turned on and off.

    Conclusion

    This is one of the most fun areas for me right now in my work, and I hope you find my initial brain dump of ideas on the topic helpful. Sensor-based devices are gaining in popularity, and all indications show that some combination of them will become much more popular in the future.

    Categories: Blogs

    Conventional HTML in ASP.NET MVC: Adopting Fubu conventions

    Jimmy Bogard - Fri, 07/11/2014 - 17:42

    Other posts in this series:

    Now that we’ve established a base for programmatically building out HTML, we can start layering on top more intelligent model-centric conventions for both displaying and editing data. Eventually, I want to get to the point of not just supporting simple conventions like “DateTime = date picker” and “bool = checkbox” but much more powerful ones. Things like “a property named ‘Comments’ should be a textarea” or “a property of an entity type should make its dropdown options the list of items from the database”. These are all things that are universal to the metadata found on those properties.

    On top of that, I still want to enable customization, but at the HTML tag level. Ultimately, these builders build one or more tags, but nothing bigger than that. I don’t want to use templating for this – complex logic inside a template is difficult to do, which is why you have concepts like Ember views or Angular directives. I want to build an equivalent to those, but for MVC.

    I built a rather lousy, but functional version, years ago, but missed the concept of an object model to build HTML tags. That lousy version was ported to MVC Contrib, and should not be used by anybody under any circumstances. Instead, I’ll pull in what FubuMVC already built, which turns out is built on top of the HtmlTags library.

    I’m not going to use any of the other pieces of FubuMVC – just the part that conventionally builds HTML tags. First things first, we’ll need to get the Fubu MVC conventions and related packages up and running in our app.

    Integrating Fubu Conventions

    First, we’ll need to install the correct packages. For this, we’ll just need a couple:

    • FubuMVC.Core.UI
    • FubuMVC.StructureMap3

    These two pull down a number of other packages. To make things easier on ourselves, we’ll also install the StructureMap package for integrating with MVC 5:

    • StructureMap.MVC5

    Once that’s done, we have StructureMap plugged in to MVC, and the components ready for plugging FubuMVC into ASP.NET MVC. We’ll need to make sure that the correct assemblies are loaded into StructureMap for scanning:

    Scan(
        scan => {
            scan.AssemblyContainingType<IFubuRequest>();
            scan.AssemblyContainingType<ITypeResolver>();
            scan.AssemblyContainingType<ITagGeneratorFactory>();
            scan.AssemblyContainingType<IFieldAccessService>();
            scan.AssemblyContainingType<StructureMapFubuRegistry>();
    
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
            scan.LookForRegistries();
        });
    

    We just make sure we add the default conventions (IFoo –> Foo) for the Fubu assemblies we referenced as part of the NuGet packages. Next, we need to configure the pieces that normally are done through FubuMVC configuration, but because we’re not pulling all of Fubu, we need to do through container configuration:

    public class FubuRegistry : Registry
    {
        public FubuRegistry()
        {
            var htmlConventionLibrary = new HtmlConventionLibrary();
            htmlConventionLibrary.Import(new DefaultHtmlConventions().Library);
            For<HtmlConventionLibrary>().Use(htmlConventionLibrary);
    
            For<IValueSource>().AddInstances(c =>
            {
                c.Type<RequestPropertyValueSource>();
            });
            For<ITagRequestActivator>().AddInstances(c =>
            {
                c.Type<ElementRequestActivator>();
                c.Type<ServiceLocatorTagRequestActivator>();
            });
            For<HttpRequestBase>().Use(c => c.GetInstance<HttpRequestWrapper>());
            For<HttpContextBase>().Use(c => c.GetInstance<HttpContextWrapper>());
                
            For<HttpRequest>().Use(() => HttpContext.Current.Request);
            For<HttpContext>().Use(() => HttpContext.Current);
    
            For<ITypeResolverStrategy>().Use<TypeResolver.DefaultStrategy>();
            For<IElementNamingConvention>().Use<DotNotationElementNamingConvention>();
            For(typeof(ITagGenerator<>)).Use(typeof(TagGenerator<>));
            For(typeof(IElementGenerator<>)).Use(typeof(ElementGenerator<>));
        }
    }
    

    There’s a bit here. First, we create an HtmlConventionLibrary, import default conventions, and register this instance with the controller. We’re going to modify this in the future but for now we’ll use the defaults. This class tells FubuMVC how to generate HtmlTag instances based on element requests (more on that soon). Next, we register a value source, which is analogous to a ValueProvider in MVC. The ITagRequestActivator is for filling in extra details around a tag request (again, normally filled in with FubuMVC configuration).

    Since FubuMVC still has pieces that bridge into ASP.NET, we need to register the HttpContext/Request classes based on HttpContext.Current. In the future ASP.NET version, this registration would go away in favor of Web API’s RequestContext.

    The ITypeResolverStrategy determines how to resolve a type based on an instance. I included this because, well, something required it so I registered it. Much of this configuration was a bit of trial-and-error until pieces worked. Not a knock on Fubu, since this is what you deal with bridging two similar frameworks together. Still much cleaner than bridging validation frameworks together *shudder*.

    The IElementNamingConvention we’re using tells Fubu to use the MVC-style notation for HTML element names (foo[0].FirstName). Finally, we register the open generic tag/element generators. Even though the naming convention is IFoo->Foo, StructureMap doesn’t automatically register open generics.

    This is the worst, ugliest part of integrating Fubu into ASP.NET MVC. If you can get past this piece, you’re 100 yards from the marathon finish line.

    Now that we have Fubu MVC configured for our application, we need to actually use it!

    Supplanting the helpers

    Because the EditorFor and DisplayFor are impossible to completely replace, we need to come up with our own methods. FubuMVC exposes similar functionality in InputFor/DisplayFor/LabelFor methods. We need to build HtmlHelper extensions that call into FubuMVC element generators instead:

    public static class FubuAspNetTagExtensions
    {
        // Similar methods for Display/Label
        public static HtmlTag Input<T>(this HtmlHelper<T> helper, 
            Expression<Func<T, object>> expression)
            where T : class
        {
            var generator = GetGenerator<T>();
    
            return generator.InputFor(expression, model: helper.ViewData.Model);
        }
    
        private static IElementGenerator<T> GetGenerator<T>() where T : class
        {
            var generator = DependencyResolver.Current.GetService<IElementGenerator<T>>();
            return generator;
        }
    }
    
    

    We build an extension method for HtmlHelper that accepts an expression for the model member you’re building an input for. Next, we use the dependency resolver (service location because MVC) to request an instance of an IElementGenerator based on the model type. Finally, we call the InputFor of IElementGenerator to generate an HtmlTag based our expression and model. Notice there’s no ModelState involved (yet). We’ll get to validation in the future.

    Finally, we need to use these Label and Input methods in our forms. Here’s one example from the Register.cshtml view from the default MVC template:

    <div class="form-group">
        @Html.Label(m => m.Email).AddClass("col-md-2 control-label")
        <div class="col-md-10">
            @Html.Input(m => m.Email).AddClass("form-control")
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    

    I left the second alone to contrast our version. So far not much is different. We do get a more elegant way of modifying the HTML, instead of weird anonymous classes, we get targeted, explicit methods. But more than that, we now have a hook to add our own conventions. What kinds of conventions? That’s what we’ll go into the next few posts.

    Ultimately, our goal is not to build magical, self-assembling views. That’s not possible or desirable. What we’re trying to achieve is standardization and intelligence around building model-driven input, display, and label elements. If you’re familiar with Angular directives or Ember views, that’s effectively what our conventions are doing – encapsulating, with intelligent, metadata-driven HTML elements.

    Next up: applying our own conventions.

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    Categories: Blogs