<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>OCTO talks !</title>
	<atom:link href="http://blog.octo.com/en/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.octo.com/en/</link>
	<description>Le blog d&#039;OCTO Technology, cabinet d&#039;architectes en systèmes d&#039;information</description>
	<lastBuildDate>Fri, 03 Feb 2012 13:46:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Data Grid or NoSQL ? same, same but different…</title>
		<link>http://blog.octo.com/en/data-grid-or-nosql-same-same-but-different/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=data-grid-or-nosql-same-same-but-different</link>
		<comments>http://blog.octo.com/en/data-grid-or-nosql-same-same-but-different/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 08:00:56 +0000</pubDate>
		<dc:creator>Olivier Mallassi</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=29587</guid>
		<description><![CDATA[For three years now, NoSQL as a piece of technologies for Big Data has spread over the world and is challenging the centralized world of RDBMS. The space of distributed storages is yet not new and banks, online gaming platforms are using for several years technologies called &#8220;data grid&#8221; to address latencies and throughput issues. [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/nosqleu-and-nosql-what%e2%80%99s-the-deal/' rel='bookmark' title='no:sql(eu) and NoSQL: What’s the deal?'>no:sql(eu) and NoSQL: What’s the deal?</a></li>
<li><a href='http://blog.octo.com/en/event-sourcing-nosql/' rel='bookmark' title='Event Sourcing &amp; noSQL'>Event Sourcing &#038; noSQL</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p>For three years now, NoSQL as a piece of technologies for Big Data has spread over the world and is challenging the centralized world of RDBMS. The space of distributed storages is yet not new and banks, online gaming platforms are using for several years technologies called &#8220;data grid&#8221; to address latencies and throughput issues. And to be completely franc, &#8220;Big Data&#8221; is not far from being the &#8220;new SOA”: a radical paradigm shift lost in the middle of commercial buzz words but that&#8217;s another story&#8230;</p>
<p><strong>What are the common points? The main differences?</strong></p>
<p><span id="more-29587"></span><br />
<em>In the rest of the article, the term nosql will be used to talk about &#8220;transaction oriented&#8221; solutions like <a href="http://www.datastax.com/">Cassandra</a>, <a href="http://wiki.basho.com/">Riak</a>, <a href="http://project-voldemort.com/">Voldemort</a>, <a href="http://aws.amazon.com/fr/dynamodb/">DynamoDB</a>. On the other side, “Data Grid” will group solutions like <a href="http://www.gigaspaces.com/">Gigaspaces</a>, <a href="http://www.vmware.com/products/application-platform/vfabric-gemfire/overview.html">Gemfire/SQLFire</a>, <a href="http://www.oracle.com/fr/products/middleware/coherence/index.html">Oracle Coherence</a>.</em></p>
<h2>Both Data Grids and NoSQL are talking about distributed storage</h2>
<p>No surprise&#8230;this is a distributed vision of the &#8220;database&#8221; and of the storage which enable to support more throughputs, more volume under, generally, cost constraints. The main idea resides in the fact that instead of using high-end server to store and query data, you use several &#8220;low-end&#8221; servers to store more data, increase the throughput and being able to scale-out, address elasticity issues. Indeed, <a href="http://blog.octo.com/datacenter-as-a-computer-une-plongee-dans-les-datacenters-des-acteurs-du-cloud/">this article</a> reminds us the unit cost of a transaction is approx.. 4 times cheaper on a cluster of low-end server than on a high end server, (the main drawback of distributed storage will be the bandwidth consumption that stays expensive).</p>
<p>So in both cases, the distributed vision of the storage implies: </p>
<ul>
<li><strong>Partitioning the data based on a key</strong>. Then the key is associated to a server (or a specific buckets served by a server).</li>
<li><strong>Routing the queries to the server that holds the data</strong>&#8230;The main idea is to avoid asking to all the servers for a specific piece of data. So the storage system needs to route the query to the right server. There are different implementations of that routing. Solution like Cassandra will implement a server side routing, implying at least and almost systematically one network hop (except if you are lucky and hit the right server). Solution like Voldemort will use a client-side routing. &#8220;Data Grid&#8221; like Gemfire will also use a client-side routing, will learn from the cluster where the data is located (and thus avoid the network hops)</li>
<li><strong>All these distributed systems use replication mechanisms</strong> to ensure the availability and, in some cases,  the durability (by mitigating the probability of losing a server before the data be replicated or by limiting the data corruption)</li>
</ul>
<h2>Data Grid and NoSQL comes from two distinct worlds: the latency oriented architecture or throughput architecture</h2>
<p>I was reading again <a href="http://www.allthingsdistributed.com/2010/11/cluster_gpu_instances_amazon_ec2.html">this article</a> of Vogels. As he stated (talking about GPU and CPU): </p>
<blockquote><p>&#8220;… the most fundamental abstraction trade-off has always been latency versus throughput. These trade-offs have even impacted the way the lowest level building blocks in our computer architectures have been designed. Modern CPUs strongly favor lower latency of operations with clock cycles in the nanoseconds &#8221;
</p></blockquote>
<p>Even if it is quite difficult, should I say dangerous, to compare things, we can see the same trade-offs between NoSQL and data grid solutions. Data Grids come from a world where each milli-seconds (and now nano-seconds) count. These &#8220;data grids&#8221; have thus rapidly quit the disk and use the memory as main storage (even if it is configurable and we will discuss about that later). </p>
<p>On the other side, NoSQL solutions have been developed mainly for web-scale industries where the latency is not less important but let say around the second (because the end user is a human). In that case, you do not need to answer quicker and quicker, but you need to serve more and more requests.</p>
<h2>NoSQL solutions have been developed to answer specific needs…whereas Data Grids are much more configurable: Bridging the gap</h2>
<p>If you look at the history of these solutions you will, at 10 000 foot high view, see that NoSQL solutions are mainly clones of the Dynamo model that have <a href="http://www.allthingsdistributed.com/2012/01/amazon-dynamodb.html">been developed at Amazon to store session and virtual caddies</a>.</p>
<p>The choices that were made fitted the <a href="http://www.allthingsdistributed.com/2007/10/amazons_dynamo.html">Amazon.com needs</a> : response time predictability, infrastructure elasticity and scaling out, multi-datacenter resiliency, design for failure&#8230;</p>
<p>&#8220;Data Grids&#8221; come from more heterogeneous (and thus richer) environments. You need to use them to relieve the RDBMS, to keep data in your local JVM, to scale&#8230;You need to integrate them with the historical part of your Information System, so you need SQL-like integration, you need java, .Net, ruby client APIs&#8230;</p>
<p>In short, data grids are clearly more configurable and so more adaptable than the NoSQL solutions. Without being exhaustive, we can think to: </p>
<ul>
<li><strong>&#8220;Data Grids&#8221; enable you controlling the way data is stored</strong>. They all have default implementation (Gigaspaces offers RDBMS by default, Gemfire offers file and disk based storage by default&#8230;.) but in all cases, you can choose the one that fits your needs: do you need to store data, do you need to relieve the existing databases&#8230;.</li>
<li>In order to minimize the latency, <strong>data grids enable you to store data synchronously (write-through) or asynchronously (write-behind) on disk</strong>. You can also define overflow strategies. In that case, data is store in memory up to a treshold where data is flushed on disk (following algorithms like LRU &#8230;). NoSQL solutions have not been designed to provide these features. </li>
<li><strong>Data grids enable you developing Event Driven Architecture</strong>. In some cases, an often-seen architecture could be a pure RDBMS plus a Message Oriented Middleware that is responsible to propagate the modifications (via events). Data Grids provide notification mechanisms for all or specified keys. Clients can so be notified on create / update / delete operations (like triggers)</li>
<li><strong>Querying is maybe the point on which pure NoSQL solutions and data grids are merging</strong>. Basically, both solutions provides pure map API which means you can put, get or delete an object by the key. Data grids already provide SQL queries (with limitations on joins) for a while but looking at the NoSQL market, you will see that these NoSQL solutions start providing secondary indexes that enable SQL-like queries, or MapReduce-like queries (with Brisk or DynamoDB that provides integration with Hadoop or Elastic MapReduce).</li>
<li><strong>Data grids enable near-cache topologies</strong>. The classical way of scaling readings with a RDBMS solution is to add a cache layer on top of the RDBMS (typically a memcached with difficulties like cache synchronization, cache partitioning to avoid collapsing the RDBMS in case of failure..). We do it so we know it works but data grids facilitates the deployment of &#8220;near cache topologies&#8221; &#8211; which means that data can be cached on the client side &#8211; ensuring the auto-eviction when the data is updated in the central storage, accelerating the readings&#8230;</li>
</ul>
<p><a href="http://blog.octo.com/wp-content/uploads/2012/01/ScreenShot021.png"><img src="http://blog.octo.com/wp-content/uploads/2012/01/ScreenShot021.png" alt="" title="ScreenShot021" width="888" height="437" class="aligncenter size-full wp-image-29662" /></a></p>
<h2>Both systems have the same constraints especially when it comes to ACID</h2>
<p>The funny thing is that both systems have the same constraints especially when it comes to ACID. </p>
<p>In fact, <strong>both solutions enables you to play with consistency and/or availability either using quorum based protocol or synchronous / asynchronous replication mechanisms</strong>. There is yet a subtility that can help data grids manage consistency (or at least conflict resolution): &#8220;data grid&#8221; use a master/slave topology per partition whereas nosql solutions use a master/master topology per partition.</p>
<p>Moreover, <strong>the &#8220;data grids&#8221; can offer you Atomicity and Transactions management BUT under certain constraints</strong>: typically, you will have to override the partitioning mechanism and ensure data colocation, you will not be able to rebalance the cluster while transactions are pending&#8230;These features come at a cost on the operability of the solution. This may not be blocking depending on the use cases but NoSQL solutions like Dynamo have made their choices: operability, elasticity with impacts on the dev side.</p>
<h2>NoSQL offer a storage vision whereas data grids offer more cases</h2>
<p>On that side, the match is not that simple.<br />
<strong>Data Grids offer much more complicated deployment options</strong>. You can use them in a classical client / server architecture: the data is stored on dedicated JVM whereas the business processes have their own dedicated JVM. In that case, the data grid is seen as a pure storage layer. That case is finally quite close of the NoSQL solutions. </p>
<p>What data grids offer (and not NoSQL solutions) is a peer-to-peer deployment where business processes and data are deployed in the same JVM. What changes is that the unit of deployment is the sum of the business process and you data. From the distributed storage point of view, there are no real advantages if you use your data grid as storage: data will be partitioned across the cluster, based on the key. This is yet quite different if your business cases necessitate writing and reading a lot of local data that is specific to your business case and must not be shared with the other business processes. In that case, you will benefit from this kind of deployment (gains in latency and bandwidth consumption).</p>
<p>The main drawback of data grids is that they need to know the java object (typically in the classpath) and in the best case, you can choose between default java serialization (Serializable or Externalizable) or the specific serialization. That can complicate upgrading the model, adding indexes&#8230;without downtime&#8230;<br />
On the opposite (and it solves the previous issues), NoSQL solutions work with a byte array: object versioning, serialization and unserialization must so be &#8220;manually&#8221; managed (even if these solutions often use protocols like Thrift, Avro…).</p>
<h2>So what? what to conclude? </h2>
<p>I am sure I forgot some points but in short that both systems are under the same constraints. The clear points is that &#8220;data grids&#8221;, due to their own story are certainly more adaptable.<br />
That does not mean you must not look at NoSQL solutions because they can fit your requirements and these solutions work (see the works of Netflix with <a href="http://techblog.netflix.com/2011/11/benchmarking-cassandra-scalability-on.html">Cassandra</a>)<br />
More generally, sometimes I am asking myself: why will we move to distributed storage (if we move to)? May be the following elements: </p>
<ul>
<li>the variability of workload and the needed elasticity</li>
<li>(maybe) the cost of this kind of infrastructure compared to traditional RDBMS infrastructure. I said maybe because I am convinced the economics equation must be explicitly posed. </li>
<li>the resiliency of the systems (and the implied cost pressure) : we now need to address higher level of failure for cheaper (because the cost of mitigate the failure must not be higher than the cost of failure itself)</li>
<li>the trivialization of infrastructure which will imply having less server diversity to serve more and more different use cases</li>
<li>the platform vision that will push forward to develop multi-tenant architecture</li>
</ul>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=29587" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/nosqleu-and-nosql-what%e2%80%99s-the-deal/' rel='bookmark' title='no:sql(eu) and NoSQL: What’s the deal?'>no:sql(eu) and NoSQL: What’s the deal?</a></li>
<li><a href='http://blog.octo.com/en/event-sourcing-nosql/' rel='bookmark' title='Event Sourcing &amp; noSQL'>Event Sourcing &#038; noSQL</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/data-grid-or-nosql-same-same-but-different/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An overview of RestKit, a Core Data enabled iOS and MacOSX framework for Restful applications</title>
		<link>http://blog.octo.com/en/overview-of-restkit-a-core-data-enabled-ios-macosx-framework-for-restful-apps/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=overview-of-restkit-a-core-data-enabled-ios-macosx-framework-for-restful-apps</link>
		<comments>http://blog.octo.com/en/overview-of-restkit-a-core-data-enabled-ios-macosx-framework-for-restful-apps/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 15:32:17 +0000</pubDate>
		<dc:creator>Rémy SAISSY</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[iOS]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mobility]]></category>
		<category><![CDATA[RestKit]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=28443</guid>
		<description><![CDATA[ASIHttpRequest, AFNetworking, MKNetworkKit,… The iOS/MacOSX programming landscape is full of helper libraries to deal with asynchronous network communications in your applications. RestKit can be seen as yet another library to do it. However, its approach is radically different since it does not only address asynchronous networking but also object mapping and a seamless persistance of [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/hadoop-distributed-file-system-overview-configuration/' rel='bookmark' title='Hadoop Distributed File System : Overview &amp; Configuration'>Hadoop Distributed File System : Overview &#038; Configuration</a></li>
<li><a href='http://blog.octo.com/en/how-to-rescue-your-data-33/' rel='bookmark' title='How to rescue your data, 3/3'>How to rescue your data, 3/3</a></li>
<li><a href='http://blog.octo.com/en/how-to-rescue-your-data/' rel='bookmark' title='How to rescue your data, 1/3'>How to rescue your data, 1/3</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p>ASIHttpRequest, AFNetworking, MKNetworkKit,… The iOS/MacOSX programming landscape is full of helper libraries to deal with asynchronous network communications in your applications.</p>
<p>RestKit can be seen as yet another library to do it. However, its approach is radically different since it does not only address asynchronous networking but also object mapping and a seamless persistance of such mappings locally through CoreData.</p>
<p>This approach is quite interesting when it comes to interact with Restful web services because of the time (and code!) you can save.</p>
<p>In this article, we are going to look at RestKit&#8217;s main functionalities through the code to do it. The objective is to give you a precise idea of what can be done and how to do it.</p>
<p><span id="more-28443"></span></p>
<h2>Network communications through RKClient</h2>
<p>In RestKit, network communications are managed by the <em>RKClient</em> class. This class encapsulates details on the HTTP level and provides control to the developer over it by simply editing properties.</p>
<p><em>RKClient</em> is where you can find the functionalities of <em>ASIHttpRequest</em>, <em>AFNetworking</em> or <em>MKNetworkKit.</em></p>
<p>From RestKit standpoint, it is an intermediate layer as we will see later in this article.</p>
<pre class="brush:c">RKClient *client = [RKClient clientWithBaseURL:@"http://api.domain.com/v1"];
[RKClient setSharedClient:client];
NSLog(@"This is my default client: %@.", [RKClient sharedClient]);
if ([[RKClient sharedClient] isNetworkReachable]){
    // Do some work...
}</pre>
<p>This code creates a new <em>RKClient</em> instance and set it as the default one. You can create as many instances as you want. Each instance is tied to a specific base URL which serves as the prefix to all network communications.<br />
<em>RKClient</em> exposes several properties to configure HTTP communications.<br />
Here is a review of the most common use case you might have.</p>
<h4>Customize HTTP Headers</h4>
<pre class="brush:c">NSLog(@"HTTP headers added: %@.", [RKClient sharedClient].HTTPHeaders);
[[RKClient sharedClient].HTTPHeaders setObject:@"MyAppSpecialHeader" forKey:@"X-MyApp-Special-Header"];
[[RKClient sharedClient].HTTPHeaders removeObjectForKey:@"X-Old-Key"];</pre>
<p>This allows you to control custom HTTP headers you want to use with your requests through this client.</p>
<h4>SSL communications</h4>
<pre class="brush:c">RKClient *sslClient = [RKClient clientWithBaseURL:@"https://api.domain.com/v1"];
sslClient.disableCertificateValidation = YES;
SecCertificateRef myCustomRootCertRef = SecCertificateCreateWithData(NULL, certData);
[sslClient addRootCertificate:myCustomRootCertRef];
NSLog(@"NSSet of my additional root certs: %@.", sslClient.additionalRootCertificates);</pre>
<p>As shown in the example, you can disable SSL certificate validation and add your own root certificates for a given <em>RKClient</em>.</p>
<h4>Request queue and Cache policy control</h4>
<p><em>RKClient</em> is asynchronous, its concurrency level is customizable and requests can suspended in which case they are enqueued until the queuing limit is reached.</p>
<pre class="brush:c">[RKClient sharedClient].requestQueue.concurrentRequestsLimit = 2;
[RKClient sharedClient].requestQueue.requestTimeout = 10;
[RKClient sharedClient].suspended  = YES;
NSLog(@"Number of requests in the queue: %d. Total number of request currently loading: %d.",
[RKClient sharedClient].loadingCount, [RKClient sharedClient].count);</pre>
<p>It is also possible to access and control the cache of the <em>RKClient</em> instance.</p>
<p>Several policies such as use the cache only when offline or use the cache when the request timeouts as builtin. The developer can dynamically change the caching policy and also has a direct access to the cache implementation so she can invalidate entries, add others, &#8230;</p>
<pre class="brush:c">[RKClient sharedClient].cachePolicy = RKRequestCachePolicyLoadIfOffline|RKRequestCachePolicyTimeout;
[RKClient sharedClient].requestCache.storagePolicy = RKRequestCacheStoragePolicyPermanently;</pre>
<h4>Builtin support for authentication schemes</h4>
<p>RestKit natively supports 4 authentication schemes:</p>
<ul>
<li>HTTP Auth</li>
<li>HTTP Basic</li>
<li>OAuth1</li>
<li>OAuth2</li>
</ul>
<p>This is configured through properties of <em>RKClient</em>.<br />
For example, to configure OAuth2 you would do the following.</p>
<pre class="brush:c">[RKClient sharedClient].authenticationType = RKRequestAuthenticationTypeOAuth2;
[RKClient sharedClient].OAuth2AccessToken = @"YourOAuth2AccessTokenHere";
[RKClient sharedClient].OAuth2RefreshToken = @"YourOAuth2RefreshTokenHere";</pre>
<p>Once configured this way, all network communications will use the credentials you specified.<br />
Other authentication schemes are configured the same way. Each have its own set of properties in <em>RKClient</em>.</p>
<h4>A real life example with RKClient</h4>
<p>Now let&#8217;s consider a real life example. Let&#8217;s say that we want to retrieve an RSS feed of today from a website which requires an HTTP Basic authentication.<br />
We don&#8217;t want to cache anything and we also don&#8217;t want to wait for more than 10 seconds to retrieve the feed.<br />
The code to do it would look like this:</p>
<pre class="brush:c">#import &lt;Foundation/Foundation.h&gt;
#import &lt;RestKit/RestKit.h&gt;

@interface MyClass : NSObject&lt;RKRequestDelegate&gt;

- (void)retrieveFeed;

@end

@implementation MyClass

- (void)retrieveFeed
{
  RKClient *client = [RKClient clientWithBaseURL:@"http://rss.domain.com"];
  client.requestQueue.requestTimeout = 10;
  client.cachePolicy = RKRequestCachePolicyNone;
  client.authenticationType = RKRequestAuthenticationTypeHTTPBasic;
  client.username = @"rssuser";
  client.password = @"rsspwd";
  NSDictionary *queryParameters = [NSDictionary dictionaryWithObjectsAndKeys:@"today", @"date", nil];
  NSString *getResourcePath = RKPathAppendQueryParams(@"/feed.xml", queryParameters);
  [client get:getResourcePath delegate:self];
}

- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response
{
  if (request.method == RKRequestMethodGET) {
        id xmlParser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeXML];
        NSError *error = nil;
        id parsedResponse = [xmlParser objectFromString:[response bodyAsString] error:&amp;error];
        if (error == nil)
            NSLog(@"GET:/user returned with HTTP Code %d and parsedContent: %@", [response statusCode], parsedResponse);
  }
}

- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error
{
  if (request.method == RKRequestMethodGET) {
    NSLog(@"Failure of GET:/user with error %@.", error);
  }
}
@end</pre>
<p>As you have probably noticed, a delegate is provided to handle the asynchronous results. RestKit relies a lot on delegate both internally and for its public interfaces.<span style="text-align: left;"> </span></p>
<p style="text-align: left;">Another interesting point is how we parsed the response of the feed which is expected to be XML content.</p>
<p style="text-align: left;">Indeed, RestKit provides a parser registry that you can use to get an instance of a parser for one of these four mimetypes:</p>
<div>
<ul>
<li>RKMIMETypeJSON for application/json</li>
<li>RKMIMETypeFormURLEncoded for application/x-www-form-urlencoded</li>
<li>RKMIMETypeXML for application/xml</li>
<li>RKMIMETypeTextXML for text/xml</li>
</ul>
<p>JSON parsing is based on <em>JSonKit</em> and XML parsing is based on <em>libxml2</em>.<br />
Therefore, most of the time, you don&#8217;t need to include another third party library for parsing network responses.</p>
<h2 style="text-align: left;">Object Mapping through RKObjectManager</h2>
<p>What makes RestKit quite different from other libraries is the object mapping layer and its seamless support for persistence through CoreData.</p>
<p><em>RKObjectManager</em> is the entry point in RestKit to manage object mappings. Each instance of this class encapsulates an <em>RKClient</em>, an <em>RKObjectRouter</em>, an <em>RKObjectMappingProvider</em> and an <em>RKManagedObjectStore.</em><br />
But let&#8217;s see by the examples how to use the Object Manager.</p>
<h4>Create a mapper for a remote API</h4>
<pre class="brush:c">RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://api.domain.com/v1"];
RKObjectManager *sslObjectManager = [RKObjectManager objecxtManagerWithBaseURL:@"https://api.domain.com/v1"];

// Initialize the managed object store because both will have Core Data managed objects.
objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"api.sql"];
sslObjectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"apissl.sql"]; 

// We want the SSL Object Manager to be our sharedManager.
[RKObjectManager setSharedManager:sslObjectManager];</pre>
<p>You can have several object managers and choose which one is the <em>sharedManager</em>. Each  Object Manager instance has an <em>RKClient</em>  instance. Therefore you can control <em>RKClient</em> parameters on a per remote API mapper basis.</p>
<h4>Create a mapping and register a route for it</h4>
<pre class="brush:c">RKManagedObjectMapping *myMapping = [RKManagedObjectMapping mappingForClass:[MyClass class]];

// Map attributes
[myMapping mapAttributes:@"id", @"name", nil];

// These attributes have different name in objc and JSON.
[myMapping mapKeyPathsToAttributes:@"expirationTime", @"expiration_time", nil];

// Since it is a Core Data managed class, we can indicate to RestKit which property is the primary key (optional).
[myMapping setPrimaryKeyAttribute:@"id"];

// Set relationships. Previously mapped classes are used here.
[myMapping hasOne:@"user" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"userMapping"]];
[myMapping hasMany:@"sessions" withMapping:[[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"sessionMapping"]];

// Set both the mapping and the serialization mapping.
[[RKObjectManager sharedManager].mappingProvider setMapping:myMapping forKeyPath:@"tokenMapping"];
[[RKObjectManager sharedManager].mappingProvider setSerializationMapping:[myMapping inverseMapping]  forClass:[MyClass class]];

// Register two routes for this class, a GET and a POST.
[[RKObjectManager sharedManager].router routeClass:[MyClass class] toResourcePath:@"/api/foo" forMethod:RKRequestMethodGET];

// The POST route has a dynamic parameter which is the objc property name prefixed by a semicolon.
[[RKObjectManager sharedManager].router routeClass:[MyClass class] toResourcePath:@"/api/foo/:id" forMethod:RKRequestMethodPOST];</pre>
<h4>Requesting a resource using its route</h4>
<pre class="brush:c">// Our object is managed through CoreData. RestKit takes care of updating it.
@interface MyClass : NSManagedObject

@property (retain, nonatomic) NSInteger id;
@property (retain, nonatomic) NSString *name;

@end

@implementation MyClass

@dynamic id, name;

@end

@interface MyController : UIViewController&lt;RKObjectLoaderDelegate&gt;

- (void)loadData;

@end

@implementation MyController

- (void)loadData
{
  // Retrieve an instance stored in CoreData. RestKit provides a category to encapsulate Core Data interactions.
  MyClass *obj = [MyClass findFirstByAttribute:@"id" withValue:@"42"];
  obj.name = @"A new name to set remotely";

  // Perform the post request.
  [MyClass postObject:obj delegate:self];
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object
{
  NSLog(@"Request succeed and  response loaded into CoreData: %@.", object);
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error
{
  NSLog(@"An error occurred: %@.", error);
}
@end</pre>
<p>Other response delegates are available and let the developer receive its content as a dictionary or an array of objects if the return was expected to be an array.</p>
<h4>Requesting a resource without a route</h4>
<p>Loading a request without a route is also possible. The use case is when a request expects an array of a specific object.<br />
In order to request without a route, the developer uses the <em>loadObjectsAtResourcePath: </em>method call.</p>
<pre class="brush:c">RKObjectMapping *userMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"sessionMapping"];

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/api/foo" objectMapping:userMapping delegate:self];</pre>
<p>Nothing else changes.</p>
<h4>Configuring a mapping</h4>
<p>In order to cope with a maximum of situation, RestKit provides a set of properties to configure each mapping to fit to what the remote API returns or expects to receive.<br />
Here are some of the most useful of these properties:</p>
<h5>Handle missing attributes</h5>
<pre class="brush:c">myMapping.setDefaultValueForMissingAttributes = YES;
myMapping.setNilForMissingRelationships = YES;</pre>
<p>You can set both missing attributes and relationships to nil.</p>
<h5>Mapping unpredictable JSON keys</h5>
<p>Let&#8217;s say for example that user id/name is the key in a JSON and that for each &#8220;key&#8221;, the value is the user object.<br />
Let&#8217;s consider the following JSON:</p>
<pre class="brush:c">{ "users":
  {
    "foo": { "id": 1234, "email": "foo@domain.com" },
    "bar": { "id": 5678", "email": "bar@domain.com" }
  }
}</pre>
<p>To handle this kind of unpredictable mapping in RestKit, we would do:</p>
<pre class="brush:c">RKObjectMapping *myMapping = [RKObjectMapping mappingForClass:[User class]];
// RestKit cannot infer this is a collection, so we force it
myMapping.forceCollectionMapping = YES;
// Map our attributes.
[myMapping mapKeyOfNestedDictionaryToAttribute:@"firstName"];
[myMapping mapFromKeyPath:@"(firstName).id" toAttribute:"userID"];
[myMapping mapFromKeyPath:@"(firstName).email" toAttribute:"email"];

[[RKObjectManager sharedManager].mappingProvider setObjectMapping:myMapping forKeyPath:@"users"];</pre>
<h5>Dates are formatted in a very specific way</h5>
<p>RestKit let the developer handle it in different ways:</p>
<ul>
<li>By default, a mapping uses an array of date formatters</li>
<li>Each mapping can define its own array of data formatters to use instead of the global one</li>
<li>Each mapping can define its preferred date formatter to use in first place</li>
</ul>
<p>&nbsp;</p>
<pre class="brush:c">myMapping.preferredDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
myMapping.dateFormatters  = [NSArray arrayWithObjects:[[[NSDateFormatter alloc] init] autorelease], [[[NSDateFormatter alloc] init] autorelease], [[[NSDateFormatter alloc] init] autorelease], nil];

// Set as the application wide default set of formatters.
[RKObjectMapping setDefaultDateFormatters:myMapping.dateFormatters];</pre>
<h5>Avoids duplicate entries of an object in the Core Data store</h5>
<pre class="brush:c">RKManagedObjectMapping *myMapping = [RKManagedObjectMapping mappingForClass:[CoreDataManagerObject class]];
myMapping.primaryKeyAttribute = @"id";</pre>
<p>Note that this is specific to objects managed with CoreData.</p>
<h4>Initializing using a seed database</h4>
<p>You can initialize the Core Data store using a seed database. For example you may want to seed your store if it is empty.</p>
<pre class="brush:c">RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://api.domain.com/api"];

// ... Initializing mappings.
NSArray *objectsInStore = [MyObject allObjects];
if (objectsInStore count] == 0) {
  NSString *storeFilename = objectManager.objectStore.storeFilename;
  NSString *pathToSeedDB = [[NSBundle mainBundle] pathForResource:@"MySeedDB" ofType:@".db"];
  RKManagedObjectStore *objectStore = objectStoreWithStoreFilename:storeFilename usingSeedDatabaseName:pathToSeedDB managedObjectModel:nil delegate:self];
  objectManager.objectStore = objectStore;
}</pre>
<h4>Handling Core Data errors</h4>
<p>Sometimes the Core Data store may have failure. For example when your data model is invalid.<br />
RestKit provides a way to handle such events with the <em>RKManagedObjectStoreDelegate</em>.</p>
<pre class="brush:c">@interface MyAppDelegate : UIResponder &lt;RKManagedObjectStoreDelegate&gt;
@end

@implementation MyAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RKObjectManager *objectManager = [RKObjectManager   objectManagerWithBaseURL:@"http://api.domain.com/api"];
  objectManager.objectStore.delegate = self;
}

// Delegates

- (void)managedObjectStore:(RKManagedObjectStore *)objectStore didFailToCreatePersistentStoreCoordinatorWithError:(NSError *)error
{
  NSLog(@"Fail to create a persistent store. Error: %@", error);
}

- (void)managedObjectStore:(RKManagedObjectStore *)objectStore didFailToDeletePersistentStore:(NSString *)pathToStoreFile error:(NSError *)error;
{
  NSLog(@"Fail to delete a persistent store at path %@. Error: %@", pathToStoreFile, error);
}

- (void)managedObjectStore:(RKManagedObjectStore *)objectStore didFailToCopySeedDatabase:(NSString *)seedDatabase error:(NSError *)error
{
  NSLog(@"Fail to copy seed database: %@. Error: %@", seedDatabase, error);
}

- (void)managedObjectStore:(RKManagedObjectStore *)objectStore didFailToSaveContext:(NSManagedObjectContext *)context error:(NSError *)error exception:(NSException *)exception
{
  NSLog(@"Fail to save context: %@. Error: %@ (%@)", context, error, exception);
}
@end</pre>
<h1 style="text-align: left;">Unit Testing</h1>
<p style="text-align: left;">In RestKit, all network communications are done using two classes: <em>RKRequest</em> and <em>RKResponse</em>.</p>
<p style="text-align: left;">Unit testing thus requires reimplementing the <em>- (void)fireASynchronousRequest</em> in <em>RKRequest</em> to avoid enqueuing the request and mocking your API.</p>
<p style="text-align: left;">In this case, your reimplemented method will build its own <em>RKResponse</em> packet and call the relevant delegates.</p>
<p style="text-align: left;">To know which one to use, it is needed to look at the source code of the version of RestKit compiled with the application.</p>
<p>Here is an example of <em>fireAsynchronousRequest</em> modification for unit test.</p>
<pre class="brush:c">- (void)fireASynchronousRequest
{
// From the original implementation.

[self prepareURLRequest];
NSString* body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding];
NSLog(@"Sending %@ request to URL %@. HTTP Body: %@", [self HTTPMethod], [[self URL] absoluteString], body);
[body release]; 

_isLoading = YES;
if ([self.delegate respondsToSelector:@selector(requestDidStartLoad:)])
[self.delegate requestDidStartLoad:self]; 

RKResponse* response = [[[RKResponse alloc] initWithRequest:self] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:RKRequestSentNotification object:self userInfo:nil];

// Now execute the mocking code.
NSString *bundlePath = nil;
NSInteger statusCode = 200;

id requestJsonObject = nil;
if (self.params != nil) {

  NSString *jsonString = [[[NSString alloc] initWithData:[self.params HTTPBody] encoding:NSUTF8StringEncoding] autorelease];

  // If you use the latest version of RestKit with Object Mapper 2.0:
  id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
  NSAssert1(parser, @"Cannot perform object load without a parser for MIME Type '%@'", RKMIMETypeJSON);
  NSError **error = nil;
  requestJsonObject = [parser objectFromString:jsonString error:error];
}

// Switch to determine which to to use
…

// Prepare the results.
NSData *responseData = nil;
if (bundlePath == nil)
responseData = [NSData data];
else
{
// Load the mock file.
NSString *responseString = [NSString stringWithContentsOfFile:bundlePath encoding:NSUTF8StringEncoding error:nil];
responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
}

// Send the response. This is a superclass to be able to return a custom statusCode.
MyHTTPURLResponse *urlResponse = [[[MyHTTPURLResponse alloc] initWithURL:_URL MIMEType:RKMIMETypeJSON expectedContentLength:[responseData length] textEncodingName:nil] autorelease];
[urlResponse setStatusCode:statusCode];

// Delegates in the order RestKit is expecting it.
[response connection:nil didReceiveResponse:urlResponse];
[response connection:nil didReceiveData:responseData];
if ([response isError] == YES)
[response connection:nil didFailWithError:[NSError errorWithDomain:@"test domain" code:statusCode userInfo:nil]];
else
[response connectionDidFinishLoading:nil];
}</pre>
<h1 style="text-align: left;"></h1>
<h1 style="text-align: left;">Conclusion</h1>
<p style="text-align: left;">The choice of integrating a third party library is an important one. RestKit is an active project and from my experience, the questions you might ask on their forums will find an answer quickly.</p>
<p style="text-align: left;">Moreover, if you need object mapping or Core Data support, RestKit is definitely a very good choice since its clean architecture and API saves a lot of time to developers.</p>
<p style="text-align: left;">If you don&#8217;t need such functionalities, then you should focus on <em>RKClient</em>&#8216;s functionalities compared to other frameworks and keep in mind that even though it is quickly moving towards blocks, RestKit still heavily relies on delegates.</p>
<p style="text-align: left;">Feel free to let me know your feelings and comments.</p>
<h1 style="text-align: left;"></h1>
<h1 style="text-align: left;">References</h1>
<p style="text-align: left;"><em>RestKit:</em> <a href="http://restkit.org/">http://restkit.org/</a></p>
<p style="text-align: left;"><em>RestKit Source Code on gitHub:</em> <a href="https://github.com/RestKit/RestKit">https://github.com/RestKit/RestKit</a></p>
<p style="text-align: left;"><em>RestKit Google Group:</em> <a href="https://groups.google.com/forum/#!forum/restkit">https://groups.google.com/forum/#!forum/restkit</a></p>
</div>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=28443" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/hadoop-distributed-file-system-overview-configuration/' rel='bookmark' title='Hadoop Distributed File System : Overview &amp; Configuration'>Hadoop Distributed File System : Overview &#038; Configuration</a></li>
<li><a href='http://blog.octo.com/en/how-to-rescue-your-data-33/' rel='bookmark' title='How to rescue your data, 3/3'>How to rescue your data, 3/3</a></li>
<li><a href='http://blog.octo.com/en/how-to-rescue-your-data/' rel='bookmark' title='How to rescue your data, 1/3'>How to rescue your data, 1/3</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/overview-of-restkit-a-core-data-enabled-ios-macosx-framework-for-restful-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Untar on iOS, the pragmatic way</title>
		<link>http://blog.octo.com/en/untar-on-ios-the-pragmatic-way/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=untar-on-ios-the-pragmatic-way</link>
		<comments>http://blog.octo.com/en/untar-on-ios-the-pragmatic-way/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 14:26:15 +0000</pubDate>
		<dc:creator>Mathieu Hausherr</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[untar]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=28355</guid>
		<description><![CDATA[The problem Why untar? Network connections cause latencies on your mobile app. Replace 10 downloads of 1Mb by 1 download of 10Mb is a good improvement to your app. There’s a well-known unix tool for that: tar. What is tar? Wikipedia says: “Tar is now commonly used to collect many files into one larger file [...]]]></description>
			<content:encoded><![CDATA[
<h2>The problem</h2>
<h3>Why untar?</h3>
<p>Network connections cause latencies on your mobile app. Replace 10 downloads of 1Mb by 1 download of 10Mb is a good improvement to your app.</p>
<p>There’s a well-known unix tool for that: tar.</p>
<p>What is tar? Wikipedia says: “Tar is now commonly used to collect many files into one larger file for distribution or archiving, while preserving file system information such as user and group permissions, dates, and directory structures.” That’s exactly what we need with some extra features.</p>
<p>How to untar an archive file on your iOS device?<span id="more-28355"></span></p>
<h3>How to untar?</h3>
<p>A goolge search about untar on iOS provide two solutions:</p>
<ul>
<li>BSD libarchive. This lib is already in your iOS device but without header files. Apple calls that a “private API”. You can’t use it in App Store. If you are doing an app for jailbroken device there isn’t any problem but I need to push my app to the App Store.</li>
<li>Davepeck BSD libarchive implementation <a href="https://github.com/davepeck/iOS-libarchive">https://github.com/davepeck/iOS-libarchive</a>. The code of libarchive is open source so davepeck has packaged this code for iOS and you can add it to your project. This libarchive implementation is the same than the tar command on your Mac. You can create or extract tar file and provide gzip or bzip compression. But this lib includes 617 files, 347 606 lines of code (without any Objective-C wrapper that you have to code by yourself) and weights 4.7MB when build. Just remember that you need wifi to download app heavier than 20MB.</li>
</ul>
<h3>Why not using libarchive?</h3>
<p>With libarchive:</p>
<ul>
<li>We add code dependencies to our project. These dependencies need to be updated.</li>
<li>More lines of code means more bugs. According to Steve McConnell’s &#8220;Code Complete&#8221;, there are on average between 15 and 50 bugs per KLOC (Kilo line of code), so if I take a calculator and make rocket science estimation, there are 5000 bugs in libarchive.</li>
<li>If Apple changes an API and break libarchive compatibility, your code will not stay reliable.</li>
</ul>
<p>Is there another way? What if I must push my app in the app store but don’t want to link this 4.7MB of hardly-maintainable code? Let’s code my own light and pragmatic untar implementation.</p>
<h3>What do we really need?</h3>
<p>Libarchive weights 4.7MB but do a lot of things we don’t really need.</p>
<p>We need to untar files but we don’t need:</p>
<ul>
<li>To create tar files.</li>
<li>To uncompress files (gzip or bzip). If we want to compress our file we can use zlib and then untar. We don’t have to untar during inflate.</li>
<li>To work with old fashion tar (from the 80’s).</li>
<li>To work with unix ownership and right: iOS will not let us set this rights even if we wanted.</li>
<li>To work with simlinks, hard links, FIFO or other special stuffs. We just want to handle files.</li>
</ul>
<h2>The solution</h2>
<h3>What’s a tar file?</h3>
<p>A tar file is composed of 512 bytes data blocks.</p>
<p>The first block is a header for the first file; the next n blocks are the content of this file and then a new file start with a new header block.</p>
<p>A tar file looks like that: (H is header block, C content block, / partial content block)</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/12/Tar-File1.png"><img class="aligncenter size-full wp-image-28400" title="Tar-File" src="http://blog.octo.com/wp-content/uploads/2011/12/Tar-File1.png" alt="" width="793" height="21" /></a></p>
<p>At the end of the tar file there is two empty blocks. A new file starts always after an integer number of blocks. Some files haven’t any content block (like folder). Each block has 512 bytes.</p>
<p>A header block comports a lot of datas. Few of these data, and none of the new UStar header data are useful for us.</p>
<p>We just need:</p>
<ul>
<li>The file name: Encoded in ASCII, it’s a relative path like “mydir/myfile.pdf”</li>
<li>The file size: Encoded in ASCII, it’s an octal value in bytes.</li>
<li>The file type: we only need two file types, ‘0’ for regular files and ‘5’ for directories</li>
</ul>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/12/Tar-Block1.png"><img class="aligncenter size-full wp-image-28401" title="Tar-Block" src="http://blog.octo.com/wp-content/uploads/2011/12/Tar-Block1.png" alt="" width="902" height="19" /></a></p>
<p>With the file size we know when the header block of the next file starts. And where to strip the content of the last block of the file.</p>
<h3>The result: Light-Untar for iOS</h3>
<p>Not so complex isn’t it? I just implemented this code in Objective-C and push it to github: <a href="https://github.com/mhausherr/Light-Untar-for-iOS">https://github.com/mhausherr/Light-Untar-for-iOS</a></p>
<p>This code is under BSD license; you can use it for your own project.</p>
<p>Is it better than libarchive? Light-Untar-for-iOS has only 2 files and 168 lines of code, which include the comment lines with the license text.</p>
<p>To use it, include the .h file and use this NSFileManager method:</p>
<pre class="brush:java">[[NSFileManager defaultManager] createFilesAndDirectoriesAtPath:@"/path/to/your/extracted/files/" withTarData:tarData error:&amp;error];</pre>
<p>tarData is an NSData. You can create the NSData with this code:</p>
<pre class="brush:java">NSData *tarData = [NSData dataWithContentsOfFile:@"/path/to/your/tar/file.tar"];</pre>
<h2>Limitations about Performances and Security</h2>
<h3>Performances</h3>
<p>Libarchive  is written directly in C and does the job faster than my Objective-C code.</p>
<p>The question is: what’s the most important thing for you?</p>
<ul>
<li>To win 40ms on each untar?</li>
<li>To save 4.7Mb of the size of your app?</li>
</ul>
<p>If you choose the second one, Light-Untar-for-iOS is for you.</p>
<h3>Security</h3>
<p>What are major security issues of tar?</p>
<ul>
<li>Symbolic links: Someone can add links to give access to folders outside the working directory.</li>
<li>Set root ownership or add execution right: Someone can add an executable file with root access and launch it.</li>
</ul>
<p>Neither of these are implemented in my code, so you can use it safely.</p>
<p>And you know what? It’s an iOS lib. On iOS<strong>,</strong> applications are sandboxed. The system himself protects this code. We don’t need any other protection.</p>
<h2>Conclusion</h2>
<p>Mobile development is primarily development on low capacity devices. Size of the build app is also important.</p>
<p>If you have a simple problem to solve, ask you what is the best: A huge framework can do that for you. Do you need really all this framework? Can’t you just implement the requested feature?</p>
<h2>To go further</h2>
<ul>
<li><a href="http://www.gnu.org/s/tar/manual/html_node/Standard.html">http://www.gnu.org/s/tar/manual/html_node/Standard.html</a></li>
<li><a href="http://en.wikipedia.org/wiki/Tar_(file_format">http://en.wikipedia.org/wiki/Tar_(file_format</a>)</li>
<li><a href="http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670">http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670</a></li>
</ul>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=28355" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/untar-on-ios-the-pragmatic-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DevOps tips and tricks, on the ops side</title>
		<link>http://blog.octo.com/en/devops-tips-and-tricks-on-the-ops-side/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=devops-tips-and-tricks-on-the-ops-side</link>
		<comments>http://blog.octo.com/en/devops-tips-and-tricks-on-the-ops-side/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 08:54:51 +0000</pubDate>
		<dc:creator>Arnaud Mazin</dc:creator>
				<category><![CDATA[Consulting chronicles]]></category>
		<category><![CDATA[Dev]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Ops]]></category>
		<category><![CDATA[production]]></category>
		<category><![CDATA[run]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=27045</guid>
		<description><![CDATA[After applying as much as possible the DevOps principles for more than a year on the run of a highly business critical project of one of our customers, here are some golden rules we eventually found out and tried to stick with. Items are here presented from an Ops perspective. One deployment tool to rule [...]]]></description>
			<content:encoded><![CDATA[
<p>After applying as much as possible the DevOps principles for more than a year on the run of a highly business critical project of one of our customers, here are some golden rules we eventually found out and tried to stick with. Items are here presented from an Ops perspective.</p>
<p><span id="more-27045"></span></p>
<h2>One deployment tool to rule them all</h2>
<p>Work hard on getting a nice deployment tool (scripts, capistrano, whatever) and use it to deploy on all your environments from development to UAT, perf and of course production. You&#8217;ll make sure you&#8217;ll apply the <strong><a title="fail-fast" href="http://en.wikipedia.org/wiki/Fail_Fast">fail fast</a></strong> principle to deployment. Make sure it pulls all the artifacts it needs from your repo, Nexus or such.</p>
<h2>If deployment is painfull do it more often, if it&#8217;s fun, do it more often</h2>
<p>Deployment must not be considered as a failure nor as an exception. It&#8217;s fine, it&#8217;s a standard and a frequent part of the job, it shows you have worked to bring out new features, improved performances, bugfixes. Don&#8217;t be scared to deploy often, « practice makes perfect ». The more often you deploy, <a href="http://www.slideshare.net/jezhumble/devops-and-agile-release-management">the smaller the changes are</a>, the lesser the risks.</p>
<h2>Monitoring is for everyone</h2>
<p>From technical (sysadmins, developers, DBA, HelpDesk) to highly non-technical people (marketing, financial, top management), every one loves to see the heartbeat of the system. Propose several screens / dashboards to present the data to each perspective.</p>
<h2>Commit developers in every steps of the production life, and give them feedback, loads of it</h2>
<p>Make sure you can wake them up during a tricky update or even better, grab some extra pizza to make sure they stay during the upgrade process.</p>
<p>Give access to all data they need to investigate, either in real-time on the production environment or at least by giving access to data / logs with as few delay as possible</p>
<h2>Use production-like database content, A.S.A.P.</h2>
<p>Real-life data often contain  stranger stuff than you could ever imagine, use them. Anonymize them (yes, you really want to avoid emailing real users during your tests), reduce their size if needed, but do keep historical data. They will help with UAT, perf testing, and will secure your production roll-out.</p>
<h2>Share tools and practices with Devs</h2>
<p>Kanbans, scrums, retrospectives, Jira, Confluence are probably used into your dev team, ritualize such principles on the ops side, you&#8217;ll share the same logic and delivery rhythm.</p>
<h2>Express needs, act as a P.O. when needed</h2>
<p>If you need something from the Devs that will help you make the run better / cheaper / faster, such as a better log classification, functionnal metrics to monitor, become a <a title="Product Owner" href="http://en.wikipedia.org/wiki/Scrum_(development)#Roles_2">Product  Owner</a>, propose user stories and make sure they take life. Negociate with the business to get a minimal amount of complexity points for ops user stories at each iteration.</p>
<h2><strong>Automatize everything that can be (especially boring stuff)</strong></h2>
<p>Script, script, script, keep your mind free from silly or time-consuming stuff, you have better things to do.</p>
<h2><strong>Manage your systems automatically</strong></h2>
<p>Use <a href="http://wiki.opscode.com/display/chef/Home">Chef</a>, <a href="http://projects.puppetlabs.com/projects/puppet">Puppet</a>, <a href="http://cfengine.com/">cfEngine</a> + a <a title="VCS" href="http://en.wikipedia.org/wiki/Revision_control">VCS</a> (git, mercurial, SVN…) to store and historize your configurations.</p>
<h2>Embrace the <a title="Test-Driven Infrastructure" href="http://www.jedi.be/blog/2009/11/12/collection-of-test-driven-infrastructure-links/">Test-Driven Infrastructure</a> Approach</h2>
<p>Try to make every change on your infrastructure testable, use the monitoring tool as a an automatic tool for it.</p>
<h2>Elect a <a href="http://www.infoq.com/articles/kanban-operations-spotify">goalie</a> to keep other ops from task-switching</h2>
<p>This will ensure you that small tasks are handled as soon as possible and keep people working on long-term tasks focussed.</p>
<p>&nbsp;</p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=27045" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/devops-tips-and-tricks-on-the-ops-side/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Devoxx 2011, the main trends</title>
		<link>http://blog.octo.com/en/devoxx-2011-the-main-trends/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=devoxx-2011-the-main-trends</link>
		<comments>http://blog.octo.com/en/devoxx-2011-the-main-trends/#comments</comments>
		<pubDate>Sat, 03 Dec 2011 12:24:35 +0000</pubDate>
		<dc:creator>Domenjoud Michel</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=28155</guid>
		<description><![CDATA[One of the biggest Java conference in the world took place in Antwerpen, Belgium on last November. This year, Devoxx main themes were (in no particular order) The future of Java Alternative languages on the JVM HTML5 JavaFX Android A bit of Cloud, NoSQL and high performance architecture We also had a great announcement about [...]]]></description>
			<content:encoded><![CDATA[
<p><img class="aligncenter" title="Devoxx11" src="http://www.sogeti.be/Global/header%20images/Special%20format/DevoxxTransparent.png" alt="" width="945" height="354" /></p>
<p>One of the biggest Java conference in the world took place in Antwerpen, Belgium on last November. This year, Devoxx main themes were (in no particular order)</p>
<ul>
<li>The future of Java</li>
<li>Alternative languages on the JVM</li>
<li>HTML5</li>
<li>JavaFX</li>
<li>Android</li>
<li>A bit of Cloud, NoSQL and high performance architecture</li>
</ul>
<p>We also had a great announcement about a new conference coming in 2012: <a title="Devoxx France" href="http://www.devoxx.com/display/FR12/Accueil">Devoxx France</a>!</p>
<p>Obviously, OCTO was there. In this article we won’t cover the sessions in details. A lot of blogs already did it. We’ll however summarize this edition’s main trends and give our impressions.</p>
<p><span id="more-28155"></span></p>
<h1><span style="text-decoration: underline;">Java</span></h1>
<h2>Java SE &amp; EE</h2>
<p>All announcements from Oracle about Java were already made at JavaOne, but the two opening keynotes gave us a good reminder and here are the key points:</p>
<ul>
<li>Java SE 7 is out since last July and brings several new functionalities.</li>
<li>Java SE 8 is planned for 2013 and will include mainly Jigsaw (Java modularity) and Lambda (closures in Java) projects.</li>
<li>Java EE 7 is planned for Q3 2012 and will be cloud oriented. Standard metadata will be provided for easing provisioning, multi-tenancy support, elasticity, etc. We should see an emerging standard for solutions such as Cloud Foundry from vmWare or OpenShift from RedHat.</li>
<li>Other standards should evolve, with by example a 2.0 version for JMS, which had no new version since 2003.</li>
</ul>
<p>Mark Reinhold gave us a talk about Project Jigsaw, which aims to allow Java applications and the JDK itself to be natively modular. For example,  we should be able to deploy Java applications as RPM package. We will also be able to take only small parts of the JDK for specific applications. This project is interesting, but still  frightening on one point : they don&#8217;t seem to be really close from projects like Maven which already had to deal with many modularity and dependencies problems for years : can we hope they won&#8217;t fall in the same traps as Maven in the beginning?</p>
<p>Another important point is the great emphasis made on JavaFX 2, which is now the main GUI framework for thick clients and mobile. Therefore, no more investments will be done on Swing, even if Oracle will continue to support it. A lot of sessions were about Java FX, and it was quite conclusive. Let’s hope it won’t became the same flop as Java FX 1.</p>
<p>We also had two great retrospectives about Java by Joshua Bloch, who made a really in depth analysis of pretty much all the original JDK classes! Coming from the guy who gave us the generics, it’s a quite interesting talk. Watch it on Parleys.com when it will become available, you could discover some tricky details about Java.</p>
<p>The Oracle guys also tried to give us some messages:</p>
<ul>
<li>They (Oracle, but also the JCP) take care of Java, and developers shouldn’t worry about its future.</li>
<li>Oracle’s behavior towards Java is all about transparency. First of all, Open JDK is now the reference implementation of Java. But the most important point is the new JCP 2.8 process, which made all JCP discussions public, and the arrival of new members such as Twitter, and London JUG and SouJUG (Brazil) in executive committees. We can hope that it will allow a lighter mood than last year (with Apache’s resignation).</li>
</ul>
<p>Talking about mood, a good moment to feel opinions differ was the debate we watched on the last day. It involved Mark Reinhold and Brian Goetz from Oracle, Joshua Bloch from Google, Emmanuel Bernard from JBoss, Ben Evans from London JUG and Brian Prince from Microsoft. A lot of questions were really controversial and although most answers were quite evasive, we had a glimpse about the cold war between these companies :</p>
<p>First, it’s always interesting to see different companies’ philosophies, from Oracle, very corporate, Google, open minded with a startup spirit, to JBoss, with a full open-source model. It’s also really unfortunate to see how bad the relations between Oracle and Google are, and to see Oracle guys acting as Android simply doesn’t exist even if it is now the most prevalent mobile OS.</p>
<p>&nbsp;</p>
<p>Apart from Java EE and Java SE, some other hot topics were addressed :</p>
<p>&nbsp;</p>
<h2>Java on the Cloud</h2>
<p>While Java EE 7 should bring standards for a Java PaaS platform next year, these platforms are already here today, and seem really promising: Cloud Foundry from Spring Source and OpenShift from Redhat/JBoss.</p>
<p>Cloud Foundry is available in beta since april 2011. It provides an open PaaS platform under Apache license and offering multi languages support : Java, Ruby, NodeJS … Cloud Foundry can be used either on CloudFoundry.com or any other commercial provider, either on your private cloud, or locally for development purpose with Micro Cloud Foundry. It provides also integration with several third party technologies, and can be fully integrated with Spring Framework.</p>
<p>OpenShift is a promising concurrent to Cloud Foundry, using JBoss and Redhat products. We had a great demo, especially on how to manage applications with JBoss Forge and Git. Some differences from Cloud Foundry are that it is for now restricted to Java, not open sourced yet and that you can’t instantiate it in a private cloud.</p>
<h2>A new generation of application servers</h2>
<p>They made really great efforts in the new version of JBoss Application Server 7. We tested it, and it’s just amazing: fast start (1,7s), low memory usage, fast deploy and undeploy, easy to configure, and testable.</p>
<p>It sounds like other application servers such as Websphere or Weblogic are now far far behind: using this open source server for plain Java EE applications should be considered more than ever.</p>
<h2>Other languages on the JVM<span class="Apple-style-span" style="font-size: 13px; font-weight: normal;"> </span></h2>
<p>Most of you already heard about Scala or Groovy. We will now have to count with Clojure, Ceylon, Kotlin and Fantom which are all new languages on the JVM. Why in the world is everyone creating a language? It seems that everyone now agrees that the JVM is an incredible piece of software but that Java still has space for improvement.</p>
<p>All of them are trying to solve something. Pick you favorite: less line of code, more modularity, having functional programming, make it easy to do parallel programming… My personal guess is that we haven’t found the real “Java killer” yet. But all these great language experiments will certainly give good ideas to its inventor. Meanwhile, these languages are to consider. They might help you on your current project. We had the “silver bullet framework”, now it’s time for the “silver bullet language”. Use them wisely.</p>
<h2>Java &amp; NoSQL</h2>
<p>This year, we saw 2 emerging projects with quite the same goal, but different approaches: Spring Data and Hibernate OGM.</p>
<p>Both of them try to give an abstraction layer on top of NoSQL databases for Java application, particularly for the really tough task which is data denormalization (Chris Anderson showed used really well how hard this point can be).</p>
<p>Where Spring Data started a different project for each type of NoSQL database, Hibernate OGM tries to apply JPA concepts on top of NoSQL databases, starting with Infinispan (an in memory datagrid solution). This approach is quite ambitious but they take the problem step by step: for now, they only handle entity modeling and simple JPQL queries.</p>
<p>&nbsp;</p>
<h1><strong><span style="text-decoration: underline;">Web and HTML5</span></strong></h1>
<p>HTML5 is a really hot topic, and we saw some very appealing demonstrations. While HTML5 isn’t fully standardized yet, most web browsers already support it, except from Internet Explorer.</p>
<p>With HTML5, we can now easily do web offline, game programming, use a webcam and microphone, do voice recognition, but we also have many simplifications in HTML tags.</p>
<p>Google is pushing hard on it. For instance, Paul Kinlan (from Google) gave us a great demo around webkit and Chrome HTML5 features.</p>
<p>Linked to that, everyone is also trying the make it easier to code in the browser. It could be the old way, but easier (jQuery) and the new way (Dart… yes, even Javascript just got competition).</p>
<p>&nbsp;</p>
<h1><strong><span style="text-decoration: underline;">Mobile &amp; Android</span></strong></h1>
<p>As we were five Java-ists we haven’t attended much sessions around mobile, but the Android keynote by Google was clear: the future is mobile. Everything is moving to the mobile so you, developers, should start to move to where the business will be. And you should hire a designer for you GUI…</p>
<p>&nbsp;</p>
<h1><strong><span style="text-decoration: underline;">Conclusion</span></strong></h1>
<p>We are living in interesting time my friends. Java and its developers took a five years vacation (healing from the generics?) but now they’re back. Jump in the train and keep learning. Because they are moving, they are moving fast.</p>
<p>&nbsp;</p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=28155" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/devoxx-2011-the-main-trends/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Complex Event Processing</title>
		<link>http://blog.octo.com/en/complex-event-processing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=complex-event-processing</link>
		<comments>http://blog.octo.com/en/complex-event-processing/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 11:25:59 +0000</pubDate>
		<dc:creator>Mathieu DESPRIEE</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[CEP]]></category>
		<category><![CDATA[Complex event processing]]></category>
		<category><![CDATA[Event Sourcing]]></category>
		<category><![CDATA[events]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=27422</guid>
		<description><![CDATA[Today’s information society abounds in a myriad of information flows, computer-based human collaborations, software agent interactions, electronic business transactions, and the explosion of data on the Internet. Understanding what is happening in these environments is becoming increasingly difficult. In other words, we need to find the best ways to make sense of this wealth of [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/event-sourcing-nosql/' rel='bookmark' title='Event Sourcing &amp; noSQL'>Event Sourcing &#038; noSQL</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p>Today’s information society abounds in a myriad of information flows, computer-based human collaborations, software agent interactions, electronic business transactions, and the explosion of data on the Internet. Understanding what is happening in these environments is becoming increasingly difficult. In other words, we need to find the best ways to make sense of this wealth of data, to improve the quality and availability of information, and to ensure effective responses. Traditional storage and data analysis technologies are not adapted to this exponential growth of volume and event rates.</p>
<p>In addition, the value of information may decay rapidly over time. For instance, some events that may help anticipate a production outage have no value once the outage happened. There is a need to process data as soon as events occur, with respect to latency constraints. We need to move away from traditional client-server (query-response) interaction models, to more asynchronous, event-oriented, loosely coupled push model, with applications able to take decisions based on events data.</p>
<p>Complex Event Processing (CEP) is a set of technologies that allows exploring temporal, causal, and semantic relationships among events to make sense of them in a timely fashion.</p>
<p>This article is the first of a serie exploring these technologies, their capabilities and possible applications.</p>
<p><span id="more-27422"></span></p>
<h2>Some business use cases</h2>
<p>Use cases that may benefit from CEP are varied, but we can identify some patterns in them, showing the decisive contribution of this technology.</p>
<h4>Manufacturing Execution systems</h4>
<p>Event processing can be used in plants to detect anomalies or determine if significant changes require re-planning of production. Plant floor systems push events from numerous sensors to a centralized control system that will explore events patterns and emit new, aggregated, rich events to take decisions.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Active diagnostics of problems, Real-time operational decision</p>
<h4>Location-based services</h4>
<p>RFID tags, mobile phones, and Wi-Fi enabled devices feed information about their spatial location into server-side systems. Applications can be tracking goods in the supply-chain, or pushing information to a customer, based on his mobile phone location.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Information dissemination, Observation systems</p>
<h4>Algorithmic trading</h4>
<p>Heterogeneity of information sources and event rates impose an event processing approach on modern financial IT systems, in which quasi real-time market analytics can hardly be implemented in conventional client-server architectures.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Information dissemination, Real-time operational decision</p>
<h4>Telecommunications</h4>
<p>Near real-time data coming from telecom subsystems could be analyzed together with business data from IT systems, or with historical data. With the use of predictive models, fraud detection can be improved.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Predictive processing, Real-time operational decision</p>
<h4>eCommerce</h4>
<p>Clickstream analysis helps in optimizing user experience on commercial web sites, to adapt advertising, or drive page layout. This requires low latency decision, with immediate pattern recognition.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Real-time operational decision</p>
<h4>Power Utilities</h4>
<p>The utility sector requires an efficient infrastructure for managing electric grids and other utilities. This requires immediate response to variations in consumption, using events coming from numerous data sources, aggregated along the grid.</p>
<p><span style="text-decoration: underline;">Patterns:</span> Real-time operational decision, Active diagnostics, Information dissemination</p>
<p>&nbsp;</p>
<h2>Criteria for adopting a complex event processing approach</h2>
<p><em><strong>“It’s all about time” !</strong></em></p>
<p>The word “<em>complex</em>” in CEP refers mainly to the complexity of <strong>state management over time</strong> while processing the events. Typical examples are:</p>
<ul>
<li>Calculations over sliding windows</li>
<li>Correlation of events along time, such as: determination that event X occurs before event Y within a precise timeframe ; or determination of a non-occurrence within a timeframe.</li>
</ul>
<p>Most CEP implementations also provide advanced pattern detection, such as a non-deterministic finite state automaton, similar to a regular expression search over a flow of events, with influence of time in the search.</p>
<p>Another key influence of time is timeliness. <strong>Timeliness</strong> is the ability to handle events and produce output in a constrained time. It can be seen as end-to-end latency, and can reach the milli-second scale with CEP, or below (cf [perf 1, 3]). CEP tools also provide the ability to arbitrate between guaranteed time and correctness of output (eg. waiting or not for late or unordered events).</p>
<p>Then come event volumes and <strong>rates</strong>: CEP tools performance can exceed 10’000 and even reach 100’000 events/s [perf 1, 2].</p>
<p>&nbsp;</p>
<p>Other complexity factors can also motivate a move towards CEP technologies as well :</p>
<ul>
<li>number and type of event sources</li>
<li>if the application is expected to change over time (new event sources, new interactions and responses)</li>
<li>richness of information in output events: such as counts, averages, composition of events from different sources</li>
<li>context dependant situations: eg. detection of events occurring within a defined spatial distance, or within a defined group of customers (possibly querying an external systems to determine the context)</li>
<li>correlation of real-time data with historical data</li>
<li>intelligence in event processing: eg. inference models or machine learning capable models</li>
</ul>
<p>This table sums up the areas in which event processing could particularly fit (from [Chandy et al 2011]) :<br />
&nbsp;</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td valign="top" width="84"><strong>Event rates</strong></td>
<td valign="top" width="150"><strong>Application complexity</strong> (time, state, context)
</td>
<td valign="top" width="85"><strong>Timeliness</strong></td>
</tr>
<tr>
<td valign="top">High</td>
<td valign="top">High</td>
<td valign="top">High</td>
</tr>
<tr>
<td valign="top">High</td>
<td valign="top">High</td>
<td valign="top">Low</td>
</tr>
<tr>
<td valign="top">High</td>
<td valign="top">Low</td>
<td valign="top">High</td>
</tr>
<tr>
<td valign="top">Low</td>
<td valign="top">High</td>
<td valign="top">High</td>
</tr>
</tbody>
</table>
<p>In other cases, more traditional messaging systems and/or transactional systems may be more suited than CEP.</p>
<p>&nbsp;</p>
<h2>Choosing a CEP technology</h2>
<p>&nbsp;</p>
<div class="mceTemp" style="text-align: center;">
<dl id="attachment_27431" class="wp-caption alignnone" style="width: 310px;">
<dt class="wp-caption-dt"><a href="http://blog.octo.com/wp-content/uploads/2011/11/cep-market-mar2011.png" target="_blank"><img class="size-medium wp-image-27431 " title="CEP Market" src="http://blog.octo.com/wp-content/uploads/2011/11/cep-market-mar2011-300x267.png" alt="CEP Market" width="300" height="267" /></a></dt>
<dd class="wp-caption-dd">CEP Market &#8211; March 2011</dd>
</dl>
</div>
<p>&nbsp;<br />
There are various vendors, having different approaches and paradigms in their event processing products. We can identify the following paradigms [Helmer et al 2011] :<br />
&nbsp;</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="text-align: center;" valign="top"><strong>Paradigm</strong></td>
<td style="text-align: center;" valign="top"><strong>Possible applications</strong></td>
</tr>
<tr>
<td valign="top">Event stream oriented and query based, this can be seen as a continuous query running on an infinite flow of data</td>
<td valign="top">Well suited for aggregation of event data, with SQL-like join logic (between events within the flow or with external DB)</td>
</tr>
<tr>
<td valign="top">ECA (event/condition/action) rule based, this approach having ancestors in active database paradigm (eg. triggers in database)</td>
<td valign="top">Well suited in scenarios where business users should be able to define event patterns, by composing simple rules</td>
</tr>
<tr>
<td valign="top">Inference rule based, with similarities to what can been seen in BRMS</td>
<td valign="top">Well suited when actions have to be taken when certain states are reached ; or in business activity monitoring context with real-time decisions</td>
</tr>
<tr>
<td valign="top">Time-state machine based</td>
<td valign="top">Well suited in monitoring situtations, but with a well defined finite state space</td>
</tr>
</tbody>
</table>
<p>One can see strong similarities with more traditional technologies, ranging from BRMS, to versatile messaging systems (JMS), or EAI.</p>
<p>Beside the ability of CEP to handle very high rates of incoming events, CEP above all brings a coherent set of specific features.</p>
<p>Here is a list that may help you refining your need around CEP :</p>
<p><strong><span style="text-decoration: underline;">Functional capabilities:</span></strong></p>
<ul>
<li>Data Reduction : Filtering, Projection (discarding some attributes), Aggregation over time windows</li>
<li>Modeling capabilities for event shape and payload, and more generally for query logic</li>
<li>Reasoning: Transformation (eg. enrichment, change of shape…), Pattern detection (including detection of the absence of an event)</li>
<li>Time handling : event timestamps, intervals of occurrence, particularly with respect to time windows and pattern detection, sliding time windows (or other kind of moving windows)</li>
<li>Context awareness : taking into account the context in which the event occurs, capability to query external systems (eg. database with business data, or historical data)</li>
<li>Logging and analysis : for audit purposes, or retrospective event processing (understanding precursor events that led to a particular output event)</li>
<li>Prediction, learning and adaptation : pattern discovery, scoring against a data-mining model, or machine-learning capabilities</li>
<li>Presence and capabilities of an integrated development environment (IDE)</li>
</ul>
<p><strong><span style="text-decoration: underline;">Non-functional capabilities :</span></strong></p>
<ul>
<li>Input and output connectivity to event sources and event sinks</li>
<li>Routing (defined statically or dynamically) and partitioning for workload distribution</li>
<li>Performance in response time (end-to-end latency)</li>
<li>Predictability : low variance of latency (e.g. 95-percentile with guaranteed latency), acceptable rate of incoming events before latency increases</li>
<li>Scalability and elasticity</li>
<li>Availability and recoverability : fault tolerance, ability to recover, continuous operation (applying change while the application is running)</li>
<li>Consistency and integrity in a distributed system : management of temporal granularity and potential network delays, clock synchronization</li>
<li>Security and privacy : segregation of event streams, and user habilitations</li>
<li>Usability, Maintainability, Manageability : depending on the kind of users that will be implementing and maintaining the logic (developers and/or business analysts)</li>
</ul>
<p>&nbsp;</p>
<h2>Conclusion and future work</h2>
<p>CEP is more an approach than a technology. On the contrary, there are several types of implementations available, and an even greater number of products on the market. Given the increasing importance of real-time information processing, choosing the best solution for your needs is not an easy task. For this purpose, our next series of articles on CEP will explore several CEP products in detail, and expose their key features.</p>
<p>&nbsp;</p>
<h3>Bibliography</h3>
<p>[Chandy et al 2011]<br />
The event processing manifesto, 2011<br />
Authors : Mani K. Chandy ; Opher Etzion ; Rainer von Ammon</p>
<p>[Grabs et al 2009]<br />
Introducing Microsoft StreamInsight, 2009<br />
Authors : Torsten Grabs, Roman Schindlauer, Ramkumar Krishnan, Jonathan Goldstein</p>
<p>[Helmer et al 2011]<br />
Reasoning in Event-Based Distributed Systems, 2011<br />
Authors : Sven Helmer, Alexandra Poulovassilis, and Fatos Xhafa</p>
<p>[perf 1]<br />
Sybase Aleri performance<br />
<a title="http://m.sybase.com/files/Data_Sheets/SybaseAleri_CEPPlatform_PerfTesting_ds.pdf" href="http://m.sybase.com/files/Data_Sheets/SybaseAleri_CEPPlatform_PerfTesting_ds.pdf" target="_blank">http://m.sybase.com/files/Data_Sheets/SybaseAleri_CEPPlatform_PerfTesting_ds.pdf</a></p>
<p>[perf 2]<br />
Esper performance<br />
<a title="http://esper.codehaus.org/esper/performance/performance.html" href="http://esper.codehaus.org/esper/performance/performance.html" target="_blank">http://esper.codehaus.org/esper/performance/performance.html</a></p>
<p>[perf 3]<br />
StreamBase performance at QCon 2011<br />
<a href="http://qconlondon.com/dl/qcon-london-2011/slides/RichardTibbetts_ComplexEventProcessingDSLForHighFrequencyTrading.pdf" title="http://qconlondon.com/dl/qcon-london-2011/slides/RichardTibbetts_ComplexEventProcessingDSLForHighFrequencyTrading.pdf" target="_blank">http://qconlondon.com/dl/qcon-london-2011/slides/RichardTibbetts_ComplexEventProcessingDSLForHighFrequencyTrading.pdf</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=27422" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/event-sourcing-nosql/' rel='bookmark' title='Event Sourcing &amp; noSQL'>Event Sourcing &#038; noSQL</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/complex-event-processing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The basics of face recognition</title>
		<link>http://blog.octo.com/en/basics-face-recognition/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=basics-face-recognition</link>
		<comments>http://blog.octo.com/en/basics-face-recognition/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 14:00:36 +0000</pubDate>
		<dc:creator>Jan Fajfr</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[face recognitiom]]></category>
		<category><![CDATA[machine learning]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=26401</guid>
		<description><![CDATA[Face Recognition is definitely one of the most popular computer vision problems. Thanks to its popularity it has been well studied over the last 50 years. The first intents to explore face recognition were made in the 60&#8242;s however it was until the 90&#8242;s when Turk and Pentland implemented the &#8220;Eigenfaces&#8221; algorithm, that this field [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/face-recognition-in-web-application/' rel='bookmark' title='Face recognition in RIA applications'>Face recognition in RIA applications</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p>Face Recognition is definitely one of the most popular computer vision problems. Thanks to its popularity it has been well studied over the last 50 years. The first intents to explore face recognition were made in the 60&#8242;s however it was until the 90&#8242;s when Turk and Pentland implemented the &#8220;Eigenfaces&#8221; algorithm, that this field showed some really exciting and useful results. </p>
<h2>Bright future</h2>
<p>Face recognition is recently getting more and more attention and we can anticipate bright future of this field. </p>
<p>Security was historically and will stay in the future the main application of face recognition in practice. Here face recognition can help with both: identification and authentication. Good example is the <a href="http://www.3dface.org/files/slides/080221/7-willich-fraport.pdf">Frankfurt airport</a> security system which uses face recognition to automatize passenger control</a>. Another application can be the security analysis of videos purchased by external city cameras systems. Potential suspects can get identified before committing crime. Take a look at the integration of <a href="http://www.ccsr.cse.dmu.ac.uk/resources/general/ethicol/Ecv12no1.html">face recognition to London Borough of Newham</a>, already in 1998.</p>
<p>Face recognition can be also used to speedup the identification of persons. We can image a systems which would recognize the client as soon as he walks into branch store (bank, assurance), and the front-office worker can than welcome the client by has name and prepare his folder before he actually gets to the counter.</p>
<p>Advertising companies are working on <a href="http://articles.latimes.com/2011/aug/21/business/la-fi-facial-recognition-20110821">ad-boards which would adapt their content to the persons passing by</a>. After analyzing the persons face, commercials would adapt to the gender, age, or even personal style. This usage however, might not conform to privacy laws. Private companies do not have rights to film persons in public places (of course, depending on the country.</p>
<p>Not to forgot, that Google and Facebook had both implemented algorithms to identify users in the huge database of photos which they maintain as part of their social network services. Third party services, such as <a href="http://face.com/">Face.com</a> offer Image base searching, which allow you search for example for picture which contain together your best friends. </p>
<p><span id="more-26401"></span></p>
<p>One of the latest usages is coming also from Google and it is the <a href="http://www.engadget.com/2011/10/18/android-ice-cream-sandwich-adds-face-unlock-feature/">Face Unlock</a> feature, which will as the name says, enable you to unlock your phone after your face has been successfully recognized.</p>
<p>Latest news come to face recognition thanks to new hardware equipment, specially 3D cameras. 3D cameras obtain much better results, thanks to their ability to obtain three dimensional image of your face and solve problems which are the main issues in 2D face recognition (illumination, background detection). <a href="http://www.wired.com/gadgetlab/2010/11/how-facial-recognition-works-in-xbox-kinect/">See the example of Microsoft Kinect </a>, which can recognize you as soon as you walk in front of the camera.</p>
<p>We should keep in mind, that face recognition will be used more and more in the future. This applies not only to face recognition, but to the whole field of machine learning. The amount of data generated every second forces us to find ways to analyze the data. Machine learning will help us to find a way to get meaningful information from the data. Face recognition is just one concrete method from this big area.</p>
<h2>How to get started?</h2>
<p>Several methods and algorithms were developed since than, which makes the orientation in the field quite difficult for the developers or computer scientists coming to face recognition for the first time.</p>
<p>I would like this article to be a nice starter to the subject which will give you three pieces of information:</p>
<ul>
<li>What are the algorithms and methods used to perform face recognition.</li>
<li>Fully describe the &#8220;Eigenfaces&#8221; algorithm.</li>
<li>Show a fully functional example of face recognition using EmguCV library and Silverlight Web Camera features. Go directly to the <a href="http://blog.octo.com/face-recognition-in-web-application/">second part of this article, describing the implementation.</a></li>
</ul>
<h2>Face recognition process</h2>
<p>The process of recognizing a face in an image has two phases:</p>
<ul>
<li><b>Face detection</b> &#8211; detecting the pixels in the image which represent the face. There are several algorithms for performing this task, one of these &#8220;Haar Cascade face detection&#8221; will be used later in the example, however not explained in the article.</li>
<li><b>Face recognition</b> &#8211; the actual task of recognizing the face by analyzing the part of the imaged identified during the face detection phase.</li>
</ul>
<p>Face recognition brings in several problems which are completely unique to this domain and which make it one of the most challenging in the group of machine learning problems.</p>
<ul>
<li><b>Illumination problem</b> &#8211; due to the reflexivity of human skin, even a slight change in the illumination of the image can widely affect the results.</li>
<li><b>Pose changes</b> &#8211; any rotation of the had of a person will affect the performance.</li>
<li><b>Time delay</b> – of course that due to the aging of the human individuals, the database have to be regulary updated.</li>
</ul>
<h2>Methods and algorithms</h2>
<ul>
<li>Apearance based statistical methods are methods which use statistics do define different ways how to measure the distance between two images. In other words they <b>try to find a way to say how similar two faces are to each other.</b> There are several methods which fall into this group. The most significant are:
<ul>
<li>Principal Component Analysis (PCA) &#8211; described in this article.</li>
<li>Linear Discriminant Analysis (<a href="http://www.vcl.fer.hr/papers_pdf/Appearance-based%20Statistical%20Methods%20for%20Face%20Recognition.pdf">more information</a>)</li>
<li>Independent Component Analysis (<a href="http://www.scribd.com/doc/26949768/Face-Recognition-Using-Independent-component-analysis-ICA">more information</a>)</li>
</ul>
<p>PCA is described in this article, others are not. For comparison of these methods refer to <a href="http://www.vcl.fer.hr/papers_pdf/Appearance-based%20Statistical%20Methods%20for%20Face%20Recognition.pdf">this paper</a>
</li>
<li><b>Gabor Filters</b> – filters commonly used in image processing, that have a capability to capture important visual features. These filters  are able to locate the important features in the image such eyes, nose or mouth. This method can be combined with the previously mentioned analytical methods to obtain better results.</li>
<li><b>Neural Networks</b> are simulating the behavior of human brain to perform machine learning tasks such as classification or prediction. In our case we need the classification of an image. The explication of Neural Networks would take at least one entire article (if not more). Basically Neural Network is a set of interconnected nodes. The edges which are between the nodes are weighted so the information which travels between two nodes is amplified. The information travels from set of input nodes, across a set of hidden nodes to a set of output nodes. The developer has to invent a way to encode the input (in this case an image) to a set of input nodes and decode the output (in this case a label identifying the person) from the set of output points.<br />
Commonly used method is to take one node for each pixel in the image on the input side of the network and one node for each person in the database on the output side as ilustrated on the following image:<br />
<a href="http://blog.octo.com/wp-content/uploads/2011/10/neural_network_face.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/neural_network_face-300x135.png" alt=" Neural Network for Face Recognition" title=" Neural Network for Face Recognition" width="300" height="135" class="aligncenter size-medium wp-image-26534" /></a><br />
For more information about face recognition using Neural Networks visit <a href="http://wwwteor.mi.infn.it/~rojo/teaching/ImageRec1.pdf">this link</a>
</li>
</ul>
<h2>Eigenfaces algorithm and PCA</h2>
<p>The eigenfaces algorithm follows the pattern which is followed by other statistical methods as well (LDA, ICA):</p>
<ol>
<li>Compute the distance between the captured image and each of the images in the database.</li>
<li>Select the example from the database, which is closest to the processed image (the one with the smallest distance to captured image).</li>
<li>If the distance is not too big – label the image as concrete person.</li>
</ol>
<h2>What is the distance between two images?</h2>
<p>The crucial question is: <b>How to express the distance between two images?</b> One possibility would be to compare the images pixel by pixel. But we can immediately feel, that this would not work. Each picture would contribute the same to the comparison, but not each pixel holds valuable information. For example background and hair pixels would arbitrary make the distance larger or smaller. Also for direct comparison we would need the faces to be perfectly aligned in all pictures and we would hope that the rotation of the head was always the same.</p>
<p>To overcome this issue the PCA algorithm creates a set of principal components, which are called eigenfaces. Eigenfaces are images, that represent the main differences between all the images in the database.<br />
The recognizer first finds an <b>average face</b> by computing the average for each pixel in the image.<br />
Each eigenface represents the differecens from the avarage face. First eigenface will represent the most significant differences between all images and the average image and the last one the least significant differences.</p>
<p>Here is the <b>average image</b> created by analyzing the faces of 10 consultants working at OCTO Technology, having 5 image of each consultant.</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/avg.jpg"><img src="http://blog.octo.com/wp-content/uploads/2011/10/avg.jpg" alt="Average Image create by the Eigenrecognizer while analysis about 100 images." title="Avarage Image" width="80" height="80" class="aligncenter size-full wp-image-26411" /></a></p>
<p>And here are the first 5 Eigenfaces:</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/eigenfaces.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/eigenfaces.png" alt="First 5 eigenfaces create by analyzing set of training images" title="Eigenfaces" width="404" height="79" class="aligncenter size-full wp-image-26416" /></a></p>
<p>Note that the consultants at OCTO are generally handsome guys and this ghost-look is characteristic to the eigenfaces of any group of persons. You can also notice that there is one face which is dominant. That is due to the fact that I had just limited number of pictures of my colleges and I could take a lot of myself using web cam. This way my face become a little dominant over others.</p>
<p>Now when we have the average image and the eigenfaces, each image in the database can be represented as composition of these. Let’s say:</p>
<p><strong>Image1 = Avarage Image + 10% Eigenface 1 + 4% Eigenface 2 + … + 1% Eigenface 5</strong></p>
<p>This basically means that we are able to express each image as a vector of percentages. The previous image becomes to<br />
our recognizer just a vector <b>[0.10, 0.4, … , 0.1].</b> The previous equation is a slight simplification of the subject. You might be asking yourself how are the coefficients of each eigenface computed. If we would enter into the details, </p>
<p>Now when we have expressed the image as a simple vector, we are able to say what is the distance between two images. Getting the distance of two vectors is not complicated and most of us remember it from school.</p>
<p>If in 2D space we have the vectors <strong>[x1,y1]</strong> and <strong>[x2,y2]</strong> we now that the distance between these two can be visualized and computed as shown in the following picture:</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/distance_image.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/distance_image.png" alt="" title="distance_image" width="292" height="169" class="aligncenter size-full wp-image-26544" /></a></p>
<p>Now we can perform similar calculation for the vectors which represent our images.</p>
<h2>Behind the scenes</h2>
<p>This part will give you some more insights into how exactly are the eigenfaces computed and what is going on behind the scenes. Feel free to skip it if you do not want to enter more into the details.</p>
<p>The key point in the PCA is the reduction of dimensional space. The question we could pose us is, how would we compare the images without eigenfaces. We would simply have to compare each pixel. Having and image with resolution 50 x 50 pixels, that would give us 2500 pixels, in other words we would have space of 2500 dimensions. When comparing using the eigenvalues we arrived to reduce the dimensional space – the number of eigenfaces is the number of dimensions in our new space.</p>
<p>Remember the equation of the distance of two points – now in this equation each pixel would contribute to the distance between images. But not each pixel holds some meaningful information. The background behind the face, the cheeks, the forehead, hairs – these are the pixels which do not give meaningful information about the face. Instead the eyes, nose, ears are important.  In the terms of Image processing lot of pixels just bring noise to the computation of the distance. One of the main ideas of PCA is the reduction of the noise by reducing the number of the dimensions.</p>
<h2>Reducing the number of dimensions</h2>
<p>You may be asking yourself, how exactly can we reduce the number of dimensions? It is not easy to imagine the transition from a space where each pixel is one dimension to a space where each eigenface is one dimension. To understand this transition, take a look at this example:</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/dimension_reduction.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/dimension_reduction.png" alt="Dimension reduction" title="Dimension reduction" width="316" height="192" class="aligncenter size-full wp-image-26546" /></a></p>
<p>In two-dimensional space, each point is defined by its two coordinates. However if we know, that several points lay on the same line, we could identify the position of each point only by knowing it&#8217;s position along the line. To obtain the x and y coordinate of the point we would need to know the slope of the line and the position of the point on the line. We have reduced the dimension by one. In this example the slope of the line becomes the principal component, the same way our eigenfaces are principal components during the face recognition algorithm. Note that we can even estimate the position for the points which are not on the line, by using the projection of the point on the line (the case of the last point).</p>
<p>From mathematical point of view eigenfaces are graphical representation of eigenvectors (sometimes called characteristic vectors) of co-variance matrix representing all the images. That it how they got their name. For more details on Principal Component Analysis and computation of eigenvectors and eigenfaces visit the following links: <a href="http://www.cognotics.com/opencv/servo_2007_series/part_4/index.html">PCA</a> and <a href="http://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors">Eigenvectors</a></p>
<h3>Isn&#8217;t there an easy way?</h3>
<p>You might be thinking, that this is too complex as introduction to the subject and you might be asking yourself whether there is an easy way to start with face recognition?</p>
<p>Well yes and no. Eigenfaces algorithm is the base of the research done in face recognition. Other analytic methods such as Linear Component Analysis and Independent Component Analysis build on the foundations defined by the eigenfaces algorithm. Gabor filters are used to identify the important features in the face and later eigenfaces algorithm can be used to compare these features.<br />
Neural Networks are complex subject, but it has been shown that rarely they have better performance then eigenfaces algorithm. Sometimes the image is first defined as linear combination of eigenfaces and than it&#8217;s describing vector is passed to the Neural Network. In other words eigenfaces algorithm builds really the base of face recognition.<br />
There are several open-source libraries which have implemented one or more of these methods, however as a developers we will not be able to use them without understanding how these algorithms work.</p>
<p>Enough of theory now! <a href="http://blog.octo.com/en/face-recognition-in-web-application/">Visit the second part of the article to see how to include face recognition into your web application.</a></p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=26401" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/face-recognition-in-web-application/' rel='bookmark' title='Face recognition in RIA applications'>Face recognition in RIA applications</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/basics-face-recognition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Face recognition in RIA applications</title>
		<link>http://blog.octo.com/en/face-recognition-in-web-application/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=face-recognition-in-web-application</link>
		<comments>http://blog.octo.com/en/face-recognition-in-web-application/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 14:00:14 +0000</pubDate>
		<dc:creator>Jan Fajfr</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[EmguCV]]></category>
		<category><![CDATA[face recognition]]></category>
		<category><![CDATA[silverlight]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=26551</guid>
		<description><![CDATA[Face recognition is exciting machine learning task which during the last decade has brought some good results, used mainly in security applications to perform person identification. However it used to be reserved only to university research and implemented only by companies specializing in this field. But the time invested into this field by universities, companies [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/basics-face-recognition/' rel='bookmark' title='The basics of face recognition'>The basics of face recognition</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p>Face recognition is exciting machine learning task which during the last decade has brought some good results, used mainly in security applications to perform person identification.<br />
However it used to be reserved only to university research and implemented only by companies specializing in this field.</p>
<p>But the time invested into this field by universities, companies and independent developers has brought its result in the means of several open-source libraries which any developer can use to perform image processing tasks including face recognition. Take a look at the <a href="http://www.cvpapers.com/rr.html">complete overview of existing computer vision algorithms and libraries.</a></p>
<p>This article will show you how to incorporate face recognition into your web page using <a href="http://www.emgu.com/wiki/index.php/Main_Page">EmguCV</a> image processing library and Silverlight Web Camera features. EmguCV is a .NET wrapper for <a href="http://opencv.willowgarage.com/wiki/">OpenCV</a> library, written in C++ by Intel and published as open-source. The method which will be used is Eigenfaces algorithm. If you are interested in the details of this algorithm, please refer to the previous article on this topic: <a href="http://blog.octo.com/en/basics-face-recognition/">The basics of face recognition</a>.</p>
<p><span id="more-26551"></span></p>
<p>This post describes quite simple application which consists of two parts &#8211; Silverlight client, which is responsible for the image capture and eventually pre-processing and the server part which performs the actual face detection and face recognition.</p>
<h2>Capturing the image with Silverlight</h2>
<p>Since the version 4 Silverlight gives us the possibility to use the camera to capture images or videos using the <b>CaptureSource</b> class. The following snippet shows how to access the camera and show directly the capture picture.</p>
<pre class="brush:csharp">
CaptureSource captureSource = new CaptureSource();
captureSource .VideoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
captureSource .CaptureImageCompleted += new EventHandler&lt;CaptureImageCompletedEventArgs&gt;(captureCompleted);

if (captureSource .State != CaptureState.Started)
{
    // Create video brush and fill the WebcamVideo rectangle with it
    var vidBrush = new VideoBrush();
    vidBrush.Stretch = Stretch.Uniform;
    vidBrush.SetSource(captureSource);
    WebcamVideo.Fill = vidBrush;

    // Ask user for permission and start the capturing
    if (CaptureDeviceConfiguration.RequestDeviceAccess())
        captureSource .Start();
}
</pre>
<p>Notice that I have to set the callback for the <b>CaptureImageCompleted</b> event. That should not surprise you, if you have worked with Silverlight before. Blocking of the user interface is not allowed, and so all operations depending on external sources are asynchronous. Now lets take a look at what happens when the image is actually captured:</p>
<pre class="brush:csharp">
private void captureCompleted(object sender, CaptureImageCompletedEventArgs e)
{
    var image = e.Result;
    var coll= new ObservableCollection&lt;int&gt;(image.Pixels);
    switch(appMode)
    {
        case AppMode.Recognition:
            client.RecognizeAsync(coll,image.PixelWidth);
            break;
        case AppMode.Training:
            client.TrainFaceAsync(coll, image.PixelWidth,TextBoxLabel.Text);
    }
}
</pre>
<p>As a result, we obtain <b>WritableBitmap</b> object, which has a simple <b>Pixels</b> property of type <b>int[]</b>. This property holds all the pixels of the image in one dimensional array created by aligning all the rows of the image to one array. Notice that each pixel is presented as Int– this means that that we have a classic 32bits representation of color for each pixel.</p>
<p>We take this array and we send it to the server. When the application is in training mode, we send also the label, which should be added to the Image. If the application is in recognition mode, we send just the image and we hope to receive the label describing the person on the image.</p>
<h2>Face recognition using EmguCV on the server</h2>
<p>As described in the previous article, face recognition has two phases: Face detection, and actual face recognition. We will use EmguCV to perform both of these tasks. EmguCV is a wrapper for OpenCV library. This basically means that we can call all the functions inside OpenCV library without the need of using constructs such as DLLImport directive and without the need of knowing the structure of the OpenCV library.</p>
<p>EmguCV is surely more friendly for C# developers than OpenCV (at least we do not have to treat the pointers), on the other hand the documentation is not perfect. Several times you will have to address directly the documentation of OpenCV to understand the structures and methods. For this point of view it is important to understand the algorithms which you want to use from EmguCV/OpenCV, because you will have hard-time finding the documentation to understand what each method does.</p>
<h3>Detecting the face</h3>
<p>I have created a function which takes the array of pixels, and the size of the image, converts the picture to gray scale, detects the face, trims the rest of the image and resizes the resulting image to demanded size, just as shown in the following picture:</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/detect_trim.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/detect_trim.png" alt="Detection and trimming" title="Detection and trimming" width="296" height="119" class="aligncenter size-full wp-image-26557" /></a></p>
<pre class="brush:csharp">
public static Image&lt;Gray, byte&gt; DetectAndTrimFace(int[] pixels, int iSize, int oSize)
{
    var inBitmap = ConvertToBitmap(pixels, iSize);
    var grayframe = new Image&lt;Gray, byte&gt;(inBitmap);
    var haar = new HaarCascade(getHaarCascade());
    var faces = haar.Detect(grayframe,1.2,3, HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(30,30));
    if (faces.Count() != 1)
        return null;

    var face = faces[0];
    var returnImage = grayframe.Copy(face.rect).Resize(oSize, oSize, INTER.CV_INTER_CUBIC);
    return returnImage;
}
</pre>
<p>The standard structure to treat images inside EmguCV is <b>Image&lt;ColorType, depth&gt;</b>. So from the previous code snippet you can see, that we are returning gray-scales image, where each pixel has 8 bits (byte structure). We first have to reconstruct an Bitmap image from pixels array and than create Image&lt;Gray, byte&gt; object from resulting Bitmap. In this step EmguCV converts automatically the image to gray-scale.</p>
<p>Next the face detection is performed using <a href="http://www.cognotics.com/opencv/servo_2007_series/part_2/sidebar.html"><b>HaarCascade</b></a> detection algrorithm. The description of this algorithm is not part this article.<br />
Once the face is detected (and if there was only one face), we copy the rectangle wrapping the face and resize it to demanded output size.<br />
It is important to use the same size, when adding the image to the training set and recognizing the face from the image.</p>
<p>For actual recognition EmguCV contains <b>EigenObjectRecognizer</b> class, which needs several arguments to be created:</p>
<ul>
<li>Array of images and corresponding array of labels.</li>
<li><b>Eigen Distance Threshold</b> – Eigenfaces algorithm measures the distance between images. This thresholds defines the maximal distance needed to classify the image as concrete person. Big values such as 5000 will make the classifer to return the closest match, even if the probability that the person has been recognized is quite small. Set it to 500 to obtain some reasonable results.</li>
<li><b>MCvTermCriteria</b> – is a class which represents OpenCV structure for terminating iterative algorithms. It is composed of two numbers the first being the number of iterations and the second one is demanded accuracy. For some algorithm it makes sense to iterate until the accuracy is not bellow certain threshold. For eigenfaces algorithm it is the number of iterations which is important and it will impact the number of eigenfaces being created. I have obtained some good results having around 40 eigenfaces for 100 images in the database, but this might depend on your scenario, quality and diversity of the images.</li>
</ul>
<pre class="brush:csharp">
MCvTermCriteria termCrit = new MCvTermCriteria(40, accuracy);
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
                 trainedImages.ToArray(),
                 labels.ToArray(),
                 eigenDistanceThreshold,
                 ref termCrit);
</pre>
<h3>Face recognition</h3>
<p>The actual face recognition is a piece of cake if we already know how to create the recognizer. First we have to detact and extract the face from the image with the help of previously mentioned DetectAndTrimFace method. And the second step is to pass this image to the recognize method of the recognizer.</p>
<pre class="brush:csharp">
public String Recognize(int[] pixels, int size)
{
   var imgFace = ImagesProcessing.DetectAndTrimFace(pixels, size,
   var recognizer = ImagesProcessing.CreateRecognizer(folder, ...);
   String label = recognizer.Recognize(imgFace);
   if(!String.IsNullOrEmpty(label))
       return label;
   return "Could not recognize";
}
</pre>
<h3>Adding the picture to the training set</h3>
<p>This again is easy. Once we do the face detection and trimming, we will just see if there is a folder for the given label and if not, we will create one. One option is to use Guid as a name of file to be sure, that we wont have collisions.</p>
<pre class="brush:csharp">
[OperationContract]
public void AddToTraining(int[] pixels, int size, String label)
{
    var faceImg = ImagesProcessing.DetectAndTrimFace(pixels, size, fixedFaceSize);
    var directoryNames = GetDirectories();
    //no such label - create directory
    if (!directoryNames.Contains(label))
        Directory.CreateDirectory(DIR + "\\" + label);

    faceImg.Save(DIR+ "\\" + label + "\\" + Guid.NewGuid().ToString() + "_" + fixedFaceSize + ".jpg");
}
</pre>
<h3>Performance</h3>
<p>The face-detection phase is quite instantaneous. Using the HaarCascade algorithm to detect face in the image, we have a chance, that OpenCV already offers a set of HaarCascade features. The creation of these features is much more time consuming, than their usage. </p>
<p>The face-recognition phase is also not that time-consuming. In this example I was working with database of 100 images (10 persons, each having in average 10 images, each image being 80&#215;80 pixels). In this setting the creation of the recognizer is almost instant. Surely the read access of images from the disk, takes more time than, the actual creation of recognizer (the eigenfaces algorithm).</p>
<p>If we have a database of pictures which does not change, we create the recognizer only once and than share it every-time there is a request for recognition. This of course is not possible when the image database changes. In that case we have to recreate the recognizer. There is no possibility to add new image to existing recognizer.</p>
<p>The bottleneck of this approach is still the network over which we have to pass the image from client to the server. To minimize the data which has to be transfer, take a look at the tip which shows you, how to perform the face detection on the client side at the end of the article.</p>
<h3>Tricks and tips</h3>
<p><b>Equalization of the image</b><br />
Histogram equalization is a technique to improve the contrast and adjust the brightness of the image. EmguCV gives us the possibility to call the equalize function which resides in OpenCV:</p>
<pre class="brush:csharp">
public static Image&lt;Gray, byte&gt; EqualizeHist(Image&lt;Gray, byte&gt; input)
{
    Image&lt;Gray, byte&gt; output = new Image&lt;Gray, byte&gt;(input.Width, input.Height);
    CvInvoke.cvEqualizeHist(input.Ptr, output.Ptr);
    return output;
}
</pre>
<p>Take a look at the picture before and after equalization:<br />
<a href="http://blog.octo.com/wp-content/uploads/2011/10/equalization.png"><img src="http://blog.octo.com/wp-content/uploads/2011/10/equalization.png" alt="Histogram equalization of image" title="Equalization" width="329" height="125" class="aligncenter size-full wp-image-26556" /></a> </p>
<p><b>Creating additional images</b><br />
Generally the results are better when the training set is large. If we do not have enough images, we can try to create new ones by slight rotation or horizontal flipping. EmguCV gives us the possibility to call Flip or Rotate method on each picture:</p>
<pre class="brush:csharp">
var fliped = faceImg.Flip(FLIP.HORIZONTAL);
var rotated = faceImg.Rotate(angle, new Gray(0.3));
</pre>
<p>Of course we have to be careful only to use Horizontal flipping (faces upside-down would just confuse the recognizer) and to rotate just to some angle.<br />
<b>More image treatment on the client side</b><br />
In the presented code, you can notice, that I am sending the image to the server, right after image capture, without any preprocesing. Because the default size of the image is 640&#215;480 pixels. Knowing that each pixel is represented by 32 bit Integer this means that we are sending roughly 1200 kB to the server for recognition or training. Since images are resized later anyway, we could resize them directly before sending to the server. Resizing the images to 320*240 would reduce the size of send data to 300 kB (but of course we can do more).<br />
Unfortunately Silverlight does not have method for resizing images, however there is a <a href="http://writeablebitmapex.codeplex.com/">great project on Codeplex</a>, which contains several extensions methods for WritableBitmap, one of them being the resize method.<br />
<b>Face detection on client side</b><br />
It is not possible to move all the face recognition process to the client side, from one simple reason: the recognizer has to, at some point, load and process all the images in the database. Performing this part on the client side, would demand us either to embark all the images into the client or transfer these images over the wire. Either of these options is not attractive for web developers.<br />
However the process of face detection could be moved to the client side, while it is not dependent on any big amount of external data. Great article which explains face detection in Silverlight is available as <a href="http://channel9.msdn.com/coding4fun/articles/FaceLight--Silverlight-4-Real-Time-Face-Detection">FaceLight project on Channel 9</a></p>
<h3>Will we log to our bank using only our web camera?</h3>
<p>Well the answer is no, face recognition is still not completely trust-worthy. Eigenface algorithm presented above is too much sensitive on the brightness changes and face-pose changes. When testing the algorithm, I obtained successful results in 60-70% of the total tries. However new algorithms have been developed combining several image processing and face recognition techniques and of course many companies are specializing in this field and develop software with much better accuracy.</p>
<p>Another problem is the fact that it is far too easy to present a taken photograph to the web camera and unless the system is capable of recognizing the real person from taken picture it will be cheated.</p>
<p>We will probably see mutual systems where the login and password will still be the main security check and face recognition will be used instead of the third confirmatory information such as RSA generated number or confirmation code.</p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=26551" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/basics-face-recognition/' rel='bookmark' title='The basics of face recognition'>The basics of face recognition</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/face-recognition-in-web-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Droidcon London 2011</title>
		<link>http://blog.octo.com/en/droidcon-london-2011/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=droidcon-london-2011</link>
		<comments>http://blog.octo.com/en/droidcon-london-2011/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 15:56:21 +0000</pubDate>
		<dc:creator>Jérôme Van Der Linden</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[droidcon]]></category>
		<category><![CDATA[mobility]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=26521</guid>
		<description><![CDATA[This year, we had the opportunity to go to the Droidcon in London, a great conference about mobility and Android. The two-day event was organized like in 2010: a barcamp the first day, and conferences with great speakers the second one. Main topics were user experience and interface, Android development, mobile apps business and distribution. [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/droidcon-london-2010/' rel='bookmark' title='Droidcon London 2010'>Droidcon London 2010</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p style="text-align: center;"><a href="http://uk.droidcon.com/" target="_blank"><img class="aligncenter size-full wp-image-26523" title="Droidcon" src="http://blog.octo.com/wp-content/uploads/2011/10/droidcon.png" alt="Droidcon UK 2011" width="383" height="153" /></a></p>
<p>This year, we had the opportunity to go to the <a href="http://uk.droidcon.com/" target="_blank">Droidcon</a> in London, a great conference about mobility and Android. The two-day event was organized like in 2010: a barcamp the first day, and conferences with great speakers the second one. Main topics were user experience and interface, Android development, mobile apps business and distribution.<br />
<span id="more-26521"></span></p>
<h1></h1>
<h1>User eXperience</h1>
<p>The number of Android users has incredibly risen! More than 300 000 applications can be downloaded on the market! What makes your app better and prevent it from user rejection ? Look and feel and responsiveness, of course!</p>
<p>&nbsp;</p>
<h2>Make your application smooth!</h2>
<p>This year, Cyril Mottier talked about UI and gave pieces of advice to develop pretty and fluid applications. It starts with a simple order: <strong>do not block the UI thread</strong> because it is the one that displays elements on screen and handle interaction with the user. Using it for non UI process leads to slow animations, laggy interface and if five-second freeze occurs: Application Not Responding messages!<br />
Android SDK offers <a href="http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html#Threads">several ways</a> to <strong>handle secondary threads for non UI processes</strong>: execute it with simple <a href="http://developer.android.com/reference/java/lang/Thread.html">Threads </a>and <a href="http://developer.android.com/reference/android/os/Handler.html">Handlers</a> (maybe with a <a href="http://developer.android.com/reference/android/os/Looper.html">Looper</a> to do <a href="http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/">operation queues</a>), create an <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask </a>or even launch a dedicated service with the <a href="http://developer.android.com/reference/android/app/IntentService.html">IntentService </a>class.<br />
Likewise, <strong>access your data asynchronously</strong>: <a href="http://developer.android.com/reference/android/content/AsyncQueryHandler.html">AsyncQueryHandler</a>, <a href="http://developer.android.com/reference/android/widget/Filter.html">Filter</a> and <a href="http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply%28%29">SharedPreference.Editor.apply()</a> can help you.</p>
<p>&nbsp;</p>
<h2>Use great components</h2>
<p>All recent successful applications understood it: nice and customized views are the key! Cyril Mottier’s open-source library <a href="http://greendroid.cyrilmottier.com/">GreenDroid</a> is one of the most known. It allows you to ease development by using its theme and numerous features for pre-Honeycomb application (and after with <a href="http://developer.android.com/sdk/compatibility-library.html#Downloading">compatibility package</a>): ActionBar, AsyncImageView, PagedView, QuickActions and more!</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/Greendroid1.png"><br />
</a><a href="http://blog.octo.com/wp-content/uploads/2011/10/Greendroid2.png"><img class="aligncenter size-large wp-image-26668" title="Greendroid" src="http://blog.octo.com/wp-content/uploads/2011/10/Greendroid2-1024x318.png" alt="" width="451" height="139" /></a></p>
<p><a id="internal-source-marker_0.9685494486643224" href="https://market.android.com/details?id=com.cyrilmottier.android.gdcatalog">GDCatalog application</a> is available on the Android market to demonstrate the capabilities of this very useful library.</p>
<p>&nbsp;</p>
<h2>Follow Google best practices to optimize your app for smartphones and tablets</h2>
<h3>ActionBar</h3>
<p>Nick Butcher introduced some guidelines to design UIs for both kinds of devices. The most noticeable UI Pattern that has become unavoidable is the ActionBar. Its aim is to<strong> help the user accessing screen details and contextual actions</strong>. This action bar places elements in a way to help user interactions. See GMail example below.</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/ActionBar-example1.png"><img class="aligncenter size-large wp-image-26774" title="ActionBar example" src="http://blog.octo.com/wp-content/uploads/2011/10/ActionBar-example1-1024x385.png" alt="" width="1024" height="385" /></a></p>
<p>On the left side, the application icon informs the user where he is. As on a website, a click on this button leads to the application main screen. A second way to navigate inside the application flow is offered by the in-app navigation button. This action can be different from traditional Android back button. The right side presents traditional application parameters button and contextual actions. More contextual informations can be added to the bar under certain conditions (items selection, etc.).<a href="http://blog.octo.com/wp-content/uploads/2011/10/ActionBar-2.png"><br />
</a></p>
<p>To implement an ActionBar on pre-Honeycomb Android version, you can use <a href="http://code.google.com/p/iosched/">Google I/O application</a> implementation, <a href="http://actionbarsherlock.com/">ActionBarSherlock </a>or previously presented <a title="Greendroid ActionBar" href="http://android.cyrilmottier.com/?p=274" target="_blank">GreenDroid</a> libraries. Upper versions (v3+) can use <a href="http://developer.android.com/guide/topics/ui/actionbar.html">SDK ActionBar</a>.</p>
<p>With the upcoming Ice Cream Sandwich version, ActionBar will be able to <strong>automatically layout the interface for phone or tablet</strong>. Little advice for this: provide text and icons for each Action item and set for each one the flag: <code>showAsAction=“ifRoom|withText”</code>.</p>
<p><a href="http://blog.octo.com/wp-content/uploads/2011/10/actionbar-phone-tablet.png"><img class="aligncenter size-full wp-image-26755" title="actionbar-phone-tablet" src="http://blog.octo.com/wp-content/uploads/2011/10/actionbar-phone-tablet.png" alt="" width="751" height="398" /></a></p>
<h3>Multi-pane layouts</h3>
<p>Since Honeycomb, a single APK can be executed on both smartphones and tablets. On large screens, it is preferred to display more complete content than a simple ListView. With <strong><a href="http://developer.android.com/guide/topics/fundamentals/fragments.html">Fragments</a></strong>, it is possible to <strong>aggregate your code</strong> to use it on 2 smartphone screens and a single tablet screen. With this concept, you can imagine a lot of different screen dispositions depending of screen sizes, orientation, etc. We will talk about this subject in a next article.</p>
<h3><a href="http://blog.octo.com/wp-content/uploads/2011/10/fragments.png"><img class="aligncenter size-full wp-image-26765" title="fragments" src="http://blog.octo.com/wp-content/uploads/2011/10/fragments.png" alt="Fragments usage" width="483" height="275" /></a></h3>
<h3>Do&#8217;s and don&#8217;ts</h3>
<p>Simple tips were given to improve development:</p>
<ul>
<li>aim for a single APK for both tablet and handset devices</li>
<li>use <a href="http://developer.android.com/sdk/compatibility-library.html">compatibility library</a></li>
<li>customize every view to represent your brand</li>
<li><strong>support both landscape and portrait modes</strong></li>
<li>extract dimensions for phones and tablets (e.g. values/dimens.xml and values-large/dimens.xml)</li>
<li>use themes and styles to reduce code redundancy</li>
<li>enable <a href="http://android-developers.blogspot.com/2011/03/android-30-hardware-acceleration.html">hardware acceleration</a></li>
</ul>
<p>And other to avoid in your application:</p>
<ul>
<li>do not use small fonts</li>
<li>tablets are not &#8220;big phones&#8221;: they fulfill a different need and <strong>require special layout optimizations</strong></li>
<li>do not assume that a device running an application with API level &gt;= 11 is a tablet: Ice Cream Sandwich is coming for both tablet and phones!</li>
<li>do not assume that all tablets have an xlarge resolution: 7&#8221; tablets have a large resolution! Detect tablets with the minimal width your application needs, generaly 600 dp:</li>
</ul>
<p>&nbsp;</p>
<pre>         &lt;manifest ... &gt;
              &lt;supports-screens android:requiresSmallestWidthDp="600" /&gt;
              ...
         &lt;/manifest&gt;</pre>
<p>&nbsp;</p>
<h1>A bit of technique</h1>
<h2>Testing</h2>
<p>You may have seen comments such as &#8220;Doesn&#8217;t work on SGSII&#8221; or &#8220;Force close on HTC Wildfire&#8221; on Android Market. Indeed, with no less than 300 phone models, it is difficult to provide an application that works on each device. The best way to minimize bugs is to test your application. You can do it manually or with low cost outsourced hands but the best way is to automate your tests.</p>
<p style="text-align: center;"><img class="aligncenter size-medium wp-image-26662" title="Android Test Frameworks" src="http://blog.octo.com/wp-content/uploads/2011/10/screen-capture-5-300x150.png" alt="Android Test Frameworks" width="300" height="150" /></p>
<p>Several frameworks exist and cover different kinds of tests:</p>
<ul>
<li><a title="Monkey" href="http://developer.android.com/guide/developing/tools/monkey.html" target="_blank">Monkey</a>, which ensures to simulate random actions on the UI (buttons, textedit, touch&#8230;). This is a good way to validate the robustness of the application.</li>
<li>The Google test api (<a href="http://developer.android.com/guide/topics/testing/testing_android.html" target="_blank">instrumentation</a>) which can be laborious to implement although essential if you want to test the interface behavior.</li>
<li><a href="http://code.google.com/p/robotium/" target="_blank"><strong>Robotium</strong></a>, a good testing framework, that simplifies the test writing over the Google&#8217;s instrumentation tests.</li>
</ul>
<p>We also came across two other frameworks (plateforms):</p>
<ul>
<li><a href="http://pivotal.github.com/robolectric/index.html" target="_blank"><strong>Robolectric</strong></a> comes with a great advantage over robotium and instrumentation: <strong>you don&#8217;t need an emulator</strong> to test your application, and everyone knows how much the emulator is slow! So, you run your tests in a standard JVM, in your favorite IDE and you gain a lot of time. Joe Moore (from Pivotal Labs) made a demo with a set of 20 tests. The standard instrumentation test took 45s on an emulator (already launched, so you can easily add one minute for the launch) while robolectric got the job done in only 12s! Moreover, it is very simple to use, simply add <code>@RunWith(RobolectricTestRunner.class)</code> on your test classes and that&#8217;s it! Give it a try, it&#8217;s free. You can get the slides <a href="http://www.slideshare.net/joemoore1/droidconuk-tdd-android-with-robolectric" target="_blank">here</a>.</li>
</ul>
<ul>
<li>All the previous solutions are either boring to implement (manual creation of the tests), nor realistic (emulator, JVM). <a href="http://bitbar.com/products" target="_blank"><strong>Testdroid</strong></a> (developed by Bitbar) promises to answer to both issues with two services:<br />
<strong>Testdroid recorder</strong>, an eclipse plugin, ensures to capture your test while you execute the application. It generates robotium code, so you can replay the tests after.<br />
<strong>Testroid server</strong> is a cloud platform that allows to automatically execute the recorded tests on multiple Android physical devices. A lightweight DeviceAnywhere? Seems promising to test your applications on real devices, on different Android releases, with different form factors&#8230;</li>
</ul>
<p>&nbsp;</p>
<h2>Do Not Repeat Yourself</h2>
<p>In our projects, a lot of tasks are repeated. The session &#8220;Kick-starting Android Application Development&#8221; presented some interesting projects to improve Android development:</p>
<p><a href="https://github.com/jvoegele/gradle-android-plugin/wiki">Android plugin for Gradle</a> project allows to use Gradle to reduce time spent on APK build, packaging, integration, etc. It can be use in integration with Maven or Ant and also allows to create Android applications in Scala.</p>
<p><strong><a href="http://code.google.com/p/roboguice/">Roboguice</a></strong>, is a Google implementation of Guice to <strong>use dependency injection</strong>. It uses reflection to inject fields at runtime and allows to get rid of resources initialization, service creation,&#8230; A simple demonstrative example to get a TextView instance:<code> @InjectView(R.id.name) TextView nameTextView;</code><br />
Another similar project (<a href="http://code.google.com/p/androidannotations/">AndroidAnnotations</a>), based on subclass code generation instead of reflection, allows to inject content with no runtime impact on performances.</p>
<p>&nbsp;</p>
<h1>Application distribution</h1>
<p>Several sessions were related to application distribution, and how to improve your application and its ranking on the Market. Here are some tips from Caroline Lewko (Wireless Industry Partnership), Thai Tran (LightBox) and Konstantinos Polychronis (Bugsense).</p>
<p>&nbsp;</p>
<h2>Do not forget marketing!</h2>
<p>Nowadays, publishing an application and keeping it visible on the stores is a challenge. WIP shared several tips to make your application successful through time. First of all, as <strong>mobile is growing fast</strong>, you have to follow the same rule! A way to move at same speed is to make <strong>short Agile development cycles</strong> and for each, a <strong>marketing review of the product</strong>. Marketing&#8217;s role is to ensure that the application always fits the market&#8217;s needs, try different implementations (<a href="http://en.wikipedia.org/wiki/A/B_testing">A/B testing</a>). It keeps the product uptodate and brings opportunities to &#8220;fail fast&#8221; instead of achieving a useless application.</p>
<p>Once you have a product that grows fast, you have to make your customers like it! It starts with a good name. Use Google and social networks to find <strong>a name that will be easily adopted by the public</strong>. Then use those social networks, especially Twitter and Facebook, to make your name and your product known. The more it is known, the more it will be downloaded and visible on stores.</p>
<p>&nbsp;</p>
<h2>Beta test your application</h2>
<p>Once you have developed it, and tested it, go to beta test. You can do it yourself, recruit some beta testers, send them the apk and get their feedback. You can go further, put your application on the Android Market and automatize feedback.</p>
<p>On the market, <strong>make your application the less visible possible</strong>: do not use your usual account, do not provide description, screenshots, keywords, use a different package name in the application to reset comments and notes when you will deploy the release, provide an invitation code to your beta testers.</p>
<p>Another solution, easier, is to get a service like <a title="Appaloosa" href="http://www.appaloosa-store.com" target="_blank">Appaloosa</a> to distribute your apps to a managed range of users. We got the opportunity to show this product during the barcamp and make a demo, which was well welcomed. We really felt the need of such a solution.</p>
<p style="text-align: center;"><a title="Appaloosa" href="http://www.appaloosa-store.com" target="_blank"><img src="http://blog.octo.com/wp-content/uploads/2011/10/png2-300x122." alt="Appaloosa" /></a></p>
<h2></h2>
<h2>Get the maximum of feedback</h2>
<p>In order to ensure customers engagement: give them a way to <strong>provide some feedback</strong> and use that data to improve your product&#8217;s features.</p>
<p>You can use frameworks like <a title="Crash Reporting Android" href="http://code.google.com/p/acra/" target="_blank">ACRA</a> or <a title="Bugsense crash reporting" href="http://www.bugsense.com" target="_blank">Bugsense</a> to <strong>retrieve crash reports</strong> (which phones and characteristics, which os version, what kind of error). Be sure to correct bugs after that.</p>
<p>Use <a title="Google Analytics" href="http://code.google.com/mobile/analytics/docs/android/" target="_blank">Google Analytics</a> or <a title="Flurry Analytics" href="http://www.flurry.com/product/analytics/index.html" target="_blank">Flurry Analytics</a> to <strong>get usage metrics</strong> (how many users, how many time, what features usage). Collect the maximum of information to improve your application navigation.</p>
<p style="text-align: center;"><img class="aligncenter size-medium wp-image-26711" title="acra / bugsense" src="http://blog.octo.com/wp-content/uploads/2011/10/acra1-300x104.png" alt="" width="300" height="104" /></p>
<p>&nbsp;</p>
<h2>Use Android Market tools for developers</h2>
<p>To conclude the conference, Richard Hyndmann from Google talked about developers facilities on the Android Market and how to get visible on it. To be at the top of rank, your app has to be fit and polished. Of course, avoid straight port from other plateform, it generally causes users rejection. If your application offers unique features for Android, it is more valuable and will be rated as so. <strong>Seasonality also assures regular update of your app&#8217;s position</strong> that can appear in several different categories like Top Free &amp; Paid apps, top grossing apps, and others. Also, do not forget to provide new format images for add banner: it is a great way to get downloaded!</p>
<p>The Android market offers a new functionality: distribution of <strong><a href="http://developer.android.com/guide/market/publishing/multiple-apks.html">multiple APK</a></strong>. It allows a developer to provide different APK files for different kind of devices. For example, one application for handset devices and another for tablets. It can simplify adoption of new platform features and lighten your apps. However, Google advices to <strong>use this feature only in special cases</strong> and always prefer a single APK file when possible.</p>
<p>It appears that Honeycomb users are ready to pay for applications! It can generate some big revenues. Some attention was given to developers ways to make money. <strong><a href="http://developer.android.com/guide/market/billing/index.html">In-App Billing</a></strong> system was presented. It is another way to sell virtual content such as additional levels for games or download files. Fees are the same for in-app purchases as the transaction fee for application purchases on the market: 30%.</p>
<p style="text-align: center;"><a href="http://blog.octo.com/wp-content/uploads/2011/10/Capture-d%E2%80%99%C3%A9cran-2011-10-16-%C3%A0-17.50.06.png"><img class="size-full wp-image-26842 aligncenter" title="In app purchase" src="http://blog.octo.com/wp-content/uploads/2011/10/Capture-d%E2%80%99%C3%A9cran-2011-10-16-%C3%A0-17.50.06.png" alt="In app purchase" width="138" height="228" /></a></p>
<p>Another tool that can be useful to prevent piracy for paid applications on market is <strong><a href="http://developer.android.com/guide/publishing/licensing.html">Lice</a></strong><strong><a href="http://developer.android.com/guide/publishing/licensing.html">nsing service</a></strong>. Its License Verification Library (LVL) allows your application to set up licensing status protection. The last feature presented is application <strong><a href="http://developer.android.com/guide/topics/data/backup.html">Data Backup</a></strong>. Implement it to offer users to save application content and preferences, even private files in the cloud. All the data can then be restored, for example when switching to a new Android device. All these tools can be used to make your applications better! Just think to use them.</p>
<p>&nbsp;</p>
<h1>What&#8217;s next?</h1>
<p>We want to finish with some interesting predictions given by Mark Murphy during the opening keynote:</p>
<ul>
<li>In 3 years, 1 application over 3 will be developed using cross platforms tools such as HTML 5 (with <a title="Phonegap" href="http://www.phonegap.com/" target="_blank">Phonegap</a> or <a title="Rhodes" href="http://rhomobile.com/products/rhodes/" target="_blank">Rhodes</a>), app generators (Appcelerator) or any other framework that could come to provide multi-platforms apps. Indeed, most companies want to provide their apps to the maximum of platforms with the smallest development cost. We even think it could be more than 1 over 3 applications&#8230;</li>
<li>In 3 years, Amazon will be the second tablet manufacturer (after Apple). The new Kindle Fire offers today a full multimedia experience on an Android based system. Will Amazon still be using Android plateform in the following years ?</li>
<li>In 3 years modded roms will be significantly more popular! Modded roms like <a href="http://www.cyanogenmod.com/">CyanogenMod</a> could diversify and meet enterprise needs in terms of security and professional tools&#8230; This is, with the rise of private application stores, one of the major points that may make Android become an important actor in enterprise.</li>
</ul>
<p>DroidCon 2011 was a great time for us, we learnt a lot, especially that next year will be tablet year! Ice Cream Sandwich is coming and will give the opportunity to develop applications for both devices kinds. Be ready and always make better products!</p>
<p>Thanks to organizers and sponsors for this year.</p>
<p style="text-align: center;"><a href="http://blog.octo.com/wp-content/uploads/2011/10/IMAG0103.jpg"><img class="aligncenter size-medium wp-image-26937" title="Sponsors" src="http://blog.octo.com/wp-content/uploads/2011/10/IMAG0103-169x300.jpg" alt="Sponsors" width="169" height="300" /></a>  <a href="http://blog.octo.com/wp-content/uploads/2011/10/IMAG0102.jpg"><img class="aligncenter size-medium wp-image-26938" title="HTCDev" src="http://blog.octo.com/wp-content/uploads/2011/10/IMAG0102-300x169.jpg" alt="HTCDev" width="300" height="169" /></a></p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=26521" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/droidcon-london-2010/' rel='bookmark' title='Droidcon London 2010'>Droidcon London 2010</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/droidcon-london-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional testing of a MVVM Silverlight application with Fitnesse</title>
		<link>http://blog.octo.com/en/functional-testing-of-a-mvvm-silverlight-application-with-fitnesse/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=functional-testing-of-a-mvvm-silverlight-application-with-fitnesse</link>
		<comments>http://blog.octo.com/en/functional-testing-of-a-mvvm-silverlight-application-with-fitnesse/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 08:30:08 +0000</pubDate>
		<dc:creator>Jean-Yves Rivallan</dc:creator>
				<category><![CDATA[IT architect's workshop]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[automapper]]></category>
		<category><![CDATA[fitnesse]]></category>
		<category><![CDATA[greenpepper]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[wcf]]></category>

		<guid isPermaLink="false">http://blog.octo.com/?p=26891</guid>
		<description><![CDATA[MVVM is a great pattern to enable (among other things) unit testing of a XAML based application GUI. If you’re not familiar with it, this article explains it well and describes its use with Greenpepper on a real life project. Functional testing works great with MVVM, but several issues prevent the use of functional testing [...]
Suggestion d'articles :<ol>
<li><a href='http://blog.octo.com/en/design-your-silverlight-application-for-tdd/' rel='bookmark' title='Design your Silverlight application for TDD !'>Design your Silverlight application for TDD !</a></li>
<li><a href='http://blog.octo.com/en/behavior-driven-development-using-mvvm-pattern-and-greenpepper-tests/' rel='bookmark' title='Behavior Driven Development using MVVM pattern and GreenPepper tests'>Behavior Driven Development using MVVM pattern and GreenPepper tests</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p id="internal-source-marker_0.5907667021159593" dir="ltr">MVVM is a great pattern to enable (among other things) unit testing of a XAML based application GUI. If you’re not familiar with it, <a href="../en/behavior-driven-development-using-mvvm-pattern-and-greenpepper-tests/">this article</a> explains it well and describes its use with Greenpepper on a real life project.</p>
<p dir="ltr">Functional testing works great with MVVM, but several issues prevent the use of functional testing tools (e.g. Fitnesse) with a Silverlight project out of the box.</p>
<p dir="ltr">If the previous article convinced you to implement automated functional testing on your application, but its GUI is in silverlight instead of WPF, let’s see how you can circumvent those issues.</p>
<p dir="ltr">The following has been implemented with Fitnesse, but should also work with Greenpepper or any other .Net automated testing framework.</p>
<h2 dir="ltr"><span id="more-26891"></span>How can Fitnesse load Silverlight code ?</h2>
<p dir="ltr">Loading silverlight code in a standard .Net CLR is a matter of referencing the proper assemblies. Since the assemblies needed to load a ViewModel have the same name than .Net counterparts, Visual Studio does not allow to add them directly (it replaces it with the .Net assembly of the same name found in the GAC).</p>
<p>So this requires some .csproj editing, as such :</p>
<pre class="brush:java" dir="ltr">&lt;Reference Include="System.ServiceModel"&gt;
  &lt;HintPath&gt;..\DLLs\System.ServiceModel.dll&lt;/HintPath&gt;
&lt;/Reference&gt;</pre>
<p dir="ltr">Silverlight assemblies must be referenced with their location on the filesystem. The assemblies required to load a View Model are System.ServiceModel, System.Windows, System.Runtime.Serialization, System.Xml, and System.Xml.Linq.</p>
<p dir="ltr">Add those assemblies as references in your Visual Studio project holding your fixtures, as well as references to your Silverlight projects in your solution, and you’re good to go.</p>
<h2 dir="ltr">What if my view model calls a WCF service ?</h2>
<p dir="ltr">Now we can call silverlight code from fitnesse. But if you’re writing a Silverlight application, chances are it is calling WCF services to do some work server-side. You can’t directly inject a WCF service implementation into a view model, since a WCF client proxy is generated to call it. Moreover, the client side interface only exposes asynchronous methods.</p>
<p dir="ltr">So the challenge is to be able to transform this :</p>
<pre class="brush:java">// Server side WCF Service signature
int DoSomeWork(int i);</pre>
<p dir="ltr">into these :</p>
<pre class="brush:java">// Client side equivalent generated by Visual Studio
IAsyncResult BeginDoSomeWork(int i, AsyncCallback callback, object asyncState);
int EndDoSomeWork(IAsyncResult result);</pre>
<p dir="ltr">Those are standard <a href="http://msdn.microsoft.com/en-us/library/2e08f6yc%28v=vs.71%29.aspx">asynchonous methods</a> any delegate can produce. A wrapper class can be created to translate the server-side service into the client-side one this way :</p>
<pre class="brush:java" dir="ltr">public class MyServiceWrapper : ClientSideNamespace.IService // Client-side interface {
 private ServerSideNamespace.IService service;
 private Func&lt;int, int&gt; SomeWorkDelegate;

 public MyServiceWrapper(ServerSideNamespace.IService service) // Server-side interface {
  this.service = service;
  this.SomeWorkDelegate = i =&gt; service.DoSomeWork(i);
 }
 public IAsyncResult BeginDoSomeWork(int i, AsyncCallback callback, object asyncState) {
  return SomeWorkDelegate.BeginInvoke(i, callback, asyncState);
 }
 public int EndDoSomeWork(IAsyncResult result) {
  return SomeWorkDelegate.EndInvoke(result);
 }
}</pre>
<p dir="ltr">Use this wrapper as a service implementation in your ViewModel and you’re good to go.</p>
<h2 dir="ltr">What if my WCF service returns more than an integer ?</h2>
<p dir="ltr">Just like method signatures differ between client and server side, data structures are not the same. Properties have the same name, but types can differ, especially Collections implementations. <a href="http://automapper.org/">Automapper</a> is an open source library able to solve this issue in a very convenient way, enabling the wrapper to translate a server-side dto into a client-side dto and vice versa.</p>
<p dir="ltr">Assuming the WCF service evolves to :</p>
<pre class="brush:java" dir="ltr">DoSomeWorkDto DoSomeWork(int i);</pre>
<p dir="ltr">The wrapper becomes :</p>
<pre class="brush:java" dir="ltr">public class MyServiceWrapper : ClientSideNamespace.IService // Client-side interface {
 private ServerSideNamespace.IService service;
 private Func&lt;int, ClientSideNamespace.DoSomeWorkDto&gt; SomeWorkDelegate;

 public MyServiceWrapper(ServerSideNamespace.IService service) // Server-side interface {
  this.service = service;
  this.SomeWorkDelegate = i =&gt; Mapper.Map&lt;ServerSideNamespace.DoSomeWorkDto, ClientSideNamespace.DoSomeWorkDto&gt;(service.DoSomeWork(i));
 }
 public IAsyncResult BeginDoSomeWork(int i, AsyncCallback callback, object asyncState) {
  return SomeWorkDelegate.BeginInvoke(i, callback, asyncState);
 }
 public ClientSideNamespace.DoSomeWorkDto EndDoSomeWork(IAsyncResult result) {
  return SomeWorkDelegate.EndInvoke(result);
 }
 static MyServiceWrapper() {
  Mapper.CreateMap&lt;ServerSideNamespace.DoSomeWorkDto, ClientSideNamespace.DoSomeWorkDto&gt;();
 }
}</pre>
<p dir="ltr">The Mapper class is pretty straightforward, just call the CreateMap method for all dto class couples (both ways if necessary). Then include a Mapper.Map call in your delegates in the wrapper and you’re good to go.</p>
<h2 dir="ltr">Conclusion</h2>
<p dir="ltr">The practice of testing an application with Fitnesse (or any functional testing tool) through its ViewModels is really valuable. <a href="../en/behavior-driven-development-using-mvvm-pattern-and-greenpepper-tests/">Matthieu’s feedback</a> was already self-explanatory about this. Not being able to achieve it on a Silverlight application would have been a shame.</p>
<p dir="ltr">At the price of a little development overhead (the WCF services wrappers), this practice is applicable on Silverlight projects too.</p>
<p dir="ltr">A recent experience with a Silverlight application developed by Octo showed that this overhead is negligible compared to the benefits of automated functional testing involving the ViewModels.</p>

 <img src="http://blog.octo.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=26891" width="1" height="1" style="display: none;" /><p>Suggestion d'articles :</p><ol>
<li><a href='http://blog.octo.com/en/design-your-silverlight-application-for-tdd/' rel='bookmark' title='Design your Silverlight application for TDD !'>Design your Silverlight application for TDD !</a></li>
<li><a href='http://blog.octo.com/en/behavior-driven-development-using-mvvm-pattern-and-greenpepper-tests/' rel='bookmark' title='Behavior Driven Development using MVVM pattern and GreenPepper tests'>Behavior Driven Development using MVVM pattern and GreenPepper tests</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.octo.com/en/functional-testing-of-a-mvvm-silverlight-application-with-fitnesse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

