Professional Documents
Culture Documents
MAR
APR
2012 An EPS Company
codemag.com - THE LEADING INDEPENDENT DEVELOPER MAGAZINE - CODE COMPONENT DEVELOPER ® MAGAZINE
Solve the
Data Puzzle!
Features
8 SharePoint Applied: ServiceBus and 62 Smashing the Myth:
SharePoint 2010 Why You Must Learn F#--Even If You
Sahil explains integrating the AppFabric ServiceBus with SharePoint 2010
Aren’t Writing Rocket Science Apps
and Office 365. To the cloud and beyond! If you work with .NET Framework, you’ve encountered F#. Aaron shows
Sahil Malik you why it’s for everyone, not just elite scientific research labs.
Aaron Erickson
14 Working with Windows Phone User Interfaces,
Part 2 68 ASP MVC 4 Highlights, Part 1
Programming for the Windows Phone is easy for anyone with Silverlight John goes out on the road with mobility support and ASP.NET MVC 4.
programming experience. Paul focuses on using some of the built-in There are new templates, a new way to generate code, and enhanced
applications with Launcher and Chooser in this second installment. support for async methods.
Paul D. Sheriff John V. Petersen
Sponsored by:
US subscriptions are US $29.99 for one year. Subscriptions outside the US pay US $44.99. Payments should be made in US dollars drawn on a US bank. American Express,
MasterCard, Visa, and Discover credit cards are accepted. Bill me o ption is available only for US subscriptions. Back issues are available. For subscription information, send
e-mail to subscriptions@code-magazine.com or contact customer service at 832-717-4445 ext 10.
Subscribe online at codemag.com
CoDe Component Developer Magazine (ISSN # 1547-5166) is published bimonthly by EPS Software Corporation, 6605 Cypresswood Drive., Suite 300, Spring, TX 77379 U.S.A.
POSTMASTER: Send address changes to CoDe Component Developer Magazine, 6605 Cypresswood Drive., Suite 300, Spring, TX 77379 U.S.A..
So Many Choices
Once again we find ourselves at a massive crossroads. A new preview of Windows 8 will be avail-
able to the public by the time you read this editorial, SQL Server 2012 is in the final stages
before a gold disk is stamped, and ASP.NET MVC is getting closer to shipment. Rumors are
that we’ll see a new version of Visual Studio Native/Non-Native Mobile tures in SQL Server 2012 as well as highlighting
within a year. And this just the Windows eco- Development two NoSQL databases: Raven DB and MongoDB.
system. CODE Magazine will explore this topic more in
the coming year.
Apple is continuing its march forward with new One of the biggest choices for developers to-
versions of OSX, iOS and their mobile phones day is the choice between developing native vs.
and tablets. Android is a force to reckon with non-native (i.e., browser-based) applications. Making Good Choices Going Forward
as Google ships new versions of the Android OS Do you pick Objective-C, Java or C#/XAML for
and many, many new hardware vendors support building mobile applications? Or do you choose My time is up for this editorial. I hope I have
it. These choices are not limited to just develop- to use HTML5, CSS and JavaScript? For most ap- opened your eyes into three areas where you
ment platforms. The world of data is on fire, too. plications I recommend leaning towards HTML5/ need to assess your choices carefully. As CODE
Oracle and Microsoft continue to push the tradi- CSS. The reason for this choice is simple to me: Magazine writers gather content and write more
tional boundaries of relational database develop- cost and reach. The power and speed of JavaS- about these choices that developers need to
ment while new ways of looking at data are upon cript accompanied by the flexibility and power make, I hope you’ll contact me and let me know
us with tools like MongoDB, RavenDB, Redis and of HTML5/CSS has never been greater. The real what trends you’d like to see us explore.
Apache Cassandra. proof is how many applications have gone from
native tools to HTML5/CSS. For me there are two
As a software developer, which of these affects that come to mind. The first one is the Amazon Rod Paddock
you? All of them. As software developers we have Kindle reader. Last year Apple and Amazon had
never been faced with such a rich and at the same a bit of a tiff when it came to in-app purchases
time perilous set of choices. And yes, I mean per- of books. Amazon took a first step around this
ilous because each and every one of these choices problem by rewriting their Kindle Reader using
comes with its associated costs. Choosing the HTML5/CSS and JavaScript. Another cool devel-
wrong platform can be costly in the form of time opment was the conversion of a game called Cut
and treasure. Allow me to prognosticate on some the Rope from native to IE 9. Cut the Rope is a
of these choices. much-loved game in the mobile gaming space.
The development team that created Cut the Rope
converted their application from Objective-C to
JavaScript and Windows 8 HTML5/CSS. This is quite an accomplishment as
this game has a cool set of user interactions that
Windows 8 is a radical step for Microsoft and you I was simply amazed they were able to convert
as a developer need to be careful when making to HTML5/CSS. If you want to learn more about
choices for this platform. As a developer, one how they converted the app to HTML5/CSS,
of the biggest things you must avoid is choos- check out this article: http://www.cuttherope.
ing JavaScript for your development language ie/dev/
for desktop applications. Visual Studio 11 Beta
(likely to be called Visual Studio 2012) provides
you multiple languages choices, including Visual Data, Data Everywhere and a Whole Lot
Basic, C# and C++. The newest member of this to Drink
family is JavaScript. In my opinion, you will make
a bad decision if you choose JavaScript for devel- The data space has been very active lately. For
oping applications on the Windows 8 platform. some companies, industry-standard relational
Why choose JavaScript when the three majors are databases have been replaced with NoSQL da-
light years beyond JavaScript in power and ro- tabases. There are key value stores, document
bustness? The ENTIRE POINT of using JavaScript databases, relational databases, column stores
for development is REACH, plain and simple. Ja- and in-memory databases. Applications like
vaScript is a universal language available across Facebook, Netflix, Twitter and Farmville have
all platforms: Windows, OSX and Linux. The Ja- required developers to think about data in
vaScript extensions found in Windows 8 are for very different ways. As companies explore this
just Windows and no more. Portability goes right change in data sores, development teams need
out the window. If you are developing for the to start thinking outside of the box of rows and
Windows platform, stay away from the JavaScript columns. With this in mind, this issue of CODE
tools. Magazine is exploring new and interesting fea-
6 Editorial codemag.com
ONLI
ON
ONLINE
LINE
LINE Q
QUICK
UICK
UICK IID
D 00
000
1203021
0
AppFabric Access Control, ServiceBus, and Cache. This ar- AppFabric ServiceBus queues are exactly what the name im-
ticle concerns ServiceBus, and its integration with Share- plies: first in first out. But it is important to understand that
Point 2010 and Office 365. AppFabric ServiceBus queues are not the same as Azure stor-
age queues. AppFabric ServiceBus queues can be roughly
What is Azure Service Bus (also known as Azure AppFabric thought of as MSMQ for the cloud. It gives you a reliable,
Service Bus)? durable storage mechanism with a listener and a sender. In
fact, you can have many listeners and many senders on a
“All applications will move to the cloud.” Isn’t that the queue. This enables some really interesting scenarios that
mantra these days? AppFabric ServiceBus queues can solve. For instance:
Sahil Malik
www.winsmarts.com No, they won’t! Developers have spent more than 30 years • Queues can perform load leveling – if your input traf-
Sahil Malik is a Microsoft MVP, writing software. Things are not moving to the cloud over- fic is unpredictable in nature, a queue acts as a shock
INETA speaker, a .NET author, night. In fact, some applications will perhaps never move absorber, and effectively queues up requests to be
consultant and trainer. to the cloud. There are many reasons for that, and some processed until the listener(s) catch up to the load.
that technology alone won’t be able to solve. Organiza- • You can use AppFabric ServiceBus queues as a load
Sahil loves interacting with fel- tions are nervous about putting their sensitive data in the balancing mechanism; many listeners can listen
low geeks in real time. His talks cloud due to lack of confidence or legal reasons. Perhaps on a queue. Very similar to MSMQ, AppFabric Ser-
and trainings are full of humor the applications that the data depends on are not cloud viceBus queues also have transactional session-full
and practical nuggets. You can ready yet. Or maybe the extra latency that the cloud in- message semantics, thereby ensuring that a mes-
find more about his trainings troduces is not ideal for a certain category of applications. sage isn’t dequeued until it is properly processed.
at http://www.winsmarts.com/ • Queues can offer decoupling – the sender and re-
training.aspx. But there is certainly an undeniable advantage that the ceiver do not have to be online at the same time.
cloud offers for certain kinds of applications. Just look at • Queues offer the equivalent of transactions for dis-
your smartphone. The apps on it depend on services in tributed systems, where semantics such as peek/
the cloud. Wouldn’t it be nice if your smartphone could lock and de-duplication offer you graceful recovery
securely pull information from on-premises applications scenarios when various components of a distributed
without offering a million security prompts or VPN issues? system might fail unpredictably.
Most smartphones that do support conventional VPN
break the VPN connection as soon as the screen turns off As amazing as AppFabric ServiceBus queues are, some-
and the phone goes into battery save mode. Traditional thing even more amazing than queues are topics. Topics
solutions are not the solution here. are just like queues, except they have a concept of rich
messages laden with metadata on which you can create
This is where AppFabric ServiceBus helps. It allows you subscriptions. You can think of subscriptions as virtual
to bridge on-premises applications with cloud applica- queues. A listener creates a subscription using a SQL-92
tions, cloud applications with on-premises applications, syntax. This allows for newer interesting scenarios such
and cloud applications with other cloud applications, as a logging subscription, fanning out messages to vari-
or on-premises applications with other on-premises ap- ous listeners, etc.
plications (perhaps on someone else’s premises) easily,
securely, without any major firewall reconfigurations. What makes me really excited about Azure, in general,
It does so by making outbound TCP or HTTP calls to a is that almost everything is exposed over a REST-based
namespace hosted in Azure. API. This truly makes Azure extremely programmable from
every single platform, including JavaScript.
Perhaps the best part about AppFabric is the rather in-
tuitive way you can use it. If you have used WCF, you While AppFabric ServiceBus is a pretty big topic in itself,
may be familiar with netTcpBinding and webHttpBind- in this article, I will demonstrate its integration with
ing. Well, AppFabric contains netTcpRelayBinding and SharePoint using webHttpRelayBinding.
webHttpRelayBinding that are rough equivalents of what
you are used to in WCF, except they work with an interme-
diary broker – which is your Azure AppFabric ServiceBus Creating an AppFabric ServiceBus REST
namespace. In addition, AppFabric ServiceBus also pro- Application
vides you with programming paradigms such as queues
and topics that go above and beyond the simple WCF pro- Developers can use ServiceBus in many ways. One of the
gramming model. most straightforward ways is to simply use it as a WCF
Summary
Figure 6: Your service being consumed in SharePoint.
Azure AppFabric ServiceBus is an invaluable arrow in your
quiver. Do you have users who wish they could easily ac-
cess on-premise data on their iPhones or other mobile also available on a REST-based API. You can also inte-
platforms? Do you have endless meetings with security- grate them with sandbox solutions using the approach I
minded IT infrastructure people who just don’t care about demonstrated.
your deadlines? Do you have an existing rich investment
in WCF that you wished was available across the Internet In later articles I will continue to push the boundaries
to other applications you care about? ServiceBus is your of what is possible with technologies that are available
friend. today.
In this article, I introduced you to the basic concepts of Until then, Happy SharePointing and Jolly Azuring!
Service Bus. Service Bus, like anything else, is a topic you
can go much deeper into, which I strongly encourage you Sahil Malik
to try. I briefly mentioned queues and topics, which are
ADVERTISERS INDEX
Advertisers Index
Android Developers Conference GOLD SPONSOR - Digital Escrow Services
www.andevcon.com 21
CODE Consulting / Mobile Apps
www.codemag.com/mobileapps 29 www.tower48.com 75
CODE Framework
www.codemag.com/framework 76
GOLD SPONSOR - Art Assets
CODE Magazine
www.codemag.com/magazine 47
CODE Training
www.codemag.com/training 35
DevTeach Developers Conference www.xamalot.com 57
www.devteach.com 15
dtSearch
Bronze Sponsor Advertising Sales:
www.dtSearch.com 61 Tammy Ferguson
832-717-4445 ext 26
National Collegiate Cyber Defense Competition tammy@code-magazine.com
www.nationalccdc.org 55
www.telerik.com 5, 7, 9
State of .NET
www.StateOfDotNet.com 25
SXSW Interactive 2012
www.sxsw.com 69
Tech Conferences Inc.
www.devconnections.com 2
Team Companion
www.teamcompanion.com 41
This listing is provided as a courtesy to our readers and advertisers.
Xiine The publisher assumes no responsibility for errors
www.xiine.com 51 or omissions.
a common task bar for your Windows Phone using the Ap- • MarketplaceSearchTask
plication Bar. This article assumes that you have Visual • MediaPlayerLauncher
Studio 2010 and the Windows Phone tools installed along • PhoneCallTask
with it. You must download and install the Windows Phone • SearchTask
tools separately to use them with Visual Studio 2010. You • SmsComposeTask
may also download the free Visual Studio 2010 Express for • WebBrowserTask
Windows Phone developer environment.
One important thing to keep in
Paul D. Sheriff Launchers mind when using either the Launcher
PSheriff@pdsa.com or Chooser APIs is that calling these
(714) 734-9792 The Windows Phone does not support multi-tasking (yet); applications could cause your
Paul D. Sheriff is the President however, you can interact with many of the built-in applica-
tions on the phone from within your application. You can in-
application to be “tombstoned.”
of PDSA, Inc. (www.pdsa.com)
and a Microsoft Partner in teract with the built-in applications on the phone in two ways:
Southern California. Paul acts as passing in data, or get back data. A Launcher type of applica- To use any of the Launcher task classes, you first need to
the Microsoft Regional Director tion lets you pass data from your application into the built-in add a using statement at the top of your Page class.
for Southern California assisting phone application. In a Chooser type of application you will
the local Microsoft offices with use a built-in phone application to select some data that is using Microsoft.Phone.Tasks;
several of their events each stored on your phone and return that data to your application.
year and being an evangelist for Next, you create a field in your Page class with a variable
them. Paul has authored literally Using a Launcher that will point to the specific Launcher you wish to use.
hundreds of books, webcasts,
videos and articles on .NET, WPF, When you use the Launcher API on the Windows Phone, SavePhoneNumberTask _Task;
Silverlight, Windows Phone and your application calls one of the built-in applications. The
SQL Server. Check out Paul’s new
user will complete a task, and then control will return to Now create an instance of the class in the constructor for
code generator called Haystack
your application. No data will be returned from a Launcher your page and hook up the Completed event.
at www.CodeHaystack.com.
application; however, your application may pass in some
data to the Launcher. As an example of using a Launcher, public LauncherPage()
you might ask a user to input a phone number, and then {
you pass that phone number to the SavePhoneNumberTask InitializeComponent();
as shown in Figure 1. If the user saves that phone number,
a return result of OK will be returned, but no other data. _Task = new SavePhoneNumberTask();
_Task.Completed += new
One important thing to keep in mind when using either the EventHandler<TaskEventArgs>(_Task_Completed);
Launcher or Chooser API is that calling these applications }
could cause your application to be “tombstoned.” It will be
your responsibility to restore any data that you want after You must create the instance of the task and hook up the
your application is reactivated from the tombstoned state. Completed event handler in the constructor because your
The Windows application will be tombstoned once it calls the Launcher
Built-In Launchers application. Upon reactivating your application, the con-
Phone does not structor will be called again and the completed event needs
support multi-tasking Windows Phone contains several built-in applications to be hooked back up so the Launcher can call the event.
(yet); however, you that your C# or Visual Basic code can launch by instan-
can interact with tiating an instance of the appropriate class. You can find In Figure 1 the user is asked to put a phone number into a
all of the Launcher classes in the Microsoft.Phone.Tasks text box named “txtPhone” on this page. When you click on
many of the built-in namespace. The list below contains the Launcher classes the Save Phone Number button the Click event will fire. At
applications on the you can use on the Windows Phone. this point you take the value from the txtPhone.Text prop-
phone from within erty and set the PhoneNumber property on the SavePhone-
your application. • EmailComposeTask NumberTask object. Now you call the Show() method of the
• MarketplaceDetailTask task object and the Launcher application will run and receive
• MarketplaceHubTask the phone number from your application. Once the new ap-
• MarketplaceReviewTask plication is running, your application will be tombstoned.
What does this code do? It creates a new Menu instance with I hope that by now your curiosity is piqued. We just saved In general, RavenDB internal
two Courses and then stores them in the session. When you a fairly complex object graph into our database, and it governors ensure that your
store an object in the session, you are merely asking the ses- saved cleanly and into a single document. Think about the application will stay up, perform
sion to remember to save that instance later on, when you call implications of this for a moment. Consider what would well and not fall over after a few
SaveChanges. Until SaveChanges is called, nothing is actually happen if we were trying to work with a relational data- months in production.
going to happen. This allows RavenDB to optimize writes to base here.
RavenDB to the smallest possible number of requests.
We would have needed to define a schema (requiring four
Now you call SaveChanges: tables to store the information), find a way to tie it to our
source control history and deploy it.
session.SaveChanges();
When loading a menu, we would need to query four ta-
And you can now go to RavenDB Management Studio and bles to show a simple menu. Whereas with RavenDB, we
see the newly saved document. In fact, if you’ll look at can load it all in a single command, as you can see here:
Figure 2, you can see that there are now two of them.
using (var session = documentStore.OpenSession())
For now, we will ignore the Hilo document; I will discuss it {
in more detail later on. Let’s focus on the Menu document. var menu = session.Load<Menu>("menus/1");
Double-click it to see its content: Console.WriteLine(menu.Name);
Querying with RavenDB With RavenDB, we move the burden from the read side
(which happens a lot) to the write side (which happens far
Now that we have some information in the database, less often). We are also dealing with entities that are far
it is time for us to get that data out. We have already bigger than standard entities in relational databases. Be-
seen that we can load entities using their ids (session. cause we can store complex object graphs inside RavenDB
Load<Menu>(“menus/1”); ). But how about when we easily, we no longer need to split an entity into multiple
want to query based on the values of the entity, and not physical representations because the data store demands it.
just its id? Let’s see how we can do that:
If you are familiar with Domain Driven Design, all entities
var menus = in RavenDB are Root Aggregate, and all other values are
from menu in session.Query<Menu>() actually Value Objects.
where menu.Name.StartsWith("Breakfast")
select menu; Let’s go back to our restaurant example and look at how
we would model an order. In a relational system, the or-
This should look familiar to you; RavenDB supports LINQ der model would probably be composed of Orders, Cus-
Figure 3: An example of an order and allows you to perform complex queries on your enti- tomers, OrderLines, Products, etc.
document in RavenDB. ties without any trouble at all. For that matter, let’s see
how we can find a Menu that has a cheap course: Each of those would be a separate entity. But does it re-
ally make sense to store OrderItems outside of an Order,
var menus = or is this just an aspect of the Order? What about Pay-
from menu in session.Query<Menu>() ments on the order? As you can see in Figure 3, modeling
where menu.Courses.Any(c => c.Cost < 2) in RavenDB is quite different.
select menu;
You can see the classes for this model in Listing 1. There
That leads to an interesting observation. Using our current are a few things to note. Both OrderLine and Payment
model, we can’t really ask for a specific Course, because are embedded inside the Order. In other words, it is non-
public bool PaidInFull And we can save it to RavenDB with the following code:
{
get session.Store(new Customer
{ {
return Payments.Sum(x => x.Amount) >= Name = "Joe Smith",
Lines.Sum(x => x.Price*x.Quantity); Attributes =
} {
} {"IsAnnoyingCustomer", true},
{"SatisfactionLevel", 8.7},
This is perfectly acceptable in RavenDB; all the data is {"LicensePlate", "B7D-12JA"}
already there. In a relational database, this sort of code }
(which is quite natural and elegant) would result in two });
separate queries to the database.
So far, this is very simple. You can see the resulting docu-
Concurrency ment in Figure 4.
Another issue that no longer raises its ugly head is concur- So far, so good. But the really fun part comes when we
rency. In a relational database, the unit of concurrency want to work with it. As you can see in Figure 4, we didn’t
is the row. But we usually have to store data in multiple really care in RavenDB that this is a dynamic property. We
tables. That makes it possible to update parts of the entity just store the data, but that is just half of the job. How do
without proper concurrency control. Anyone who ever had we work with this information?
to make sure that whenever an OrderLine or a Payment is
updated, the Order is properly locked so we won’t have a As it turns out, really easily:
race condition is intimately familiar with the problem.
session.Query<Customer>()
With RavenDB we don’t have to worry about that. The .Where(x => x.Attributes["IsAnnoyingCustomer"]
unit of change is the document, and the document can .Equals(true)
contain complex objects, so changing an OrderLine or )
adding a Payment means that we don’t make any contor- .ToList();
tions with regards to concurrency control in non-trivial
scenarios. What we need to do is simply ask for optimistic This will prodouce the right results, and give us a really
concurrency, like so: nice interface to query dynamic properties without any
problem at all.
session.Advanced.UseOptimisticConcurrency = true;
Of course, I don’t recommend going that route unless you
And any call to SaveChanges will use optimistic concur- actually need dynamic properties. It is easier to work with
rency and throw a ConcurrencyException if someone went static properties, not because of any RavenDB limitation,
behind our back and changed the entities that we modi- but simply because you can use the compiler to help you.
fied.
1. Loading a document (or documents) by id. For a surprisingly large number of cases, returning stale This way you don’t really have
2. Querying an index. information is perfectly fine. Just consider everywhere to worry about defining most
were you have ever applied caching. In those cases, you indexes ahead of time. You can let
But what is an index? Here you go: were explicitly deciding to return potentially stale infor- RavenDB create and manage them
mation for the user in order to increase performance. for you. It will do the right thing.
from customer in docs.Customers
select new { customer.Name }; Along with reporting whether a response is stale or not,
we report how stale it is. You can see a full example in
This is a RavenDB index, indeed. “Wait!” I can hear you say, Listing 2 where we show how you can get the statistics
“This isn’t an index, this is a LINQ statement.” It is both. for a request and make a decision based on the informa-
tion provided there.
The way indexes in RavenDB work, you construct a
LINQ statement and hand it over to RavenDB. RavenDB Finally, remember that RavenDB is composed of two ma-
will then execute this LINQ statement on a background jor components. Indexes can be stale, but documents
thread, finding all the Customers in the database and never are. That means that if you make a request by id,
projecting out their names. We can then take the names you are guaranteed never to get old information.
and store them in an index.
You might wonder if I pre-defined an Since RavenDB can create indexes for us on the fly, do
index behind your back. Well, no, not you want to define your own static indexes? The answer
really. What we actually did is ask Rav- is, as you might have imagined, yes.
enDB to query all Customers’ documents
where Attributes.IsAnnoyingCustomer Static indexes are useful in any number of scenarios, from
is equal to true. And because we didn’t full text searches to geo-spatial queries, from map reduce
explicitly specify an index, what hap- operations to event sourcing. I don’t have the space in
pens is that the query goes to RavenDB this article to cover static indexes in enough depth (that
and it is up to the Query Optimizer to can be an article or two all on its own), so I would just
decide what indexes is going to handle say that proper use of indexes can make your RavenDB
this query. applications shine.
Listing 2: Working with stale indexes There is a lot more to learn and do. RavenDB supports
sharding, map reduce, spatial queries, replication and
RavenQueryStatistics stats;
much more. It has a fully async API and is available for
var queryable = session.Query<Customer>()
Silverlight as well.
.Statistics(out stats)
.Where(x => x.Attributes["IsAnnoyingCustomer"].Equals(false));
You can read more about it at http://ravendb.net or join
var customers = queryable.ToList(); the discussions about it in the mailing list http://groups.
google.com/group/ravendb/
customers = queryable.ToList();
}
New York
Los Angeles
Philadelphia
es:
Phoenix Includ out
All Abws 8!
o
Dallas Wind
Houston
The goal of the State of .NET events is to share our extensive experience.
Due to our efforts around CODE Magazine, CODE Consulting, CODE Training,
and our community involvement, we are in a unique position to see a
larger number of real-world projects than anyone else in the industry.
Our relationship with Microsoft provides us a behind-the-scenes look. In
combination, this results in a unique position, and as a content provider,
we are eager to share this information. An EPS Event
ONLINE QUICK ID 1203051
are so many of them that I can’t list them in a single The examples use the AdventureWorks2008R2 OLTP da-
article. So, I’m penning a two-part Baker’s Dozen. The tabase. (As of this writing, the AdventureWorks OLTP
first part of this “twin-bill” (yes, expect a few baseball database hasn’t yet been updated for SQL Server 2012).
analogies!) will be 13 new T-SQL and database engine You can find AdventureWorks2008R2 on the CodePlex
features in SQL Server 2012. The “night-cap” in the next site: http://msftdbprodsamples.codeplex.com/releases/
issue will be 13 new features in SQL Server Integration view/55330.
Services and the new Business Intelligence Semantic
Model. Tip 1: The Baker’s Dozen Spotlight: The New
Columnstore index
Kevin S. Goff
Kgoff@KevinSGoff.NET Starting Lineup for Game 1 Over the last 3-5 years, many companies have sent a
Kevin S. Goff has been a SQL clear message that they view Microsoft SQL Server as a
Server MVP since 2010, and Normally, in Baker’s Dozen tradition, I say, “What’s on viable option for large database applications. No longer
was a C# MVP from 2005-2009. the menu?” This time I’m saying, “The starting lineup is just a “database server for medium-size companies,”
He is currently a full-time SQL as follows!” SQL Server has become the database of choice for
Server/Business Intelligence companies like WiPro Technologies (2nd largest IT
Practice Manager for SetFocus, • Leading off, the Baker’s Dozen Spotlight: The new company in India), Arcelik (one of Europe’s largest
LLC, a Microsoft Certified Part- Columnstore index in SQL Server 2012, which can manufacturers), and Clalit Health Services (Israel’s
ner for Learning Solutions. provide dramatic performance improvements in largest HMO) – all of whom have converted Oracle/SAP
many data warehousing scenarios Systems to SQL Server.
• Batting second, the new SSDT environment
• Batting third, the new sequence generator object But Microsoft hasn’t rested on the laurels that have
• Batting fourth, the new Lag and Lead functions helped it achieve a more “prime-time” status: they
• Batting fifth, the Baker’s Dozen Potpourri: the new continue to augment their flagship database product.
Percentile window functions One can plainly see that in the Parallel Data Warehouse
• Batting sixth, the new Fetch language feature for appliance that scales to petabytes (http://msdn.micro-
paging result sets soft.com/en-us/library/ee730351.aspx). One can also
• Batting seventh, the new EXECUTE…WITH RESULTS see it in the topic of this first tip: the new Columnstore
for extending the use of stored procedure result sets index that can increase the performance of data ware-
• Batting eighth, the new IIF feature house queries by anywhere from 10-100 times.
• Batting ninth, the new TRY…CONVERT feature
Article Project File • Batting tenth (yes, I realize there are only 9 players The new Columnstore index groups and stores data for
on a team), a set of new date and DateTime functions each column and then join all columns to build the
You can find the entire source • Batting eleventh, the new THROW statement to index. (By contrast, regular indexes group and store
code and project file on my throw an error data for each row and then join all the rows to build the
website at www.KevinSGoff.net, • Batting twelfth, two new string and formatting index.) Here are the major attributes of the Columnstore
in the download area. functions index (with an example to follow):
• And last but not least, the new FileTable feature
• Based on Microsoft’s Vertipaq technology that’s
Enhancements in Batter Up! The Demo Database for the Examples used in Microsoft PowerPivot – a highly com-
SQL Server 2012 pressed index, more compressed than a non-clus-
Each new version of SQL Server As I am writing this article (early January 2012), SQL tered covering index.
always provides some exciting new Server 2012 is in a release candidate status, which • Very easy to create (same syntax as an existing
functions. A data warehousing generally means that the product is beyond the beta/ index, but with the Columnstore keyword).
professional will definitely look technology preview status and that a formal release to • It is a read-only index: meaning that once you
forward to the new Columnstore manufacturing (RTM) is next. At the PASS Summit in create it, SQL Server will not maintain it when
index, which offers query October 2011, Microsoft announced that SQL Server 2012 you subsequently insert new rows to the table.
performance boosts of anywhere was on schedule for a formal release in the first half of This makes Columnstore indexes useful for data
from 10-100 times! 2012. warehousing scenarios (where data is loaded on
26 The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) codemag.com
Figure 1: Results of processing time with Columnstore index.
codemag.com The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) 27
Listing 2: Query to test performance
set statistics io on -- Now Create ColumnStore Index and re-run query
set statistics time on CREATE NONCLUSTERED COLUMNSTORE INDEX [IX_BPO_ColumnStore]
ON [BigPurchaseOrderHeader]
select Vendor.Name, SUM(TotalDue) as TotDue (VendorID, TotalDue)
from Purchasing.Vendor GO
join dbo.BigPurchaseOrderHeader BPO on
Vendor.BusinessEntityID = BPO.VendorID
group by Vendor.Name -- Now drop Columnstore and try a non-clustered
-- covering index
-- Results of query performance in Figure 1: (this reads
-- across 10,000,000 rows -- Performance is better than a clustered index but still
-- not as good as a Columnstore index
The performance numbers show that, indeed, Microsoft (NOTE: SSDT was previously known as code-named
“hit the ball out of the park” with Columnstore indexes. “Juneau.”)
This is one of the most significant enhancements in the
history of SQL Server with regards to data warehouse You can read more about SSDT here: http://msdn.microsoft.
query performance!!! com/en-us/data/gg427686.
Tip 2: The New SSDT (SQL Server Data Tools) Tip 3: New Sequence Generator Object
Environment
Have you ever wanted a table-independent identity
One of the frustrations of SQL Server and Business generator? Other databases (e.g. Oracle) have had a
Intelligence Developers has been the lag of Business sequence generator to produce a new integer identity on
Intelligence Development Studio (BIDS) with respect to demand, without association to a specific table. Imagine
Visual Studio. Additionally, developers working in BIDS a scenario where you could create an integer value for
often need to ALT-TAB back and forth with SQL Server every row in every table, where the value is unique across
Management Studio. tables – and without the complexity of a uniqueidentifier.
28 The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) codemag.com
FROM THE PRODUCERS OF CODE MAGAZINE
shu ters
shut ers tockk
rstock
Mobile Development from the
Most Trusted Source in .NET!
Looking for a company who can help you with your mobile platform projects, provide man-power and know-how,
and reduce your overall risk?
CODE Consulting is your perfect partner! It is difficult to ignore the growing demand for applications that run on mobile devices like
smart phones and slate devices, but you don’t have to venture into this new technology alone. CODE Consulting is here to help you develop
your mobile applications on Android, iOS (iPhone/iPad/iPod), Windows Phone, WebOS, and more. CODE Consulting provides a wide
range of services for every need and scale, from mentoring your team to make sure your mobile project is on track, to the complete design
and development of your mobile application.
CODE Consulting is the consulting, development, and custom software arm of CODE Magazine. We have access to the most extensive network
of experts through both in-house staff, as well as a vast network of CODE authors, trainers and consultants, MVP and RD networks, and
community involvement. At CODE Consulting, we work with technologies and standards like .NET, Java, Objective-C, HTML, CSS, JavaScript,
Silverlight, SOA, and much more.
30 The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) codemag.com
Listing 5: New Percentile functions
USE AdventureWorks2008R2 order by sum(TotalDue) desc) as Rank ,
GO ROUND(PERCENT_RANK() over
-- PercentRank = (Rank minus 1 ) / (TotalRows - 1) (partition by CreditRating
order by sum(TotalDue) desc) * 100,4) as PctRank ,
-- Percentile_Cont = Median ( between 0 and 1, .5 for middle score) ROUND(CUME_DIST() over
(Partition by CreditRating
-- Cumulative distance = # of rows higher/lower than lowest value order by sum(TotalDue) desc),4) as Cumul_Dist,
-- / # of total rows ROUND(PERCENTILE_CONT(.5) within group
(order by sum(TotalDue) desc)
over (partition by Vendor.CreditRating) ,2)
select Vendor.Name as VendorName, CreditRating as Rating, as Median_Interpolate,
ROUND(sum(TotalDue),2) as VendorTotal, ROUND(PERCENTILE_DISC(.5) within group
(order by sum(TotalDue) desc)
ROUND(First_Value (sum(TotalDue)) over (partition by Vendor.CreditRating) ,2)
over (Partition by CreditRating as Median_Actual
order by sum(TotalDue) ),2) as VendorLow,
ROUND(Last_Value (sum(TotalDue) ) from Purchasing.PurchaseOrderHeader
over (Partition by CreditRating join Purchasing.Vendor on BusinessEntityID = VendorID
order by sum(TotalDue) where CreditRating = 3
RANGE BETWEEN CURRENT ROW AND UNBOUNDED group by Vendor.Name, CreditRating
FOLLOWING ),2) as VendorHigh, order by CreditRating, VendorTotal desc
rank() over (partition by CreditRating
impacted by outlier conditions. In my Baker’s Dozen performance. Fortunately, SQL Server 2012 provides two
article in the November/December 2011 issue (QuickID new functions (PERCENTILE_CONT and PERCENTILE_
1112061), I showed a workaround for calculating a DISC) to natively handle a median calculation.
median average by assigning a row number and then
averaging the middle values (which would be 1 value Figure 5 shows a screen shot for a result set that shows
for an odd number of rows and 2 values for an even seven vendors, ranked by their sales dollars. See Listing
number of rows). 5 for a new code example, plus Figure 5 for the screen
shot.
DECLARE @NumObservations int = @@ROWCOUNT
• First_Value – provides the first value (thus the name)
;WITH ScoreCTE AS ( across a set of rows, based on a particular order
SELECT Id, Score, • Last_Value – provides the last value across a set of
ROW_NUMBER() OVER (ORDER BY Score) rows, based on a particular order, with the option
AS ScoreRank of specifying a “between” range
FROM @StudentScore) • PERCENT_RANK – the percentage of rows/values
in the range/window (“distribution”) of rows that
SELECT AVG(Score) AS Median FROM ScoreCTE are the same or lower than the current row. For ex-
WHERE ( ScoreRank IN ample, in Figure 5, the vendor Federal Sport has a
((@NumObservations+1)/2, percentile rank of 33.33%. That means that 33% (2
(@NumObservations+2)/2) ) rows) of the total number of other rows (6 rows)
have a sales dollar amount lower than vendor Fed-
While this type of code works, it’s usually better for a eral Sport.
software product to provide a native function, providing • CUME_DIST – similar to the Percentile Rank func-
the native function provides good functionality and tion in the example in Figure 5, the ranking for
codemag.com The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) 31
Vendor Federal Sport (3) divided by the total num- certain functions, but others don’t. Take, for instance,
ber of rows (7) (i.e., .4286). This number repre- the IIF function. It exists in MDX and in SSRS, but not
sents the relative position of the vendor with re- T-SQL….
spect to the total number of rows.
• PERCENTILE_CONT and PERCENTILE_DISC, for all Until now!!!
intents and purposes, both calculate the median
score/value (i.e., “middle score”), over a set of SELECT IIF(CreditRating=1,'Good Credit Rating',
rows. In Figure 5, the middle vendor dollar amount 'Bad Credit Rating')
is Inner City Bikes with sales of $27,308.61. In this AS CreditMessage, Name
scenario, with an odd number of vendors in Figure FROM Purchasing.Vendor
5, both functions return the same value. However,
had the number of vendors in Figure 5 been an Tip 9: The New TRY…CONVERT and TRY…PARSE
even number (such as 8 vendors), the PERCEN- Features
TILE_CONT function would calculate/interpolate a
median by taking the straight average of vendors If you follow baseball closely, you know that some hitters
4 and 5. in the lineup contribute not by hitting home runs, but
by getting the “little things done” (like laying down a
Tip 6: New Fetch Language Feature for Paging bunt, or hitting into an out that advances another base
Result Sets runner).
When Microsoft introduced the new ROW_NUMBER func- Well, SQL Server 2012 has a few of these types of “role
tion in SQL Server 2005, developers used it (in conjunc- players” that, while not huge features, can certainly help
tion with the new common table expression capability) to a team out. For instance, have you ever wanted to parse
generate an internal row number for paging result sets. a value to see if it’s a valid date?
While this worked quite well, it meant using either a sub-
query or common table expression, since a ROW_NUM- SELECT IIF(
BER (windowing) function cannot be used in the WHERE TRY_CONVERT(date, '02/29/2010') is NULL,
clause. 'Invalid Date', 'Date')
AS TestDateResult
SQL Server 2012 now contains a new set of statements:
offset and fetch next. SELECT TRY_PARSE( 'cannot be a number' as int)
AS result1,
OFFSET (@PageNumber-1) * @RowsPerPage ROWS TRY_PARSE( '100' as int)
FETCH NEXT @RowsPerPage ROWS ONLY AS result2
See Listing 6 for the full code example, which retrieves N Tip 10: A Set of New Date and DateTime Functions
number of rows based on page number Y (where both N
and Y are variables). Listing 6 also contains the sample Another nice “utility player” in the Microsoft line-up is
output. the new set of date and DateTime functions.
Tip 7: The New EXECUTE…WITH RESULTS For instance, creating a new date is as simple as using
the new function DATEFROMPARTS:
Have you ever wanted to rename the columns from a
stored procedure result set? Listing 7 shows an example SELECT DATEFROMPARTS( 2011, 12, 24) AS NewDate
of the new EXECUTE WITH RESULTS statement, which
allows you to rename the columns from a result set. SELECT datediff(mi,
DATETIMEOFFSETFROMPARTS
Tip 8: The New IIF Feature (2011, 01, 8, 8, 00, 00, 0, -5, 0, 7 ) ,
DATETIMEOFFSETFROMPARTS
As an instructor, I sometimes have challenges in teaching (2011, 01, 8, 10, 30, 00, 0, -8, 0, 7 ))
students that certain Microsoft languages/tools have As MinutesDiff
32 The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) codemag.com
This next one is a personal favorite of mine: the ability GO
to determine the last day of a month, using the new EXEC dbo.ThrowTest
EOMONTH function:
This further improves error-handling scenarios in SQL
DECLARE @date DATE Server 2012.
SET @date = getdate()
SELECT EOMONTH ( @date ) AS Result; Tip 12: New String and Formatting Functions
Tip 11: New Ability to Throw an Error Suppose you’re working with an international application,
and need to display currencies in different country
In SQL Server 2005, Microsoft made tremendous strides in currency formats (such as the output in Figure 6, which
exception handling with the implementation of TRY-CATCH. uses the different currency symbols).
This allowed SQL developers to build more robust stored
procedures with transactions and better error handling. SQL Server 2012 contains a new capability in the FORMAT
function to render currency in different formats:
Part of the improved methodology in SQL Server 2005
was the ability to raise an error “politely” (using DECLARE @Dollars MONEY = 1412.95
RAISERROR) back to the calling application. However,
this introduced one complication: it changed the error SELECT
line number. FORMAT(@Dollars,'c','en-US') [US],
FORMAT(@Dollars,'c','it-IT') [Italy],
Fortunately, Microsoft has further refined this capability FORMAT(@Dollars,'c','fr') [France],
by allowing developers to “throw” the same error that FORMAT(@Dollars,'c','ar-SA') [Arabic],
was “caught” to begin with: FORMAT(@Dollars,'c','ja-JP') [Japan]
codemag.com The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) 33
Listing 8: New FileTable
EXEC sp_configure filestream_access_level, 2
RECONFIGURE --The sys.database_files shows 3 file types - for the data file,
Go -- the log file, and the FILESTREAM
SELECT * FROM sys.database_files
USE MASTER Go
GO
--go back to master
IF DB_ID ('FileTableExampleDB') IS NOT NULL USE MASTER
DROP DATABASE FileTableExampleDB GO
GO
-- Set the non-transaction access level and directory name
for me (and probably others) with regards to this topic. DELETE FROM [dbo].[tblFileTableBaseballLogos]
The feature is called FileTable.
Next Time Around in the Baker’s Dozen
The SQL Server FileTable is a mechanism that allows
you to map a folder/file system structure to a special In the “night-cap” of this Baker’s Dozen doubleheader
database table, where SQL Server maintains a (i.e., in the next issue), I’ll cover the new features in SQL
relationship dynamically. Yes, it’s that simple. (FileTable Server 2012 Integration Features. SSIS has always been
builds on the concept of the FileStream object from SQL a good tool for ETL development, though certain aspects
Server 2008). Listing 8 shows an example of creating of the tool have had “opportunities for improvement.”
a FileTable database, with a table that synchronizes a Microsoft meticulously re-crafted many aspects of SSIS
folder of images. The listing does the following: in SQL Server 2012. As a result, a good tool just got much
better. Stay tuned!
• Configures the instance of SQL Server for FileStream
access Kevin S. Goff
• Creates an empty database FileTableExampleDB
with FileStream capabilities
• Alters the new database and sets a FileStream di-
rectory name reference
• Creates a table with a reference to a specific direc-
tory (in this case, a folder that will hold images)
This means I can load the folder with images (Figure 7), and
have a corresponding table (tblFileTableBaseballLogos)
that’s associated with the images (Figure 8).
34 The Baker’s Dozen Doubleheader: 26 New Features in SQL Server 2012 (Part 1 of 2) codemag.com
FROM THE PRODUCERS OF CODE MAGAZINE
g 2 012
Sprin dule
Sche
Scheduled Classes
The following classes are currently scheduled for the Spring 2012. The most up to date information, as well as additional details, can be found at
www.codemag.com/training.
The CODE Framework can be downloaded for free (including source Learn JavaScript and jQuery in a Day!
code) from Codeplex.com. It consists of various components
and tools that help developers with common aspects of business This intensive 1-day lecture style boot-camp on JavaScript and
application development, such as simplified SOA development with jQuery has been designed specifically for developers who wish to
various clients, or WPF development, data access, and much more. quickly learn how to use these important technologies in various
The main focus of this framework is to enable productive, flexible, scenarios. Attendees of this class (who are assumed to know at least
and highly maintainable business application development. This the basics of another programming language such as C#, Visual
workshop answers all your CODE Framework questions. Attendees Basic, C++, or...) will first learn JavaScript language concepts and
will learn proper application architecture and design, enabling syntax and will then learn how to apply these concepts in various
attendees to build systems that are easy and productive to build scenarios including the use of the popular jQuery open-source
using the CODE Framework on various the supported platforms JavaScript framework. The class then proceeds towards a detailed
such as Windows, Web and Mobile. The workshop teaches highly look at the powerful features provided by jQuery, including its
productive development techniques. These topics are CODE Training various versions and modules (including 3rd party modules). The
specialties that are not taught anywhere else, making this one of aspects learned in this training class are generic and can be used
our most popular classes. Attendees of this workshop will learn in any JavaScript development environment, although most of
how to work productively and build future proof applications and the examples will use HTML web browser scenarios, sometimes in
systems, regardless of their prior knowledge (or lack thereof). combination with Microsoft back-end technologies to facilitate the
explanation of certain concepts.
Learn HTML5 and CSS3 in a Day! Note: This class can also be booked at a discount as part of our new
“Web Combo” class.
This intensive 1-day lecture style boot-camp on HTML5 and CSS3 for
developers who wish to understand what is new in HTML5 and CSS3,
how to apply those technologies and techniques to daily development A Day of SOA & WCF with Markus Egger
tasks today and tomorrow, and to judge the impact HTML5 will have on
the overall development landscape (including a discussion on HTML5 in Spend a day with Microsoft RD (Regional Director) and veteran MVP
non-browser scenarios, such as Windows 8 Metro). The class includes a Markus Egger to lean all about SOA (“Service Oriented Architecture”)
detailed look at all the aspects of HTML5 (such as new features, document and WCF! Attendees of this class will not just learn how to use
structures, changed elements, and so forth) as well as a general review WCF and SOA to a point where they can immediately start to build
of CSS and a close look at CSS3. The class also provides a guidance as to applications based on these techniques, but they will also be able to
which HTML5 features are ready for prime-time, which you still should evaluate the impact of these techniques and technologies on their
hold off on, and which may be useful in specific scenarios. future development efforts. This comprehensive 1-day class starts
at a beginner level, but quickly moves beyond theory to enable
Note: This class can also be booked at a discount as part of our new attendees to learn how to write real world SOA & WCF applications.
“Web Combo” class. Attendees will get to see many real-world examples that showcase
the benefits of such systems and have the opportunity to discuss
their projects and have their questions personally answered by MVP
iOS (iPhone/iPad/iPod) for .NET Developers and RD Markus Egger.
Apple has single-handedly re-invented mobile development, and Note: This class can also be booked at a discount as part of our new
started the whole “app craze”, with the iOS operating system used “Web Combo” class.
Visual Studio LightSwitch Windows Phone 7 (and 7.5) applications. No prior mobile device
With LightSwitch, RAD (Rapid Application Development) returns development knowledge is required.
to the world of Visual Studio, enabling incredibly fast business
application development for the “90% need”, with the ability to
further extend LightSwitch applications with “normal” Visual Studio WPF for Business Applications
techniques and technologies.
WPF, the de-facto standard for .NET Windows development, is a very
In this 2-day class, attendees will learn everything there is to know important technology for business application developers. However,
about Visual Studio LightSwitch, starting with the basic concepts coming from Windows Forms, WPF is a huge paradigm shift. This class
and paradigms behind LightSwitch. The workshop then continues will help drastically reduce the learning curve and allow attendees to
with the creation of a representative LightSwitch application. write productive WPF code quickly.
Attendees also learn how to properly organize and structure these
types of applications and how to best use technologies utilized by This workshop answers all your WPF questions by teaching
LightSwitch, such as Silverlight and WCF RIA Services. The workshop fundamental techniques that apply to WPF. Attendees will also learn
also allocates a significant amount of time towards LightSwitch proper application architecture and design, enabling attendees to
extension as real-world applications often need to venture beyond build systems that are easy and productive to build in WPF, but can
the built-in capabilities of LightSwitch. also be easily extended to other platforms and clients. The workshop
teaches highly productive development techniques. Time is also
allocated towards teaching attendees how to build applications
Web Combo - SOA & WCF, ASP.NET MVC, that look professional, and how to do so productively and without
the need of artistic talent. Many of these topics are CODE Training
JavaScript & jQuery and HTML5 & CSS3 specialties that are not taught anywhere else, making this one of our
This “Web Combo“ provides an easy and discounted way to book a most popular classes.
series of four of our most popular classes as a single event: “A Day
of SOA and WCF with Markus Egger“, “Learn ASP.NET MVC in a Day!“, Attendees of this workshop will learn how to work productively and
“Learn JavaScript and jQuery in a Day!“, and “Learn HTML5 and CSS3 build future proof applications and systems, regardless of their prior
in a Day!“. This provides a knowledge-packed 4-day event, allowing WPF knowledge (or lack thereof).
attendees to get up to speed with four of the most important areas of
modern web development (and beyond) in less than a week!
Mobile May 16 – 17, 2012 Windows Phone 7 and 7.5 (Mango) for .NET Developers
CODE May 24 – 25, 2012 Being Productive with the CODE Framework
* Individual line items can be booked as individual days. Alternatively, blocks (color-coded) can be booked in combination at greatly discounted rates.
Group and repeat-customer rebates may apply as well. For details, visit www.codemag.com/training
** Note that exact dates are subject to change based on customer needs. Please double-check dates on www.codemag.com/training
p Today !
Sig U
To sign up, visit www.codemag.com/training or contact us via
email (info@codemag.com) or phone (1-832-717-4445 ext 13).
Call us for group or repeat-customer discounts! TR AINING
An EPS Company
ADVERTORIAL
request in the form of a work item on the backlog in and other Outlook/TFS integration features we already
Team Foundation Server (TFS). Doing that manually could mentioned.
mean that you must copy important information from the
email to appropriate work item fields, attach the email On top of that, TeamCompanion offers a powerful agile
and all its attachments to the work item, fill up other project management toolset with team support. Most
necessary fields, possibly send a confirmation reply and non-developer users will find in TeamCompanion every-
other similar steps. This is way too many small steps that thing they require to work with TFS and they will never
will make you want to avoid dealing with new requests in need to switch from Outlook to any other tool.
the first place.
Ognjen Bajic
Using TeamCompanion from Ekobit, you create a new Information at Your Fingertips obajic@ekobit.hr
work item based on an email with just one click. Easily, TeamCompanion Product Owner
quickly and effortlessly. If a related work item already Making information available in an easy manner and at
exists, it is just as easy to find it and attach the email the right time is what TeamCompanion excels at. Drag
to it instead. work item queries to the Outlook Favorites folder to have
them always in sight and configure their scheduled ex-
And there is much more in this Outlook add-in than just ecution at regular intervals. As soon as there are chang-
email integration. It integrates Outlook and TFS in many es, you will be notified. Changed, new, and unread work
other ways: It connects Outlook appointments or tasks items appear clearly highlighted in bold, just the way
with respective work items, lets you set up work item re- newly received emails do. This is the least intrusive and
mainders, helps you send TFS reports via email or search most efficient way to be notified of changes. Usually, you
emails related to a particular work item, etc. would subscribe to receive notification emails. Scheduled
queries can spare you of such emails and provide the
same information in a much more efficient way. Ana Roje Ivancic
Stakeholders and Developers Collaborate Principal Tester
If you still like notifications and subscribe to them, than
By bridging the gap between email communication and when a build, changeset or work item change notification
TFS work item management, TeamCompanion connects arrives, it is easy to open the related TFS object from that
two worlds: the outside world of various stakeholders’ email and drill in its properties.
types and the inner world of the development team.
Stakeholders are looking at the project from outside
and usually can’t access TFS directly. This bridge en- Agile Project Management
sures their continuous involvement and high quality
direct communication. Uninterrupted interaction with TeamCompanion comes with a powerful agile project man-
stakeholders critically contributes to the success of the agement feature set. It works out of the box with all three
project. standard process templates (Agile, CMMI and Scrum) and is
highly configurable and suitable for any agile methodology.
Besides improving your communication with all involved It covers all major phases of agile processes: product back-
in the project, TeamCompanion provides you the right in- log grooming including ordering of product backlog items
formation whenever and wherever you need it. It helps (PBIs), sprint planning and assigning PBIs to sprints includ-
you work more efficiently and easily collaborate. ing capacity planning, resource load balancing and progress
tracking using the burndown chart. Velocity chart, various
embedded statistics and the burndown chart are based on
Full-fledged Team Foundation Server Client the transactional work item database and reflect all changes
to work items in real time. Using drag and drop you can
TeamCompanion is a full-featured TFS client inside Out- easily reorder PBIs, plan them for a particular sprint or sim-
look that supports all work item management related ply assign tasks to team members. All these actions directly
actions, SQL Server reports, and SharePoint document change all charts and statistics and help you constantly
library integration, adding to this many unique en- keep track of the project status and trends.
hancements. You can create and edit work items and
work item queries, execute queries in various ways, Once the team starts sprinting, TeamCompanion continu-
group query results or export them to Excel or Project. ously keeps load statistics for each team member and the
There are also work item reminders and appointments, team burndown up to date.
Figure 2: With real-time burndown chart and remaining capacity statistics for each team
member, it is easy to track progress during the sprint.
of scenarios, ranging from Windows to web and mobile up to the standards you set in the last decade or two,
scenarios using a wide variety of technologies, and out- not to mention expectations in the future? How can we
performing conventional multi-tiered applications in a fulfill the expectations of a technical and economic envi-
range of metrics. Using CODE Framework, it also becomes ronment where it is not acceptable to have to throw out
easy and extremely productive to build SOA layers. the entire application to support the latest mobile de-
vice or browser? And how do we fulfill those expectations
In today’s application landscape, there only seems to be in a way that’s a realistically feasible approach, highly
one aspect that is certain: Uncertainty. Which UI tech- productive, creates highly flexible and exquisitely archi-
nology or which mobile platform will be dominant in the tected systems that are easy to maintain without a large
years to come? We know that for business applications squad of rocket-science-level developers, and generally
especially, rich Windows UIs are still very popular and promotes high quality as a goal that is easy to achieve? Markus Egger
the most productive type of application. We also have megger@eps-software.com
no doubt about the significance of web applications in Markus is an international
general, and HTML5 in particular. We know that iOS and Services are the Answer speaker, having presented ses-
Android are important mobile operating systems, and we sions at numerous conferences
hope Windows Phone will catch up. There also is a good I believe very strongly that Services and SOA (Service in North and South America
chance that Windows 8 Metro will have a significant role Oriented Architecture) are a very good answer to this and Europe. Markus has written
to play. But do we know any of these for sure? And how problem. And by that, I do not mean the creation of XML many articles for publications
many of these does any system have to support now or Web Services or the creation of REST Services or any simi- including CODE Magazine, Visual
in the future? Even if you know that you want to build lar technology you might choose. Instead, I am talking Studio Magazine, MSDN Brazil,
your application based on HTML5, which is going to be about creating services that are more abstract and bro- asp.net Pro, FoxPro Advisor,
the predominant tool for building such applications a few ken out as generically callable objects with an agreed- Fuchs, FoxTalk and Microsoft
years down the road? Or which approach to building Win- upon interface (“contracts”). Once such abstract services Office and Database Journal.
dows 8 Metro applications will be the one you choose? are created, various deployment choices can be made. Markus is the publisher of CODE
Magazine.
Do you feel that REST is the ideal way to get to those ser-
Basing your systems on SOA and vices? Fine choice! You like XML Web Services, and SOAP
Markus is also the President and
Services is the best way to deal with the better? That’s fine with me too. You prefer binary optimized
Chief Software Architect of EPS
Software Corp., a custom software
uncertainties of today’s development services for efficiency? In scenarios where binary optimized development and consulting
landscape, build systems that will be services are technically possible, they might be the best firm located Houston, Texas.
maintainable for a long time, and adjust choice of all. But these are decisions that are made later. He specializes in consulting for
Start out with a REST Service and you might be stuck with object-oriented development,
flexibly to new demands. REST forever. The same is true for many systems that are Internet development, B2B, and
based solely on SOAP. But if you start out generic, you have Web Services. EPS does most of its
In short: It is currently impossible to answer many of these great freedom in choice. Perhaps you use TCP/IP-based ser- development using Microsoft Vi-
questions now, and it’s certainly impossible to answer these vices initially, but then decide you want to write an iOS or sual Studio (.NET). EPS has worked
questions if you are aiming for a 5- or 10- or even 20-year ho- Android client, and REST is the better choice for that. With on software projects for Fortune
rizon. 20 years may seem like an extremely long time in IT, but solid architecture, that is simply a deployment choice. 500 companies including Philip
realistically speaking, databases that have been maintained Morris, Qualcomm, Shell, and
for 10 or 20 years, or business logic that has its roots in VB6 None of these aspects are new. SOA has been around for a Microsoft. Markus has also worked
is not uncommon. In fact, one of the most common operating while and different types of service standards as well. But as a contractor on the Microsoft
systems in use today (Windows XP) is now more than a de- how do you really approach a project that utilizes SOA and Visual Studio team, where he
cade old. Although UI choices and platforms (such as phones do so in a way that is highly productive yet at the same was mostly responsible for object
and slates) have changed very rapidly and will likely continue easy to do, even for junior developers? And how do you modeling and other object- and
to do so, middle-tiers and databases have evolved at a much really call services using all these different standards? component-related technologies.
slower pace. Consider CODE Magazine as an example. The sub-
scriber system we are using for the magazine has continually If you have done service work in the past, you know that
evolved over the years, but many of its components are now a lot of this theory is not necessarily the way things work
over a dozen years old and that is perfectly fine. in the real world. Lots of services are stuck in SOAP. Lots
of services are REST-based and cannot adjust to other
So how do you work productively as a developer or archi- standards. In fact, many environments are specifically
tect in such an environment? How can you build middle geared towards the creation of specific types of services
tiers, business logic, and databases in a way that will live but can’t easily cross over to other standards. If you are
1. GetAllCustomers()
2. SearchCustomers()
3. GetCustomer()
4. SaveCustomer()
[OperationContract]
SearchCustomersResponse SearchCustomers(
SearchCustomersRequest request);
[OperationContract]
GetCustomerResponse GetCustomer(
GetCustomerRequest request);
[OperationContract]
SaveCustomerResponse SaveCustomer(
CustomerInformation request);
}
© Taalvi - Fotolia.com
SUBSCRIBE TODAY
AND DON’T MISS AN ISSUE!
Special offer!
Get a 3-year subscription for the price of 2!
www.codemag.com/subscribe/cm412
/// <summary>Response contract for GetCustomer() operation</summary> ///<summary>The customer›s company name.</summary>
public class GetCustomerResponse [DataMember(IsRequired = true)]
{ public string CompanyName { get; set; }
/// <summary>Constructor</summary>
/// <remarks>Explicitly set default values for all properties ///<summary>City, State for the customer›s main offices.</summary>
/// in the constructor</remarks> [DataMember(IsRequired = true)]
public GetCustomerResponse() public string Address { get; set; }
{
Success = false; /// <summary>Main phone line (switchboard) for the
FailureInformation = string.Empty; /// customer.</summary>
[DataMember(IsRequired = true)]
Customer = new CustomerInformation(); public string Phone { get; set; }
}
/// <summary>Customer’s total credit limit for all
/// <summary>Indicates whether the call succeeded without errors /// departments.</summary>
/// or problems.</summary> [DataMember(IsRequired = true)]
/// <remarks>'Success' is a standard member for CODE Framework public decimal CreditLimit { get; set; }
/// contracts. It is not technically required but we recommend
/// supporting it.</remarks> /// <summary>Date of customer›s first signed contract
[DataMember(IsRequired = true)] /// with us.</summary>
public bool Success { get; set; } [DataMember(IsRequired = true)]
public DateTime CustomerSince { get; set; }
/// <summary>If Success is false, FailureInformation contains a }
/// brief indicator of what went wrong.</summary>
/// <remarks>This should NOT contain an exception message for /// <summary>Shortened customer information suitable for use
/// security reasons. ‹FailureInformation› is a standard member for /// in lists</summary>
/// CODE Framework contracts. It is not technically required but we /// <remarks>For detailed customer information, use the
/// recommend supporting it.</remarks> /// CustomerInformation contract. However, for large lists (with
[DataMember(IsRequired = true)] /// potentially large amounts of data), use this contract
public string FailureInformation { get; set; } /// instead.</remarks>
[DataContract]
/// <summary>This is the payload this sample call will public class CustomerQuickInformation
/// return.</summary> {
[DataMember(IsRequired = true)] /// <summary>Constructor</summary>
public CustomerInformation Customer { get; set; } /// <remarks>Explicitly set default values for all properties
} /// in the constructor</remarks>
public CustomerQuickInformation()
/// <summary>Detailed information for a single customer.</summary> {
[DataContract] Id = Guid.Empty;
public class CustomerInformation FullName = string.Empty;
{ }
/// <summary>Constructor</summary>
/// <remarks>Explicitly set default values for all properties /// <summary>Unique customer ID</summary>
Once the creation of the new implementation project fin- to be executed to retrieve the list runs (the part that is
ishes, you have a project with all the required references to represented by a TODO comment) and finally, the Success
.NET Framework assemblies, CODE Framework assemblies, and flag is set to true, and the response object is returned. If
of course the contract assemblies for all the contracts you any of this fails, the catch-block kicks in, uses the CODE
choose to implement (ICustomerService, in this case). You Framework Logging System to log the problem away, and
also end up with a valid default implementation of all services returns a response that indicates failure with some fairly
(in a file called CustomerService in this example). The default rudimentary failure information (slightly more detailed
implementation is a class that implements the contract inter- than in the snippet above, which we trimmed for brevity)
face by creating implementations for all the required opera- that allows the caller to track down further information.
tions. For instance, the default for GetAllCustomers() is:
Note the use of the CODE Framework Logging System.
public GetAllCustomersResponse GetAllCustomers( This is a good idea, because there are other components
GetAllCustomersRequest request) in the system that can pick up this information, as we will
{ see below. Of course, a lot of people have their own log-
try ging systems or may even use other logging frameworks.
{ That is fine. You can easily plug those into the CODE
var response = new GetAllCustomersResponse(); Framework LoggingMediator object. This is an example of
a design philosophy we follow throughout all parts of the
// TODO: Add service-specific code here framework: We provide interesting default features, but
enable bringing in other components easily if desired.
response.Success = true;
return response; At this point, it is up to you to create the missing logic. For
} instance, you could go to the database to retrieve the cus-
catch (Exception ex) tomer information and return it from the service. This could
{ be done any number of ways. For instance, you could use
LoggingMediator.Log(ex); Entity Framework or NHibernate to connect to a database.
return new GetAllCustomersResponse
{
Success = false,
FailureInformation = «Generic fault...»
};
}
}
}
If you are now scratching your head and wondering how host.AllowHttpCrossDomainCalls();
that works and whether that is even really possible fol- host.AllowSilverlightCrossDomainCalls();
lowing REST paradigms: We are exposing these services
as REST services that support POST operations. RESTafar-
ians may now point out that this is not following all the Taking the Services for a Spin
REST paradigms that should support other verbs and so
forth and they are absolutely correct! Mapping an exist- Now that you have your services up and running, how
ing service to REST in this fashion only supports and uses can you take them for a spin? Using the development
www.Xamalot.com
ONLINE QUICK ID 1203071
solution called MongoDB. MongoDB straddles the quick lookup and management capabilities for your Mon-
NoSQL space nicely. A low barrier to entry and great goDB system.
performance help MongoDB continue to gain followers.
However, like all database solutions, MongoDB will not MongoDB uses JavaScript in the MongoDB shell. Every-
solve all of your problems. You need to know when and thing done in the shell will be JavaScript. When you en-
how to use it properly and more importantly, when not ter a command without the parenthesis the code for the
to use it. command displays. Having the ability to use JavaScript
can be really powerful whether you are writing MapRe-
duce queries or creating custom functions you want to
Mike Benner Oddly Familiar use in the shell.
me@mikebenner.com
http://mikebenner.com MongoDB stores your data in documents using a JSON-
https://twitter.com/#!/refried
chicken
style syntax known as BSON (binary JSON) making it a Installation
part of the document-oriented class of NoSQL solutions.
Mike Benner is CTO of Author- This article uses Mongo 2.0.2 for all of the examples, but
ityLabs where he gets to play anything over 2.x should work. You can download the lat-
with large amounts of data MongoDB is considered a
est version from http://www.mongodb.org/downloads.
and technologies. He is also a document-oriented datastore and The MongoDB shell that comes bundled in the download
technology mentor for Gang- it stores those documents in a will be sufficient for all examples.
plank and heads the Gangplank
Jr Initiative and coaches their
JSON-style syntax called BSON
(binary json). After downloading and unzipping the binary you will
robotics team.
need to create a path for the data to be stored. The de-
http://authoritylabs.com
fault location is /data/db. MongoDB does not create this
http://gangplankhq.com
Document-oriented solutions can take some getting directory, so you need to create it yourself. After you’ve
used to. Traditional RMDBS systems house their data created the directory you can start MongoDB by simply
in very well-defined schemas which are represented as calling:
tables. Each table definition is comprised of various
columns which effectively define the data model in /path/to/mongofiles/bin/mongod
that RMDBS system. Each time data is inserted into a
table, a new row is created. This data can be queried, If the installation went as it should, MongoDB is running
updated, deleted and inserted using Structured Query and the real fun begins.
Language (SQL). MongoDB, on the other hand, does
not store its data in tables; MongoDB stores its data
in collections. MongoDB collections are comprised of One Document to Rule Them All
JSON documents instead of rows. Documents consist
of key/value pairs – essentially a JSON hash. Unlike The examples will use Major League Baseball players and
traditional RDMBS systems which adhere to a strict their statistics. The database will be named mlb and con-
data schema, Mongo does not have a strict data sche- tains a collection called players. The documents in players
ma. MongoDB doesn’t care if you have a key/value pair hold the individual player details and statistics.
in one document but not in another. Each document
can contain its own data structure (if needed) in the All of the examples in this article will use the MongoDB
same collection. See Listing 1 for an example of the shell that comes bundled with the download. The shell
flexibility in action. uses JavaScript for all commands and functions.
An example of schemaless flexibility, Listing 1 has four Now you’re going to start the Mongo shell so that you
MongoDB documents that reside in the same collection. can interact with the MongoDB instance. To start the
Each document has an _id and name key, but the similari- MongoDB shell, open a terminal/command prompt and
ties stop there. A couple of documents contain a platform navigate to the location in which you installed MongoDB.
key. One document has a Twitter key and some have oper- Then type the following commands:
ating_system and homepage keys.
/path/to/mongofiles/bin/mongo
A powerful command-line shell comes bundled with use mlb;
MongoDB. You use the MongoDB shell for managing the
server, setting up authentication and everything else you This launched the Mongo shell, created a new database
need. Third-party graphical administration tools do exist named mlb and switched to that database. Using the db
for MongoDB and you’ll find them at http://www.mon- command before each method call tells MongoDB to ref-
godb.org/display/DOCS/Admin+UIs. These tools provide erence the mlb database.
You will now create a new collection and insert a new Listing 2: Inserting additional players
JSON document into that collection. In your terminal/
db.players.insert({
command window, enter the following:
name: "Miguel Montero",
age: 26,
db.players.insert({
bats: "left",
name: "Harry Blanco",
throws: "left",
age: 40, years_played: [
bats: "right", {year: 2011, team: "Arizona
throws: "left", Diamondbacks"},
years_played: [ {year: 2010, team: "Arizona
{year: 2011, team: "Arizona Diamondbacks"}
Diamondbacks"}, ]}
{year: 2010, team: "New York Mets"} );
]} db.players.insert({
); name: "Konrad Schmidt",
db.players.find(); age: 27,
bats: "right",
You have now created a collection named players and throws: "right",
inserted a document with the details of Harry Blanco. years_played: [
MongoDB does not require a predefined schema so your {year: 2011, team: "Arizona
collection was created for free just by referencing it in Diamondbacks"},
the command. Similar to the flexibility with key/value {year: 2010, team: "Arizona
Diamondbacks"}
pairs in documents, you can just as easily create new col-
]}
lections. The flexibility of schemaless design comes with a
);
caveat; typos will create new collections or keys if you are
not careful. You can see your new collection by entering
the show collections command. query against those embedded documents and create in-
dexes on keys contained within them.
Retrieving Documents
Diving for Data
db.players.find() returns all the documents in the col-
lection. In our case we only have one document to re- Go add a couple more players (Listing 2) to the mlb col-
turn. If you look at the output you will see a key we did lection. After inserting the additional documents, run
not insert labeled _id. _id refers to the MongoDB Objec- db.players.count() in the console/terminal to return the
tId that is assigned to all of your documents. Think of it total number of records in the collection.
as incrementing the primary key field in a SQL system.
This ObjectId gets created using a combination of items db.players.count();
which go beyond the scope of this article, but have to
do with MongoDB’s clustering and sharding capabili- The shell simply shows 3. Now how about all of the play-
ties. ers that bat right-handed?
MongoDB does not support joins like a typical SQL solu- db.players.find({ bats: "right"});
tion. Instead MongoDB uses embedded documents. Our
insert command contained an array of embedded docu- The query returns two documents containing Harry and
ments called years_played. Embedded documents allow Konrad. What about players that played in the year 2011?
you to make a single query and return all the data back
without joining to other tables. Even better, you can db.players.find({ "years_played.year": 2011});
Updates, Upserts and Document Replacement Query your collection again and you will see he was not
added a second time but his record was updated to reflect
Updating documents in your collection is not as straight his ability to switch hit.
forward as in SQL. For example, if we wanted to correct
Miguel Montero’s age to 28 and that he throws right
handed, we can’t simply do this: House Cleaning
db.players.update({"name": "Miguel Montero"}, For most developers and DBAs, learning MongoDB re-
{age:28, throws: "right"} quires a paradigm shift and learning to think about
); things differently can cause you to make mistakes, but
they are easy enough to clean up in MongoDB. The re-
The document-oriented nature of MongoDB causes the move command will let you delete documents based on
update to replace all the values in the current document the criteria you provide. For example, you can remove
with completely new values, removing keys you did not Miguel Montero with the following command:
provide in the update. MongoDB replaces the document
because it does not track the key/values in the document db.players.remove({"name": "Miguel Montero"});
like a RDBMS does for columns. Using another special
operator, we can avoid replacing the whole document. Not using any criteria will cause all records to be re-
moved.
db.players.update({"name": "Miguel Montero"},
{$set: {age:28, throws: "right"}} db.players.remove();
);
Or you can just drop the whole collection.
The addition of $set in the update function informs Mon-
goDB to update the keys in the document and not to remove db.players.drop();
MongoDB goes well beyond being a document-oriented MongoDB has a feature called
data store with special tricks for accessing and updating capped collections that enables
your data. For example, MongoDB has built-in cluster- you to build a collection that is
ing called Replica Sets. MongoDB also has the ability to limited to a specific size. A capped
Shard across multiple servers and allows you to write Ma- collection is a performant First
In First Out collection (FIFO) that
pReduce functions.
can be useful in situations such as
logging.
Replica Sets are a solution in which three or more servers
operate with a single primary and multiple secondaries/ You can update documents in
arbiters. If you lose your primary for any reason, a vote a capped collection but that
will take place and one of the secondaries will be pro- document will still be removed
moted, minimizing downtime and data loss. While you based on the order that it was
can always run MongoDB in a standalone solution, you inserted.
should always use a Replica Set in your production en-
vironments. You cannot remove documents
from a capped collection. They
When your app collects more data than you know what are removed automatically as the
to do with you will find yourself needing to shard across collection hits its storage limit.
multiple servers. MongoDB gives that option to you out
of the box. The sharding capabilities of MongoDB makes
scaling to handle your growth easy by setting up multiple
Replica Sets and spreading your data across them with
relative ease. Sharding can be useful when your inserts
are coming faster than your disk can handle, when your
collection reaches MongoDB’s 10TB collection limit or
you need more performance for reads and need to share
the load across servers.
Where to Next?
I encourage you to look through the operators linked to
earlier and see what other queries you could run. Mon-
goDB allows JavaScript, so be creative. It takes time to
really grasp the doors MongoDB opens. Look at your ex-
isting apps and imagine how you could structure your
data in MongoDB.
Mike Benner
2010. If you write code on the .NET Framework, you public class Invoice
would have to be living under a rock to have not heard {
of F#. public LineItems InvoiceLineItems { get; set; }
So you know it’s there – the question really is, what is it public void ProcessLineItems()
useful for? Why do you need another programming lan- {
guage? Is C# not good enough? Conventional wisdom has //what if LineItems is null?
told us that C# is what you use for line of business apps, foreach(var item in this.InvoiceLineItems)
and that you only use F# for scientific apps, heavy math {
Aaron Erickson apps, or apps that do monte-carlo simulation. Strangely //process each lineitem
Website: http://nomadic- missing from that list are apps that you and I are likely to }
developer.com/ be asked to write. F#, according to some, is like the One }
Twitter: AaronErickson
Ring to Rule Them All – all powerful, but so dangerous }
Aaron Erickson is a technology that it must be kept under lock and key!
writer, software developer and In this example, Invoice contains an implied contract.
consultant at ThoughtWorks. Specifically, it states that InvoiceLineItems will be ini-
His life’s work is helping
F# isn’t just for Wall Street; tialized before someone tries to call ProcessLineItems. Of
convert the best human capital it is a compelling technology for course, one can fix this code rather easily:
into results for companies that Main Street as well.
empower both the knowledge public class Invoice
workers who produce software, Balderdash, I say, to those who want to keep the power {
and the people in the compa- of F# locked up inside of research labs, universities and public LineItems InvoiceLineItems { get; set; }
nies whom we serve. hedge funds. Power to the people! F# isn’t just for Wall
Aaron frequently speaks at Street; it is a compelling technology for Main Street as public void ProcessLineItems()
events such as TechEd, VSLive, well. In this article, I will cover specific reasons, with {
and .NET user groups – with examples, that demonstrate why you should learn this if (this.InvoiceLineItems != null)
a goal of furthering the language and advocate for its adoption. {
exchange of ideas – be they //Now we guarantee that LineItems isn't null
technology contributions – or foreach(var item in this.InvoiceLineItems)
observations about the tech- The Evils of Null – Use F# to Set Yourself Free {
nology consulting business. From NullReferenceException Console.WriteLine( item );
}
If you have written any non-trivial amount of code, and }
actually seen such code through to production, you have }
likely had to deal with the dreaded NullReferenceExcep- }
tion. It is one of the most common types of Exceptions,
particularly in production. It is also one of the hardest to Now at least we do not throw the NullReferenceExcep-
track down, particularly in complex systems with lots of tion. However, we have also added “code-noise” making
moving parts. the code harder to understand at a glance, adding three
lines that are there purely due to the fact that the object
The Source of NullReferenceException may be ill constructed at the time of the line items being
processed.
A very common cause of NullReferenceException is failure
to fulfill an implied contract. Much like a married man Now lets look at this from the F# point of view:
who gets in trouble for not getting the implied flowers
that are due on an anniversary, systems get in trouble type Invoice = { InvoiceLineItems : LineItems }
when they expect a value to exist in, say, a member vari- with
able, but none does, causing the offending NullRefer- this.ProcessLineItems() =
enceException: this.InvoiceLineItems |> Seq.iter (
62 Smashing the Myth: Why You Must Learn F# – Even If You Aren’t Writing Rocket Science Apps codemag.com
fun item -> Console.WriteLine( item ) invoice is to be paid to the normal address. It is not un-
) common to have fields like this that are optional – and it
is common that programmers will use null as a sentinel
Certainly, the syntax is different. Here, in F#, we use the value to represent the idea of “value not provided.” How
type keyword to define an F# record – a concept with cer- does F# handle such a situation if null is not allowed?
tain similarities to a C# class, but some really important
differences. The properties of the record get defined in the type Invoice = { InvoiceLineItems : LineItems;
braces that follow – the part that reads { InvoiceLineIt- BillToAddress : Address option }
ems : LineItems } (note, I called the property InvoiceLi- with
neItems purely for clarity of type versus name when com- this.ProcessLineItems() =
paring the syntaxes – one could just call the property Lin- this.InvoiceLineItems |> Seq.iter (
eItems as well for brevity). The part after the with state- fun item -> Console.WriteLine( item )
ment is where you can define methods for your record, like )
we do here with ProcessLineItems. The implementation
of the method then passes the InvoiceLineItems to Seq. If something is optional, in F#, you use the option key-
iter, which takes as its parameter the thing that should be word after the type name to indicate that you can have
done to each individual item when iterating. zero or one address. Great! But have we re-introduced
null? Not so fast:
That all said, do not let the syntax make you think F# is
hard. It is certainly different, particularly coming from //with a bill to
“curly-brace centric” languages like C#. Once you get let myInvoice = {
used to it – usually after a couple weeks of working with InvoiceLineItems = someLineItems;
the language – it will feel far more natural. BillToAddress = Some(myOtherAddress) }
In the case above, we have added an optional field – Bill- Perhaps so, perhaps not. F# will not will stop you from
ToAddress. Lack of a BillToAddress may indicate that the writing bad code that crashes orbiters. However, it does
codemag.com Smashing the Myth: Why You Must Learn F# – Even If You Aren’t Writing Rocket Science Apps 63
give you tools you can use to help avoid this class of let recommendationForFreezingWeatherWrongAgain =
problem should you choose to use these tools. Consider clothingRecommendation 32m<farenheight>
this example one might use in a piece of software that
recommends what to wear given certain weather condi- //but this will work!
tions: let recommendationForFreezingWeatherRight =
clothingRecommendation 0m<celsius>
public enum Clothing { Parka, Jacket, Shirt, Bikini }
In doing this we have done two important things. The
public class ClothingRecommendationEngine most obvious is that we have avoided a bug – the old code
{ would have left you outside in freezing weather wearing a
public static Clothing DoRecommendation(decimal t) bikini. The F# code recommends a nice, warm coat instead.
{ This alone makes it a win! But more importantly, the new
if (t < 0m) return Parka; version of the code is more clear. Before, the reader would
if (t < 15m) return Jacket; have had to look all around the rest of the code to infer
if (t < 30m) return Shirt; what units were expected. This new version makes the ex-
return Bikini; //unless your legs are hairy pected units much more explicit. The API of the F#-based
} recommendation engine requires much less guesswork.
}
This is no small thing. In any non-trivial piece of code, we
This is rather straightforward – based on the tempera- deal with numeric concepts. Most interesting software
Learn More about F# ture, recommend a given type of clothing. Upon closer deals in things that have numeric units – money, time,
inspection, you will notice that the algorithm assumes inventory or any other thing that we may count.
You can learn more about F#
online by visiting the HubFS
you are providing the temperature in Celsius. Imagine a
community at http://cs.hubfs. programmer in, say, Belize or the Cayman Islands, two of
net/, or by trying F# online at three countries that have yet to convert to Celsius. You F# Will Save You from Mutation
http://www.tryfsharp.org/. If you might end up doing this:
would like to take a deeper dive, Mutation – variables in your code may not be the root of
we recommend Professional F# 2.0 var recommendationForFreezingWeather = all evil, but they are close. Granted, they are a necessary
by Aaron Erickson, Ted Neward, ClothingRecommendationEngine.DoRecommendation(32m); evil for a small subset of problems. But I am not too far
Richard Minerich, and Talbott off when I say that variables, as we know them in C#, are
Crowell, available on amazon. In the event that it’s freezing someday in Belize, your like little demons inside your codebase that make it bug-
com (http://www.amazon.com/ software may be perceived to have a bit of an issue! gier and harder to maintain.
Professional-F-2-0-Ted-Neward/
dp/047052801X). Will F# Save Me From Freezing in Belize? Programming Without Variables? Are You Nuts?
“Units of measure” is the concept in F# that solves this The problem with variables is that they vary. Borrowing an
type of problem. We can rewrite the C# version using F# analogy from mechanical engineering, they are the moving
as follows: parts of your software. Any machine that does much needs
moving parts. However, any mechanical engineer worth her
type Clothing = Parka | Jacket | Shirt | Bikini salt does everything she can to reduce to the bare minimum
[<Measure>] type celsius the number of moving parts in a given machine. Doing so
reduces the number of things that can go wrong, reducing
let clothingRecommendation (temp:decimal<celsius>) = the amount of maintenance a given machine needs.
match temp with
| t when t < 0m<celsius> -> Parka Software is no different. You want as many moving parts
| t when t < 15m<celsius> -> Jacket (variables) as absolutely needed, but no more than that.
| t when t < 30m<celsius> -> Shirt Let’s look at a common example, a Money class:
| _ -> Bikini
public class Money
The code has many similar concepts, with a key differ- {
ence being the [<Measure>] type Celsius line, and the public string Currency { get; set; }
associated parameter temp that takes on what, to a C# public decimal Amount { get; set; }
programmer, looks like a generic specification. In fact, }
you can read it the same way – just as you would have
a List<T> in C#, in F#, you can have a decimal (or other Despite this being a small class, this code has far too
numeric type) of M, so long as M is a unit of measure. many moving parts. The first thing that needs to be done
is that we need to make sure that when this object is
So how does this help? The consumer of the function will created that both Currency and Amount have valid values
not be able to just pass any number to the recommenda- upon creation:
tion engine:
public class Money
//this will yield a compile failure... {
let recommendationForFreezingWeatherWrong = private Money() {} //remove parameterless cons
clothingRecommendation 32m public Money(string currency, decimal amount)
{
//as will this... Currency = currency;
64 Smashing the Myth: Why You Must Learn F# – Even If You Aren’t Writing Rocket Science Apps codemag.com
Amount = amount; have to go against a lot of established C# convention (no
} automatic properties for you!), and write lots of extra
public string Currency { get; set; } code. In F#, our Money class is as follows:
public decimal Amount { get; set; }
} type Money = { Currency : string; Amount: decimal }
This is a good first step. However, there are still too many Yes, that is one line of code. If you are being paid by line
moving parts. Changing currency should not be possible of code, this may not make you particularly happy. How-
without changing the amount, since a currency change ever, if you care about productivity and making it easier
implies an amount change outside of a rare case of a 1:1 to do the right thing, you probably should consider F#.
currency conversion ratio. We need to change the code to The F# difference isn’t that it lets you write immutable
enforce that constraint: code – you can do that in C# with a lot of work. F# makes
it simpler to do so, which results in more code being right
public class Money by default, which is a net win for your development team.
{
private readonly string _currency;
private Money() {} You Don’t Need to Understand Monads
public Money (string currency, decimal amount)
{ Notice that in this article, not once did I mention the
_currency = currency; word monads. One of the biggest reasons that F# has a
Amount = amount; reputation as a “hard to learn language for people with
} too many IQ points” has nothing to do with the language
public string Currency { get { return _currency; } } itself, but the functional programming community. Many
public decimal Amount { get; set; } of these people, God bless them, work in environments
} where the word monad has as clear of a meaning that the
word beer has to the rest of us. To these folks, catamor-
The improved version now has a _currency as a readon- phism is a word to be used in normal parlance. Nothing
ly property, which enforces a constraint that you can’t wrong with that – these folks do a great job pushing the
change the currency of an existing amount of money. It envelope and inventing things. We would not have things
is one less moving part – one that should never move in like Google, Pandora, or Siri without them!
the first place (i.e., if you want something as a differ-
ent currency, create a new Money object after doing a However, just as we took things from NASA and the Space
conversion). Program and integrated them into technologies that help
us on a day-to-day basis, we need to capitalize on the
While the design is improved, frankly, I am still a bit best technologies that come from our research labs. F#
paranoid. In a large system I could, in theory, pass my is one of those things – once a product of Microsoft Re-
money to some function out there, it could store a refer- search, it sits on your desk in Visual Studio 2010, ready
ence to me, change my amount later, and without some for you to write less buggy, more stable software with it.
explicit checks, I may not know it. To solve this problem, The next move is yours – load it up in Visual Studio 2010,
I can make the class immutable in C# as follows: or even consider trying it out on the web at http://www.
tryfsharp.org/. Either way, you will quickly be on your
public class Money way to enjoying its many benefits.
{
private readonly string _currency; Aaron Erickson
private readonly decimal _amount;
private Money() {}
public Money (string currency, decimal amount)
{
_currency = currency;
_amount = amount;
}
public string Currency { get { return _currency; } }
public decimal Amount { get { return _amount; } }
}
In C#, you can do immutability, but you will work for it.
Every time you want to make something immutable, you
codemag.com Smashing the Myth: Why You Must Learn F# – Even If You Aren’t Writing Rocket Science Apps 65
Post Mortem: Xiine for iOS
In the Sept/Oct 2011 issue of CODE Magazine, I wrote about Xiine for Android. Let me remind you that
Xiine is an electronic reader application for CODE Magazine. It was originally written in C# using WPF and is
based on SOA architecture. With this software, all subscribers (it’s free) can read CODE Magazine issues
on a PC. You can download Xiine at http://www. Like logging in and choosing a brand, there is
xiine.com. minimal difference between the Android and iOS
versions for choosing an article from the list.
Xiine is popular for digital content. There are
desktop, Web, WebOS, and of course, the Android There wasn’t much work to do to write the code
edition, which is now being distributed by An- for the interface because we could base the iOS
droid Market and Amazon Marketplace. on the Android code that already existed.
There was one platform missing, though: the iOS Because we already had the Android version, we
version. That’s the reason we decided to write didn’t need to worry about layout and how the
Xiine for iOS and share this new experience. objects would fit in different screen resolutions.
Because CODE is a magazine, the same version We already had the layout set and even though
should be supported on both the iPod Touch/ Objective-C was a brand new language for us, it
iPhone and the iPad. Figure 1: The architecture for Xiine service is simple. was learnable.
Xiine for iOS was CODE’s very first Apple project we could have the same simplicity and functional-
and we passed through some roadblocks. ity: Enter the user name and password. Because we already had
the Android version, we didn’t
We wanted the users to have a good UI experi- After the log in, the user can see the available need to worry about layout and
ence, just like the Android version so we made a brands (see Figure 2). The iOS version is much how the objects would fit in
list of goals: the same as the Android page and shows the title
and description on the list. different screen resolutions.
• Authenticate Xiine users.
• List available brands and respective issues. After the brand is chosen, a list of magazine Just like when we built the Android version, the
• Make clean and intuitive screens. issues with complete information is displayed usage of the JSON library was one of the most
• Display user information. when a magazine is clicked (Figure 3). It’s a important parts of the project, as all the infor-
• Enable reading articles. little bit different on the iOS version, but not mation needed was available from a WCF service.
• List already read articles. much. Also, we had already made the changes needed
• Zoom in and out on an article page.
• Save a history of what has been read.
• Use up minimal code-writing time.
The Architecture
Memory Management
preview here: http://www.asp.net/mvc/mvc4. ASP.NET MVC out page. Structurally, it is very similar to ASP.NET MVC 3.
4 also runs inside of Visual Studio 10 and the Visual Studio In ASP.NET MVC 4, you will see a number of new additions
11 Developer Preview. MVC 4 can be hosted alongside MVC in the header:
3. You can find all the details concerning installation in the
aforementioned link. As with all developer preview/pre- • jQuery UI CSS
release software, features sets are subject to change, which • jQuery UI js library
may range from minor tweaks to major changes. Please keep • Ajax login js library
that in mind as you evaluate any developer preview as to
how you can incorporate it into your development efforts. In addition, you will see a number of new CSS class defi-
John V. Petersen nitions. For example, the new content-wrapper class en-
email: johnvpetersen@gmail.com capsulates the body which facilitates centering. Return-
blog: codebetter.com/johnpetersen Major New Features that Microsoft has ing to the header section, you will now find this code:
twitter: @johnvpetersen
Announced Thus Far
John Petersen has been develop- <meta name="viewport" content="width=device-width">
ing software for 20 years, starting
with dBASE, FoxBase+ and Clipper According to the public site, the following are the major Viewport is an HTML 5 meta tag that controls how your
thereafter, migrating to FoxPro new features that are part of the ASP.NET MVC 4 roadmap: content will appear in mobile browsers. This, in combina-
and Visual FoxPro and Visual Ba- tion with the new CSS classes is how adaptive render-
sic. Other areas of concentration • Revamped project templates ing works in ASP.NET MVC 4. While you could have always
included Oracle and SQL Server. • New mobile project template added this yourself, it’s nice to have the default project
John is the Philadelphia Microsoft • Recipes (a new method to generate code) templates handle these tasks.
Practice Director for CEI America • Enhanced support for async methods
(www.ceiamerica.com), a Micro-
soft Gold Partner. From 1995 to
2001, he was a Microsoft Visual
In this article, I’ll take a quick look at two of the four ma- New Mobile Project Template
jor features: revamped project templates and the mobile
FoxPro MVP. Today, his emphasis
project templates. In the next article, I’ll address recipes While adaptive rendering of a site that is primarily de-
is on ASP MVC .NET applications.
He is a current Microsoft ASP.NET and async support. Hopefully by the time part 2 comes signed for desktop browsers will get you pretty far, there
MVP and a member of ASP Insid- out, Microsoft will announce a more definitive release are situations when you will want to create a site that
ers and a member of the Telerik date for ASP.NET MVC 4 and they will lock-in the feature is written specifically for mobile devices. Recognizing
Community Insiders Program. set. For a complete list of announced new features, be that need, the ASP.NET MVC 4 team went ahead and gave
John is also a member of the sure to refer to the release notes http://www.asp.net/ us a mobile application template out of the box. In the
development team that develops whitepapers/mvc4-release-notes. Jan/Feb 2012 issue of CODE Magazine I introduced you to
and maintains the Nerd Dinner jQuery Mobile. As you learned, it was relatively simple to
Application (www.nerddinner. incorporate the jQuery Mobile libraries and CSS into your
com). John has published five Revamped Project Templates existing applications. Nevertheless, for those that are
books and over 60 industry just getting up and running with jQuery Mobile, it’s nice
articles. John also participates The steps to create an ASP.NET MVC project have not to have all of that in the box. Figure 5 illustrates how the
in several open source projects. changed. However, ASP.NET MVC 4 presents you with a home page (home/index) appears in a desktop browser.
In 2004, John graduated from new option in the new project dialog box illustrated in
the Rutgers University School of Figure 1. Figure 5 is probably not what you would want rendering
Law with a Juris Doctor Degree. to the desktop. Then again, I used jQuery Mobile to opti-
He passed the Pennsylvania and I will discuss the new mobile project application template mize this project for mobile devices. Figure 6 illustrates
New Jersey Bar exams and was in in the next section. To illustrate the new default Inter- how the home page appears on a mobile device.
private practice for several years.
net/intranet project templates, let’s keep the defaults in
Figure 1. As you can see in Figure 2, ASP.NET MVC 4 has Reviewing the contents in Views/Shared/_Layout.cshtml,
a significantly revised CSS design. we see something that is far less complex than its In-
ternet/intranet application template counterpart. In the
Even if you do not take advantage of the new mobile ap- header section, you will find references to the jQuery Mo-
plication templates, through a technique called adaptive bile CSS and js library resources. As with other jQuery
rendering, your application will adjust to different form Mobile pages, you will find references to the HTML5 se-
factors as illustrated in Figure 3. mantic markup data-role item.
Figure 4 illustrates how adaptive the rendering is with The support for mobile applications looks very encourag-
respect to the new Ajax-based login screen. ing. Up to this point, you have seen two separate examples
where in each case I demonstrated a distinctive project
As you navigate through the project artifacts to see template. What about cases where you have one project
what’s new, be sure to focus on the Views/Shared/_Lay- that could serve content to a variety of devices? What
SPONSORED SIDEBAR:
Project Success Kit
CODE Consultants can help you
build applications better and
faster, with reduced risk and
increased return. The Project
Success Kit will help increase
the quality of your development
team. In all of our services, we
aim to achieve an excellent level
of maintainability and reusability.
We provide training, development,
project management and
architectural expertise.
If the browser making the request is actually a mo- Figure 10 illustrates the view that is rendered when navi-
bile device, than any overridden browser settings are gating to the home page with an iPhone.
Figure 9: The ViewSwitcher Controller provides the ability to override default browser.
If you navigate to the same page from any other mo- this series, I’ll pick up with two additional major features
Figure 10: Display Modes allow bile device, the default mobile layout (_Layout.Mobile. in ASP.NET MVC 4: recipes and async method support.
us to create device-specific views. cshtml) will be rendered. Recipes are code generation plugins that are supported
through NuGet. Perhaps you have wanted to customize
what happens when you add an area, controller, view,
Conclusion etc. Recipes will make that task easier than before. As for
async method support, this feature ties into the C# 5 and
As you can see, if I could summarize ASP.NET MVC 4 in one the Async CTP (http://msdn.microsoft.com/en-us/vstu-
phrase it would be “Mobility Support – Out of the Box!” dio/async.aspx). Perhaps you have a long running task
Granted, we could do these same things with MVC 3. But that you would like to make cancellable. While we have
it would have required us to roll our own templates and in been able to handle these tasks with Ajax and JavaScript,
spite of our best efforts, nothing would be baked into the it would be nice if we could achieve the same thing with
framework. Display Modes is a great example of why we native C# code.
want such things baked into the framework. And like so
much in the ASP.NET MVC Framework, we get the best of John V. Petersen
both worlds: baked in functionality and extensibility. This
reminds me of when Microsoft introduced remote valida-
tion in ASP.NET MVC 3. Again, we were able to achieve the
same things before. With remote validation being baked
into framework, a much more elegant solution evolved,
one that makes it easier to bring new folks on board.
These new baked-in mobility features will make it easier
than ever for developers who have wanted to extend
their mobile applications to mobile devices. In part 2 of
Pythagorean Theorem—is itself based on rigor going to be able to progress. They chose to re-
and logic and proof. Lots of geometric “founda- main mired in the concrete, and not bother with March/April 2012
tions” are in fact derivations. the abstraction, because to them, numbers were Volume 13 Issue 2
about counting sheep and rocks and land.
Interpretations Group Publisher
The Greeks took an abstraction, simplified the Markus Egger
The Greeks were famous for their schools and system, and a whole new way of thinking opened Associate Publisher
Rick Strahl
centers of learning, most of which got absorbed up.
into other cultures when the Greek Golden Age Editor-in-Chief
Rod Paddock
came to a crashing halt after some 50 short years And that, my friends, is what an abstraction
Managing Editor
in the historical spotlight. Lessons abound in this should do. Ellen Whitney
Grecian view of the world that we can utilize for
Content Editors
software. (For those interested in a light refresher on math H. Kevin Fansler
combined with the place in history and historical Erik Ruthruff
For starters, notice that the power of math came context surrounding these discoveries, I highly Melanie Spiller
when rather than adding to the mental model, recommend the book, Mathematics for the Non- Writers In This Issue
the Greeks stripped it down. They reduced it to mathematician, by Morris Kline.) Milton Abe Mike Benner
Markus Egger Oren Eini
its simplest essence: just the number, with no Aaron Erickson Kevin S. Goff
units or attachments. That suggests that maybe, Ted Neward Sahil Malik Ted Neward
just maybe, sometimes the right thing to do in Rod Paddock John V. Petersen
Paul Sheriff
a model is strip it down, not bury it underneath
more levels of abstraction. Technical Reviewers
Markus Egger
Rod Paddock
This is part of the problem I have with object/ Art & Layout
relational mapping tools: by the time we get King Laurin GmbH
through all the code to put the string into the info@raffeiner.bz.it
table, it’s been through dozens of classes and nu- Production
merous transformations. If the data wants to be Franz Wimmer
King Laurin GmbH
stored relationally, why not present it that way? 39057 St. Michael/ Eppan, Italy
And if it doesn’t want to be presented that way,
Printing
then why store it that way? Fry Communications, Inc.
800 West Church Rd.
The other lesson to learn is that simple empirical Mechanicsburg, PA 17055
evidentiary “proofs” are nothing but: no matter Advertising Sales
Tammy Ferguson
how many tests we write, we haven’t “proven” the 832-717-4445 ext 26
software safe unless we can somehow, based on tammy@code-magazine.com
logic and some core axioms, reason out the re- Circulation & Distribution
sults apart from the actual units. In other words, General Circulation: EPS Software Corp.
it is possible to have software failures despite Newsstand: Ingram Periodicals, Inc.
Media Solutions
unit tests that cover 100% of your codebase. Source Interlink International
Yes, unit tests will help give us evidence that the The News Group
cases we anticipated are covered. And that’s a Subscriptions
good feeling, no doubt about it. But that’s not Circulation Manager
“proven” correct. Cleo Gaither
832-717-4445 ext 10
subscriptions@code-magazine.com
Type systems, as it turns out, are the program-
ming language’s attempt to provide that math- US subscriptions are US $29.99 for one year. Subscriptions
outside the US are US $44.99. Payments should be made
ematical basis for determining a program’s in US dollars drawn on a US bank. American Express,
correctness, and even there we run into some MasterCard, Visa, and Discover credit cards accepted.
distinct cliff edges. It has become fashionable Bill me option is available only for US subscriptions.
Back issues are available. For subscription information,
in the past decade to discard type systems and email subscriptions@code-magazine.com
rigorous type checking by a software system de- or contact customer service at
signed for such checking (e.g., a compiler) in 832-717-4445 ext 10.
favor of languages that “get out of the way” and
a scaffolding mechanism to run a piece of the Subscribe online at
www.code-magazine.com
system. Instead, we look at the results (e.g., a
unit test). CODE Component Developer Magazine
EPS Software Corporation /
Publishing Division
The ancient Babylonians used the value “3” to 6605 Cypresswood Drive, Ste 300, Spring, Texas 77379
describe the magic number used when calculat- Phone: 832-717-4445
ing the area of a circle, because it was the closest Fax: 832-717-4460
approximation they could make to the value pi.
It was good enough for their use, but that didn’t
make it right. And without that, they were never
Managed Coder:
On Abstraction
Writing software is hard, particularly when the schedules keep programmers “nose to the
grindstone”; every so often, it’s important to take a breather and look around the world and
discover what we can find—ironically, what we find can often help us write software better.
Programmers, software designers, and architects an even more accurate source of popular percep- that we do to the greater good of humanity. I’ve
constantly talk about the need for “good abstrac- tions. seen (in fact, I’ve made) the comparison of the
tions” and “well-defined models” of the software software abstractions we build to the “flickering
being built, but recent readings have led me to Anybody here remember the opening scenes of shadows” that Plato used to describe the concept
wonder whether we’re using the idea correctly. the recent TRON movie sequel? You know, the of “forms,” the abstract essence, if you will, of
one where they took Jeff Bridges (my twin from the material world around us. The analogy he
It’s not uncommon for software guys to argue— a distant universe) and reverse-aged him to look used is that we are men in a cave, sitting with our
for days at a time, in some cases—over the “ab- like he did in the original TRON movie and had backs to a fire, only able to view objects passing
stractions” being written. Everywhere you look him play both himself (the good guy) and the in front of the fire (but behind us) as shadows
in software, we find abstractions. Everything in program-copy of him from twenty years ago (the flickering against the wall. We can glean the basic
software seems to be an abstraction over some- bad guy)? If you don’t, no worries: go grab the shapes, but without any degree of accuracy, and
thing else: objects are abstractions over data- TRON:Legacy soundtrack from your favorite music none of the nuance.
bases, databases are abstractions over one or store. It’s good coding music.
more files, files are abstractions over file streams, The rationale, then, is that the closer our mod-
which in turn are abstractions of the data moving Cue up “The Grid” and listen to the little back- els can get to the “real world” the better. The
across the peripheral bus (itself an abstraction) story speech he gives. deeper the level of nuance, the more accurately
that communicates with the hard drive, storing the model reflects the business world, the more
bits of data in (you guessed it) abstractions of The Grid. A digital frontier. I tried to picture clus- successful the software will be.
sectors, tracks, blocks, and who knows what else. ters of information as they moved through the
Drill down far enough, and sure enough, it all computer. What did they look like? Ships, motor- Mathematics
turns into 1’s and 0’s. But even those 1’s and 0’s cyles? Were the circuits like freeways?
are abstractions for an arbitrary decision made The Greeks had a different notion of abstraction.
somewhere around the “big bang” of the com- Waaaait a minute. I realize this is a movie, fic- They were really the first civilization to notice
puting universe, to consider a certain amount of tionalized to Hollywood’s weird, distorted tastes, that whether you had three rocks, three pigs,
positive current to be a “1” and a certain amount but this is a little over the top. When’s the last or three acres, an abstract idea of “three-ness”
of a negative current to be a “0”. Maybe. I’m not time you kicked off a build and saw a little mo- was present, and it didn’t really matter whether
sure—I’m a software guy, I deal in abstractions, torcycle light-cycle take off across your screen, you were adding together rocks, pigs, or acres
not a hardware guy who ends up watching those complete with cool energy trail to kill all those (or even some combination of all of them): the
voltage fluctuations in oscilloscopes which dance other motorcycle light-cycles trying to use the concept of combining “three” and “three” yielded
around in patterns that, while pretty, mean abso- CPU? Or clicked “Save” in Word and saw a big ol’ “six” regardless of what kinds of things we were
lutely nothing to me. supertanker full of article data shove off and sail combining.
across the bus to rendezvous with the stream on
I’m a software guy. We use abstractions. Keep the other end of a buffer? That led to all kinds of interesting realizations.
your bits and bytes away from me, man—I deal in It meant that we didn’t have to think about the
managed code. You know, that code that runs on Yes, I’m mixing metaphors here. Or, if you prefer, concrete aspects of things, which led to the de-
a virtual machine, which is sometimes executing all of our abstractions. If you’re having a hard velopment of geometry, for one. I know, I kinda
inside a virtual machine, which in turn is running time keeping them all straight, then imagine how hated geometry in school, too, but when you
on top of an operating system (itself an abstrac- the people who don’t live with this stuff all the think about it, somehow these old guys in to-
tion over the machine), which is often running time must feel. gas figured out that if you have a right triangle,
in some kind of virtual machine environment on the squares of the right-angled sides will always
the chip. If you want to experience this feeling firsthand, equal the square of the opposite side. Every time.
go find a college quarterback and ask him to walk Without fail.
With all these abstractions in place, it’s a wonder you through a play of his on video, complete with
that anybody in the software world realizes that the jargon. Heck, high school, even. Anybody And they did this not by simply writing test after
it’s all just 1’s and 0’s in the end. Or that anybody who suggests that football quarterbacks aren’t test after test, and if a certain number of these
can understand what we do. intelligent has never played the game. (Whether empirical tests pass, declaring that it must be so
they can pass an English exam or an accounting for all numbers a, b and c. The Greeks did this
The Grid class is another question entirely.) by rigorous application of logic, relying on ba-
sic axioms (fundamental truths of mathematics)
Actually, it’s pretty obvious that they don’t. I Flickering Shadows and derivations and applications based on those
could cite examples of conversations with ev- truths. What we take as a fundamental truth—the
eryday people (I refuse to call them “users” for In many ways, we imagine the creations of these
purposes of this article), but instead I’ll point to abstractions to be a kind of noble art, something (Continued on page 73)
han
Less t
ay!
per d
Affordable High-Tech
Digital Escrow
Tower 48 is the most advanced and affordable digital escrow solution available. Designed and built specifically for software and other
digital assets, Tower 48 makes escrow inexpensive and hassle free. Better yet, as a vendor, you can turn escrow into a service you offer to
your customers and create a new revenue stream for yourself.
Regardless of whether you are a vendor who wants to offer this service to their customers, or whether you are a customer looking for extra
protection, visit our web site to start a free and hassle-free trial account or to learn more about our services and digital escrow in general!
shu
ssh
h uuttte
hut ooccckk
toc
ersstto
tters
ter
Application Framework from the
Most Trusted Source in .NET!
Brought to you by CODE Magazine, the CODE Framework is a free and open-source business application development framework,
focusing on productivity, maintainability, and great application architecture. The CODE Framework provides a wide range of features,
from various UI development approaches (Windows, Web, Mobile,…) to Middle-Tier and Service components, to data access, security,
various utility features, and much much more. CODE Framework also aims to not re-invent features that are already available by making
“mashability” with other frameworks a high priority.
To get the CODE Framework, visit www.codemag.com/framework or download various versions and tools from http://codeframework.codeplex.com.