Wednesday, October 23, 2013

Orthogonal

In comp sci, the term orthogonal is used to describe that all objects of the same type, in the same namespace have the same set of properties and methods on them. In the larger world, the meaning is a thing that has all right angles.

"Ha ha." That is what most users, when they are feeling nice, think of programmers, all right angles.

Thursday, August 29, 2013

New JQuery Hottish Stuff

 It seems like we acquired some plugin fatigue, and not much happened this year in JQuery.

But here are some very nice new plugins:

http://cloudfour.github.io/SimpleSlideView/responsive.html

http://fineuploader.com/fine-uploader-basic-demo.html


Also I think we should all start to get really into JQuery Mobile and responsive design, which is the new progressive enhancement.

JQuery Mobile:
http://jquerymobile.com/demos/1.3.0-beta.1/

http://jquerymobile.com/demos/1.3.0-beta.1/docs/content/content-grids-responsive.html#

http://jquerymobile.com/demos/1.3.0-beta.1/docs/content/content-collapsible.html

Tuesday, August 20, 2013

Clean Code - Assessing Code Quality - Part 2

Clean Code starts with good names

Articulate names for your coding objects are the primary tool for creating clearly understandable code.

Do not add gratuitous context

Prefixing your code names with extra context like the business name, name space, or extra type information just add superfluous information that must be read. Give your object a good descriptive name, and leave off the code hierarchical context, you tooling can tell you how it participates in the hierarchy.

What is in a Name?

Objects and Functions

Objects should use Pascal Case, and start with a capital letter and Functions should be Camel Cased, and start with a lower case letter.  

Classes and Variables

Classes and variable names should be nouns, named after a problem domain actor, a system API or an artifact. Examples are Document, and User. Classes should use Pascal Case, and start with a capital letter.

Interface

An interface should be an adjective, or in some cases a descriptive noun.  Interfaces should be named as nouns, noun phrases, or adjectives that describe the behavior. Interfaces are prefixed with an “I” Examples are printable, and enumerable, don’t be afraid to make up your own adjectives.

Functions and Methods

Functions and methods should have names that are verbs, denoting the action they are going to take. Methods are Camel Case, and start with a lower case letter.  Examples are export, save, add, delete.

Methods Names

Method names often need to have more information to differentiate the method between implementations.  So often you will need to suffix your name with a Camel Case description of the operation details. For Example, saveToDisk, and printToClient.

Adding Method Scope Information

Often with a complex class, we can have multiple methods that perform similar actions but differ by the arguments that they take. Most often we tackle that problem with method overloading with the same name and different signature, but sometimes it is helpful to add an adverb explaining the “how” that happens to the verb.

Abbreviations

Most Abbreviations only obfuscate the meaning of the code, so in most cases use the full word. Notable cases are where the Comp-Sci Solution Domain standard abbreviations exist. Below is an example of standard names.

Abbreviation
Description
arg
argument (function parameter)
bin
binary
bool
boolean
char
character
doc
document
elm
element (dom node)
fn
function
hex
hexadecimal
id
identifier
int
Integer
max
maximum
min
minimum
num
number
obj
object
oct
octal
prop
property
seq
sequence
str
string
substr
sub-string

Adding Scope into a name

Sometimes it helps to add scope into the name of an object.  We can note an object as being internal to its parent by prefixing it with the underscore sigil, marking _tempName as private to the function. A not on JavaScript and closure, never mark a variable that you are going to be closing over as private, as this send that wrong signal.
For noting that an object is in the global scope, prefix the object with global, and for the object using camel casing. Like globalUserPrintQueue, note that we prefix with scope, include information from the problem domain, and then include information from the solution domain.

What the Name Describes

The name primarily should describe the behavior of the problem domain. If the solution domain will assist in the next programmer’s understanding then include that also in your name.  So if the item in the problem domain is the “User” and we want to make a standard assembly for creating the user. We can use the description from the solution domain. So we have userFactory.

Functions are Cohesive

A function should be both compact and cohesive.  The function body should be less than thirty lines of code, and should perform only one function without side effects. All the actions that the function should perform should form a coherent whole, and only perform one operation or just one set of coherent operations.

One Level of Abstraction

A function should contain only one level of abstraction. Like in the case of the solution, would be one level of abstraction and a separate level of abstraction, animal.  So we want our method to contain only one level of abstraction, of course polymorphism is excused from this.

Logically Organization

Your classes should be logically organized, and the flow should be from less-complex, at the top to more-complex, the implementation details, towards the bottom. Your code should progressively reveal complexity to the maintainer as your code is read, divulging intricacies like an onion.

You should group Classes that perform similar operations into Namespaces, establishing a code hierarchy.

Note on case and notations:

Pascal case: The first letter of all words is capitalized; no spaces, underscores or special characters are used. Example: BackgoundColor, Gray.
Camel case: Except for the very first letter, with is lower case, the first letter of all words is capitalized, no spaces, underscores or special characters are used. Example: backgoundColor, gray.
Uppercase: All the letters are capitalized, by common convention this is reserved for use on abbreviations of 4 letters or less.  Example:  System.IO, MSDN.Library
Hungarian notation:  The name will be prefixed with an abbreviation of the objects data type, and be in Camel case, meaning that the first letter (the abbreviated type) will not be capitalized, but the beginning of each word after will be capitalized.

So some rules from Clean Code

1.       Do not add gratuitous context.
2.       Use Names based on the solution domain first, and then names based on the problem domain.
3.       Use descriptive names.
4.       A method should be cohesive, and responsible for only one thing.
5.       Include only one level of abstraction in a method.

Monday, August 19, 2013

Assessing Code Quality - Part 1



Knowing what good is, and being able to articulate what code demonstrates quality is important in setting up a technology roadmap for the group.

"Easy is good, 
simple is better." 
-g.dirlam 2012

Eloquent is better than Elegant

A hallmark of  very good code is that it is "less." So this is a simple lesson, elegant code gets you good, removing code from the overall code footprint means you have achieved "very good."

In order to be useful to a business the code base does not have to house elegant solutions, if this was a prerequisite for business code then almost all  businesses would be closed. So if it does not need to be elegant than what does it need to be? Code needs to be maintainable. And it is easier to maintain smaller blocks of code than it is to  maintain large code-bases.

So it is true that good names are better than clever design patterns. It is in the nature of a programmer to be self satisfied with creating a clever solution of design patterns, but trust me, real accomplishment comes from giving all the objects in your solution names that everyone can understand.

"Give me some sugar baby," syntactic sugar allows modern programs to be more eloquent, to express relationships in compressed form. Keeping current with modern trends allow you to write inline lambda expressions that do highly complex things, in short segments of code. Use sugar, but just make sure to keep it legible.

In order to be eloquent, the programmer needs to choose fully articulate descriptive names for the objects in his code.

So some rules from Clean Code

  1. Do not add gratuitous context.
  2. Use Names based on the solution domain first, then names based on the problem domain.
  3. Use descriptive names.
  4. A method should be cohesive, and responsible for only one thing.
  5. Include only one level of abstraction in a method.

Needs to run and perform as expected

So business code needs to be maintainable, and it also must meet the needs of business, and thereby be functionally business complete. This means that that the solution meets all the actual requirements to be feature complete with the business. By this I mean that the program performs all the expected functions, that the program runs as expected and conducts business.

So to sum-up. Codes needs to perform and run properly, it needs to meet the immediate business need, it needs to be written in a clear and concise manner, it needs to be small and maintainable. If you are really industrious you can make sure it scales globally as far as localization, and that it can run a vast array of servers.



Thursday, August 8, 2013

What my friends from AP taught me.

"Do you know that feeling when you get a gift that you really needed, but you just did not know you needed it." That is how I think about the good times that I spent with my friends from Hyderabad.

I suppose I will never truly know what they think about the first world and U.S. culture specifically, but what I did realize is that coming from a different culture affords them different overall strengths and weaknesses. Please understand all individuals are extremely complex, and cultures are not even knowable when you have been raised in them, but if we use a broad enough brush, we should be able to paint some generalizations. 

So without future introspection we will get to "What I learned from my Friends from Andhra Pradesh."

Emotional control is important, it is a skill that you need to work on. 
So I joined an almost exclusively indian team, almost all coming from A.P. Soon on, I realized that they had much better control over when they wanted to go to argue and go on the warpath. I would run around creating chaos, and they would shake their heads and say "No Gareth" in the nicest of ways. After a couple of episodes of this, I started to feel like a clod. It took some time, and also backing down to one or two cups of coffee, but I got to the point that just because I was feeling badly did not mean that I would make a emotional mess for everyone.
 Being a good person is important, it is something you need to refine and work on.
You need to endeavor to be a good person. You need to continue to work at it. Oddly enough, the overall definition of what a good person does seems to be remarkably similar. Dutiful, honest, giving, not greedy, concerned for the welfare of others, yup, really I never found anything different in our definitions. What I did notice is the fact that my friends from AP meant it, they were not just saying, they were trying to work at it. Not always succeeding mind you, but they would like to change the world for the better with their actions. This is never too far away from their conversations. You really can't go a whole day without someone in the group pointing out how someones actions are selfless and for everyones good. Which brings us to the next point...
Working in a group involves skills and communication, you should get better at this.  
When working in the group, you need to point out successful things that people in the group are doing and praises them. Praising and teasing are strong team building activities. 
So it might not be much of a cultural exchange.  I do value the ten odd words of Telegu that I know know, and the three written words I can scratch out. I know more about the geography and the history of the different cultures and languages there. All in all an amazing experience for me.

 

 

Wednesday, August 7, 2013

Retrospectively Yours: Reviewing The Past

I just finished up a letter to a programmer mentor and friend, he will no doubt think of it as way too long, but c'est la vie. It made me wonder if we don't remember the transitional steps we go through and the important ideas we coalesce into our tool-sets and where they come from.

I like to think of engineering teams as a group that picks ideas. What ideas that are picked up by the group and "internalized" is probably the most important decision made in the development group. Ideas that functionally result in a mess, can be catastrophic to an organization, and will be a millstone around the organization long after those responsible have left.

The steps in my own professional development from script-kiddie to tool-builder, have taken me to many interesting intellectual places, from standards driven development to custom extension building, but still, even after 20 years worth of programming I am not insured of making the correct decision. That is where my team comes in, during the collaborative process we all contribute to finding a decision that results in the minimum overall institutional mess, and believe you me, the decisions I arrive at myself are considerably weaker then the team decisions.

On a good team, your team mates are just your friends, and you look to your friends to help moderate your behavior and to help you make sound judgements. Also you expect to be able to help them, and to care about the various outcomes. When I look to my past in programming, I just see groups of friends, cheerfully writing code, building websites and stuffing up managers.

Technical Team Leadership

"Being an IT team lead is allot like being a really ugly mathletics cheerleader."
-g.dirlam 2013

Collaborative teams means that the team leader is there as a discussion moderator, he has little particular power. I like to say that I team leaders power consist of moderating the discussion, and controlling the learning syllabus. These are powerful tools when used in collaborative environments, the set the agenda of the team, and establish the team's technical trajectory.

The single most important goals of a team leader should be to facilitate skills enhancement and increase unit cohesion.  You want to create a process that bakes in cross-functional skills and creates collaboration and dependencies in your team.

The discussion moderator will be rewarded for having useful discussions and for the corollary he will be punished and made the subject of derision and mocking. Teams communicate with meetings, if they are heinous, it erodes the team's cohesion. Ending your meetings on time, and sending discussions that are not useful for the whole team to the "parking lot" are activities that will result in you making friends. If you run rambling meeting, your team will make you the butt of their jokes. Also it is a useful sign that the team is broken.

It is important that you start establishing your technical roadmap as soon as possible, and that you put some love into it. You will need some organic, growing artifacts to support your thoughts, and give them life. This roadmap will dictate the development of a learning syllabus for the team.

It is hard to get to the point where you have enough trust to share what you don't know. But it is exactly here that you need to get yourself and your team. You need to be open, you need to be fair, and you need to be positive for long enough that your team sees these as personality traits, so that your team decides they can trust you with what they actually do not know.

How could you attempt to fill in technical gaps if you don't know they exist? Why should your team point out things they are not good at, if you the team leader never admits to not knowing technical things. It is easy for us to say we don't know a business process, and say, look we say we don't know things, but then when it comes to the technical, we make out as if we already knew it. It is hard to admit we don't know something that we really should have known, but if you don't as a team leader, there is no way you will establish the trust of your team. Truth is an important foundation of life-long learning, and this allows you to set the team syllabus.


Tuesday, August 6, 2013

Hip Hip 'Array

['hip', 'hip'] 
//the hip hip array.

Thursday, October 4, 2012

A big mess (draft)


Okay, so I have been creating large scale web applications for over 10 years, and have seen allot of other people's work also. The one thing that jumps out at me, is just how ridiculously disheveled and unorganized our applications are. Its like every application I have ever worked on was to impersonate a 13 year old boy's room. Actually, when I was 13, I think I kept my room in better order then these applications. 

Usually I am faced with a dog-pile of hundreds of items stored in the folders, "Scripts", "Images ", and "Styles". Without any useful segregation  separation  or tagging. Just hundreds of things, and all I know, is someone tossed this name on it, and said, "hey, its a image" or "he-ay, this is a style sheet". And just to be clear, just knowing something is a style sheet, is not really useful, especially when the style sheet in question contains thousands of selectors, which go as far as to over-write each other in order of precedence.

So what I really want most in life, is for my work life to be more usefully organized on the file-system. So I can up with Dhui, for a project that I am working on.

Now Dhui, good bless its soul, is at it heart, a series of CSS classes that are used to decorate the class attribute of HTML tags. Once you have established your tags, you place all you dhui related resources in a location.

o I just started a new github project called Gooi. Which is located here.

Monday, September 24, 2012

Gooi - my new endervor (Draft)

So I just started a new github project called Gooi. Which is located here.

Gooi will be a pureJs application scaffold. It will concentrate on the presentation layer and server connectivity of a web site. I expect that it will include some external plugins where they are available to take care of some of the underlining activities.

Gooi's topography will be explicitly represented on the file-system. The folder Gooi will represent the taxon, the top level of the scaffold's taxonomy. 

The taxonomy will be scoped into the following domains, "Core", "Helpers", "Page", "Type", "Picto", "Ux" and a "Plugins" location. Each will house all the Broader Terms, those resources that are logically grouped under that category. Each top level category will house any general resources, and all appropriate related term nodes. 

Gooi attempts to manage resources by implementing a controlled vocabulary and will  associate all "related term" resources via placement in the file-system and the resource's file name to establish its placement in the taxonomy. 

The first two hierarchical levels of the Gooi app scaffold are represented below, with sample broader terms added as examples, see Figure 2 in the appendix. 

Gooi attempts to solve the following problems. 

  • Presentation Resource Management and Categorization
    • Images
    • Sprites
    • web fonts
    • style sheets
  • Consolidation of resources, 




Figure 1.
Note: Taxon > domains > broader terms > related terms

Figure 2.

  • Gooi
    • GooiCore 
      • GooiCoreLoader
      • GooiCoreModules
      • GooiCorePackages 
      • GooiCorePrimatives
      • GooiCoreSockets 
    • GooiHelpers
      • GooiCoreArrays
      • GooiCoreUtilities
    • GooiPage
      • GooiPageHeader
        • GooiPageHeaderMenu
      • GooiPageContent
    • GooiType
    • GooiPicto
    • GooiUx
      • GooiUxButton 
      • GooiUxFaceted 
      • GooiUxForm
      • GooiUxGrid
    • Plugins
      • JSon2 (1.3kb)
      • Microajax (.4kb)
      • Qwery (2.6kb)
      • yepnope (1.8kb)
Auxiliary project resources, like the Topography document and it's associated resources and the solutions readme file will be prefixed with an underscore and added to the Gooi folder root.












Friday, September 21, 2012

Thoughts on being a programmer - retweet



  • Don't be an asshole.
  • Simple code is hard to write.
  • Exquisitely simple code is exquisitely hard to write.
  • Just because it's easy to understand doesn't mean it was easy to write.
  • In fact, the easier it is to understand, the harder it probably was to write.
  • There are many ways to do something.
  • The first way you think of is highly unlikely to be the best way.
  • Anyway, there probably is no best way - just lots of ways that are differently good.
  • There's always plenty of room for improvement - in your code, in your abilities, in you.
  • If you think you're as good as you're ever going to be - you're probably right.
  • "One-line changes" aren't.
  • Learn to desire success more than you fear failure.
  • You're only old when you can no longer learn new tricks.
  • Always back up before tidying up.
  • RTFM.
  • Err vicariously.
  • Sometimes it's OK to be a bit of an asshole. But don't make a habit of it.

 -- reposted from http://www.yelsew.com/thoughts.html

Saturday, September 8, 2012

GoF in ES

Learning JavaScript Design Patterns

Preparing Yourself for Modern JavaScript Development

Understanding JavaScript OOP

ES Style Guide

JavaScript and the Semicolon

Sometimes, we realize that we have taken a course for decades, and have not really thought about why. I found myself in that curious position when I read this entry JavaScript Semicolon Insertion, whose author knows 50 times more about the state of the ECMAScript specification then I do.

So I have written allot of javascript over the years. I have been writing JavaScript professionally since 1997 and the browser wars, so that is allot of semicolons. I never really thought to wonder about it, just inserted them in the appropriate place at some line terminations.

Good.
function add(event, callback) {
  if (fn_p(event)) {
    callback = event
    event    = this.default_event }
  insert_callback.call(this)
  return this

  function insert_callback() {
    if (this.value)  fire(this, event, callback)
    else             add_callback(this, event, callback) }
    }
}

Bad
function add(event, callback) {
  if (fn_p(event)) {
    callback = event;
    event    = this.default_event;
  }
  insert_callback.call(this);
  return this;

  function insert_callback() {
    if (this.value) {
      fire(this, event, callback);
    }
    else {
      add_callback(this, event, callback);
    }
  }
}

But, this is all well and good from a human readability standpoint, but I have serious doubts about the adverse reactions from putting good human readable code through javascript uglification and minification.

How old men retweet

Programs must be written for people to read, and only incidentally for machines to execute.

-Sussman

A computer is like a violin. You can imagine a novice trying first a phonograph and then a violin. The latter, he says, sounds terrible. That is the argument we have heard from our humanists and most of our computer scientists. Computer programs are good, they say, for particular purposes, but they aren't flexible. Neither is a violin, or a typewriter, until you learn how to use it.

Marvin Minsky,
Why Programming Is a Good Medium for Expressing Poorly-Understood and Sloppily-Formulated Ideas

From:

Donald E. Knuth, Fundamental Algorithms (Volume 1 of The Art of Computer Programming)

Wednesday, September 5, 2012

Retweeting Einstein

"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction." -- Albert Einstein

Friday, July 22, 2011

Functional Patterns in our Everyday Code

Modern Programming
During the advent of modern programming, which I think of as post 2005 code base, we have received many enhancements to our programming toolsets.  Much ado has been made about these enhancements, often these are the frameworks that Web 2.0 has been built on.
The modern programming tools are very aware of the upcoming Mobile Application Flood,  but they also own a considerable amount to older programming techniques first developed in LISP as early back as the 1960's.  Python popularized much of the functional programming style, and was incorporated into ECMAScript. 

Functional Programming
Javascript and its adopted parent ECMAScript were developed with functional capabilities from the very beginning. Methods in JavaScript are first class and can be passed as around as arguments. Consider the following Native Javascript Code:


<script language="ecmascript" type="text/ecmascript">
    Array.prototype.AlertOnce = function () { alert('A') };
    [1, 2, 3].AlertOnce();
script>


The script applies an anonymous function to the array object as an extension method, via the prototype pattern.

In the script below, the anonymous function iterates the array, and runs once per primary object occurrence in the array.


<script language="ecmascript" type="text/ecmascript">
    var IEnum = [1, 2, 3];
    IEnum.forEach(function (ele, i) {
        alert(i + ':' + ele)
    });
script>


Contrasted with the JQuery Method, below. The methods are almost identical.


<script language="ecmascript" type="text/ecmascript">
    var IEnum = [1, 2, 3];
    $(IEnum).each(function (i, ele) {
        alert(i + ':' + ele)
    });
script>


As compared to a Lambda expression in VB.Net


Dim IEnum = New List(Of Integer)(New Integer() {1, 2, 3})
IEnum.ForEach(Function(i) System.Diagnostics.Debug.Print( i ) )

or in C#

List<int> IEnum = new List<int>(new int[] { 1, 2, 3 });
IEnum.ForEach(i => i.ToString());


These scripts demonstrate multiple ideas. To wit, JavaScript natively supports the sort of iterating across collections pattern that we usually think of JQuery for. And .net now supports a wide set of functional programming, this now includes anonymous methods, JavaScript like prototyping via extension methods (and on those extension methods, even method chaining).

Conclusion:
Instead of thinking about JQuery, or .Net extension methods, we should be seeing these new pieces as functional programming patterns and getting used to thinking in terms of delegates, callbacks and prototypes.

Monday, July 11, 2011

Rest Service Implementation


WCF Rest-like Service
Proto-type implementation

Vocabulary

Representational State Transfer:  Low level stateless software architecture approach that uses the structure of URI's (uniform resource locator) and HTTP 1.0 verbs to define resultant service data displays. REST outlines how to define, access and address data sources without the need for additional messaging layers or session tracking.
Windows Communication Foundation: WCF is a platform that supports a multitude of different methods to expose data services, in a service-oriented methodology. It is request agnostic, meaning it is not tied to a single request method like REST, or SOAP.
Http Client: Object to initiate a Http Request, previously known as XHR or XMLHttpRequest. This safe for scripting object was used to initiate AJAX calls.

Document

This document is meant to detail the top level technological decisions that were made in the proto-type WCF Rest-like Service implementation. This document, based on proto-type implementation is meant to postulate possible guidelines, as such this document will remain in draft format in perpetuity, and will be superseded by any and all Guidance Documents or White Pages on the technologies in this document.

References - Prerequisites

      WCF Rest Service Template 4.0 for Visual Basic
      WCF Rest Starter Kit (http client)
      Visual Studios 2010, .Net Framework 4.0
      IIS 7.0

Http Verbs

It seems appropriate to start any discussion of restful(like) solutions with a conversation about HTTP Request Methods. These are often referred to as "verbs."  Most of us are familiar with "Get" and "Post" but have failed up to now to notice the other request methods that the http protocol supports. For now, let it be sufficient (until we begin our discussion on routing masks) to say that restful services respond to not only the URI of a request, but also route based on the action that is described via the Request Method. WCF commonly responds to GET, POST, PUT and DELETE for crud operations, there are more Verbs in the HTTP Protocol Specification, but they are not in common usage in Restful services.

Routes

Guideline: Configure your routes in the virtual route table, accessed in code in the Global.asax file in a custom Procedure called RegisterRoutes.  This behavior is similar to the routing mechanism employed by MVC.Net web sites.
fig. 1

Private Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
  RegisterRoutes()
End Sub

Private Sub RegisterRoutes()
  RouteTable.Routes.Add(New ServiceRoute("RouteName", New WebServiceHostFactory(), GetType(MyApplication.MyClass)))
End Sub


Application Start

Creating a response to a request in a virtual location (there is no physical file to respond to the request), means that a listener will have to be created.  WCF supplies a factory method to create this listener, with the WebServiceHostFactory class. This factory class should be called at application start,  and added as a Route to the application's RouteTable object.
fig. 2

RouteTable.Routes.Add(New ServiceRoute("RouteName", New WebServiceHostFactory(), GetType(MyApplication.MyClass)))


Routing

Incoming request are passed from IIS to the WebServiceHostFactory, where they are routed according to the RouteTable rules into the class specified in the Routes.Add type argument. The request is then picked up by the Class, and is handled by a method of the class based on the "verbs" and the arguments specified by the request.

 

Route Masks, (HTTP Method and UriTemplates)

The WCF Rest Template offers Common Routing, and templates for the most common scenerios. These are mostly self defining, based on the HTTP method, and also the existance of an id or name argument. It is worth noting, that all arguments passed via a URI will be of type string.
fig. 3

      <WebGet(UriTemplate := "")>
        Public Function GetCollection() As List(Of SampleItem)
            Throw New NotImplementedException()
        End Function
       
        <WebInvoke(UriTemplate := "", Method := "POST")>
        Public Function Create(ByVal instance As SampleItem) As SampleItem
            Throw New NotImplementedException()
        End Function
       
        <WebGet(UriTemplate := "{id}")>
        Public Function [Get](ByVal id As String) As SampleItem
            Throw New NotImplementedException()
        End Function
       
        <WebInvoke(UriTemplate := "{id}", Method := "PUT")>
        Public Function Update(ByVal id As String, ByVal instance As SampleItem) As SampleItem
            Throw New NotImplementedException()
        End Function
       
        <WebInvoke(UriTemplate := "{id}", Method := "DELETE")>
        Public Sub Delete(ByVal id As String)
            Throw New NotImplementedException()
        End Sub

 
Restful services have some common practices, which govern there usage, and these should be adhered to as long as they do not create odiously architected solutions. There is an expectation that reaching the root a Restful Object (in a URL Get), that object will return an unfiltered list of objects of that type.  When an "id" or "name" is specified in a Get on a Restful Object then the expectation is that the Restful Service will return a single instance of the item in question.  Using the HTTP Method, "Delete" means that the requesting caller would like to see that item removed from the underling persistence store.  This is clear, but the Delete could be requested using either a "id" as in "please remove the item with this id from the persistence store" or the object could be sent in a http form, meaning "please remove the item in the persistence store that resembles this item." The Put and Post methods have similar problems, as the user community is not 100% decided on a usage for these items. For the purposes of our discussion, we will assume that POST is equal to a form post in which the requestor desires that we insert the item into the persistence store, and that a PUT is when the requestor desires us to perform an update on an item in the persistence store.

            A Note of Caution: It is incumbent on me to offer a note of caution on POST and PUT, the   Restful service creator should handle PUTs in POSTs and POSTs in PUTs, or send back an    explanation on why the desired result was not achieved.


Complex Routes

Routes that specify multiple filtering items at different levels of the Restful Portion of the Resource Locator, are complex routes.

Complex routes need to be specified on the top hierarchical level. For instance, there is a parent-child relationship and the service should list a collection of children, filtered by the parent id, then the handler method will be created on the parent level.

fig. 4

      <WebGet(UriTemplate := "{id}/Child")>
        Public Function GetChildCollection() As List(Of SampleItem)
            Throw New NotImplementedException()
        End Function
       

Introducing the HtHttpClient

The WCF Rest starter kit comes with a new and improved HttpClient Utility. This new client, like the old XMLHttpRequest Utility allows a thread to programmatically access the web resources without the overhead of a user-interface. The new HttpClient is a major update of functionality, since the XHR methodologies of early 2000 contained no support for Http Request Methods beyond GET and POST and also were not concerned about serialization. Modern Service Architectures have significant enhancements to serialization and do not stop at POX (Plain Old XML, simply returning a document of XML data). The WCF service and the HttpClient come together in serialization of strongly typed data, you may expose your data from the WCF as "exact type" and consume it in your interface as the same "exact type" that you exposed it as. This methodology means that a WSDL data contract is not only unnecessary, but also undesirable, in so far as the WSDL creates a new type that the client consumes.
Additionally the new HttpClient has built in support for "DELETE" and "PUT" Http Verbs, as well as the more common, "GET" and "POST" of XHR.

Usage

The HttpClient is located in the Microsoft.Http.dll, which is included in the WCF Rest Starter Kit. Adding Headers is simple in the
 fig. 5

        Using client As New HttpClient("http://localhost:8080/Route/")
            Using response As HttpResponseMessage = client.[Get]("Action?id=3")
                response.EnsureStatusIsSuccessful()
                Dim anon = response.Content.ReadAsDataContract(Of List(Of ContractLibrary.Interfaces.IItem))()
            End Using
        End Using


Custom Headers

Adding Headers is simple in the HttpClient. Access the DefaultHeaders Collection of your instantiated client and then call the Add method.
fig. 6

        client.DefaultHeaders.Add("CustomHeader", HeaderValue)


Security/Authentication

The Restful service site is secured through the usual Microsoft Web Security Provider, and needs no configuration beyond what is usually contained in a .net web site. Accessing the resources in a secure manner usually means that you will be sending a set of credentials (as system.net.icredentials) in the Http Request of the HttpClient Utility.
fig. 7

        client.TransportSettings.Credentials = Credentials


Configuration

The options specified in the web.config file of the Rest service are fairly straight forward.  Though please note the last WCF section, and in particular the attribute HelpEnabled, which automatically creates an operation description page for each route when the route action is "/help."

Authentication:

    <roleManager defaultProvider=".." enabled="true">
      <providers>
        <add name=".." connectionStringName=".." applicationName=".." type="System.Web.Security.SqlRoleProvider, .."/>
      providers>
    roleManager>
    <authorization>
      <deny users="?" />
    authorization>

Routing :

    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    modules>

WCF:

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
     
    serviceHostingEnvironment>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      webHttpEndpoint>
    standardEndpoints>
  system.serviceModel>