<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Safari Books Online's Official Blog</title>
	
	<link>http://blog.safaribooksonline.com</link>
	<description>Your On-Demand Digital Learning Library</description>
	<lastBuildDate>Thu, 23 May 2013 23:05:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/SafariBooksOnlineBlog" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="safaribooksonlineblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Instrumenting APIs with Links in REST</title>
		<link>http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/#comments</comments>
		<pubDate>Thu, 23 May 2013 23:05:56 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[IANA]]></category>
		<category><![CDATA[Links]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[RESTful]]></category>
		<category><![CDATA[RESTful API]]></category>
		<category><![CDATA[RFC 5988]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=10078</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>REST is now the most common approach used for designing Web APIs. A well-designed REST API is based upon media types that define the message formats used in client-server exchanges. See REST APIs in the REST API Design Rulebook for &#8230; <a href="http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/">Instrumenting APIs with Links in REST</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>REST is now the most common approach used for designing Web APIs. A well-designed REST API is based upon media types that define the message formats used in client-server exchanges. See <a href="http://my.safaribooksonline.com/9781449317904/id2813725?iid=2013-05-blog-rest-book-9781449317904-SBOBlog">REST APIs</a> in the <em>REST API Design Rulebook</em> for more on this topic. A media type will document both the structure of a valid message and the hypermedia &#8220;controls&#8221; used to interact with resources.</p>
<p>Examples of controls are forms or typed links. The HTML media type defines several controls, including:<br />
<span id="more-10078"></span></p>
<ul>
<li>The <code>img</code> and <code>a</code> elements use links for transclusion and navigation</li>
<li>The <code>form</code> elements are used to construct requests to a server</li>
</ul>
<p>Typed links are the most common form of control and provide the means for clients to traverse the functionality exposed by an API. When we are designing a new API, it&#8217;s useful to draw on existing patterns for designing links. It turns out that there is both a common conceptual framework that we can use, as well as an existing registry of link types.</p>
<h2>A Conceptual Link Framework</h2>
<p>Both HTML and Atom include a generic <code>link</code> element. For more on Atom, read <a href="http://my.safaribooksonline.com/9781449383312/atom_everywhere?iid=2013-05-blog-rest-book-9781449383312-SBOBlog">Chapter 7.6: Atom Everywhere</a> in <em>Rest in Practice</em>. In HTML, this is most commonly used to reference stylesheets:</p>
<pre>	&lt;link rel="stylesheet" type="text/css" media="screen" href="/stylesheet.css" /&gt;</pre>
<p>Atom uses the <code>atom:link</code> element in a number of ways, for example, to publish the permalink to a blog post and the URI used to edit it:</p>
<pre>   &lt;atom:link href="http://example.org/2003/12/13/atom03" /&gt;
   &lt;atom:link rel="edit" href="http://example.org/2003/12/13/atom03/edit"/&gt;</pre>
<p>The common aspects of these elements have been standardized as part of <a href="http://tools.ietf.org/html/rfc5988">RFC 5988</a> (Request for Comments), which describes a conceptual framework for defining links in media types. This is exactly what we need for creating RESTful APIs.</p>
<p>RFC 5988 describes a number of key aspects of a link:</p>
<ul>
<li>The <em>Context URI</em> &#8212; the resource to which the link applies, such as a specific Atom feed entry</li>
<li>The <em>Target URI</em> &#8212; the resource that is being referenced in the link, such as a stylesheet</li>
<li>The <em>Link Relation</em> &#8212; the type of the link, such as &#8220;edit&#8221; or &#8220;stylesheet&#8221; in the above examples</li>
</ul>
<p>Optionally, there may be some standard Target Attributes that describe an aspect of the destination resource, like its title or expected media type (<code>text/css</code>).</p>
<p>But the RFC doesn&#8217;t define how links should be expressed, just its properties. The HTML and Atom examples show one way to capture that information in an XML format, while a potential JSON encoding might be:</p>
<pre>	{
      "link": {
         "href": "http://example.iana.org/resource1",
		 "type": "text/html"
      }
    }</pre>
<p>Our media type documentation needs to define how a link will be formatted and, most importantly, what types of links a client might encounter. Client behavior is driven through discovering and following typed links.</p>
<p>Media types that use RFC 5988 style links are easily extended: all we need to do is define new types of link relations.</p>
<h2>The IANA Link Registry</h2>
<p>We may also be able to re-use existing link types. The IANA (Internet Assigned Numbers Authority) maintains <a href="http://www.iana.org/assignments/link-relations/link-relations.xml">a central registry for common link relations</a>. There are a wide range of relations including:</p>
<ul>
<li>A <code>bookmark</code> providing a permalink</li>
<li>A <code>describes</code> relation that asserts that one resource provides a description of another</li>
<li>An <code>edit</code> relation refers to a resource that can be used to edit the content of the context URI</li>
<li>Navigation relationships (<code>previous</code>, <code>first</code>, <code>last</code>, <code>next</code>) for moving within a list of resources</li>
</ul>
<p>The registry is an excellent point of reference, either for inclusion in a custom media-type or as a source of new relations for an existing type. New types can be added to the registry, and it&#8217;s also possible to use <a href="http://tools.ietf.org/html/rfc5988#page-6">a URI as an identifier for a link type</a>, rather than a short name.</p>
<h2>Instrumenting Existing APIs</h2>
<p>Handily, RFC 5988 also defines a way to publish links via the Link HTTP header. This has a number of advantages:</p>
<ul>
<li>Links can be published without changing current formats or clients, making it possible to make existing APIs more RESTful</li>
<li>Links can be used by clients without the need to parse and understand specific media types, allowing for some generic client interactions</li>
<li>Where a resource exposes data in multiple formats, it provides a consistent location for exposing the links that are common to all representations</li>
</ul>
<p>The &#8220;edit&#8221; link from the earlier Atom example could be included in an HTTP header as:</p>
<pre>   Link: &lt;http://example.org/2003/12/13/atom03/edit&gt;; rel="edit"</pre>
<p>Similarly, paging links could be exposed like this:</p>
<pre>   Link: &lt;http://example.iana.org/collection/1&gt;; rel="first",
      &lt;http://example.iana.org/collection/100&gt;; rel="last",
      &lt;http://example.iana.org/collection/3&gt;; rel="next",
      &lt;http://example.iana.org/collection/2&gt;; rel="previous",</pre>
<p>An API could also link to both the license associated with the data it returns and its terms of use:</p>
<pre>   Link: &lt;http://opendatacommons.org/licenses/odbl/&gt;; rel="license",
      &lt;http://example.iana.org/about/terms-of-service&gt;; rel="terms-of-service",</pre>
<h2>Summing Up</h2>
<p>Typed links are a core feature of any RESTful API. They provide the means for clients to traverse the functionality exposed by the API. By building on a common conceptual framework, and an existing registry of link relations, we can take advantage of existing experience and design patterns when designing new APIs.</p>
<p>Where we have limited freedom to add links to existing media types, we can still make those APIs more RESTful by exposing links at the HTTP protocol level.</p>
<p>For more details about REST, see the ebooks referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449383312?iid=2013-05-blog-rest-book-9781449383312-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7242-techbus/images/9781449383312/9781449383312_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>REST continues to gain momentum as the best method for building web services, leaving many web architects to consider whether and how to include this approach in their SOA and SOAP-dominated world. <a title="Rest in Practice" href="http://my.safaribooksonline.com/9781449383312?iid=2013-05-blog-rest-book-9781449383312-SBOBlog" target="_blank">Rest in Practice</a> offers a down-to-earth explanation of REST, with techniques and examples that show you how to design and implement integration solutions using the REST architectural style.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449317904?iid=2013-05-blog-rest-book-9781449317904-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7242-techbus/images/9781449317904/9781449317904_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>The basic rules of REST APIs &#8211; &#8220;many nouns, few verbs, stick with HTTP&#8221; &#8211; seem easy, but that simplicity and power require discipline to work smoothly. <a title="REST API Design Rulebook" href="http://my.safaribooksonline.com/9781449317904?iid=2013-05-blog-rest-book-9781449317904-SBOBlog" target="_blank">REST API Design Rulebook</a> provides the next steps for implementing complex REST projects on simple and extensible foundations.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9780132869904?iid=2013-05-blog-rest-book-9780132869904-SBOBlog" target="_blank"><img src="http://my.safaribooksonline.com/static/201305-7241-my/images/9780132869904/9780132869904_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="SOA with REST: Principles, Patterns &amp; Constraints for Building Enterprise Solutions with REST" href="http://my.safaribooksonline.com/9780132869904?iid=2013-05-blog-rest-book-9780132869904-SBOBlog" target="_blank">SOA with REST: Principles, Patterns &amp; Constraints for Building Enterprise Solutions with REST</a> is the first comprehensive tutorial and reference for designing and building RESTful services as part of service-oriented solutions and in conjunction with service-oriented architecture (SOA). This book demonstrates that REST is not only a suitable medium for building truly service-oriented solutions, but also that the service-oriented architectural model is a necessary foundation for REST technology architectures to realize their full business potential.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/leigh.jpg"><img class="alignnone size-thumbnail wp-image-10097" title="leigh" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/leigh-150x150.jpg" alt="" width="150" height="150" /></a></td>
<td>Leigh Dodds is a freelance consultant specializing in Linked Data, Open Data and API development. Passionate about the web, open standards, and open source he enjoys exploring how to apply new technologies to create interesting products. He&#8217;s also quite fond of gaming, Lego, Minecraft and a good beer. You can reach Leigh on<br />
Github: <a href="https://github.com/ldodds">https://github.com/ldodds</a> or on Twitter: <a href="http://www.twitter.com/ldodds">@ldodds</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/">Instrumenting APIs with Links in REST</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/a4pJoqG_X2c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/23/instrumenting-apis-with-links-in-rest/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Hypermedia in Your RESTful API Design</title>
		<link>http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/#comments</comments>
		<pubDate>Wed, 22 May 2013 18:16:27 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[HATEOS]]></category>
		<category><![CDATA[Hypermedia]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9948</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>In simple terms, hypermedia is how people consuming your services discover your system. One of the great things about hypermedia is that it&#8217;s dynamic – so the links you provide through hypermedia can change depending upon the state of the &#8230; <a href="http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/">Using Hypermedia in Your RESTful API Design</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>In simple terms, hypermedia is how people consuming your services discover your system. One of the great things about hypermedia is that it&#8217;s dynamic – so the links you provide through hypermedia can change depending upon the state of the resource your system is providing at runtime (this contrasts with traditional SOA where links/endpoints are static). Hypermedia is often forgotten in RESTful systems design, but HATEOS (Hypermedia as the Engine of Application State) is a core component of REST.</p>
<p>Using hypermedia in the field can sometimes be elusive, or daunting. For more background details, read <a href="http://my.safaribooksonline.com/9780132869904/ch06lev1sec4?iid=2013-05-blog-rest-book-9780132869904-SBOBlog">Chapter 6.4: The Role of Hypermedia</a> in <code>SOA with REST</code>. Take, for instance, the user resource in the ubiquitous user admin system. Many RESTful systems support the following:<br />
<span id="more-9948"></span></p>
<pre>GET /users 		- Get all users
GET /users/123 	        - Get a specific user
POST /users 		- Create a new user
PUT /users/123 	        - Update a specific user
DELETE /users/123	- Delete a specific user</pre>
<p>Your system may support all five of the above actions on the user resource, but access is probably limited. Normal users can probably view themselves, update themselves, and view other people&#8217;s information, but probably can&#8217;t delete users, list all users or update other users.</p>
<p>So your API, which supports five operations against users, actually only supports those operations in certain circumstances.</p>
<p>This is where hypermedia can make your API easier to understand, and can simplify how your services are consumed.</p>
<p>In a system that does not employ hypermedia, when you GET a specific user you may often serve up some data such as:</p>
<pre>{
	“id”:”456”,
	“name”:“Fred Jones”,
	“role”:“Normal”
}</pre>
<p>However, this does not let us understand immediately what Dave (an admin) can do in relation to the system.</p>
<p>A better representation of viewing a user (using hypermedia) could be:</p>
<pre>{
	“id”:”456”,
	“name”:“Fred Jones”,
	“role”:“Normal”,
	“actions”: [
		{ “ability”: “List all users”, “method”:”GET”, “uri”:”/users”},
		{ “ability”: “Delete Fred”, “method”:”DELETE”, “uri”:”/users/456”},
		{ “ability”: “Edit Fred”, “method”:”PUT”, “uri”:”/users/456”},
		{ “ability”: “View my profile”, “method”:”PUT”, “uri”:”/users/789”},
	]
}</pre>
<p>This shows us that Dave can list all users, delete that user, edit that user, and also view their profile.</p>
<p>For a normal user looking at Fred, a representation could instead be:</p>
<pre>{
	“id”:”456”,
	“name”:“Fred Jones”,
	“role”:“Normal”,
	“actions”: [
		{ “ability”: “View my profile”, “method”:”PUT”, “uri”:”/users/789”},
	]
}</pre>
<p>Note that as a normal user looking at Fred, there are no admin operations like listing all users, or deleting/updating other users. The only action they can do (in terms of the user administration sub system) is view their own profile.</p>
<p>So by using hypermedia, we are dynamically offering up different operations on our system, depending upon the type of user accessing the service.</p>
<p>We&#8217;re enabling discovery of our system, and allowing that dynamically driven information to be driven by our state – we are representing the state of our system and transferring that state through our API.</p>
<p>Where this gets useful is in the consumer end of our API.</p>
<p>Often, websites that use a remote service (whether RESTful or not) know far too much about the inner workings of the service they are using.</p>
<p>You often see code like this:</p>
<pre>%h2 Dave's profile page
- if current_user.is_admin?
  =link_to '/users', 'List all users'
  =link_to '/users/789/delete', 'Delete Dave'
  =link_to '/users/789/edit', 'Edit Dave'

- if current_user != user_being_viewed
  =link_to '/users/123', 'View my own profile'

%p 
 Name: 
 = current_user.name
%p
 Role:
 = current_user.role</pre>
<p>In this small example, the website knows about a few things it doesn&#8217;t need to:</p>
<ul>
<li>The uri to list the users</li>
<li>Whether or not a user is an admin</li>
<li>Whether or not a user can list other users</li>
<li>Whether or not a user can update/delete the user</li>
</ul>
<p>By using hypermedia though, we can push the responsibility of that knowledge back to the service, and away from the consuming website:</p>
<pre>%h2 Dave's profile page
- current_user.actions.each do |action|
  link_to action.uri, action.name
%p 
 Name: 
 = current_user.name
%p
 Role:
 = current_user.role</pre>
<p>Now obviously, you&#8217;re never going to be able to build completely dumb websites that consume RESTful services, and there&#8217;s always going to be some knowledge of the API that leaks out into the consumer application. Limiting those <code>if</code> statements, however, is a worthy goal, which pushes knowledge away from your consuming application.</p>
<p>Another trick to building APIs that expose state, is to push the state of fields within your resource representation. This isn&#8217;t strictly hypermedia, but borrows from its understanding of how applications should represent themselves.</p>
<p>Take a user representation before:</p>
<pre>{
	“id”:”456”,
	“name”:“Fred Jones”,
	“role”:“Normal”
	actions[
 		… actions
	]
}</pre>
<p>One thing that is missing from this is any indication of whether the person viewing that user can edit any fields (think a profile update page).</p>
<p>Another representation (for an Admin) could be:</p>
<pre>{
	field { “name”:“id”, “value”:“456”, “editable”:“false”, “type”:“text” }
	field { “name”:“name”, “value”:“Fred Jones”, “editable”:“true”, “type”:“text” }
	field { “name”:“role”, “value”:“Normal”, “editable”:“true”, “type”:“select”,
		“options”:[“Normal”, “Hacker”, “Admin”]
	}
	actions[
 		… actions
	]
}</pre>
<p>And the representation for a normal user:</p>
<pre>{
	field { “name”:“id”, “value”:“456”, “editable”:“false”, “type”:“text” }
	field { “name”:“name”, “value”:“Fred Jones”, “editable”:“true”, “type”:“text” }
	field { “name”:“role”, “value”:“Normal”, “editable”:“false”, “type”:“text” }
	actions[
 		… actions
	]
}</pre>
<p>So depending upon the type of user, and who they are viewing, the options change.<br />
For example, a normal user cannot edit their role, but for an admin user, the role field is editable, and a list of potential options are given.</p>
<p>This is where APIs get really useful, and start pushing the state of their resources to the client side. By using this kind of pattern, a single client website page can use the same view to render a representation in HTML without having to resort to <code>if/else</code> statements. The logic remains inside the service.</p>
<p>For more details about REST, see the ebooks referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449383312?iid=2013-05-blog-rest-book-9781449383312-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7242-techbus/images/9781449383312/9781449383312_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>REST continues to gain momentum as the best method for building web services, leaving many web architects to consider whether and how to include this approach in their SOA and SOAP-dominated world. <a title="Rest in Practice" href="http://my.safaribooksonline.com/9781449383312?iid=2013-05-blog-rest-book-9781449383312-SBOBlog" target="_blank">Rest in Practice</a> offers a down-to-earth explanation of REST, with techniques and examples that show you how to design and implement integration solutions using the REST architectural style.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449317904?iid=2013-05-blog-rest-book-9781449317904-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7242-techbus/images/9781449317904/9781449317904_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>The basic rules of REST APIs &#8211; &#8220;many nouns, few verbs, stick with HTTP&#8221; &#8211; seem easy, but that simplicity and power require discipline to work smoothly. <a title="REST API Design Rulebook" href="http://my.safaribooksonline.com/9781449317904?iid=2013-05-blog-rest-book-9781449317904-SBOBlog" target="_blank">REST API Design Rulebook</a> provides the next steps for implementing complex REST projects on simple and extensible foundations.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9780132869904?iid=2013-05-blog-rest-book-9780132869904-SBOBlog" target="_blank"><img src="http://my.safaribooksonline.com/static/201305-7241-my/images/9780132869904/9780132869904_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="SOA with REST: Principles, Patterns &amp; Constraints for Building Enterprise Solutions with REST" href="http://my.safaribooksonline.com/9780132869904?iid=2013-05-blog-rest-book-9780132869904-SBOBlog" target="_blank">SOA with REST: Principles, Patterns &amp; Constraints for Building Enterprise Solutions with REST</a> is the first comprehensive tutorial and reference for designing and building RESTful services as part of service-oriented solutions and in conjunction with service-oriented architecture (SOA). This book demonstrates that REST is not only a suitable medium for building truly service-oriented solutions, but also that the service-oriented architectural model is a necessary foundation for REST technology architectures to realize their full business potential.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/benphoto.png"><img class="alignnone size-thumbnail wp-image-10057" title="benphoto" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/benphoto-150x150.png" alt="" width="150" height="150" /></a></td>
<td>Ben Keeping is a freelance developer based in the UK. He currently specializes in applications written in .NET and Ruby, using lean and agile techniques. He can be contacted <a href="http://www.twitter.com/benkeeping">@benkeeping</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/">Using Hypermedia in Your RESTful API Design</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/Z-3NQiSYVvk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/22/using-hypermedia-in-your-restful-api-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrating Data from MySQL into HBase</title>
		<link>http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/#comments</comments>
		<pubDate>Tue, 21 May 2013 21:21:51 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[HBase]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[Migrating Data]]></category>
		<category><![CDATA[mySQL]]></category>
		<category><![CDATA[RDBMS]]></category>
		<category><![CDATA[TSV Format]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9941</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>HBase lets you store big data on commodity machines. It can scale up to millions of rows and columns each, putting Big Data processing, in real time, within reach of even individual developers, which is extremely difficult, if not impossible, &#8230; <a href="http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/">Migrating Data from MySQL into HBase</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>HBase lets you store big data on commodity machines. It can scale up to millions of rows and columns each, putting Big Data processing, in real time, within reach of even individual developers, which is extremely difficult, if not impossible, with Relational Database Management Systems (RDBMS). For an introduction to HBase, be sure to read <a href="http://blog.safaribooksonline.com/2013/04/26/hbase-an-opensource-bigtable-database/">HBase – An OpenSource BigTable Database</a>. In this post, I will talk about data migrations, showing you how to migrate your data from MySQL into an HBase data store.<br />
<span id="more-9941"></span><br />
There are three primary ways to migrate data into HBase:</p>
<ul>
<li>Put API</li>
<li>Bulk load tool</li>
<li>MapReduce Job</li>
</ul>
<p>The Put API is probably the most straightforward way to import data quickly into an HBase table. It’s not recommended, however, to be used when importing huge amounts of data. You can think of it as the “Hello World” of HBase data migration.</p>
<p>The bulk load tool, on the other hand, runs a MapReduce job behind the scenes to populate data into an HBase table. Once populated, the tool also supports generating the HBase internal file format (HFile), enabling you to feed the freshly imported data directly into a running HBase cluster.</p>
<p>To quickly and reliably load a huge data file, you can use the importTSV tool. Since data migration is a write-intensive task, if you go the custom MapReduce job route, you will have to handle issues like optimal configuration to make sure data writes are not clogged. Let’s see how you can load data from a MySQL table into an HBase table with importTSV.</p>
<p>First, you will have to export your table data from an RDBMS, like MySQL, into a TSV format (remember, we’re using the Import TSV tool). You will have to make sure that there’s a field representing the row key of the HBase table row. There are scripts that can do this for you.</p>
<p>Now, since importTSV uses a MapReduce job in the backend to import data, you will have to spin a MapReduce instance on your cluster. Starting a MapReduce daemon can be done by executing this command on the master node:</p>
<pre>hadoop$ $HADOOP_HOME/bin/start-mapred.sh</pre>
<p>Follow along with these four steps to load data from a TSV file to HBase table:</p>
<ol>
<ol>
<li>Since importTSV only reads data from HDFS, you have to copy the TSV file from local file system to HDFS directory:
<pre>hac@client1$ $HADOOP_HOME/bin/hadoop fs -mkdir /user/hac/input/2-1

hac@client1$ $HADOOP_HOME/bin/hadoop fs -copyFromLocal hly-temp-10pctl.tsv
 /user/hac/input/2-1</pre>
</li>
<li>Create a target table in HBase and add a column family to it. If the table already exists, you can alter it and old data will not be changed. I’ve added a ‘t’ column family where data will be populated:
<pre>hac@client1$ $HBASE_HOME/bin/hbase shell
hbase&gt; create 'hly_temp', {NAME =&gt; 't', VERSIONS =&gt; 1}

hbase&gt; alter 'hly_temp', {NAME =&gt; 't', VERSIONS =&gt; 1}
hbase&gt; enable 'hly_temp'</pre>
</li>
<li>Add hbase-site.xml and HBase dependency JARs in Hadoop classpath:
<pre>hac@client1$ ln -s $HBASE_HOME/conf/hbase-site.xml $HA-DOOP_HOME/conf/hbase-site.xml

hadoop@client1$ vi $HADOOP_HOME/conf/hadoop-env.sh
<em>export HADOOP_CLASSPATH=/usr/local/zookeeper/current/zookeeper-3.4.3.jar:/usr/ local/hbase/current/lib/guava-r09.jar </em></pre>
</li>
<li>Finally, run the importTSV tool by running this script:
<pre>hac@client1$ $HADOOP_HOME/bin/hadoop jar $HBASE_HOME/hbase-0.92.1.jar 
   importtsv \-Dim-porttsv.columns=HBASE_ROW_KEY,t:v01,t:v02,t:v03,t:v04,
   t:v05,t:v06,t:v07,t:v08,t:v09,t:v10,t:v11,t:v12,t:v13,t:v14,t:v15,
   t:v16,t:v17,t:v18,t:v19,t:v20,t:v21,t:v22,t:v23,t:v24 \
hly_temp \
/user/hac/input/2-1</pre>
</li>
</ol>
</ol>
<p>What you’re doing here is running importTSV with the following parameters:</p>
<ol>
<ol>
<ul>
<li><code>Porttsv.columns</code>, which specifies the row key column. I’ve used <code>HBASE_ROW_KEY</code> that specifies the row key.</li>
<li>Mapping information between the HBase table column family and the data columns in your TSV file. In this case, the data was arranged in the TSV file as <code>row_key</code>, <code>value01</code>, <code>value02</code> and so on.</li>
<li>TSV file path.</li>
</ul>
</ol>
</ol>
<p>You can check the status of your MapReduce data migration job on the Admin page:</p>
<pre>http://&lt;master_node_name&gt;:&lt;default_port&gt;/jobtracker.jsp</pre>
<p>This is one of the several ways you can migrate MySQL database tables into HBase table. You can find a lot more hands-on examples in the books referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<p>Check out these Hbase books available from Safari Books Online:</p>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449314682?iid=2013-04-blog-hbase-book-9781449314682-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201304-7199-techbus/images/9781449314682/9781449314682_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781449314682?iid=2013-04-blog-hbase-book-9781449314682-SBOBlog" target="_blank">HBase: The Definitive Guide</a> shows you how Apache HBase can fulfill your needs. As the open source implementation of Google&#8217;s BigTable architecture, HBase scales to billions of rows and millions of columns, while ensuring that write and read performance remain constant. This book provides the details you require to evaluate this high-performance, non-relational database, or put it into practice right away.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781849517140?iid=2013-04-blog-hbase-book-9781849517140-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201304-7199-techbus/images/9781849517140/9781849517140_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781849517140?iid=2013-04-blog-hbase-book-9781849517140-SBOBlog" target="_blank">HBase Administration Cookbook</a> provides practical examples and simple step-by-step instructions for you to administrate HBase with ease. The recipes cover a wide range of processes for managing a fully distributed, highly available HBase cluster on the cloud. Working with such a huge amount of data means that an organized and manageable process is key and this book will help you to achieve that.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781617290527?iid=2013-04-blog-hbase-book-9781617290527-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201304-7199-techbus/images/9781617290527/9781617290527_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781617290527?iid=2013-04-blog-hbase-book-9781617290527-SBOBlog" target="_blank">HBase in Action</a> has all of the knowledge you need to design, build, and run applications using HBase. First, it introduces you to the fundamentals of distributed systems and large scale data handling. Then, you&#8217;ll explore real-world applications and code samples with just enough theory to understand the practical techniques. You&#8217;ll see how to build applications with HBase and take advantage of the MapReduce processing framework. And along the way you&#8217;ll learn patterns and best practices.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://weblog.safaribooksonline.com/wp-content/uploads/2012/08/salman_haq.jpg"><img class="alignnone size-full wp-image-6134" title="salman_haq" src="http://weblog.safaribooksonline.com/wp-content/uploads/2012/08/salman_haq.jpg" alt="" width="110" height="139" /></a></td>
<td>Salman Ul Haq is a techpreneur, co-founder and CEO of <a href="http://www.tunacode.com">TunaCode, Inc.</a>, a startup that delivers GPU-accelerated computing solutions to time-critical application domains. He holds a degree is Computer Systems Engineering. His current focus is on delivering the right solution for cloud security. He can be reached at <a href="mailto:salman@tuncacode.com">salman@tunacode.com</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/">Migrating Data from MySQL into HBase</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/GeeZBvAfp2E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/21/migrating-data-from-mysql-into-hbase/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET Entity Framework: Using Database Migration to Seed a Database</title>
		<link>http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/#comments</comments>
		<pubDate>Mon, 20 May 2013 17:37:29 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[.NET Entity Framework]]></category>
		<category><![CDATA[Code First Migrations]]></category>
		<category><![CDATA[Database Migration]]></category>
		<category><![CDATA[seed]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9950</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>If you have been following along, you know that I&#8217;ve been writing a series of posts on the .NET Entity Framework, and this post is the last in the series. The Entity Framework (EF) is an object-relational database mapper that &#8230; <a href="http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/">.NET Entity Framework: Using Database Migration to Seed a Database</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p><img class="alignleft size-full wp-image-10030 thumb" title="data" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/data1.jpg" alt="" width="150" height="113" />If you have been following along, you know that I&#8217;ve been writing a series of posts on <a href="http://blog.safaribooksonline.com/2013/04/17/the-net-entity-framework-code-first/">the .NET Entity Framework</a>, and this post is the last in the series.</p>
<p>The Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As shown in the <a href="http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/">Using Database Migration</a> post, you can easily use EF to create your database from the classes that are defined in your project code. You can then use Code First Migrations to handle any database changes for the life cycle of your application.<br />
<span id="more-9950"></span><br />
During the course of developing your application (or during the testing phase), you often make changes either to the data collected or to the way data is processed. Sometimes you may have a bug in your code that has let corrupt or incorrect data get into your database. This can give you unpredictable results, and you can end up dropping and creating a database multiple times. When this happens, you are sometimes faced with the undesirable task of getting data back into the database to test your bug fixes. In the past this was a painstakingly slow process, since you had to add all of your test data back into the database.</p>
<p>Well, Entity Framework and Code First Migration has a solution for that. In the last blog post on <a href="http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/">Data Migration</a>, you saw that running the <code>Enable-Migrations -ContextTypeName SafariCodeFirst.SeminarContext</code> command created a Migrations folder and two C# source files:</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/SolutionExplorer1.jpg"><img class="alignnone size-full wp-image-10019" title="SolutionExplorer" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/SolutionExplorer1.jpg" alt="" width="273" height="247" /></a></p>
<p>As previously described, the Configuration.cs file contains the settings for Migrations to work its magic, which in this case is to seed the database. If you examine Configuration.cs, you will see that Migrations has already created a stub method called Seed as the code below shows. It even contains some commented out code that shows how to go about adding a seed data to the table.</p>
<pre>namespace SafariCodeFirst.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(SafariCodeFirst.SeminarContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet&lt;T&gt;.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p =&gt; p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }
}</pre>
<p>Let&#8217;s remove the commented out code (or leave it for future reference) and add the code to seed the database as shown here:</p>
<pre>        protected override void Seed(SafariCodeFirst.SeminarContext context)
        {

            context.Seminars.AddOrUpdate(
                p =&gt; p.Name,
              new Seminar
              {
                  Name = "Seed Seminar One",
                  Speaker = "Marshall Harrison"
              },

              new Seminar
              {
                  Name = "Seed Seminar Two",
                  Speaker = "Marshall Harrison"
              },
              new Seminar
              {
                  Name = "Seed Seminar Three",
                  Speaker = "Marshall Harrison"
              }
            );

        }</pre>
<p>You can see how the <code>Context.Seminars.AddOrUpdate</code> helper class is used to create three new seminars if they don’t exist. If the database rows exist, then they will be updated. One thing to note is that you need the line that reads <code>p =&gt; p.Name</code>, or you will add all three seminars each time you run <code>Update-Database</code>, since that is used to identify the records.</p>
<p>So now that the code is ready, let&#8217;s delete all of the rows in the table and then run <code>Update-Database</code>. Your database should look like the following figure after the command finishes running:</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DatabaseSeedRecords.jpg"><img class="alignnone size-full wp-image-10017" title="DatabaseSeedRecords" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DatabaseSeedRecords.jpg" alt="" width="508" height="216" /></a></p>
<p>Let’s make one small change to the code and prove that the Seed method will update the existing rows if they already exist. Change the Speaker for “Seed Seminar Three” to read “Jim Smith” and run the <code>Update-Database</code> command again, and then check the results. You will see that this time, instead of adding records, the data was simply updated.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DatabaseSeedRecords2.jpg"><img class="alignnone size-full wp-image-10018" title="DatabaseSeedRecords2" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DatabaseSeedRecords2.jpg" alt="" width="537" height="227" /></a></p>
<p>As shown here, you can use Entity Framework and Code First Migrations to seed your database and make your life as a developer a lot easier. Of course, there are other things that configuration.cs can be used for, but I hope I have piqued your interest in Entity Framework so you will start experimenting with it on your own.</p>
<h2>Safari Books Online has the content you need</h2>
<p>Check out these .NET Entity Framework books available from Safari Books Online:</p>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449317867?iid=2013-05-blog-netentity-book-9781449317867-socialmedia"><img src="http://my.safaribooksonline.com/static/201304-7174-techbus/images/9781449317867/9781449317867_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781449317867?iid=2013-05-blog-netentity-book-9781449317867-socialmedia">Programming Entity Framework: Code First</a> acts as an extension to <em>Programming Entity Framework 2nd Edition</em>. Code First is an additional means of building a model to be used with the Entity Framework and is creating a lot of excitement in the .NET development community. The book begins with an overview of what Code First is, why it was created, how it fits into the Entity Framework and when to use it over the alternatives.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781935182184?iid=2013-05-blog-netentity-book-9781935182184-socialmedia"><img src="http://techbus.safaribooksonline.com/static/201305-7225-techbus/images/9781935182184/9781935182184_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781935182184?iid=2013-05-blog-netentity-book-9781935182184-socialmedia">Entity Framework 4 in Action</a> is an introduction to the Entity Framework for developers working in .NET who possess a working knowledge of ADO.NET. Beginning with a review of the core ideas behind the Object Relational Management (ORM) model, it outlines how the Entity Framework offers a smooth transition from a traditional ADO.NET approach. Featuring numerous examples and in-depth case studies, the book explores the Entity Framework story in clear, easy-to-follow detail.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781849684460?iid=2013-05-blog-netentity-book-9781849684460-socialmedia"><img src="http://my.safaribooksonline.com/static/201304-7171-techbus/images/9781849684460/9781849684460_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781849684460?iid=2013-05-blog-netentity-book-9781849684460-socialmedia">Entity Framework 4.1: Expert&#8217;s Cookbook</a> holds many examples to help guide you through tough technical decisions and avoid technical landmines. The book will guide you from just using Entity Framework to enhancing the data access wizard. You will be guided through complex mapping scenarios, query definition, reusability, integration with other technologies, and architectural management. The approach is step-by-step and test driven so that it is focused as much as possible on solving problems and getting the most out of the time spent working through the book.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Marshall.jpg"><img class="alignnone size-medium wp-image-9434" title="Marshall" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Marshall-240x300.jpg" alt="" width="240" height="300" /></a></td>
<td>Marshall Harrison is the founder of GotSpeech.Net and GotUC.net as well as the owner and CEO of GotSpeech Consulting LLC. He holds a B.S. degree in Computer Science and was a Microsoft MVP from 2006 – 2011. He is currently focusing on Microsoft Lync as well as Windows 8 and Windows Phone 8 devleopment. He can be reached through his blog at <a href="http://GotspeechGuy.com">GotspeechGuy.com</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/">.NET Entity Framework: Using Database Migration to Seed a Database</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/Y2WcSgcsAvw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/20/entity-framework-using-database-migration-to-seed-our-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AngularJS Tips and Tricks Using ngResource</title>
		<link>http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/#comments</comments>
		<pubDate>Thu, 16 May 2013 16:40:42 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[AngularJS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[ngresource]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9865</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>AngularJS is a JavaScript framework that can help you write web applications quickly using less code. AngularJS is not a library, rather it is an entirely different way of thinking about writing web applications. As such, AngularJS has certain opinions &#8230; <a href="http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/">AngularJS Tips and Tricks Using ngResource</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>AngularJS is a JavaScript framework that can help you write web applications quickly using less code. AngularJS is not a library, rather it is an entirely different way of thinking about writing web applications. As such, AngularJS has certain opinions about how you should be using it. Whereas in the vanilla JavaScript world, you are given a blank canvas on which to paint, AngularJS provides structure, organization and patterns to work with.</p>
<p>In this post we are focusing on using the ngResource module in AngularJS, which is &#8220;a factory that creates a resource object and lets you interact with RESTful server-side data sources.&#8221; Read <a href="http://my.safaribooksonline.com/9781939902009/h2_78_xhtml?iid=2013-05-blog-angularjs-book-9781939902009-SBOBlog">Chapter 9: Practical Applications, Ajax</a> to see an example using ngResource with Ajax.<br />
<span id="more-9865"></span></p>
<h2>Why Can’t AngularJS Find the ngResource Module?</h2>
<p>I’ve seen this question asked again and again by people starting out with AngularJS. You often see this in the JavaScript console:</p>
<pre>Uncaught Error: No module: ngResource</pre>
<p>The answer is that you have not included the appropriate JavaScript file. ngResource is not part of the AngularJS core distribution (it used to be), and if you want to use it, you must go download angular-resource.js (or angular-resource.min.js) from the AngularJS repository.</p>
<h2>How Can I Make $resource Synchronous?</h2>
<p>If you do something like this in a controller:</p>
<pre>var User = $resource('/path/to/user/:id');
$scope.user = User.get({id: 1});
$scope.user.name = $scope.user.first_name + ' ' + $scope.user.last_name;</pre>
<p>You will find that $scope.user is, in fact, undefined, and you get a lovely JavaScript error. You may believe that you need to make ngResource synchronous so that your $scope.user will be populated when you need it. This is incorrect. What’s happening is: User.get() returns a promise, and when a promise lives in a Scope, it is automatically resolved, but it is undefined until then (more about <a href="http://docs.angularjs.org/api/ng.$q">promises</a>).</p>
<p>What you really want to do is execute code after the User.get() call is finished up. You can do it like this:</p>
<pre>var User = $resource('/path/to/user/:id');
$scope.user = User.get({id: 1}, function() {
  $scope.user.name = $scope.user.first_name + ' ' + $scope.user.last_name;
});</pre>
<p>You will still get $scope.user eventually, when the request completes. After it is complete, you will be able to concatenate names.</p>
<h2>PUTting to URLs</h2>
<p>If you need to PUT, you need to PUT. ngResource does not support PUT out of the box, but it is extremely easy to implement:</p>
<pre>var res = $resource('/your/url/:id', {foo: 'bar'}, {'put': {method: 
  'PUT', params: {foo: 'baz'}, isArray: false}});</pre>
<p>The first parameter is the URL, of course. The second parameter is for default request parameters. For example, if you want to hit /your/url?foo=bar, use the above. The third parameter is where the good stuff happens. This creates a custom method called “put” that executes a PUT request against your URL. In addition, we can supply different default parameters for this particular method. To use our put, do this:</p>
<pre>res.put({id: 1234}, {extra: 'post data goes here'}, 
  function success() {}, function error() {});</pre>
<p>This was an example of creating a custom Resource (“class”) method. We could have called our method whatever we wanted to, and supplied default parameters for a shortcut to some commonly used resource. You’ll see another example below.</p>
<h2>Basic Authentication</h2>
<p>ngResource’s $resource service uses the built-in $http service for its requests. It’s simply an abstraction layer on top of that to make it easy to work with RESTful URLs. $resource itself isn’t very configurable, but $http is. One way to tackle the problem is to implement a solution akin to that found here. Once we’ve included the handy Base64 service, we can go about making that request this way:</p>
<pre>function MyCtrl($scope, $resource, Base64, $http) {

  // Use this method for Angular 1.0.x.
  // Logs into a page protected by basic authentication.  Grabs
  // username and password from $scope, which would likely be bound to
  // "text" and "password" &lt;input&gt; tags, respectively.
  $scope.login = function login() {
    // modify the Authorization header to send the username &amp; password
    $http.defaults.headers.common.Authorization = 'Basic ' + 
      Base64.encode($scope.username + ':' + $scope.password);
    // get the Resource object.
    $scope.res = $resource('/your/secured/url/here');
    // need to actually execute the request; do whatever with this
    $scope.res.get();
    // restore old defaults
    $http.defaults.headers.common.Authorization = 'Basic ';
  };

  // use this method if using Angular 1.1.1+
  $scope.unstableLogin = function login() {
    // get the Resource object w/ custom "get" method
    $scope.res = $resource('/your/secured/url/here', {}, 
       {get: {method: 'GET', headers: {Authorization: 'Basic ' + 
       Base64.encode($scope.username + ':' + $scope.password)}}});
    // need to actually execute the request; do whatever with this
    $scope.res.get();
  };
}</pre>
<p>The problem with this approach is that browser behavior differs. In Firefox, if you put in incorrect credentials, you get a 401 response and that’s that. If you are in Chrome, however, the user will be prompted (with the default basic auth prompt) for the login and password repeatedly until the user hits “Cancel”, at which point you will receive your 401. In fact, the request is still in a “Pending” state while this occurs. Not only is this annoying and awful, AngularJS doesn’t have access to whatever the user entered.</p>
<p>A workaround, if appropriate, is to tell your web server to return something other than 401 on an authentication failure, and go from there. In AngularJS, a 500 (for example) will cause the $http promise to be rejected and you can handle it however you’d like. This is not recommended if you actually ever need the login prompt to occur!</p>
<p>Hopefully this has been helpful for someone looking to solve ngResource-related problems.</p>
<p>For more details about AngularJS, see the ebooks referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781939902009?iid=2013-05-blog-angularjs-book-9781939902009-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7220-techbus/images/9781939902009/9781939902009_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="Developing an AngularJS Edge" href="http://my.safaribooksonline.com/9781939902009?iid=2013-05-blog-angularjs-book-9781939902009-SBOBlog" target="_blank">Developing an AngularJS Edge</a> is intended for intermediate JavaScript programmers. No attempt has been made to explain the JavaScript syntax used (except in the cases where AngularJS may introduce a peculiarity), nor do we explain concepts such as closures, function chaining, callbacks, or other common patterns. What we do explain are basic AngularJS concepts, components, and their applications. We provide examples along the way, answer questions, and correct common misconceptions. Together, we’ll build a working single-page weblog application using AngularJS, which will help you become proficient with using AngularJS to go out and create your own applications.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449355852?iid=2013-05-blog-angularjs-book-9781449355852-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7216-techbus/images/9781449355852/9781449355852_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>Develop smaller, lighter web apps that are simple to create and easy to test, extend, and maintain as they grow. <a title="AngularJS" href="http://my.safaribooksonline.com/9781449355852?iid=2013-05-blog-angularjs-book-9781449355852-SBOBlog" target="_blank">AngularJS</a> is a hands-on guide that introduces you to AngularJS, the open source JavaScript framework that uses Model–view–controller (MVC) architecture, data binding, client-side templates, and dependency injection to create a much-needed structure for building web applications.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781782166764?iid=2013-05-blog-angularjs-book-9781782166764-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7220-techbus/images/9781782166764/9781782166764_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="Instant AngularJS Starter" href="http://my.safaribooksonline.com/9781782166764?iid=2013-05-blog-angularjs-book-9781782166764-SBOBlog" target="_blank">Instant AngularJS Starter</a> is designed to get you ramped up on AngularJS as quickly and efficiently as possible. By the end of this book, you’ll possess all of the knowledge you need to make full-featured, real-life applications with AngularJS. The code samples are reusable, and specifically intended to give you a head start on your next project. This book will transform your curiosity about AngularJS into a set of production-ready AngularJS skills, through a broad overview of the framework and deep dives into its key features.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/chris.final_.photo_.png"><img class="alignnone size-full wp-image-9908" title="chris.final.photo" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/chris.final_.photo_.png" alt="" width="150" height="163" /></a></td>
<td>Christopher Hiller is a full-stack software engineer living and working in Portland, OR. He has over 15 years of web development experience and is a JavaScript zealot. When not coding epic masterpieces, he enjoys being a new dad, gaming, craft beers and woodworking. Chris can be contacted via GitHub, at: <a href="http://github.com/boneskull">http://github.com/boneskull</a>. You can also reach him on Twitter: <a href="http://www.twitter.com/misterhiller">@misterhiller</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/">AngularJS Tips and Tricks Using ngResource</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/LCllDRFIPEI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/16/angularjs-ngresource-tips-and-tricks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Monoids for Programmers: A Scala Example</title>
		<link>http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/#comments</comments>
		<pubDate>Wed, 15 May 2013 17:01:57 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[binary operation]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9956</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>The term monoid frustrates a lot of programmers who otherwise are pretty versatile with higher-order generics, mutexes and even XSLT. This blog post will show how using monoids can be very simple and practical. Monoids are the basis of more &#8230; <a href="http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/">Monoids for Programmers: A Scala Example</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>The term <em>monoid</em> frustrates a lot of programmers who otherwise are pretty versatile with higher-order generics, mutexes and even XSLT. This blog post will show how using monoids can be very simple and practical. Monoids are the basis of more complicated algebraic structures in mathematics, and are the underlying entities in many operations that we do while coding. There is a code sample in this post for Scala, which is becoming a lingua franca these days, and subsequent posts will focus on Scala.<br />
<span id="more-9956"></span></p>
<p>When you deal with various types in a programming language you will notice common patterns of behavior for binary operations. Here are some examples:</p>
<ol>
<li>Integers with addition. We know that <code>(a+b)+c == a+(b+c)</code> and <code>0+n == n+0 == n</code>; same with multiplication: <code>(a*b)*c == a*(b*c)</code> and <code>1*n == n*1 == n</code></li>
<li>Strings with concatenation. <code>a+(b+c)==(a+b)+c; ""+s==s</code> and <code>s+"" == s</code>, etc.</li>
<li>Lists with concatenation, like <code>List(1,2)+List(3,4) == List(1,2,3,4)</code>.</li>
<li>Sets with their union, like <code>Set(1,2,3)+Set(2,4) == Set(1,2,3,4)</code>.</li>
</ol>
<p>See a common pattern with a data type, a binary operation, and a special instance of the type, and certain rules? This common pattern is called monoid. Read <a href="http://my.safaribooksonline.com/9781457100406/monoids?iid=2013-05-blog-scala-book-9781457100406-socialmedia">Chapter 12: Monoids</a> for more details about monoids.</p>
<h2>Formally</h2>
<p>Now, I’ll give a strict formal definition of monoid. Given a type <code>T</code>, a binary operation <code>Op:(T,T) =&gt; T</code>, and an instance <code>Zero: T</code>, with the properties that will be specified below, the triple <code>(T, Op, Zero)</code> is called a monoid. Here are the properties:</p>
<ol>
<li>Neutral element: <code>Zero `Op` a == a `Op` Zero == a</code></li>
<li>Associativity: <code>(a `Op` b) `Op` c == a `Op` (b `Op` c)</code></li>
</ol>
<p>Now, not every binary operation in the world is associative. For example, this average: <code>avg(10, avg(30, 50)) != avg(avg(10, 30), 50)</code>; and for tuples, <code>(a,(b,c)) != ((a,b),c)</code>.</p>
<p>So, you may be wondering what’s good about associativity? With an associative operation, you can reorganize a calculation in any order. Say, for instance, that we have the following expression:</p>
<pre>(a1 `Op` (a2 `Op` (a3 `Op` (a4...))))</pre>
<p>In Scala we have, <code>(Zero /: a) (x `Op` y)</code>. This calculation can be regrouped and run in parallel, enabling map/reduce as follows:</p>
<pre>(a0 `Op` a1 … `Op` a99) -------&gt; p0 ---\
(a100 `Op` a101 … `Op` a199) ----&gt; p1 ----&gt;  p0 `Op` … `Op` p9	
. . .                                                                      /   
(a900 `Op` a901 … `Op` a999) ----&gt; p9 --/</pre>
<p>The definition above is all that you need to check whether you have a monoid. But it is important to see relationships between monoids. If you have just types, without any additional structure, any function, such as <code>f:A=&gt;B</code>, is good for mapping instances of one type to instances of another. But if we have monoids, mappings between monoids should preserve operations.</p>
<h2>Mappings Between Monoids</h2>
<p>For two monoids, <code>(A, OpA, ZeroA)</code> and <code>(B, OpB, ZeroB)</code>, we define a mapping from one monoid to another, such as with a function <code>f: A =&gt; B</code>, that <code>f(ZeroA) = ZeroB</code> and <code>f(x OpA y) = f(x) OpB f(y)</code>.</p>
<p>Here are some good examples of monoid mappings:</p>
<ul>
<ul>
<li><code>exp: (Double,+,0) =&gt; (Double,*,1); exp(a+b) == exp(a)*exp(b)</code></li>
<li>length: <code>(String,+,””) =&gt; (Int,+,0)</code></li>
<li>sum: <code>(List[Int],++,Nil) =&gt; (Int,+,0)</code></li>
</ul>
</ul>
<h2>Free Monoids</h2>
<p>For any type <code>T</code> we can build a monoid on it. Such a monoid will have an interesting universal property, as discussed next.</p>
<p>Suppose we have a type <code>A</code>, a monoid <code>(B, OpB, ZeroB)</code>, and a function <code>f:A=&gt;B</code>. This function just maps instances of <code>A</code> to instances of <code>B</code>. Now we can extend this function to a monoid mapping from <code>List[A]</code> to <code>(B, OpB, ZeroB)</code>.</p>
<p>Obviously, if we have <code>f:A=&gt;B</code>, we can apply <code>f</code> to elements of any list of elements of type <code>A</code>, and then fold as follows:</p>
<pre>  
f'(Nil) = ZeroB and f'(list1 + list2) = f'(list1) OpB f'(list2)</pre>
<p>This monoid mapping is uniquely determined by <code>f</code>, and it defines <code>f</code> if applied to singletons.</p>
<p><code>List[A]</code> is a free monoid because it’s built out of <code>A</code> with no constraints, in a universal way.</p>
<p>Let&#8217;s look at a simple example. Suppose we have the following:</p>
<pre>						
object WeekDay extends Enumeration {
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}</pre>
<p>And the following function:</p>
<pre>						
WeekDay=&gt;Int = (Mon-&gt;1, Tue-&gt;1, Wed-&gt;1, Thu-&gt;1, Fri-&gt;1,
Sat-&gt;0, Sun-&gt;0)</pre>
<p>Having a monoid <code>(Int, +, 0)</code>, we can automatically extend this mapping to <code>List[WeekDay]-&gt;Int</code>, which counts the number of working days.</p>
<h2>More Properties?</h2>
<p>Not all monoids are created equal. We can find classes of monoids that have additional properties, reflecting the nature of their operations. In this section we will discuss some of those properties.</p>
<h3>Commutative Monoids</h3>
<p>To start with, here is the commutativity law: for all <code>a</code> and <code>b</code>, <code>a `Op` b == b `Op` a</code>.</p>
<p>Some monoids are commutative, and some are not:</p>
<pre>					
2+3==3+2</pre>
<p>But that isn&#8217;t true with strings:</p>
<pre>"hello" + "world" != "world" + "hello"</pre>
<p>You might wonder if we can build a free commutative monoid? Say we have a list of characters: &#8220;<code>abracadabra</code>&#8220;. Forget about the concatenation order; we can just count the number of each entry &#8211; or sort the list, obtaining &#8220;<code>aaaaabbcdrr</code>&#8220;. Only the number of occurrences of each element matters &#8211; meaning, we have what is known as a Multiset or a Bag:</p>
<pre>{
  "partridges in a pear tree": 1,
  "turtle doves": 2,
  "french hens": 3,
  "calling birds": 4
}</pre>
<p>To count, say, all of the birds, we don’t need to know on which day they were appended to the multiset.</p>
<h3>How About Sets?</h3>
<p>Sets have an interesting property: a set <code>A</code> joined with itself is still <code>set A</code>. Instances with properties like this are called idempotent:</p>
<pre>x `Op` x == x</pre>
<p>If we take Bags and add the property for each instance that is idempotent, we have Sets.<br />
Here’s the hierarchy, from <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.49.3252">Alexander Bunkenburg, &#8220;The Boom Hierarchy&#8221;</a>.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/vlad.screen.jpg"><img class="alignnone size-full wp-image-9967" title="vlad.screen" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/vlad.screen.jpg" alt="" width="500" height="383" /></a></p>
<h2>In Scala</h2>
<p>To define a monoid in Scala, we declare the following:</p>
<pre>trait Monoid[T] {
 def Zero: T
 def op: (T,T) =&gt; T
}</pre>
<p>Then, if we define a new class, it can also extend <code>Monoid[T]</code>. This is impossible if the class already exists, like, <code>Int</code> or <code>String</code>. We may need to specify which operation we mean to be the monoidal operation. This is where type class should be used. In Haskell, a type class is defined as just an interface. In Scala; however, it is more complicated. It can depend upon the scope, and involves a so-called witness object. All this will be explained in more detail in my next blog post, so stay tuned.</p>
<h2>Safari Books Online has the content you need</h2>
<p>Check out these monoid and Scala books available from Safari Books Online:</p>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781457100406/?iid=2013-05-blog-scala-book-9781457100406/-socialmedia"><img src="http://techbus.safaribooksonline.com/static/201305-7224-techbus/images/9781457100406/9781457100406_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781457100406/?iid=2013-05-blog-scala-book-9781457100406/-socialmedia">Learn You a Haskell for Great Good!</a> begins with an overview of Node.js and then quickly dives into the code, core concepts, and APIs. In-depth coverage pares down the essentials to cover debugging, unit testing, and flow control so that you can start building and testing your own modules right away.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9780596155339?iid=2013-05-blog-scala-book-9780596155339-socialmedia"><img src="http://techbus.safaribooksonline.com/static/201305-7225-techbus/images/9780596155339/9780596155339_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9780596155339?iid=2013-05-blog-scala-book-9780596155339-socialmedia">Real World Haskell</a> takes you through the basics of functional programming at a brisk pace, and then helps you increase your understanding of Haskell in real-world issues like I/O, performance, dealing with data, concurrency, and more. Be sure to look at The Data Structures chapter to learn more about monoids.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781935182702?iid=2013-05-blog-scala-book-9781935182702-socialmedia"><img src="http://techbus.safaribooksonline.com/static/201305-7225-techbus/images/9781935182702/9781935182702_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781935182702?iid=2013-05-blog-scala-book-9781935182702-socialmedia">Scala in Depth</a> is a unique new book designed to help you integrate Scala effectively into your development process. By presenting the emerging best practices and designs from the Scala community, it guides you though dozens of powerful techniques example by example.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/vlad.headshot.jpg"><img class="alignnone size-full wp-image-9965" title="vlad.headshot" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/vlad.headshot.jpg" alt="" width="100" height="100" /></a></td>
<td>Vlad Patryshev was born in Russia, and has an education in Math (including now popular category theory). Since 1998 in the US, he worked at Borland (JBuilder team), then at Google in various teams, and had a 20% project, an onscreen keyboard, now available on various Google pages. He then changed several Bay Area startups, and now is working at <a href="http://www.healthexpense.com">HealthExpense.com</a>. A functional programmer and a Scala fan since 2008, he is now an organizer of Scala BASE and Bay Area Categories and Types meetups. As a hobby, he rides his road bike, builds decks, and drives around the US (Key West to the Polar Circle in Alaska). He can be reached at <a href="https://twitter.com/vpatryshev">@vpatryshev</a>.</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p><a href="http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/">Monoids for Programmers: A Scala Example</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/pqUmeSFXm_c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/15/monoids-for-programmers-a-scala-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.NET Entity Framework: Using Database Migration</title>
		<link>http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/#comments</comments>
		<pubDate>Tue, 14 May 2013 17:46:29 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[.NET Entity Framework]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[migrations]]></category>
		<category><![CDATA[Package Manager Console]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9954</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As we saw in the first blog post on Entity Framework, you can use &#8230; <a href="http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/">.NET Entity Framework: Using Database Migration</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As we saw in the first blog post on <a href="http://blog.safaribooksonline.com/2013/04/17/the-net-entity-framework-code-first/">Entity Framework</a>, you can use EF to create your database from the classes you have defined in your project code. You can add or remove properties from your classes and have EF migrate the changes into your database as well.</p>
<p>As developers, you often face projects where the specifications change over time for many reasons. Sometimes the client isn’t sure exactly what they need or their needs change during the course of the project. The design and analysis may determine that you need to add fields to the database or even remove fields from the database for one reason or another. For example, you may have new requirements to keep track of a user’s email address. Or you may need to add and track a user’s cell phone. A field/column entitled fName may even need to be renamed to firstName, or maybe you need to split a name into separate fields. There are many reasons that database fields/columns may need to change on a given project.</p>
<p>For this blog post, we are going to revisit the Visual Studio project used in <a href="http://blog.safaribooksonline.com/2013/04/17/the-net-entity-framework-code-first/">The .NET Entity Framework Code First</a> post. If you haven’t created that project, follow along with this post, but we recommend viewing that sample code.<br />
<span id="more-9954"></span><br />
If you open the project from <em>The .NET Entity Framework Code First</em>, you will see the following classes:</p>
<pre>   public class Seminar
    {
        public int SeminarId { get; set; }
        public string Name { get; set; }
        public virtual List Topics { get; set; }

    }

    public class Topic
    {
        public int TopicId { get; set; }
        public string Title { get; set; }

        public int SeminarId { get; set; }
        public virtual Seminar Seminar { get; set; }
    }</pre>
<p>And our database looked like this:</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/ServerExplorer.jpg"><img class="alignnone size-full wp-image-9982" title="ServerExplorer" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/ServerExplorer.jpg" alt="" width="305" height="447" /></a></p>
<p>Now, for the sake of our discussion, let’s say that we already have run our application at least once so our database has already been created, and we have decided that we want to add the keynote speaker’s name to the database. We can do that by just adding it as a property in our SeminarID class and then getting a DBA to write the necessary SQL. If you were allowed, you could write the SQL to add the field/column to the database table. That would just modify the database, however, and that is not the best approach since you may need to change it later. The best approach is to automate tracking and manage the migrations as the project grows. To do that we will use Code First Migrations.</p>
<p>First, you need to enable Code First Migrations using the Package Manager Console. If it isn’t already open, select Tools-&gt;Library Package Manager-&gt;Package Manager Console. Now run the command shown below. Notice that we used the Namespace of our application and the name of our DbContext class to create a fully qualified context:</p>
<pre>Enable-Migrations -ContextTypeName SafariCodeFirst.SeminarContext</pre>
<p>Visual Studio will process the command and you should get a result that looks something like this:</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/PackageManager.jpg"><img class="alignnone size-full wp-image-9980" title="PackageManager" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/PackageManager.jpg" alt="" width="500" height="75" /></a></p>
<p>You will also get a new Migrations folder added to your project that contains two files.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/SolutionExplorer.jpg"><img class="alignnone size-full wp-image-9983" title="SolutionExplorer" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/SolutionExplorer.jpg" alt="" width="273" height="247" /></a></p>
<p>Configuration.cs contains the settings that Migrations uses to do its magic work. We won’t touch it for this blog post, but in a future post we will show you how to use it to provide seed data for your database. The other file is named <code>&lt;timestamp&gt;_IntialCreate.cs</code> and contains the code shown here:</p>
<pre>namespace SafariCodeFirst.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class InitialCreate : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Seminars",
                c =&gt; new
                    {
                        SeminarId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t =&gt; t.SeminarId);

            CreateTable(
                "dbo.Topics",
                c =&gt; new
                    {
                        TopicId = c.Int(nullable: false, identity: true),
                        Title = c.String(),
                        SeminarId = c.Int(nullable: false),
                    })
                .PrimaryKey(t =&gt; t.TopicId)
                .ForeignKey("dbo.Seminars", t =&gt; t.SeminarId, cascadeDelete: true)
                .Index(t =&gt; t.SeminarId);

        }

        public override void Down()
        {
            DropIndex("dbo.Topics", new[] { "SeminarId" });
            DropForeignKey("dbo.Topics", "SeminarId", "dbo.Seminars");
            DropTable("dbo.Topics");
            DropTable("dbo.Seminars");
        }
    }
}</pre>
<p>Closer examination shows that it contains the code to take you from an empty database to one that contains the tables for the Seminar and Topic classes defined in our code.</p>
<p>Now that we have enabled Migrations and the basics are all in place, let&#8217;s modify our Seminar class to add a key note speaker so that our Seminar class now looks like this:</p>
<pre>   public class Seminar
    {
        public int SeminarId { get; set; }
        public string Name { get; set; }
        public string Speaker { get; set; }
        public virtual List&lt;Topic&gt; Topics { get; set; }

    }</pre>
<p>Next, we need to run migrations again using the command <code>Add-Migration AddSpeaker</code>. You can give this any name you want, but it is good to make it descriptive of the changes. Add-Migration will check for changes between the model classes and the last migration that was run, createing a new migration. You will notice that it is called <code>&lt;timestamp&gt;_AddSpeaker.cs</code>, and it has been added to the Migrations folder in our project. The timestamp part of the name is what Migrations uses to keep changes in order to track which changes have been applied. Now we need to run Update-Database so that any pending changes get applied to the database. I like to use the –Verbose switch so that I can see what is going on.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/Update-Database.jpg"><img class="alignnone size-full wp-image-9984" title="Update-Database" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/Update-Database.jpg" alt="" width="500" height="108" /></a></p>
<p>Now if you refresh the database in Server Explorer you will see that your changes have taken place and the new field/column have been added to the Seminars table.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/RefreshedServerExplorer.jpg"><img class="alignnone size-full wp-image-9981" title="RefreshedServerExplorer" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/RefreshedServerExplorer.jpg" alt="" width="295" height="351" /></a></p>
<p>We can go on and on like this, adding and dropping properties from our model classes and running the Add-Migration and Update-Database commands, as our database changes over the life cycle of our application. We still need to manually add code to the application to collect the user’s input or display the data to the user, but as you have seen, all of the hard work in our project has been taken care of for us by the Entity Framework and Code First Migrations.</p>
<h2>Safari Books Online has the content you need</h2>
<p>Check out these .NET Entity Framework books available from Safari Books Online:</p>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449317867?iid=2013-05-blog-netentity-book-9781449317867-socialmedia"><img src="http://my.safaribooksonline.com/static/201304-7174-techbus/images/9781449317867/9781449317867_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781449317867?iid=2013-05-blog-netentity-book-9781449317867-socialmedia">Programming Entity Framework: Code First</a> acts as an extension to <em>Programming Entity Framework 2nd Edition</em>. Code First is an additional means of building a model to be used with the Entity Framework and is creating a lot of excitement in the .NET development community. The book begins with an overview of what Code First is, why it was created, how it fits into the Entity Framework and when to use it over the alternatives.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781935182184?iid=2013-05-blog-netentity-book-9781935182184-socialmedia"><img src="http://techbus.safaribooksonline.com/static/201305-7225-techbus/images/9781935182184/9781935182184_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781935182184?iid=2013-05-blog-netentity-book-9781935182184-socialmedia">Entity Framework 4 in Action</a> is an introduction to the Entity Framework for developers working in .NET who possess a working knowledge of ADO.NET. Beginning with a review of the core ideas behind the Object Relational Management (ORM) model, it outlines how the Entity Framework offers a smooth transition from a traditional ADO.NET approach. Featuring numerous examples and in-depth case studies, the book explores the Entity Framework story in clear, easy-to-follow detail.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781849684460?iid=2013-05-blog-netentity-book-9781849684460-socialmedia"><img src="http://my.safaribooksonline.com/static/201304-7171-techbus/images/9781849684460/9781849684460_s.jpg" alt="" /></a></td>
<td><a href="http://my.safaribooksonline.com/9781849684460?iid=2013-05-blog-netentity-book-9781849684460-socialmedia">Entity Framework 4.1: Expert&#8217;s Cookbook</a> holds many examples to help guide you through tough technical decisions and avoid technical landmines. The book will guide you from just using Entity Framework to enhancing the data access wizard. You will be guided through complex mapping scenarios, query definition, reusability, integration with other technologies, and architectural management. The approach is step-by-step and test driven so that it is focused as much as possible on solving problems and getting the most out of the time spent working through the book.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Marshall.jpg"><img class="alignnone size-medium wp-image-9434" title="Marshall" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Marshall-240x300.jpg" alt="" width="240" height="300" /></a></td>
<td>Marshall Harrison is the founder of GotSpeech.Net and GotUC.net as well as the owner and CEO of GotSpeech Consulting LLC. He holds a B.S. degree in Computer Science and was a Microsoft MVP from 2006 – 2011. He is currently focusing on Microsoft Lync as well as Windows 8 and Windows Phone 8 devleopment. He can be reached through his blog at <a href="http://GotspeechGuy.com">GotspeechGuy.com</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/">.NET Entity Framework: Using Database Migration</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/USrjbE9Y0HY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/14/entity-framework-using-database-migration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making Node.js Talk</title>
		<link>http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/#comments</comments>
		<pubDate>Fri, 10 May 2013 18:06:39 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[Event Emitter]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JSON Stream]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[Streams]]></category>
		<category><![CDATA[TCP]]></category>
		<category><![CDATA[telnet]]></category>
		<category><![CDATA[TLS]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9860</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>In our previous Using Streams in Node.js post, we introduced the concept of streams and what abstractions and tools Node.js has for consuming or producing them. Streams have many usages, ranging from abstracting file access, to streaming Hypertext Transfer Protocol &#8230; <a href="http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/">Making Node.js Talk</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p><img class="alignleft  wp-image-9919 thumb" title="js-code" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/js-code.png" alt="" width="180" height="119" />In our previous <a href="http://blog.safaribooksonline.com/2013/05/01/using-streams-in-node-js/">Using Streams in Node.js</a> post, we introduced the concept of streams and what abstractions and tools Node.js has for consuming or producing them.</p>
<p>Streams have many usages, ranging from abstracting file access, to streaming Hypertext Transfer Protocol (HTTP) requests and response bodies. In this post, we&#8217;re going to see how we can make two or more Node.js processes talk to each other, building a communication protocol on top of streams. Be sure to read Pedro&#8217;s <a href="http://techbus.safaribooksonline.com/9781118240564/chapter09_html?iid=2013-05-blog-nodejs-book-9781118240564-socialmedia">Chapter 9: Reading and Writing Streams of Data</a> in <em>Professional Node.js: Building Javascript Based Scalable Software</em> to learn more about Node.js streams.<br />
<span id="more-9860"></span><br />
Using some of these methods, you can build a mesh of Node.js processes that are loosely coupled, talking to each other as they need remote services.</p>
<h2>TCP Server</h2>
<p>A simple way of having two Node.js processes communicate with each other is by using Transmission Control Protocol (TCP). TCP is a protocol designed to transport data from one network device to another in a reliable and ordered way. It allows two nodes to establish a communication channel and pass a stream of ordered bytes between them. Node.js offers a streaming interface for both connected peers.</p>
<p>To be able to accept TCP connections, you need to create a TCP Server using the net module:</p>
<pre>var net = require('net');

var server = net.createServer();</pre>
<p>Then we can make this server listen on a certain TCP port:</p>
<pre>var port = 3000;

server.listen(port);

server.once('listening', function() {
  console.log('Server listening on port %d', port);
});</pre>
<p>Once the server is listening, it accepts connections on that port and emits a connection event:</p>
<pre>server.on('connection', function(stream) {
  stream.pipe(stream);
});</pre>
<p>Every time a peer connects to our server we get a connection event. In the event listener function call, we get the server socket object, which represents the two-way connection to the other connected peer. This object is a duplex stream that is writable and readable. When you write to it, it sends that data to the remote peer, and when you read to it, you read the data that the remote peer has sent you.</p>
<p>Here we&#8217;re simply piping the stream back to itself. All of the bytes that the server gets on this connection are sent back to the peer, effectively making an echo server.</p>
<p>Here is the source code of the entire server:</p>
<pre>var net = require('net');

var server = net.createServer();

var port = 3000;

server.listen(port);

server.once('listening', function() {
  console.log('Server listening on port %d', port);
});

server.on('connection', function(stream) {
  stream.pipe(stream);
});</pre>
<p>You can save this file with the name 01_tcp_server.js and launch it using the command line (you can access all of the source code found in this article <a href="https://github.com/pgte/making-node-talk-article-src">here</a>):</p>
<pre>$ node 01_tcp_server.js
Server listening on port 3000</pre>
<p>You can then test this server using a command-line TCP client like telnet or nc:</p>
<pre>$ nc localhost 3000
hey
hey
what's up?
what's up?</pre>
<h2>TCP Client</h2>
<p>Now we can create a TCP client that connects to our TCP server (02_tcp_client.js):</p>
<pre>var net = require('net');

var port = 3000;
var host = 'localhost';

var stream = net.connect(port, host);
stream.setEncoding('utf8');

var interval = setInterval(function() {
  var date = (new Date).toString();
  stream.write('It\'s ' + date);
}, 1000);

setTimeout(function() {
  clearInterval(interval);
  stream.end();
}, 5100);

stream.on('readable', function() {
  var chunk;
  while(chunk = stream.read()) {
    console.log('got from server: %j', chunk);
  }
});</pre>
<p>Here we&#8217;re using the net.connect function to create a TCP connection to our server. Then we&#8217;re setting the connection encoding to UTF-8 so that we can read back strings instead of raw byte buffers. Next, we create an interval, writing the current date to the stream for every second that passes. Shortly after 5 seconds have elapsed, we stop the recurring interval and end the stream, effectively ending the connection.</p>
<p>In the last chunk of code we set up a readable event listener for when we receive data that was sent back from the server, thus printing it out.</p>
<p>You can test all of this by launching this client script while having the server running:</p>
<pre>$ node 02_tcp_client.js
got from server: "It's Mon May 06 2013 12:35:34 GMT+0100 (WEST)"
got from server: "It's Mon May 06 2013 12:35:35 GMT+0100 (WEST)"
got from server: "It's Mon May 06 2013 12:35:36 GMT+0100 (WEST)"
got from server: "It's Mon May 06 2013 12:35:37 GMT+0100 (WEST)"
$</pre>
<h2>Reconnect</h2>
<p>If we want to establish a long-lasting connection, we may need to reconnect to the server if the network link goes down. For that, we can use the reconnect module. Let&#8217;s then create a package.json manifest where we state that dependency:</p>
<pre>{
  "name": "my-connected-node-processes",
  "version": "0.0.1",
  "dependencies": {
    "reconnect": "*"
  }
}</pre>
<p>Let&#8217;s then download and install this missing dependency:</p>
<pre>$ npm install</pre>
<p>Here is our reconnecting client (03_reconnecting_tcp_client.js):</p>
<pre>var reconnect = require('reconnect');

var port = 3000;
var host = 'localhost';

var reconnector =
reconnect(function(stream) {
  stream.setEncoding('utf8');

  var interval = setInterval(function() {
    var date = (new Date).toString();
    stream.write('It\'s ' + date);
  }, 1000);

  stream.on('readable', function() {
    var chunk;
    while(chunk = stream.read()) {
      console.log('got from server: %j', chunk);
    }
  });

  stream.once('end', function() {
    clearInterval(interval);
  });

}).connect(port, host);

setTimeout(function() {
  reconnector.reconnect = false;
  reconnector.disconnect();
}, 10000);</pre>
<p>To test the reconnecting effect of the client, you can start off by having the server down, and then launching the client. You will have to launch it before the client terminates, though, which is 10 seconds after.</p>
<h2>Event Emitter</h2>
<p>We&#8217;ve seen how we can connect two processes together, but all we&#8217;ve sent were unstructured string messages. TCP is a byte streaming protocol and does not mark message boundaries. For that, we can use JSON Stream, which JSON-encodes JavaScript objects to be sent down the wire and decodes them once they reach the other side.</p>
<p>So JSON Stream provides an object stream, allowing us to read and write JavaScript objects instead of bytes or strings. On top of the JSON Stream protocol, we&#8217;ll add the emit stream module, which transforms an object stream into an event emitter and vice-versa. Actually, and to save us some work, we&#8217;re going to use the duplex-emitter module, which makes all the stream connecting for us. Let&#8217;s then add duplex-emitter to the package.json manifest:</p>
<pre>{
  "name": "my-connected-node-processes",
  "version": "0.0.1",
  "dependencies": {
    "reconnect": "*",
    "duplex-emitter": "*"
  }
}</pre>
<p>Now, download and install it:</p>
<pre>$ npm install</pre>
<p>Let&#8217;s then change the server to use duplex emitter to transform the peer stream into an event emitter and then send an arbitrary ping event every second (04_server_events.js):</p>
<pre>var net = require('net');
var server = net.createServer();
var port = 3000;
server.listen(port);
server.once('listening', function() {
  console.log('Server listening on port %d', port);
});

var duplexEmitter = require('duplex-emitter');

server.on('connection', function(stream) {
  var peer = duplexEmitter(stream);

  var interval =
  setInterval(function() {
    peer.emit('ping', Date.now());
  }, 1000);

  peer.on('pong', function(myTimestamp, hisTimestamp) {
    console.log('got pong from peer with args %d and %d', myTimestamp, hisTimestamp);
  });
});</pre>
<p>Here the server also listens for remote pong events and prints the two arguments that they come with.</p>
<p>Now let&#8217;s create a client that also does a similar thing and reacts to remote ping events, sending back a pong event (05_client_events.js):</p>
<pre>var reconnect = require('reconnect');
var duplexEmitter = require('duplex-emitter');

var port = 3000;
var host = 'localhost';

var reconnector =
reconnect(function(stream) {
  var peer = duplexEmitter(stream);

  peer.on('ping', function(timestamp) {
    console.log('got ping from peer %d', timestamp);
    peer.emit('pong', timestamp, Date.now());
  });

}).connect(port, host);</pre>
<p>You can then launch the server:</p>
<pre>$ node 04_server_events.js</pre>
<p>And, on a separate command-line window, launch the client:</p>
<pre>$ node 05_client_events.js</pre>
<p>You should see the server printing lines like:</p>
<pre>got pong from peer with args 1367841664066 and 1367841664074
got pong from peer with args 1367841665067 and 1367841665069
got pong from peer with args 1367841666069 and 1367841666070
got pong from peer with args 1367841667070 and 1367841667071
got pong from peer with args 1367841668070 and 1367841668071</pre>
<p>And the client printing lines like:</p>
<pre>got ping from peer 1367841664066
got ping from peer 1367841665067
got ping from peer 1367841666069
got ping from peer 1367841667070</pre>
<h2>Summary</h2>
<p>Using TCP you can establish a raw stream between two Node.js processes. On top of this stream you can use the JSONStream and the emit-stream modules to turn that stream into an event emitter. By emitting events into that stream, you are transmitting that event to the remote peer. You can also listen for the remove events using the common event emitter API.</p>
<p>Using these techniques, we created a distributed Node.js-based application, making it less coupled and more flexible, scalable and reliable to changes.</p>
<h2>Safari Books Online has the content you need</h2>
<p>Check out these Node.js books available from Safari Books Online:</p>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781118240564?iid=2013-05-blog-nodejs-book-9781118240564-socialmedia"><img src="http://my.safaribooksonline.com/static/201301-7048-my/images/9781118240564/9781118240564_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>Node.js is a powerful and popular new framework for writing scalable network programs using JavaScript. <a href="http://my.safaribooksonline.com/9781118240564?iid=2013-05-blog-nodejs-book-9781118240564-socialmedia">Professional Node.js</a> begins with an overview of Node.js and then quickly dives into the code, core concepts, and APIs. In-depth coverage pares down the essentials to cover debugging, unit testing, and flow control so that you can start building and testing your own modules right away.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9780132966276?iid=2013-05-blog-nodejs-book-9780132966276-socialmedia"><img src="http://my.safaribooksonline.com/static/201301-7048-my/images/9780132966276/9780132966276_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>In just 24 sessions of one hour or less, <a href="http://my.safaribooksonline.com/9780132966276?iid=2013-05-blog-nodejs-book-9780132966276-socialmedia">Sams Teach Yourself Node.js in 24 Hours</a> will help you master the Node.js platform and use it to build server-side applications with extraordinary speed and scalability. Using this text’s straightforward, step-by-step approach, you’ll move from basic installation, configuration, and programming all the way through real-time messaging between browser and server, testing and deployment. Every lesson and case-study application builds on what you’ve already learned, giving you a rock-solid foundation for real-world success!</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781849517188?iid=2013-05-blog-nodejs-book-9781849517188-socialmedia"><img src="http://my.safaribooksonline.com/static/201301-7048-my/images/9781849517188/9781849517188_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>This book shows you how to transfer your JavaScript skills to server side programming. With simple examples and supporting code, <a href="hhttp://my.safaribooksonline.com/9781849517188?iid=2013-05-blog-nodejs-book-9781849517188-socialmedia">Node Cookbook</a> talks you through various server side scenarios often saving you time, effort, and trouble by demonstrating best practices and showing you how to avoid security faux pas.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/book/programming/javascript/9781849515146?iid=2013-05-blog-nodejs-book-9781849515146-socialmedia"><img src="http://my.safaribooksonline.com/static/201301-7048-my/images/9781849515146/9781849515146_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a href="http://my.safaribooksonline.com/book/programming/javascript/9781849515146?iid=2013-05-blog-nodejs-book-9781849515146-socialmedia">Node Web Development</a> gives you an excellent starting point straight into the heart of developing server side web applications with node. You will learn, through practical examples, how to use the HTTP Server and Client objects, the Connect and Express application frameworks, the algorithms for asynchronous execution, and use both SQL and MongoDB databases.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Pedro-Teixeira.jpg"><img class="alignnone size-full wp-image-9689" title="Pedro Teixeira" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/04/Pedro-Teixeira.jpg" alt="" width="240" height="264" /></a></td>
<td>Pedro Teixeira is a geek, programmer, freelancer, and entrepreneur. Author of some <a href="https://npmjs.org/~pgte">Node.js modules</a>, the <a href="http://nodetuts.com/">Node Tuts screencast show</a>, some books about Node.js and overall fervent proclaimer of the <a href="http://nodejs.org/">Node.js</a> creed. He is also the Co-founder and Partner of <a href="http://thenodefirm.com/">The Node Firm</a>, and the organizer of the <a href="http://lxjs.org/">Lisbon JavaScript Conference</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/">Making Node.js Talk</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/F_dqLstDBDs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/10/making-node-js-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debugging Backbone’s Events</title>
		<link>http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/#comments</comments>
		<pubDate>Thu, 09 May 2013 17:33:37 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[.on method]]></category>
		<category><![CDATA[Backbone collections]]></category>
		<category><![CDATA[Backbone.js]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[Github]]></category>
		<category><![CDATA[MV* framework]]></category>
		<category><![CDATA[Observer design pattern]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9863</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>Backbone.js is a client-side MV* framework that provides a simple, but powerful, events API. All Backbone objects (Models, Collections, Views &#38; Routers) trigger events and can listen to events. This architecture is an implementation of the Observer design pattern and &#8230; <a href="http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/">Debugging Backbone&#8217;s Events</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>Backbone.js is a client-side MV* framework that provides a simple, but powerful, events API. All Backbone objects (Models, Collections, Views &amp; Routers) trigger events and can listen to events. This architecture is an implementation of the <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer design pattern</a> and using events makes it easier to keep the various parts of your application loosely coupled.</p>
<p>In this post we&#8217;ll look at how to set a handler to listen to all of the events on a Backbone object, and why this is useful. Backbone has two main methods for setting up event handlers: .on and .listenTo. For the examples in this post, we&#8217;ll be using the .on method. This method works in similar ways to other event libraries, such as jQuery or NodeJS&#8217;s EventEmitter.<br />
<span id="more-9863"></span><br />
The .listenTo method was added to Backbone in version 0.9.9 and it is a useful tool to prevent memory leaks. It&#8217;s primarily used when a short-lived object needs to observe events in a long-lived object. An example would be if a view needs to listen to changes on a model. The view may be destroyed and created multiple times in the course of running the application, but the model is likely to only be instantiated once &#8211; when the application is initialized.</p>
<p>There is a whole <a href="http://backbonejs.org/#Events-catalog">catalog of events</a> that are triggered internally by Backbone. It is also possible to trigger and listen to custom events. A useful feature of Backbone Collections is that any event triggered on a model within that collection will also be triggered on the collection itself. For example:</p>
<pre>var collection, debug, javascript, python, ruby;

debug = function(name) {
  return function() {
    console.log(name + ":", arguments);
  };
};

ruby = new Backbone.Model({ id: 1, name: "Ruby", score:5 });
javascript = new Backbone.Model({ id: 2, name: "Javascript", score:5 });
python = new Backbone.Model({ id: 3, name: "Python", score:5 });

collection = new Backbone.Collection([ruby, javascript, python]);
collection.on("change", debug("collection - change"));

ruby.set("score", 10);
// Log: collection - change: [Backbone.Model, Object]</pre>
<p>In the above code, you can see that when we changed an attribute on the ruby model, the change event was triggered on the collection. This also works with custom events:</p>
<pre>collection.on("someCustomEvent", debug("Some Custom Event"));

python.trigger("someCustomEvent", "custom data");

// Log: Some Custom Event: ["custom data"]</pre>
<p>So any event that is triggered on a model, whether a built-in Backbone event or a custom event, will be triggered on the collection that the model belongs to. Let&#8217;s dive into <a href="http://backbonejs.org/docs/backbone.html#section-87">Backbone&#8217;s source</a> to see how this is implemented:</p>
<pre>set: function(models, options) {
  // Logic to add to or update models in a collection

  model.on('all', this._onModelEvent, this); 

}

_onModelEvent: function(event, model, collection, options) {
      if ((event === 'add' || event === 'remove') &amp;&amp; 
         collection !== this) return;
      if (event === 'destroy') this.remove(model, options);
      if (model &amp;&amp; event === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        if (model.id != null) this._byId[model.id] = model;
      }
      this.trigger.apply(this, arguments);
    }</pre>
<p>When a Model is added to a Backbone Collection, a handler is added to the special &#8220;all&#8221; event. For instance, the _onModelEvent handler needs to perform custom logic for some events:</p>
<ul>
<li>add and remove events are stopped from being re-triggered, since they are usually initiated by the collection.</li>
<li>destroy events on the model cause the model to be removed from the collection.</li>
<li>change events to the models idAttribute cause the collection to adjust its internal _byId lookup hash.</li>
<li>All events, except for add and remove, are re-triggered on the collection.</li>
</ul>
<p>The Backbone source is well commented and very readable. To see how the events system sets up listeners for the &#8220;all&#8221; event look at the <a href="http://backbonejs.org/docs/backbone.html#section-13">Backbone Events</a> section.</p>
<p>Now that you&#8217;ve seen how the &#8220;all&#8221; event is used internally by Backbone, let&#8217;s see how it can be used in your own application. While plugin authors may use .on(&#8220;all&#8221;,&#8230;&#8221;) to implement advanced functionality, most of the time I use this feature for debugging. In a complex Backbone application, multiple events are fired by models and collections, and it can help to log them all to the console. To illustrate how this can be useful, let&#8217;s add some all listeners to <a href="http://backstopmedia.github.io/hubbub/">Hubbub</a>, an example Backbone application, to manage some Github issues. Navigate to the application, open up the console, and enter the following code:</p>
<pre>var debug;
debug = function(name) {
  return function() {
    console.log(name + ":", arguments);
  };
};

app.board.issues.on("all", debug("board.issues"));
app.board.repos.on("all", debug("board.repos"));
app.board.on("all", debug("board"));</pre>
<p>Now try adding a repo to your board and moving issues around. You will see a steady stream of events being logged to the console. The order of these events can be really useful in debugging an application. For example, if you see unexpected change events on your models after sync events, then you may need to check that the responses from your server are as you expect.</p>
<p>We&#8217;ve only touched the surface of what can be done with Backbone Events. The &#8220;all&#8221; event is incredibly useful for debugging in Backbone, and it would be great if Node&#8217;s EventEmitter had the same feature.</p>
<p>For more details about Backbone.js, see the ebooks referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781939902016?iid=2013-04-blog-backbone-book-9781939902016-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7214-techbus/images/9781939902016/9781939902016_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>While there are many frameworks that seem to be faster to get started with, Backbone&#8217;s lack of surprises, clear documentation, speed and flexibility make it a good fit for all types of applications. <a title="Developing a Backbone.js Edge" href="http://my.safaribooksonline.com/9781939902016?iid=2013-04-blog-backbone-book-9781939902016-SBOBlog" target="_blank">Developing a Backbone.js Edge</a> incorporates the best practices and techniques from the combined authors&#8217; experience of developing many Backbone applications. Some of the resources on the web advocate inefficient or inelegant solutions and there are few that cover the whole library. In this book we aim to provide a complete guide to Backbone and equip you to start using the library straight away.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449328535?iid=2013-04-blog-backbone-book-9781449328535-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7214-techbus/images/9781449328535/9781449328535_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>If you’re looking to use the single-page application model to build your site’s frontend, Backbone.js is an ideal framework for the job. <a title="Developing Backbone.js Applications" href="http://my.safaribooksonline.com/9781449328535?iid=2013-04-blog-backbone-book-9781449328535-SBOBlog" target="_blank">Developing Backbone.js Applications</a> provides all of the information you need to create structured JavaScript applications using Backbone.js and its unique flavor of the model-view-controller (MVC) architecture.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781449337735?iid=2013-04-blog-backbone-book-9781449337735-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7218-techbus/images/9781449337735/9781449337735_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td>The enthusiasm behind Node doesn’t just reflect the promise of server-side JavaScript. Developers also have the potential to create elegant applications with this open source framework that are much easier to maintain. Follow author Mike Wilson as he builds a social network application oriented toward real-time updates. <a title="Building Node Applications with MongoDB and Backbone" href="http://my.safaribooksonline.com/9781449337735?iid=2013-04-blog-backbone-book-9781449337735-SBOBlog" target="_blank">Building Node Applications with MongoDB and Backbone</a> shows you how to build complete applications that combine the strengths of Node, the MongoDB scalable storage solution, and the Backbone toolkit for clean application design in the browser.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/dave_small.jpg"><img class="alignnone size-full wp-image-9873" title="dave_small" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/dave_small.jpg" alt="" width="150" height="162" /></a></td>
<td>Dave Tonge is a Backbone.js contributor and web developer at Simple Creativity. He is a co-author of <a title="Developing a Backbone.js Edge" href="http://my.safaribooksonline.com/9781939902016?iid=2013-04-blog-backbone-book-9781939902016-SBOBlog" target="_blank">Developing a Backbone.js Edge</a>, and can be reached at: <a href="http://www.github.com/davidgtonge">github.com/davidgtonge</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/">Debugging Backbone&#8217;s Events</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/safaribooksonline/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/n9iHbYQxnpU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/09/debugging-backbones-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Node.js and Windows Azure: Getting Started</title>
		<link>http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/</link>
		<comments>http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/#comments</comments>
		<pubDate>Wed, 08 May 2013 17:31:53 +0000</pubDate>
		<dc:creator>Safari Books Online</dc:creator>
				<category><![CDATA[Content - Highlights and Reviews]]></category>
		<category><![CDATA[Programming & Development]]></category>
		<category><![CDATA[Cloud Services]]></category>
		<category><![CDATA[Infrastructure Services]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[PaaS]]></category>
		<category><![CDATA[Windows Azure]]></category>

		<guid isPermaLink="false">http://blog.safaribooksonline.com/?p=9787</guid>
		<description><![CDATA[<p><p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p>If you’re looking for a cloud platform to build and deploy highly scalable Node.js applications and services, Windows Azure is a good fit. It supports a wide variety of programming tools, frameworks, and development tools, including Node.js. In this post, &#8230; <a href="http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/">Continue reading <span class="meta-nav">&#8594;</span></a></p></p><p><a href="http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/">Node.js and Windows Azure: Getting Started</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog</a>
<a href="http://blog.safaribooksonline.com">Safari Books Online&#039;s Official Blog - Your On-Demand Digital Learning Library</a></p><p><img class="alignleft size-full wp-image-9853 thumb" title="computer" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/computer1.png" alt="" width="180" height="176" />If you’re looking for a cloud platform to build and deploy highly scalable Node.js applications and services, Windows Azure is a good fit. It supports a wide variety of programming tools, frameworks, and development tools, including Node.js.</p>
<p>In this post, we’ll take a look at various options for building and deploying Node applications on Windows Azure. If you’re new to Windows Azure, you can sign up for a <a href="http://www.windowsazure.com/en-us/pricing/free-trial/?WT.mc_id=A7171371E">free trial</a> to get started. Windows Azure development is a vast topic, and here we’ll just focus on the basics of getting up and running with Node.js. To dive deeper, take a look at <a href="http://my.safaribooksonline.com/9781430235637/chapter_1_windows_azure_platfo?iid=2013-04-blog-azure-book-9781430235637-SBOBlog">Chapter 1: Windows Azure Platform Overview</a> in <em>Windows Azure Platform</em>.<br />
<span id="more-9787"></span></p>
<p>There are three ways to deploy Node applications and services on Windows Azure:</p>
<ul>
<li><a href="http://www.windowsazure.com/en-us/home/scenarios/web-sites/">Windows Azure web sites</a> – highly scalable sites that can be provisioned and deployed quickly. You can deploy your code via FTP, or configure your site for continuous integration with a GitHub repo, Dropbox folder, or TFS repository.</li>
<li><a href="http://www.windowsazure.com/en-us/home/scenarios/infrastructure-services/">Infrastructure services</a> – a scalable on-demand infrastructure that you can use to bring existing workloads to the cloud as-is, or spin up new Windows or Linux virtual machines in minutes.</li>
<li><a href="http://www.windowsazure.com/en-us/home/scenarios/cloud-services/">Cloud Services</a> – a rich PaaS environment with automated provisioning, load balancing, auto-scaling, and OS/security management, so that you can concentrate on writing code.</li>
</ul>
<p>As a rule of thumb, you’ll want to use Web Sites for simple projects. For more complex scenarios, you can use Infrastructure Services if you want maximum control of configuration details, or Cloud Services if you want to minimize your ongoing operational responsibilities. Regardless of which you choose, you have two options for deploying and managing your site:</p>
<ul>
<li>For those who prefer the GUI approach, there is a web interface (the Windows Azure <a href="https://manage.windowsazure.com/">management portal</a>) that provides options for provisioning, starting, stopping, or deleting your applications and services.</li>
<li>For those who prefer the command line, a set of PowerShell cmdlets is available for managing cloud deployments from Windows. In Mac or Linux environments you can use the cross-platform command line interface, which is written in Node.js and will run on any OS that supports Node. These tools, as well as Node.js SDKs for Windows, Mac, and Linux, are available for free download from the Windows Azure <a href="https://www.windowsazure.com/en-us/downloads/?fb=en-us">download center</a>.</li>
</ul>
<p>When you create a Windows Azure Web Site there are two options for Node developers. The Node JS Empty Sites is a pre-built website set up with Node.js, and the Node JS Starter Site also includes the popular Express MVC framework.</p>
<p>For spinning up a virtual machine to host your Node applications on Windows Azure Infrastructure Services, there are several options. One is to simply deploy a base OS and then build your preferred Node environment on top of it. This is the quick create option in the Windows Azure management portal, and current OS options include: Windows Server 2012, Windows Server 2008 R2, openSUSE 12.3, SUSE Linux Enterprise Server 11 SP2, OpenLogic CentOS 6.3, or Ubuntu Server versions 12.04 LTS, 12.10, or 13.04.</p>
<p>An even faster way to get a Node.js development environment up and running on Infrastructure Services is to take advantage of the pre-built virtual machine images available on <a href="http://vmdepot.msopentech.com/">VM Depot</a>, a community-driven catalog of preconfigured operating systems, applications, and development stacks that can easily be deployed on Windows Azure. Current options on VM Depot include <a href="http://vmdepot.msopentech.com/Vhd/Show?vhdId=319&amp;version=336">Node.js 10.5-0 on Ubuntu 12.10</a>.</p>
<p>Note that Windows Azure Web Sites and Cloud Services provide automated tools for deploying and managing your applications, but with virtual machines you’ll need to use SSH to manage your deployments. This is another factor to take into account when choosing among the Azure options for Node developers.</p>
<p>To get started with Windows Azure cloud services, see the <em>Build and deploy a Node.js application to a Windows Azure Cloud Service</em> <a href="http://www.windowsazure.com/en-us/develop/nodejs/tutorials/getting-started/">tutorial</a>. The New-AzureServiceProject cmdlet sets up the structure for deploying a Cloud Service, and the Add-AzureNodeWebRole cmdlet generates scaffolding for a basic Node.js application. After editing the generated server.js as desired, you can run your application locally in an emulator, which you launch with the Start-AzureEmulator cmdlet.</p>
<p><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/Node-VM-Depot.png"><img class="alignnone size-full wp-image-9791" title="Node VM Depot" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/Node-VM-Depot.png" alt="" width="500" height="375" /></a></p>
<p>The entire dev/test/deploy process is automated through the cmdlets, so that you can concentrate on building your application. Similar options are available for Mac and Linux users via the cross-platform command line interface. And regardless of how you create it, your Node.js-based Cloud Service has full access to Azure’s APIs for services such as compute, storage, caching, and messaging (Service Bus). For an overview of the Azure APIs you can use from a Node application, see the <a href="https://github.com/WindowsAzure/azure-sdk-for-node#library-features">GitHub repo</a> for the SDK.</p>
<p>That’s a high-level overview of the options for getting started with Node.js on Windows Azure. See below for books covering Windows Azure as well as Node.js. In future posts we’ll take a closer look at how to take full advantage of Azure services and how to monitor performance of your Node.js applications on Windows Azure.</p>
<p>You can find a wealth of information on Node.js and Windows Azure in the eBooks referenced below.</p>
<h2>Safari Books Online has the content you need</h2>
<table>
<tbody>
<tr>
<td><a href="http://my.safaribooksonline.com/9781119963103?iid=2013-04-blog-nodejs-book-9781119963103-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7212-techbus/images/9781119963103/9781119963103_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="Smashing Node.js: JavaScript Everywhere, 2nd Edition" href="http://my.safaribooksonline.com/9781119963103?iid=2013-04-blog-nodejs-book-9781119963103-SBOBlog" target="_blank">Smashing Node.js: JavaScript Everywhere, 2nd Edition</a> equips you with the necessary tools to understand Node.js and its uses in developing efficient web applications. With more traditional web servers becoming obsolete, having knowledge on servers that achieve high scalability and optimal resource consumption using Node.js is the key to your app development success. Teaching you the essentials to making event-driven server-side apps, this book demonstrates how you can use less space and take less time for communication between web client and server.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781118240564?iid=2013-04-blog-nodejs-book-9781118240564-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7212-techbus/images/9781118240564/9781118240564_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="Professional Node.js: Building Javascript Based Scalable Software" href="http://my.safaribooksonline.com/9781118240564?iid=2013-04-blog-nodejs-book-9781118240564-SBOBlog" target="_blank">Professional Node.js: Building Javascript Based Scalable Software</a> is a no nonsense book that begins with an overview of Node.js and then quickly dives into the code, core concepts, and APIs. In-depth coverage pares down the essentials to cover debugging, unit testing, and flow control so that you can start building and testing your own modules right away.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781430235637?iid=2013-04-blog-azure-book-9781430235637-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7216-techbus/images/9781430235637/9781430235637_s.gif" alt="" hspace="70" vspace="30" /></a></td>
<td>In <a title="Windows Azure Platform" href="http://my.safaribooksonline.com/9781430235637?iid=2013-04-blog-azure-book-9781430235637-SBOBlog" target="_blank">Windows Azure Platform</a> is divided into three key parts: Windows Azure, SQL Azure, and Windows Azure AppFabric. Each of these plays a unique role in the functioning of your cloud service. It is the goal of this book to show you how to use these components, both separately and together, to build flawless cloud applications as well as hybrid architectures that fit in alongside your business&#8217; existing systems.</td>
</tr>
<tr>
<td><a href="http://my.safaribooksonline.com/9781849685603?iid=2013-04-blog-azure-book-9781849685603-SBOBlog" target="_blank"><img src="http://techbus.safaribooksonline.com/static/201305-7216-techbus/images/9781849685603/9781849685603_s.jpg" alt="" hspace="70" vspace="30" /></a></td>
<td><a title="Windows Azure Programming Patterns for Start-ups" href="http://my.safaribooksonline.com/9781849685603?iid=2013-04-blog-azure-book-9781849685603-SBOBlog" target="_blank">Windows Azure Programming Patterns for Start-ups</a> is an incremental guide that will take you from the essentials of the Windows Azure platform up to the realization of your own cloud services running on the platform. You will learn how to apply different technologies of the Windows Azure platform with the help of examples all focusing on one single fictitious start-up scenario.</td>
</tr>
</tbody>
</table>
<h3>About the author</h3>
<table>
<tbody>
<tr>
<td valign="top" width="84"><a href="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DougMahugh.jpg"><img class="alignnone size-full wp-image-9789" title="DougMahugh" src="http://blog.safaribooksonline.com/wp-content/uploads/2013/05/DougMahugh.jpg" alt="" width="300" height="307" /></a></td>
<td>Doug Mahugh is lead technical evangelist at Microsoft Open Technologies, Inc., a wholly owned subsidiary of Microsoft Corporation responsible for advancing the company’s investments in interoperability, open source, and open standards. He can be reached at <a href="mailto:dmahugh@microsoft.com">dmahugh@microsoft.com</a>, or on Twitter at <a href="http://www.twitter.com/dmahugh">@dmahugh</a>.</td>
</tr>
</tbody>
</table>
<p><a href="http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/">Node.js and Windows Azure: Getting Started</a>
<a rel="author" href="http://blog.safaribooksonline.com/author/manager/">Safari Books Online</a></p><img src="http://feeds.feedburner.com/~r/SafariBooksOnlineBlog/~4/EeEisGs20lA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.safaribooksonline.com/2013/05/08/node-js-and-windows-azure-getting-started/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
