Bower broke Wiredep, and how to fix it….

Well, in reality Bower did not intentionally break Wiredep. A few weeks ago Bower published a standard for the use of the bower.json file. In the “main” section of the bower.json file, bower states

  • Use source files with module exports and imports over pre-built distribution files.
  • Do not include minified files.
  • Do not include assets files like images, fonts, audio, or video
  • Filenames should not be versioned (Bad: package.1.1.0.js; Good: package.js).
  • Globs like js/*.js are not allowed.

So, in this case, the preference for items listed in “main” would be the less or sass files and not the actual css files. Sounds great in theory. But not as awesome in reality.

In version 3.3.5 of bootstrap, they have implemented this suggestion by dropping the “dist/css/bootstrap.css” from the main section of their bower.son file.

That on its own is great, Bootstrap is conforming to the suggested standard set by Bower. Except for one thing…

Wiredep is this awesome tool that automatically injects css and js files into your views based on your bower.json file. So if you include Bootstrap, it will look in the “main” section of bootstrap’s bower.son file and pull the css and js files and add them to your view. Except now that css file is gone…

But not all is lost. Wiredep allows you to override those sections in your own bower.json file using the “overrides” section. So if you are trying to upgrade to 3.3.5 of bootstrap or 4.4.0 of font-awesome, you can add this code to your bower.json file and all will be well again…

“overrides”: {
        “bootstrap”: {
            “main”: [
                “dist/js/bootstrap.js”,
                “dist/css/bootstrap.css”,
                “less/bootstrap.less”
            ]
        },
        “font-awesome”: {
            “main”: [
                “less/font-awesome.less”,
                “css/font-awesome.min.css”,
                “scss/font-awesome.scss”
            ]
        }
    }

RESTful Web Services with Web API – Part 3 – Query String Params

we are working through a series on WebAPI and RESTful services. In the last post I worked through implementing the verbs associate with REST. We often find ourselves in a situation where we need a little more flexibility that just Get all items or get one item by id. Sometimes we want to search for a group of items or filter. With WebAPI that is as simple as adding in a query string param to our get method. Lets check it out….

 

In our example we have been working on a “Post” service for a blog site. At this moment, our Post service has a get method that looks like this..

        public IEnumerable<Post> Get()

        {

            return dm.posts;

        }

Just a quick reminder about how the posts look. 

        public List<Post> posts =newList<Post>(newPost[] {

            new Post {ID = 1, Author = “Jon”, Title = “Blogging For Dummies”

                        Body = “A very short blog post”, Tags = new string[] {“soft skills”, “beginner”}},

            new Post {ID = 2, Author = “Lee”, Title = “Blogging For Smart People”

                        Body = “A shorter blog post”, Tags = new string[] {“soft skills”, “Expert”}}

        });

I would like to have an option to filter my posts by Tag. So, if I query /api/Posts/?Tag=Expert I would only get Lee’s smart people post… To make this work, we will rely on the magic of WebAPI to pass the query string into a param for our method. 

So, lets add that option to our get post. 

 public IEnumerable<Post> Get(string tag null)

  

We are making it an optional parameter by adding a default value of null. So when we have tag == null then nothing has been passed in and we just pass back the list… Like this…

            if (tag == null)

            {

                return dm.posts;

            }

Yep, that part is easy. Now, if a query string param is present, WebAPI will match it up with the method params and plug them in. So in this case, /api/Posts/?Tag=Expert, WebAPI will set the tag param to Expert in our method. So the only part left here is is to query the repository for all the posts matching the tag that was passed in. It should end up looking like this…

        public IEnumerable<Post> Get(string tag null)

        {

            if (tag == null)

            {

                return dm.posts;

            }

 

            return (from p in dm.posts where p.Tags.Contains(tag) select p).ToList();

        }

Thats it, it is just that easy to add query string support to your API.

RESTful Web Services with Web API – Part 2 – Verbs

In my last post, we began work on a ReSTful API using WebAPI in .Net. If you have not followed along with that post yet, head over there and run through it. What we ended up with was a simple API dealing with BlogPosts that only worked with the Get verb. In this post we will work through the other verbs that are used with ReST. 

Get      /api/Posts/:id    Get a single BlogPost

Post    /api/Posts         Add a new BlogPost

Put      /api/Posts/:id     Update a single BlogPost

Delete /api/Posts/:id     Delete a single BlogPost

 

Ok, so the data handling we have right now will rapidly fall apart when we try adding and updating blog posts. To keep it simple for learning purposes, we are going to institute some quick and dirty data management using a singleton repository. That will get us through for now so you can continue to see these routes in action. You can pick up the full code for the repository on https://github.com/jonathanfmills/WebApiBlog but if you are just reading through, don’t worry about that too much right now.  

Lets start with the Get verb to return a single BlogPost. Right now your PostsController should look like this:

    public class PostsController : ApiController

    {

        repository dm = repository.GetModelInstance();

 

        public IEnumerable<Post> Get()

        {

            return dm.posts;

        }

 

What we want to add next is a new method that will return an individual Post from the array based on a variable being passed in. So, to do that, we add a new method under the current one that returns  Post and takes an int param. It should look something like this. our repository returns an instance of posts that implements iQueryable so we can query it directly. 

public Post Get(int id)

        {

            return dm.posts.Where(x => x.ID == id).First();

        }

With this in place, WebApi will look for a route like /api/posts/2 and pass the 2 into this get method. Just that simple. No, really…

Ok, lets add a new Post to our list. We will do that by using the “Post” verb. So we will create a new method called Post. We need a parameter that will hold the new BlogPost so we take a parameter of type Post. WebApi will look at the input from the post and fit it into the object type that we are expecting. As if by magic…. But just go with it.  Now, we don’t want to just return void. We want to let the calling application to know that it was successful. So we set it up with an HttpResponseMessage as the return type. The method will look like this.

public HttpResponseMessage Post(Post p)

        {

            dm.AddBlogPost(p);

            return new HttpResponseMessage(HttpStatusCode.OK);

        }

So, when you post to /api/posts with a form or json payload, WebApi will automatically parse the payload and load it into a Post object. (Or whatever object type you use as a param for the function. Super easy. 

Now, how do you test this…. I use fiddler to make this happen. Its super easy to do and its free…. If you don’t have it already, go download it… http://www.telerik.com/fiddler

Fire up fiddler and go to the compose tab. Send a JSon doc to localhost/api/posts. It should look like this…

Screen Shot 2014 11 07 at 8 38 10 AM

 

 

Now, in your browser, a quick get to /api/posts should return three posts. 

[
    {
      ID: 1,
      Author: “Jon”,
      Title: “Blogging For Dummies”,
      Body: “A very short blog post”,
      Tags: [
         “soft skills”,
         “beginner”
      ]
   },
   {
      ID: 2,
      Author: “Lee”,
      Title: “Blogging For Smart People”,
      Body: “A shorter blog post”,
      Tags: [
         “soft skills”,
         “Expert”
      ]
   },
   {
      ID: 3,
      Author: “Jon”,
      Title: null,
      Body: “This is a new Post”,
      Tags: null
   }
]

And a get to /api/posts/3 should just return the new post….

Ok, so we can get and post. Lets do a put now… Remember, a “Put” will update a specific BlogPost so we will need to create a method called Put that will take 2 params. The first one will be the Id of the BlogPost, same as the Get. The second param will be the full BlogPost object that we want to update. In the body of the method, we will want to pull the original BlogPost and update only the fields we allow. We wouldn’t want to update the ID for instance. 

The Put method will end up looking like this…

public HttpResponseMessage Put(int id, Post p)

        {

            dm.UpdateBlogPost(id, p);

            return new HttpResponseMessage(HttpStatusCode.OK);

 

        }

 

The Update method looks like this… 

public void UpdateBlogPost(int id, Post p)

        {

            Post post = posts.Where(x => x.ID == id).First();

            post.Author = p.Author;

            post.Body = p.Body;

            post.Title = p.Title;

        }

 

3 down, 1 to go. Delete is just as easy as all the rest. We simply create a method called “Delete” and pass in the id… Done..

public HttpResponseMessage Delete(int id)

        {

            dm.DeleteBlogPost(id);

            return new HttpResponseMessage(HttpStatusCode.OK);

 

        }

The DeleteBlogPost method looks like this… 

 public void DeleteBlogPost(int id)

        {

            Post p = posts.Where(x => x.ID == id).First();

            posts.Remove(p);

        }

Thats it, The 4 common ReST verbs implemented in WebApi. In the next post, we will start talking about query string params as well. 

 

RESTful Web Services with Web API

Web API is a very nice clean way to get a very robust RESTful web service set up. If you have not had a chance to look at it yet, now is your chance. In this post, I will set up a simple RESTful web service using Web API. I am using VS 2013. You can accomplish the same thing in 2012 using NuGet to download the Microsoft ASP.NET Web API package. 

 

Alright, since this is  blog post, lets build a blog api… We will set up the basic CRUD services for BlogPosts. Start by Creating a new project…. 

Screen Shot 2014 10 28 at 9 11 32 AM

For the purposes of this post, we are going to create an empty project. So select empty and then add the WebAPI references.

Screen Shot 2014 10 28 at 9 13 38 AM

Ok, so some stuff has happened as if by magic, so lets look around for a minute at the important stuff. 

Look in App_start and open WebApiConfig.cs. This has the routing config for your API. You will see a chunk of code that looks like this…

            config.Routes.MapHttpRoute(

                name: “DefaultApi”,

                routeTemplate: “api/{controller}/{id}”,

                defaults: new { id = RouteParameter.Optional }

            );

 

This is the routing rules that your API will follow. In this case, to access your API, you would would start in http://localhost/api. The next piece is the controller. WebAPI will look in the controllers folder for a controller that matches what is passed in here. So, http://localhost/api/posts will look in the controller folder for a PostsController and route to that. The id field is declared optional. We will do something with that in a minute…. 

Ok, so lets go over to the models folder for a minute and get a model created so we have a framework for what a post looks like. Right click on models and select add – > class… Lets call it Post

Screen Shot 2014 10 28 at 9 27 31 AM

 

For the purposes of this post, lets keep it fairly simple. We will add a few fields to Post so we have some data. Lets do Author, Title, Body, and an Array of Tags. Posts should look like this when added…

 public class Post

    {

        public string Author { get; set; }

        public string Title { get; set; }

        public string Body { get; set; }

        public string[] Tags { get; set; }

    }

Ok, now that we know what a Post looks like, lets get some api routes built. Lets start by building a controller. Right click on the controllers folder and click add -> Controller. You will get a box with lots of options. You can have one created with the gets and posts already set up, but what is the fun in that. Just select an empty controller for now. 

Screen Shot 2014 10 28 at 10 04 23 AM

 

name it PostsController and click ok… Now you have an empty controller all ready to go. Lets start out first with some data to pass around. Lets create an array of posts to return. Drop in something like this…

public class PostsController : ApiController

    {

        Post[] posts = new Post[] {

            newPost {Author =“Jon”, Title =“Blogging For Dummies”,

                     Body =“A very short blog post”, Tags new string[] {“soft skills”, “beginner”}}, 

             newPost {Author =“Lee”, Title =“Blogging For Smart People”,

                      Body =“A shorter blog post”, Tags new string[] {“soft skills”, “Expert”}}

        };

 

Now that we have some data, lets set up our get route. This is where WebAPI really shines. For the generic “Get” on our API, all we need to do is create a method called get… yep, thats it. because we are returning a list of Posts, we set it up with a return type of IEnumerable<Post> and WebAPI will deal with all the rest. Your method will look like this…

public IEnumerable<Post> Get()

        {

            return posts;

        }

 

Yea, thats it… Web API will worry about all the rest. With that done, click run and lets get started.  

If you get a screen that looks like everything is broken, that means you did it right…. 

Screen Shot 2014 10 28 at 10 24 53 AM

Thats because you are pointing to just http://localhost… Remember that the controller is at /api/Posts. so update your url to localhost:<port>/api/posts and you should be set…

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<ArrayOfPost xmlns:i=”http://www.w3.org/2001/XMLSchema-instance” xmlns=”http://schemas.datacontract.org/2004/07/BlogPost.Models”>
    <Post>
        <Author>Jon</Author>
        <Body>A very short blog post</Body>
        <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
             <d3p1:string>soft skills</d3p1:string>
             <d3p1:string>beginner</d3p1:string>
         </Tags>
         <Title>Blogging For Dummies</Title>
     </Post>
     <Post>
         <Author>Lee</Author>
         <Body>A shorter blog post</Body>
             <Tags xmlns:d3p1=”http://schemas.microsoft.com/2003/10/Serialization/Arrays”>
                  <d3p1:string>soft skills</d3p1:string>
                  <d3p1:string>Expert</d3p1:string>
            </Tags>
            <Title>Blogging For Smart People</Title>
     </Post>
</ArrayOfPost>

But wait, why is this XML, I want JSON… Don’t worry, WebAPI returns the data type that is being requested by the client. So if your client sends application/json it will get JSON back. But, I know you want to see JSON when you do it this way so here is a quick fix. add this line to your WebApiConfig and you will see json in the browser

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

Ok, so just like that, we have a working basic API for Posts. In the next post, We will add the other verbs, and then get more complicated with repositories and dependency injection. Stay tuned… 

Quick application scaffolding with Express

Ok, maybe I am the only one who didn’t know this but getting a basic application scaffolding set up in Node is ridiculously easy…. Check this out.

 

In a terminal window.. Create a new directory… Called what you want. 

mkdir NewTestApp ; cd NewTestApp

install express globally so you can execute it from the command line. 

npm install -g express

now, express will create a full blown Node app with express, jade, all of your parsers, and routing with one simple command… 

express newAppName

Done, lots of stuff installed and ready to go. But, before you go anywhere, you need to get the dependancies installed. cd into the new directory and run npm install. 

cd newAppName && npm install

That will get everything installed and ready to go. The way it sets everything up to run is with a script in /bin/www that starts up the server on port 3000… To start it up, run this:

DEBUG=my-application ./bin/www

Done. Take a few minutes to look around and see how the routing is done but this approach will save you from having to redo all the requires and initial routing work every time you want to play with something. 

 

What is a Hypermedia API Anyway?

Hypermedia is one of those terms that get floated around every time a RESTful web services conversation starts up. Or maybe I am just terrible at dinner conversations…  At its core, Hypermedia refers to anything that is not text. So in HTML the hypermedia portion would be the image tags, hyperlinks, resources (css/javascript), etc… Thats great, but in APIs, you don’t see a lot of images getting pulled in. Its basically just JSON responses… So, where does Hypermedia come in to RESTful APIs?  Fielding put it this way… 

When I say hypertext, I mean the simultaneous presentation of information and controls such that the information becomes the affordance through which the user (or automaton) obtains choices and selects actions… Hypertext does not need to be HTML on a browser. Machines can follow links when they understand the data format and relationship types. –Roy Fielding

 

So, what he is saying here that in addition to presenting back the data, or information, you should also present back some controls to act on the data. 

Here is an example.  I will use a speaker/session interaction to show what I mean. 

A typical response to a “Speaker” request from an api would look like this…

{

    SpeakerId: 4982174123,

    Name:  “Jonathan Mills”

    Bio: “This is Jon’s Bio”

    Sessions: [{

        Title: “This is my session”,

        Description: “This session is awesome”

    }]

}

Ultimately, this is fine, but it does not help a developer understand what the API is trying to do without consulting lots of documentation. Adding in some “Hypermedia” or in Fielding’s words, some controls will add some clarity to the API consumer as to what options they have in using the API. Check out the response with some hypermedia added in. 

{

    _id: 4982174123,

    Name:  “Jonathan Mills”

    Bio: “This is Jon’s Bio”

    Sessions: [{

        _id: 12379485749

        Title: “This is my session”,

        Description: “This session is awesome”

        _links:{
           Details:{
              “href”:”http://localhost:8080/Sessions/Details/12379485749″
           }
        }

    }]

    _links:{
         ExtendedBio:{
             “href”:”http://localhost:8080/Speaker/Extended/4982174123″
         }
    }

}

Adding in the Hypermedia links, gives the API consumer a clear understanding of what other options they have when dealing with your API. 

Ok, now realistically, this is just one component of a larger conversation but this should give you a pretty good understanding of what someone is talking about next time they throw out that term… 

 

Responsive NavBars with Bootstrap

Creating responsive navigation can be painful. But with bootstrap, we can get something that looks nice and clean knocked out fairly quickly. In this post, I will walk you through the basics of getting a responsive navbar up and running. 

 

First things first, lets get some nav items in a list. 

 

<body>
    <ul>
        <li>Home</li>
        <li>About</li>
        <li>Contact Us</li>
        <li>Login</li>
    </ul>
</body>

Looking in the browser, it should look something like this… 

Screen Shot 2014 10 10 at 9 18 38 AM

 

Ok, not super awesome… But with just a few tags, this will start to look good…

Start by dropping bootstrap into your project. I use http://bower.io/ to manage all of my web dependancies, but you can get it from http://getbootstrap.com/

Now we include the bootstrap.css in our project. Your href will look different than mine….

<head lang=”en”>
<meta charset=”UTF-8″>
<title>BootStrap</title>
<link rel=”stylesheet” type=”text/css” href=”bower_components/bootstrap/dist/css/bootstrap.css”>
</head>

Your page should change slightly now due to different fonts from the css but for the most part its the same. 

Screen Shot 2014 10 10 at 9 37 22 AM

Now is where the magic happens. We are going to use some class attributes to set the whole thing up as a navbar. First we wrap the whole thing in a div with a class of “navbar”. We add in a class of navbar-default to add a little theme to it. You could use navbar-inverse instead to set a different feel.

The navbar will look for items with a “nav” and “navbar-nav” classes and style them appropriately, so we add those tags to the <ul>, In order for any of this to work… your list items must be links… So add that in too. It should look like this… 

<div class=”navbar navbar-default”>
    <ul class=”nav navbar-nav”>
        <li><a href=”#”>Home</a></li>
        <li><a href=”#”>About</a></li>
        <li><a href=”#”>Contact Us</a></li>
        <li><a href=”#”>Login</a></li>
    </ul>
</div>

The results would be pretty dramatic…

Screen Shot 2014 10 10 at 10 35 45 AM

Ok, don’t get too excited yet, we still have to make this thing responsive.  We start by creating a button with three bars… That seems to be the current “Click me, I am a menu” standard.  We are going to use the class “navbar-toggle” to have it only show up when your screen is small. You will have to shrink your browser size to see it. Add it in under your div, but before your <ul> like this…

<div class=”navbar navbar-default”>    
    <button type=”button” class=”navbar-toggle” >
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
    </button>
<ul class=”nav navbar-nav”>

….

Now, when your browser is small, it will look like this.. 

 

Screen Shot 2014 10 10 at 10 57 29 AM

Thats great and all, but we want it to replace the menu, not just appear, so now we have to break out the navbar-collapse class. create a new <div> with the class navbar-collapse, collapse,  and an id of navBarCollapse )the id can be anything you want… and move the list into that. We also add a “data-toggle” tag to the button and a “data-target” that points to the id of the list items.. It should now look like this.. 

<div class=”navbar navbar-default”>
    <button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”#navBarCollapse”>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
        <span class=”icon-bar”></span>
    </button>

</div>

<div class=”navbar-collapse collapse” id=“navBarCollapse”>
    <ul class=”nav navbar-nav”>
        <li><a href=”#”>Home</a></li>
        <li><a href=”#”>About</a></li>
        <li><a href=”#”>Contact Us</a></li>
        <li><a href=”#”>Login</a></li>
    </ul>
</div>

 

Now, we need to be sure we pull in the bootstrap scripts and add jquery to make the drop downs work. 

<script src=”bower_components/jquery/dist/jquery.js”></script>
<script src=”bower_components/bootstrap/dist/js/bootstrap.js”></script>

When clicked, it should look like this..

.Screen Shot 2014 10 10 at 10 57 29 AM

That’s it. You should now have a fully responsive navbar… Let me know what you think. 

Seek out and Learn from feedback

Nothing is more scary than the criticism of your peers. Well, except maybe never improving on your skills. One of the most important steps you can take to improving yourself as a developer (or in anything really) is to actively seek out people to review what you have done, and honestly listen to what they have to say. We have all sat in code reviews where you hear people tearing down what you have done, or questioning everything little thing. The first gut reaction to that situation is to throw up a wall, dig a trench, and defend your code to the death. If we want to improve, I mean really get better at what we do, we need to embrace those opportunities to have other people look at our stuff, and listen as they tear it apart. Yes, they will not always be right. Sometimes people are just nitpick everything. But going in with an open mind and a desire to learn will drastically change your outlook on those situations. 

If you really want to get better, push some code out to github and send a tweet like this… “Just tried consuming secure rest apis using auth-tokens in angular and would love some feedback.” #Angular @angularjs…. Or post to reddit programming or stack overflow with a request for feedback. No matter what you do, actively seek constructive feedback from others. Its absolutely the best way to keep yourself moving forward.  

Don’t Get Stale

Let’s face it, the career we have chosen is a fast paced, rapidly changing one that requires immense amounts of research and learning to keep up with. In my current position, I get the opportunity to talk daily with developers from all skillets and career objectives and I am regularly frustrated by how many of them don’t attempt to stay on top of whats going on in technology. Phrases like “I have not gotten to use that in my current job” just don’t cut it when you are looking to advance your career. We all need to remember that it is not your employers job to keep you up to date on our skills. Ultimately, you are responsible for you.

 

The good part of this conversation is that keeping up with technology is not really even that hard. The resources available to you are almost limitless. Here are just a few examples of tools that will get you moving. 

This is a very short list of the massive amount of options that exist to keep your skills sharp. As a dev, I set aside at least 30-45 minutes a day to exploring the new tech that is out there It is a very small investment that could vastly improve your career…