Sunday, June 24, 2012

Including a Web API in knockout (going from hard coded to dynamic) (Part 1)

Technologies

ASP.NET MVC 4.0 Release candidate, Web API, Knockout.js, C#

Goal

Make a web architecture that separates the API from the UI and will move toward mobile.  Use the technologies listed above, together.  Move toward using Upshot.js, Entity Framework, and Knockout mapping if they help.

Background

In my last post I got Knockout working in MVC 4.0.  I’m happy with that but the way the sample was created that I was following, it was hard-coding the JSON on the client:
$(function () {

    var data = 
        [
            { Id: 1, Name: "Ball Handling" },
            { Id: 2, Name: "Passing" },
            { Id: 3, Name: "Shooting" },
            { Id: 4, Name: "Rebounding" },
            { Id: 5, Name: "Transition" },
            { Id: 6, Name: "Defense" },
            { Id: 7, Name: "Team Offense" },
            { Id: 8, Name: "Team Defense" }
        ];

    var viewModel = {

        tags: ko.observableArray(data),
        tagToAdd: ko.observable(""),

        //behaviors
        addTag: function () {
            this.tags.push({ Name: this.tagToAdd() });
            this.tagToAdd("");
        }

    };

    ko.applyBindings(viewModel);

});

Since I want to have a dynamic application that has a database and a web API, I need to make sure that I can get data from my server.  And I don’t know how to do that.  So here’s how!

What I want to do is replace the block where var data = “bla bla bla” with var data = data from my web API.  But first I need a web API.  Well, good thing, I already created a new Web API project in Visual Studio, so if I’m smart enough, I should just be able to call it………

wr1b1zhf

Getting it done, the steps


My first question is how does the UI “see” the API?  In particular, what’s the API’s address if Visual Studio has a dynamic server name like localhost:30983445. 

I ran into this page about single page web apps and thought to myself that maybe I had been doing it wrong.  Maybe I want to create a single-page web application and all of this wiring exists!?

So I started learning more about SPA (Single Page Applications) by watching this video with Steve Sanderson.  It’s an architecture.

So I went to my Visual Studio to find the SPA template and it was not there.  So I did some searching and found on this forum this, "Alright folks.. I found the answer. Single page templates have been withdrawn from MVC4 RC release and will not be available in the final release too. The team have identified that there are incompatibilities and they would like to work on it further before its released."  Son of a!!!!!!!!!

The page also gave instructions on how to hack around it so I started doing that.

I installed the Single Page Application Nuget Package (details on this page) into my non-Web API project.

It seems to have done it’s job.  I noticed it uninstalled some knockout stuff.  I hope that’s not an issue:
Successfully uninstalled 'jQuery 1.6.2'.
Successfully uninstalled 'knockoutjs 2.0.0'.

I was psyched to download a demo SPA app from Bart Jolling but it didn’t run.  I figured it had to do with the move from Beta to release candidate.  So I kept watching the video.

At 21 minutes, 40 seconds in the video, Steve says that Web API URLs have  a /API prefix.  So maybe this is the answer to my question.  I go and test this a little.

I started thinking that the place I need to implement my knockout is in my Web API project.  It turns out the the Web API projects can be both the web API and client.  I don’t know how good this practice is but it gets me past this current scenario so I move all of my modifications from the other project into my Web API project to see if I’m at least on the same, stable ground there.

I add the scripts that I think I have to have to _Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/themes/base/css", "~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript" src="http://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
    <script type="text/javascript" src="~/Scripts/knockout-2.1.0.js"></script>
    <script type="text/javascript" src="~/Scripts/knockout.mapping-latest.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

I went into the Index.cshtml page and tried to paste my same code but it was angry.  So I started to think maybe it would work if the more robust Mobile Template was the main project and it had the Web API stuff embedded in it.  This is seeming more plausible: from that project I get this option:

5xo2ppkf

So I decided to try to solve my project within the Mobile template to make it have a web API inside of it.  My goal was to only prove that I could get anything from my web API so I just pasted in the stuff from the default ValuesController that comes out of the box in the Web API template:
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post(string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

Now I needed to test if I would be able call /api/values/get/5 and have it return “values”.  (or even if that URL existed).  At this point I deleted the API project since I was no longer planning to use it and wanted a clean solution and no noise.  So I was very stoked to see this:

image

It’s returning XML from my Web API within my Mobile App.  It’s looking good.

Continued in next post….(I ran out of space on this Blogger site!!!!!!!!! WTH).

Saturday, June 23, 2012

Scenario 1: Getting MVC 4.0 Release Candidate working with Knockout.js

Goal

To prove that I can make MVC 4.0 work with Knockout.js

Workflow

  1. Create the projects in Visual Studio 2010.
  2. Followed this guy’s steps for installing Knockoutjs using Nuget.  His instructions weren’t very complete, so I’m providing more detailed info here.

The _Layout.cshtml contents that worked for me are as follows.  Note the order of the scripts at the bottom:

        </div>

@Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")
<script type="text/javascript" src="http://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<script type="text/javascript" src="~/Scripts/knockout-2.1.0.js"></script>
@RenderSection("scripts", required: false)
</body>
</html>

I put the codeFile.js reference into the scripts section so it renders last.


@{
ViewBag.Title = "Test Page";
}

@section scripts
{
<script src="../../Scripts/codeFile.js" type="text/javascript"></script>
}


<div id="tagsList" class="box">
<div class="box-head">

After that, I got it to run (woo hoo, neat!):


asdf


Lessons learned



  • Use sections for scripts on the Razor pages

  • Use Nuget to get packages

  • Be clear in writing your stuff.  The guy that published his article was fast and it helped but it wasn’t very clear so I toiled too much. 

Next steps



  • Tweak this guy’s code so it works with my app / domain.

To do’s



  • Haven’t yet verified that I have knockout.mapping working

Other stuff I did and learned during this post



  • Checked out JSFiddle, which is pretty interesting.
  • Added Sharper Photo to Live Writer.
  • Downloaded and installed PreCode for pasting code in my blog in Live Writer. 
  • I found that Syntax Highlighter for Windows Live Writer sucks. 
  • Sharper Photo plug in for Live Writer sucks.  I’m downloading Clipboard Live now and hope it’s better.

Starting a new, fun project

I'm going to be building a new web and mobile app using Microsoft technologies as the core.  I'm excited about it.  My architecture is as follows:

  • ASP.NET MVC 4.0
  • Web API middle-tier
  • knockout.js
  • SQL Server
  • LINQ to SQL
I think this is the right architecture for me.  I'm excited.  


I'm also excited about the coming of Windows 8 and related apps.  I think that I'm in a good place skills-wise to really contribute as Windows 8 shows power in the market.


Now that Silverlight is further out of the picture and MVC seems so.  Here's an article on the changes coming from a developer perspective given the coming of Windows 8 and the going of Windows Phone 7.


I'm going to update my blog as I learn new things on this development project.


Another thought I'm having is that I'm going to build my web API with a tendency toward building the model on the server site, incrementally, rather than trying to post a big blob once my user's done creating something.  This might be bad architecture but I don't know another way.

Monday, June 04, 2012

Work styles: Disruptive, collaborative, or both?

Pick your poison.  But why not do both in harmony?
Our work styles can be seen as disruptive (creating major change without regard to the current situation), collaborative (partnering deeply with peers to get things done), or a mixture of both.

Disruptive.  The disruptive style is cool and exciting.  It's about innovation and major change.  When I was in 8th Grade, when asked what I wanted to do when I grew up, I told my teacher, Mrs. Moore, that I wanted to either be a heavy equipment operator or a brain surgeon.  She laughed and asked me if I realized as she did that those two fields were markedly different.  I did not and I responded, "I really want to change things dramatically."  I suppose both on macro (bulldozer) and micro (brain) scales.  This still holds true to me.

Collaborative.  The collaborative work style is a really critical, key and important one that I have had to learn over the years.  As an aggressive person who wants to change things drastically I've learned that I have to collaborate and partner with others to get things done.  Leading without followers is not possible.  Sometimes I have to take the back seat and let others drive.

Having both of these capabilities as a disruptive, innovative person and a collaborative person provides balance and synergy between two forces.  Both are good for change but together they provide a pace that is realistic,  sustainable, and powerful.

Three categories of spending: preferred, emergency, unnecessary

Money and spending are part of our lives every day.  Having new ways to think about money and how we spend it can really help us set budgets, spend, earn, and save wisely.
Figuring out how to manage your money is an ongoing battle but having simple processes to follow to help you think effectively about money can really help.  Three categories of money are Emergency (those funds you need when things aren't well), Unnecessary (frivolous uses of funds), and Preferred (how you'd rather spend your money).

Preferred.  In the Preferred category we are spending our money on things we prefer that add value to our lives.  These are the things we are proud of, need, and make us more whole as people.  They are our investments into ourselves and those around us that we are happy to make.

Emergency.  In the Emergency category we need to spend money on things that came up unexpectedly like car repairs, job loss, or fixes of any kind.  This is a "risk pool" of funds that we need to have to feel safe when things go wrong. Many of us do not have a big enough emergency pool but we're working to build it.

Unnecessary.  Finally, the Unnecessary category of money is what we don't need to spend.  We shouldn't be allocating funds to this category but we probably do all of the time (expensive meals, drinking too much, unnecessary services). Many of us probably have a larger-than-we'd-like set of things in this category and we need to analyze and consider using this category less and the other two more.

Through the proper categorization and consideration of the way we use funds, we can get to a budget and set of categories and thought processes that we prefer about money.  Good luck.

We'll get you the technology, people and processes you need for your objectives

EfficiTrends seeks to be your personal and extremely knowledgeable concierge for your journey, whatever it might be.
"We'll get you the technology, people and processes you need for your objectives."  Everyone struggles with one or more parts of this equation.  Let's try to further understand the various parts of this and how I and people like me can help you with your project, whatever it might be.

A) "We'll ..."  (Who we are).  We are EfficiTrends.  We are a consulting group.  We help people and businesses become more effective at achieving their goals.  We are a small but growing team of free-thinking, creative, experienced professionals who can help people of many walks get things done.

B)  "We'll get you the ..." (Service delivery method).  Our service is fast, collaborative, and proactive.  We try to anticipate your needs before you have them.  We go into our networks, experience, and knowledge base to get you the stuff you need for your objectives.  We are very aggressive at identifying and acquiring the stuff you need to be successful.  We bring this valuable stuff to you, whatever it might be.

C) "We'll get you the technology ..."  Technology is a key, core part of the EfficiTrends business.  We live and breathe technology and believe that it can and will have a very positive affect on your lives, those of your customers, and staff.  We are advocates of technology but do not only run from that perspective.  Hence:

D)  "We'll get you the technology, people ..."  Sometimes technology isn't enough and we need to bring in people and subject matter experts to support the technology purchase decision or dialog.  Our people will help you become more comfortable with your situation, whatever it might be and get you through the change curve required.

E)  "We'll get you the technology, people, and processes ..."  Processes are all about value.  They're about sustainability.  Whether these processes are thought processes or business processes, we want you to have them because they are valuable and measurable.

F) "We'll get you the technology, people, and processes you ..."  (The customer).  Our customers are a huge part of our service offering.  They're everything, in fact!  Without you, we wouldn't be here and we do everything possible to keep you engaged and driving the dialog.

G)  "We'll get you the technology, people, and processes you need for your objectives."  Your objectives can be hard to nail down.  Sometimes they're completely obvious and transparent like "I need a car to pick me up at my house located at 4834 Elm Street in Seattle on June 5, 2012 at 8 AM PST."  But even then that could have some gaps in it.  What kind of car?  Where is the car going to?  How much gas is needed in the tank?  Do you have any special needs?  EfficiTrends is excellent at analysis of all kinds from data to requirements to business process.  We look deep into you and your business to understand the opportunities that are lying within and beneath.

EfficiTrends will get you the technology, people, and processes you need for your objectives.  What are your objectives and how can we help you today?