Options for Mobile Development


The must have gift for Christmas 2012, according to many sources, is a tablet. For the average consumer, there is no need to have a desktop or notebook to accomplish day to day computing. Microsoft is aware of the trend and created Windows 8 with a focus on tablets (obvious when examining the very touch friendly user interface). In addition, smart phone sales are expected to top 600 million this year, up from almost half a million in 2011.

Looking at various industries, there is a push to enable workers to accomplish work quicker without the need to be tied to a computer. Gartner sees both mobile device battles (who will win this war) and mobile applications as two of the top trends for 2013.

What does this mean for the developer (or IT manager or executive)? You cannot ignore mobile application development much longer. But where do you place your chips? This article runs through the choices for application development for the mobile space and the options available.

The Mobile Space

As of today, there is a plethora of vendors in the mobile space and one clear winner: Apple iOS. Apple currently controls about 65% of the mobile traffic, with Android in a distant second with about 20%. Other players who have at least a blip on the screen are Java ME, Symbian, Blackberry and Windows Phone. Of these distant runners, only Microsoft is on any type of uphill trend and this trend has been rather anemic thus far. But Microsoft has unified its OS look and feel across all platforms with Windows 8 and Windows Phone 8, so I would not count them out of the game.

Which should you spend time learning and developing for? It is hard to argue against iOS, as Apple has the largest share of the mobile market right now. Even if you are not aiming for mobile phones, there is a good reason to consider iPad for your line of business applications. But it is also hard to ignore Android, as the sales are definitely on the rise. I would definitely invest in both iOS and Android in a mobile strategy.

Then there is Windows Phone. While the jury is still out, and many have decided to ignore the platform for now, it is hard to bet against a giant that has already set up a store, is using Apple’s strategy of controlling hardware (fewer bugs due to fragmented hardware?) and is leveraging .NET as for development (.NET skills (esp. C#) are currently one of the most sought after skills in job ads). Christmas season 2012 will give a hint whether Microsoft is a good ship to tie anchor to, but considering the ability of leveraging code across multiple application types, it may be a cheaper road to travel, even if the numbers are not that big (more about this in a minute).

Application Development Strategies

Assuming you would like to write for more than one platform, there are numerous strategies to choose from. What you choose depends on your goals. The following sections cover the three strategies currently available for development for mobile.

  • Write for Each Platform
  • Write Once, Run Everywhere
  • Write Once, Wrap Everywhere
  • Use Native Wrappers for Connected Functionality

Write for Each Platform

This is the most tedious approach, but gives you the power to take advantage of features of each platform. You end up with truly native applications, which is a plus, but end up spending more money on development. Despite the cost, many companies have adopted this strategy, as it yields a better UI experience. Overall, this is the best strategy if you need the richest application on each platform and want it to run completely on the device.

With a good design (planning is not optional), you can reduce the time spent developing each platform, but you will still end up spending more with this option. On the positive, there are numerous applications, primarily games, that require a connection that have people giving them horrible ratings due to the always connected state. These apps are primarily on not always connected platforms, like the Nook, but phones do fall out of service from time to time.

Write Once, Run Everywhere

Just as Java promised in the 90s, there are some vendors who have embraced the idea of creating tools that allow you to write a single code base and compile it for many different platforms. An example of this approach is found in Antenna Software, which a client used last year.

The positive side of this type of paradigm is you only write code once and then deploy to the platforms available. You also end up with native applications, which is useful in a disconnected scenario (similar to the write for each platform strategy). The downside is you generally have to learn a new language and may have to work with a limited set of features (although the vendor will continue to add features to improve their platform). You will also have a limited set of platforms to choose from, as compilers have to be created for each platform.

I am a bit skeptical with this approach, having been burned by Java’s promise years ago. While Java touted “write once, run everywhere”, the reality was more likely to be “write once, debug everywhere”, due to the great differences in platforms. In all likelihood, this is a decent route for some, but consider the learning curve for the new language, and that you may have to tweak the application for each platform.

Write Once, Wrap Everywhere

While this sounds like the same approach as the last section, it is subtly different. The approach here is to use HTML5 and use the native browser on the device. Essentially, you are writing a web application that will run locally on the phone.

This means you can only create an application as rich as the HTML5 capabilities of the phone(s) you are targeting. This is not a major downside, as HTML5 is very rich. The app itself, wraps the browser, so you will have the ability to access the native features of the device.

This is the approach taken by PhoneGap, an open source project that was acquired by Adobe. As of the end of 2011, the following platforms were supported with PhoneGap: iOS, Android, Symbian, Blackberry, WebOS, WP7 and Samsung Bada. It also appears a few commercial vendors have gotten into the game.

Please note that while HTML5 shows a lot of promise, there are some inconsistencies in platforms, so you have to know the limitations of the platform to end up with the best looking application. As with the last option, you will likely have to tweak applications for each platform. To get past the inconsistencies, it is useful to have a development tool that helps you design once and deploy across all platforms. One tool that shows a lot of promise for this type of development is Telerik’s Kendo UI (realize you still have to package with something like PhoneGap to get the native wrappers).

Use Native Wrappers for Connected Functionality

This might be better labeled “write a web application in HTML5” and connect to it via a native wrapper. This is the approach taken by Orubase, by Syncfusion. Native wrappers are created for different platforms and the application itself runs on your servers. Orubase also leverages ASP.NET MVC for the backend, which should make it attractive to .NET shops.

One downside is the connected nature of the application, meaning you need to connect to the web application for full functionality. This is only a partial downside, however, as vendors are instituting local storage solutions. You also have to consider line of business applications, which benefit from an “always on” connection (not completely always on using the web paradigm, which is inherently stateless, but that is a topic for another day).

An Apple Caveat

You can only develop for iOS on Apple. Apple has decided not to make the SDK and development tools available on Windows. On the positive side, it gives Apple a lot of control. On the negative, it means you have to buy a Mac to develop for iPads and iPhones. This means you will need a Mac to develop for iOS. With some of the strategies above, you might be able to use an iPhone emulator instead.

Which Strategy to Choose?

It really depends on what you are developing. For games, I would recommend native on each platform, despite  the costs. Gaming is a fickle market and a bad game dies rather quickly. The same is true for many consumer applications or any application that focuses solely on user data on a single device.

For internal applications and many line of business applications, the always connected scenario works well. The app looks native, due to the wrapper, but the functionality is maintained on the server. One potential caveat here is how different mobile platforms handle the sites. If you end up having to create separate sites for each platform, this could be a nightmare, but it is still a great option for reducing costs and still getting mobile applications out to your internal users and partners.

As a compromise position, if compromise is the right word, the creation of native applications in HTML5 shows a lot of promise. The standards are still in the infant stage, but the mobile space has adopted them faster than the desktop/notebook space, so there is a lot of promise in this space. If you are already leveraging HTML5 in your organization, this could be a good solution.

The write once, run everywhere option is also promising, especially if you would also like to offload some of the work to the vendor. I am not sure I can accept the downside of the learning curve to program on these tools, but vendors like Antenna also have other products, like mobile gateways, that still make them a good option for many business scenarios.

Peace and Grace,
Greg

Twitter: @gbworld

IT Consulting: Is the rate fair?


DISCLAIMER: This post uses very general and rough figures. The true rate has to be calculated individually to determine whether an opportunity is good or not. It is good to use rough figures, however, to determine if the contract is even in the ballpark where it makes sense. Taking this approach, you will not knee jerk towards an opportunity that is obviously a bad choice. You need to work in real figures to determine if a deal is good or bad for you.

NOTE: This post is written largely because so many people I know have taken contracts that they felt were good deals, only to find they were not nearly as rosy as they appeared. Generally, the reason for this is the individual did not calculate in his true earnings (including benefits) when he saw the hourly figure. Hopefully this post will help you make a better decision.

One of the questions I often get asked is “do you think X dollars an hour is a fair rate?” This is a hard question to answer, as I am not always sure what the person is worth, especially if I just met them. But I can, and do, answer how to determine if a rate is fair for you.

Let’s get a profile of the person who normally asks this type of question. They are generally a full time employee making in the mid 80s per year. In most cases, they have a $50 an hour contract dangling in front of them. I can generally probe to determine what other goodies there are.

Calculating Contract Hourly

First, let’s break down a full time gig at $85,000 per year. To determine the hourly, you take the yearly salary and divide by the number of hours worked in a year. If you want to calculate 40 hours per week, the number of hours is 2080. This yields an hourly of $40.87. You may actually average more than 40 hours per week and desire to adjust this.

This is where most people stop. The problem is the true hourly is a bit more complicated. First, the average person in the United States gets 7 holiday days per year, 10 vacation days (first year, rising to 3 or more after a few years) and a number of sick days. I generally don’t include sick days in calculations, as I don’t generally use any of them. You may be different on this front. Just taking the vacation and holiday days, a full timer is paid for at least 136 hours he does not have to work (a bit more than 3 weeks). With these hours, the rate goes to $43.77 for 40 hours a week.

You also, to be fair to yourself, have to start calculating what you receive based on 1944 hours instead of 2080. The reason is you are not going to paid for these hours as a contractor, unless the contracting company baked it in. if you do not use 1944 in your calculations, you are leaving these hours out, which means you will have to make up for them in “overtime” hours (mostly paid at 1 times rate rather than 1.5 (unless it is in the contract, which is rare)). I will include both the optimistic 2080 hours and the more realistic 1944 hours in the calculations below.

Now you have to calculate in your benefits. The normal company pays over $9500 per year for medical benefits. If you go on COBRA, you eat 100% of this cost. If you calculate this by 2080 (use this figure when figuring expenses, as this is how you are paid as a full time employee), this is another $4.57 per hour.at 2080 hours and $4.89 at 1944 hours.. If you use the adjustment of what you actually work,  You might reduce the cost by buying insurance through the contracting company (if they offer it, although it will probably be worse coverage than your current employer’s plans) or by buying your own insurance. We are now at $48.29 per hour for 2080 hours a year ($48.61 at 1944 hours).

NOTE: If you have a consultant benefits package, use real figures here for the costs you pay today and what you will pay for insurance as a consultant. It will yield an accurate figure. The above is a ballpark figure.

What about other benefits? Does your company offer health club benefits that you take advantage of? Child care? Education, including being sent to conferences? Certification? All of these have to be calculated in, unless you are willing to lose them without compensation. As an example, a week at a conference like TechEd or VSLive generally rack up at least $5000 in cost, or another $2.40 in hourly benefits ($2.57 if you calculated at 1944).

And what about retirement? If your company offers a match on 401-K, and you max it out (usually 3% of salary), you have another $2550 per year at $85K, which is another $1.27 per hour ($1.31 at 1944 hours).

At this point, you are at as much as $51.96 per hour, which is a $1.96 per hour loss when you look at the whole picture ($52.49 if you used 1944 hours for a $2.49 per hour loss). Now, the loss may not mean as much to you because you are not interested in retirement, for example. And, for the short term, I don’t see a problem with this. To pay off current debt, the extra hourly may be a better situation for now. If so, that is fine, but realize the situation.

If you have run the calculations, moving to a contract positions, without benefits, you should make 20% more per hour to break even. This is true regardless of your salary. While you might end up with more “overtime” with the contract, consider that a bonus for taking the position rather than a guarantee.

The takeaways here:

  • You need to figure out your true hourly worth
  • You should make at least 20% more on a W2 contract to break even.
  • You can add overtime in as a reason to move to a contract, but don’t count it in your calculations of whether or not the contract is a fiscally sound decision.

NOTE: For each $5000 you make above $85,000, you need to add between $2 and $2.50 per hour to determine a good rate.

1099 and Corporation to Corporation (Corp 2 Corp or C2C)

In the above example, I assumed the contract was still W2. Some contracts are either 1099 or Corp to Corp. Of the two, C2C will be the more financially rewarding, as you can easily write a lot more expenses off your taxes. It is also the more time consuming to set up.

With each of these models, the rate should go up approximately 10% to cover your self-employment tax, as the tax write offs will vary by individual. The addition of your personal share of FICA (social security) and Medicare do not vary, you have to add these to your calculations. To cover yourself, the 10% is added on the total of the W2 calculation, as you will be paying for every dollar you are paid from the consulting company.

If we take our previous example, the hourly should be between $57 and $58 per hour to break even. Count the items you can write off (need a new computer for work?) as a bonus.

With C2C, you will have a few additional expenses, like errors and omissions insurance. Even at the worst, a few extra dollars per hour is sufficient to cover these expenses. Be sure to include expenses of an accountant, as he will be worth his weight in gold determining how much of the corporate dollars are paid to you in salary and how many simply pass through to you at the end of the year.

Travel

Okay, this is the big one. You see what you think is a good rate in another town and want to know if it really is good. Or you have heard about someone being paid $100 per hour on a traveling gig and think that sounds great. But wonder if it is really is a good rate.

The way to calculate this is determine the costs of various expenses. If you travel, you will incur the following expenses: Flight, car/taxi (include fuel if you rent a car), hotel and meals. To calculate these you need to determine a low, average and high for expenses. Start with a travel sight and do the research.

For my work in Austin, the T&E (Travel and Expenses) averaged the following

    • Flight – $500
    • Hotel – $650
  • Auto – $ 285
  • Gas – $40
  • Food – $200

Added together, the cost was $1675 per week average. A top figure is more like $2000 per week. This means $42 to $50 per hour. If we add this cost to the hourly we calculated before, we get the following rough figures.

  • W2    – $102/hour
  • 1099/C2C – $110/hour

Now, you can certainly save on travel if the contract is long term. There are extended stays places and even most hotels will offer a monthly rate. In some states, like Texas, once you rent more than a month, you get the hotel tourism taxes taken off the rate, saving you even more. Booking flights out far into the future yields further savings, but this can burn you on many airlines (not as much on Southwest, where you can use the unused flight dollars without penalty for a year, but you will also never auto-upgrade to first class). You can also save on food in the correct hotel, by cooking for yourself or taking advantage of meals in the hotel. Don’t count these in on your initial calculations, however; consider them a bonus.

Summary

To determine whether or not a deal is good, you have to monetize everything. One good way to do this is start with a 40 hour week (2080 hours per year) and subtract hours for holidays and vacations (and possibly sick leave if you use it up every year). Use this figure to determine your true hourly salary. Then determine the difference between benefits (most likely most go from something to nothing) and determine the hourly value of those benefits.

What is often shocking is many people thought they were getting a great deal in a consulting gig and find that they were winning slightly in the gross take home, but losing in the game. It is quite easy, when looking at $50 per hour, to see it as a $15,000 increase over $85,000 and then realize it was actually a loss (or very slight increase) once all benefits were taken into account.

Peace and Grace,
Greg

Twitter: @gbworld

Career Focus


This post comes at the completion of an assignment which was more development focused than I would like. While I focused as much as possible on adding business value, the core reason I am moving on is I did not feel the assignment was correct for my career. Working out of a paying gig may sound like a strange strategy for some of you, so I will explain it in more detail.

I see two types of people in every field. There are those who are in it for the job and those who want a career. Those focused solely on the job look at the current assignment based on what it does for them at the moment. They are likely to bounce around a lot, salary surfing, to get as high up the financial pole, but their moves are tactical. They rarely focus on long term strategies.

At the other end are career focused people. They see each assignment as a chance to improve themselves and – more importantly – their worth. They act as consultants to their employer(s), even when they are a full time employee. Their focus is on leaving every place they camped out better than when they set up the tent.

Please note that I have nothing against those who are job focused. I have just chosen software and architecture as my career. This post is focused on others who have this focus or would like to have it.

Working Yourself Out of a Job

I mentioned briefly that I worked myself out of a position. My primary reason was the group I was in had a strong focus on quantity, often to the detriment of quality. While I could have pushed out a lot of happy path code and made the manager happy, I am to the point where my code is my reputation and taking too many shortcuts to push more code was a reputation buster to me. My personal belief is one must be willing to compromise, but should never completely give in when you know the push is in a direction that ultimately damages your client.

I understand why some people do not walk when asked to do something they know is contrary to good practices. We live in a world where layoffs seem more the rule than the exception and jobs feel scarce. But there are three things I know that you may not.

  1. The bad job situation is largely hype when it comes to development jobs*. Even through the worst of the recession, IT has only seen low single digit unemployment, with the majority of the hardship falling on the networking side. Companies have been hiring as late as the week of Christmas for the past few years, so don’t believe that it is impossible for good people to get a position, even in a hard economy.
  2. Good people will rarely find it hard to get work. There is a potential we will experience really bad times in the future, but to date I have found I make more money when the economy is bad, as businesses get pickier on who they hire. You might think “but businesses also lower rates”, which is true … if you buy in. If you are unwilling to lower your rates, and can back up your skill, you will likely find that you can raise your rates and businesses will pay it. NOTE: If you are working with recruiters, you have to sell them you are worth your rate. This is more easily done before a bad turn in the economy and a layoff. Be proactive.
  3. Compromising you best qualities to keep a job will likely hurt you more than leaving the position. There are two reasons for this. First, you are a brand. Yes, I mean you are a product. If you are willing to be a product with poor quality ingredients, you may sell to the Walmart crowd (read: lower rates), but the people you really want to attract will turn you away. In addition, you will find it harder to market to new clients and end up having to sell yourself solely on your past. Second, you will develop bad habits. This leads full circle to damaging your brand. (Note to self: Blog on brand next)

* Realistically, the bad job situation is hype to all career focused individuals, as they focus on success. There may be down moments, but you will rarely find yourself unmarketable if you focus on career.

Now, let’s take this one step farther, as working yourself out of a job when you have a philosophical difference is one thing. I will also contend you should be working yourself out of a job even when you don’t.

What do I mean? I mean Bring it! Always bring your best game to every position you take, consulting or full time. Finish off the work better than anyone else. Make it easy to maintain and utilize best practices, preferably those either a) you document or b) are so well documented you can point out great examples.

Now you may think that this will lead to them firing you. This is a possibility. But do you REALLY want to work for someone who would fire the best? If so, you need to rethink job focus versus career focus. The bigger danger to being better is having a myopic employer that feels you are too good to advance, as you make him look good. If this is the case, you don’t want to work here either – at least not for this boss. But perhaps you can work on getting your boss a better position so you can take over his. It is a far more lasting rise to power to push someone else up the ladder, while pulling good people up with you, than it is to walk over someone to get to the top. The later method has you always watching your back for the inevitable knife.

So let’s summarize what I have said thus far

  • Bring your best, even when you truly work yourself out of employment. It pays off great dividends in the long run.
  • Work as a consultant, even when you are a full time employee. A “true’ consultant looks for ways to improve things and that is a very valuable skill.
  • Work to help other good people advance, even those on top of you.

Career Focus

So what is career focus? Career focus is looking at the long term. It is continuous improvement on a personal level. And a desire to help others improve. It is taking the time to learn new skills, even when it is off the company time. It is also focusing on more than the latest sexy thing that Microsoft (or another tech company) just rolled out.

Even more important, it is planning your next moves far ahead of playing them. Like a good game of chess, you examine what you need to learn to not only remain relevant, but to excel. Get involved in beta programs and participate in making products better. Write a book, create a blog, speak at user’s groups. All of this builds your brand.

A note on career. While you will certainly rise in both money and reputation when you are career focused, neither or these should be an all consuming goal for your career. With excellence, you gain both reputation and money, but when you focus on gaining reputation or money, you often sink excellence, either by pricing your brand higher than the value you bring or coming across as an arrogant bore.

Take time to teach things to others, even when you are just learning. One of the greatest ways to learn a new technology, habit, paradigm or technique is to teach others. If you wait to be the best at something, you will often gain your reputation at being the best of a sinking technology.

And be willing to make mistakes. More importantly, be willing to own them and admit them. Anyone who gets rid of someone solely for making a mistake ends up with people who never grow or take chances. You don’t want to work for that person either.

Do Something Today … And Every Day

Denis Waitley, a great motivational speaker, states “when you are green, your are growning, as soon as you stop growing, you shrivel up, turn brown, and die”. While you may not experience a physical death by not growing every day, you will certainly kill your career and move back into a job focus.

Today you should write down at least three things you can learn that will make you better at your career. Initially, you might focus on three new, hot technologies. But you eventually need to get back to some foundational topics, business topics and soft skills.

Whether you realize it or not, learning to market yourself is extremely important, even if you are moving from one full time position to another. And learning more about business is paramount to getting through the glass ceiling set above the developer.

I realize some of you may only want to be developers for the rest of your working life. If so, be the best. But most of you will find you want to contribute even more. Perhaps this is management, but it may also be architecture or business process management. Either way, learning more about business is critical to your success. I would also argue it is critical to success as a developer, but you may need some time to have that soak in.

The important takeaway is you need to do something today and every day. Even if all you do today is determine what you need to learn, you need to do it.

Summary

I guess the best way to summarize what I have said is you have to determine what you want to do when you grow up. I say this whether you just graduated college or you are near the end of your career. If moving up to a decent salary and coding until you retire is your focus, then aim for being one of the best coders you can be.

Make sure you are always growing. Learn the latest tech, but also learn how to build better foundations. Learn how to bring more value to businesses. Learn how to be a better person and have better relationships. Move in the direction where people want you to work for them because you bring value. And learn to be a joy to be around. One of the most valuable skills is having people wanting you around even when you are brining bad news.

Best of luck to you.

Peace and Grace,
Greg

Twitter: @gbworld

Session and Cookies in ASP.NET MVC? Oh my!


This post is brought to you by this post on LinkedIn (you may need to belong to the ASP.NET MVC group). The question of the day:

In MVC it bad practice to use session & cookies then what are the options to maintain session

If you understand how HTTP works, you understand this is a bad question, or at least one born out of ignorance.

Before getting into the meat, let’s examine two important concepts: synchronicity and state.

Synchronicity is whether or not we immediately get feedback. For example, if I fill out a form to join and immediately get logged on, it is a synchronous system. If, instead, I fill out the form and get a email with a link and then log in, it is asynchronous. A better example is a chat application (synchronous) versus email (asynchronous) or the difference between the chat window in Facebook (synchronous) versus either sending a Facebook message, playing words with friends or using Twitter (asynchronous).

Now to state. State is the current “data” stored about you, or something else, in the system. Oversimplification, but consider I have $1000 in the bank. The state of my account is $1000 on the positive side. If I then get $100 cash, the state is $900 in the bank. The same is true if I change my Facebook status to single (not my real status, of course, but it would be my state in the system).

How applications work (and some history)

The first applications were normally either dumb terminals (maximum statefulness and synchronicity) or client/server applications (high level of statefulness and synchronicity). When you logged in, you were connected full time to the server, so any changes were instantly reflected. Not 100% true, but it covers the general nature.

Now, let’s move up to the web. The client is not connected to the server except when making a request, making it an asynchronous and stateless system. This may take a moment to sink in, but I feel the need to disgress (ADHD popping up?) and cover how we got here.

I first got on the Internet in the late 80s through shell programs on a BBS (bulletin board system). At this point in time, you had email and newsgroups as your primary means of communication with other people. To organize information, you had Gopher. Gopher was a decent system for putting “books” on the Internet, but a bad system for user interaction.

One more step into ADHD land? :: The government (and education) started what would become the “Internet” in the late 1960s as ARPANET. They brought education in, and ultimately other countries (our allies), in the 1970s.

Now, let’s cover the WWW. Gopher was a bit of a pain to program with. But that changed when Tim Bernas-Lee took a government standard (SGML, or Standard Generalized Markup Language) and created HTML (HyperText Markup Language). The main push was to make it easier to disseminate information, but it was easy enough to create applications that were interactive. I could go deeper (will consider in another post) and get into what HyperText truly means (perhaps a post on REST?).

Now, you have a bit of background, let’s get to the core. Hypertext applications are both stateless and asynchronous. The operations in these types of applications may be synchronous (added to avoid arguments from purists), but the basic nature of the communication is asynchronous, as you

Hypertext applications work on a request and response system. You create a request and send it to the server. Prior to your request coming in, the server has no clue who you are, even if you have contacted it 20 times in the last 2 minutes. Every request is treated as a new request from an unknown entity, making it stateless. The server disconnects after the response is sent, so it is non-connected (except to handle requests) and you can take time to determine the next course of action, making it asynchronous.

Now some may argue with the last line of the last paragraph, thinking “if I am logged in, I can’t walk away for a long time; I have to fill in the form within X minutes or I have to start over”. This is true, but as long as you have some means of saving state to the server, you can pick up with the remainder of your work at any time. And, if you are not logged in, you can keep the page open, shut down your computer, and come back and click links on the page hours, or even days, later. So the basic nature of hypertext is stateless. That is our important takeaway to move to session and cookies.

Persistence

Persistence is the mechanism by which state is stored until a user is ready to use it again. Long term persistence is usually handled either by a database or files. Once the user has changed something, the information is normally persisted to these long term persistent stores.

In addition to long term persistence, there is short term persistence. This is where cache comes in. Cache is persisting of state in memory. What about session? Session is a cache that includes bits to tie information to a particular user. Session also allows for expiration of cached state based on a user logging out (immediate) or timing out (end of session time). When either condition is met (log out or time out), the user specific state is cleared.

It should be noted that the main difference between a database, files, memory cache and session is where the state is stored. This is important for reliability and speed. Storing in memory fails if the machine is rebooted (or worse, the power pulled), but it is much faster to retrieve from memory than involve I/O (either pulling from disk, over the network or both).

Then what are cookies? Cookies are another form of persistence mechanism, only the information is stored on the client. The cookie may simply persist a user ID (to retrieve from session) or it may persist all of the user’s data (impractical over a certain amount of information). If it is just an ID, you need another method to pull the rest of the information, which means persistence on the server.

In Summary, for this section of this post (there are others, just not relevant):

Server Side Persistence

Database

Files (XML or otherwise)

Cache (temporary)

Session (temporary)

Client Side Persistence

Cookies

Kludges, aka sessions and cookies

This may seem unfair calling these items kludges, but let’s examine. You have a stateless mechanism (web pages), as they do not hold state. The client is only connected for the length of a request and either errors or fulfills the request and then shuts it down. The request is forgotten after the response is sent.

But, you need state. So you first create a means of storing information on the client. This is the cookie. Think of a cookie as a property bag storing name/value pairs. This is sent to the client as part of the header of the response (ie, the part you don’t see in your browser). The client then stores it and sends it back with every request to this server.

But what happens if you need more information than can be stored in a cookie. Then you create an in-memory cache tied to the user via some type of session ID. If you have been paying attention, you realize the session ID is sent to the user with every request and sent back in.

But, what if people find out cookies can be used for things they don’t like and turn them off? This was an early problem with the web (mid 90s). Browser developers put the ability to refuse cookies (the cookie is still sent, but it is not stored, so it will not be sent with the next request). To solve this, another cookie store was created on the client side and they called these “server cookies”. When the user decided to turn off cookies, these cookies stay alive, as they are in a different store.

The store for server cookies was designed to purge when the user left the site, but since the developer on the server side has some control, this did not always happen. The end result is while it is harder to turn off server cookies in all browsers, it is not impossible.

Are Session and Cookies bad in ASP.NET MVC?

If you have read this far, it should be obvious that session and cookies are simply a persistence mechanism between stateless requests. Are they bad? Yes and no. In many cases, cookies and session are a crutch to cover up bad architecture and design. In those cases, I would say they are bad. Overall, I would question the use of session and cookies in ASP.NET MVC, especially if you don’t truly understand the nature of Hypertext communication (and no, this session is not the 101 class).

On the original post, Ignat Andrei posted “And if it is a problem – it’s not only a MVC problem – it’s an ASP.NET problem.”. Correct, it is a problem in ASP.NET, as well. Or at least a variation of the same kludgy solution. In fact, it is a “problem” in all HTTP centered apps that allow for session (web server controlled in-memory cache) and cookies.

One of the beauties of ASP.NET MVC is you can get rid of a false reliance on the Session object and/or cookies for most of your work. Not that MVC is really that different from any other web application (it is just a pattern), but that the pattern should get you thinking in paradigms where you don’t rely on kludgy state mechanisms.

ASP.NET MVC was created due to a couple of reasons. The most obvious is Ruby on Rails, since Rails uses the MVC pattern. But another concern is pushing people towards a paradigm that encourages use of best practices, primarily separation of concerns. While the paradigm works fairly well, in many cases, you don’t solve process and people problems with technology, at least not completely.

Now back to the question of bad for session. Why would it be bad? One reason is users generally use session as a crutch to store page items. This is overcoming bad architecture with bad practices.

Another reason is session takes up space on the server. You don’t get session for free. When you use session, you take up memory and reduce scale. This is not always bad, but you do have to be aware of it. The question comes down whether scalability is an issue. The same is true of any form of in-memory cache, but you can easily switch to a distributed cache if you are using MemoryCache, by using a factory or provider pattern; you don’t have the easy configuration change type of switch going from Session to distributed (at least not without adapters) and even if you could, the purpose and pattern are different.

Another reason is IIS recycles. Not often that it screws over most of your users, but it does. Since HTTP is stateless, the user can still request pages, but now he is hosed as far as anything stuck in session goes. The same can be true of having to log back in, depending on your mechanisms, however.

Another reason is web farms. Not a big deal for the single server “share my club” type of site, but if you have a site on multiple servers, you end up with session in memory on all of the servers (at least the potential of that). ouch!

Now the comeback is “Greg, I use session state in SQL Server”. Great! Then why use session at all? If you are taking the trip to SQL Server for every hit, why incur the consumption of extra space for items that may never be requested. And why incur the extra overhead of clearing a user’s session, including the piece where you clear the data out of SQL Server. It is pure overhead at this point.

Does this mean never use session? Let’s look at that in a section entitled …

What if I feel the need to use Session in ASP.NET MVC

Did you not read the rest of this post? Okay, so there is an alternative: Use TempData instead. It is an abstraction in ASP.NET MVC on top of the old ASP.NET session. And it allows you to more easily change types of persistence. Realize this is still an abstraction on top of a kludge, but it is a useful abstraction as it is easily switched to a better method.

But you did not answer if it was bad …

As with everything in life, there is no one size fits all answer. As an example, I present adriamycin. Originally developed as an antibiotic, it was found to be too toxic. But it is rather effective on certain types of cancer, so while it is a poison, and should generally not be consumed, there are times it is the most effective path.

Read that again. What I am saying is I would generally avoid session like the plague, but there are always exceptions.

If you want a rule of thumb: Avoid the use of session to store temporary values, unless you can find no other mechanism, or the factors of developing the application make session a better option. The same can be said of storing in cookies.

The Aspects of Development and Session

All of this stems back to the aspects of development. There are five major aspects to consider:

  • Availability
  • Scalability
  • Maintainability
  • Performance
  • Security
  • In addition to these, time and budget have to be considered, as they are valid concerns. If using session is needed for time, for example, you may have to code it that way. But make sure there is time to remove it later if you find you are using it in a kludgy manner. The same is true of budget, but then time is money.

To figure what is best, you look at each application uniquely and determine the best mix of the aspects. If scalability is the biggest issue, you may lose some performance to better separate out concerns (monoliths run fast, but scale horribly). In financial applications, security is often the biggest concern. In general, maintainability (or the lack thereof) cost more money than any other aspect.

Summary

Session (and cookies) are often used as persistent mechanisms of convenience. They were both built as kludges to make a stateless system stateful. As such, unless you have a proper reason for using them, you should not use them. And, if you have a proper reason, you should examine it and see the proper reason is based more on familiarity than true need.

But, the above advice should be said for every architecture/design you have. You should examine all of your assumptions and ensure you have made proper decisions. Only then can you be sure things are solid (nice play on words, eh?)

Realize that the above has a caveat. You have to be able to examine within the time constraints of the project. If you can’t deliver, it does not matter how good the product is.

For your club website, session, while not the best solution, is probably fine. The same is true for the use of cookies. Once you move into the Enterprise space, however, these kludges can become costly.

Peace and Grace,
Greg

Twitter: @gbworld