glasses-logo

<dominikgorecki> Web development on the Microsoft Stack <dominikgorecki>

Implementing Password Reset in MVC 4 EF Code First using Simple Membership – Part 2

I apologize for the long delay between part 1 and part 2, but I’ve been really busy. I’ve created 2 new jQuery plugins (scrolling related) and I’ve put out my own RWD Grid Framework called Bare Bones. Check them out!

So it took me a while to figure out where we left off and what the next step is. Before you continue with this tutorial, you should already have a working copy of where we ended up with Part 1: an extended account model that allows for email entry. That was the hard part.  In Part 2, I’m going to explain how to use WebSecurity.GeneratePasswordResetToken that will create a token used to reset a user’s password. This is currently the most common way to recover a password: an email is sent to the user’s verified email address with a link the user can use to reset their password.

Part II – Create the Reset Functionality

The great part is that Simple Membership already comes with the functionality built in so all we need to do is implement it. Now that we have an email in our membership from Part 1, we’ll first need to create the request for reset page, then send the email, and finally a page to actually reset the password.  As suggested by Alec on my Code First tutorial, I will wrap up all the DB contexts in “using” statements to ensure it is properly disposed of as soon as it’s not needed.

Step 1 : Setup the LostPassword Page

Create the GET action in AccountController for LostPassword that simply returns View():

// GET: Account/LostPassword
[AllowAnonymous]
public ActionResult LostPassword()
{
    return View();
}

Then create the view that allows for the user to input their email address to receive their reset link. Note: Some websites like you to type in your username instead of your email address; however, I like the ones that allow you to enter your email address because–as sometimes happens to me–the user may have forgotten their username as well! Also if you want to do things right, I would suggest creating a LostPasswordModel that can be used on the view page so you can create validate it against the Email DataType and create custom error messages:

LostPasswordModel in AccountModels.cs:

public class LostPasswordModel
 {
    [Required(ErrorMessage = "We need your email to send you a reset link!")]
    [Display(Name = "Your account email")]
    [EmailAddress(ErrorMessage= "Not a valid email--what are you trying to do here?")]
    public string Email { get; set; }
 }

Create a new view based on the GET action we created (LostPassword.cshtml):

@model PasswordResetApp.Models.LostPasswordModel
@{
    ViewBag.Title = "Lost Password";
}

<h2>Lost Password</h2>

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary()
   <fieldset>
      <legend>Lost Password Form</legend>
      <ol>
         <li>
             @Html.LabelFor(m => m.Email)
             @Html.TextBoxFor(m => m.Email)
         </li>
      </ol>
      <input type="submit" value="Recover Account" />
   </fieldset>
}

Step 2: Process the LostPassword POST

Create the POST part of the LostPassword action. This is a little tricky because you would think that you could use the Membership.GetUserNameByEmail method, but you can’t since that in Simple Membership that is not implemented. We will need to first look-up the username with a Linq query to load the MembershipUser object with (line 11 in our example). After that you generate the token (line 26) and send the email (line 49). Read the comments in this example carefully. The first comment on line 58 deals with privacy: you may not want to let the end user know that the email has not been found since that gives a third party possibly valuable information. The next comment on line 69 talks about how you may want to redirect to a “success” page since, right now, this example does not do anything if the email is successful sent. I didn’t want to add too much superfluous crap to this example; I leave the UX\flow up to you.

Here is the POST action for LostPassword in AccountController.cs:

// POST: Account/LostPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult LostPassword(LostPasswordModel model)
{
   if (ModelState.IsValid)
   {
      MembershipUser user;
      using (var context = new UsersContext())
      {
         var foundUserName = (from u in context.UserProfiles
                              where u.Email == model.Email
                              select u.UserName).FirstOrDefault();
         if (foundUserName != null)
         {
            user = Membership.GetUser(foundUserName.ToString());
         }
         else
         {
            user = null;
         }
      }
      if (user != null)
      {
         // Generae password token that will be used in the email link to authenticate user
         var token = WebSecurity.GeneratePasswordResetToken(user.UserName);
         // Generate the html link sent via email
         string resetLink = "<a href='"
            + Url.Action("ResetPassword", "Account", new { rt = token }, "http") 
            + "'>Reset Password Link</a>";

         // Email stuff
         string subject = "Reset your password for asdf.com";
         string body = "You link: " + resetLink;
         string from = "[email protected]";

         MailMessage message = new MailMessage(from, model.Email);
         message.Subject = subject;
         message.Body = body;
         SmtpClient client = new SmtpClient();

         // Attempt to send the email
         try
         {
            client.Send(message);
         }
         catch (Exception e)
         {
            ModelState.AddModelError("", "Issue sending email: " + e.Message);
         }
      }         
      else // Email not found
      {
         /* Note: You may not want to provide the following information
         * since it gives an intruder information as to whether a
         * certain email address is registered with this website or not.
         * If you're really concerned about privacy, you may want to
         * forward to the same "Success" page regardless whether an
         * user was found or not. This is only for illustration purposes.
         */
         ModelState.AddModelError("", "No user found by that email.");
      }
   }

   /* You may want to send the user to a "Success" page upon the successful
   * sending of the reset email link. Right now, if we are 100% successful
   * nothing happens on the page. :P
   */
   return View(model);
}

Step 3: Set-up SMTP

Temporarily set the SMTP settings to create a file in a directory so you can test out your solution (later you’ll want to set-up a valid SMTP server here so your application can actually send the email). Go into you main Web.Config and add this at the bottom (I show the </configuration> tag to illustrate the placement):

   <system.net>
      <mailSettings>
         <smtp deliveryMethod="SpecifiedPickupDirectory">
            <specifiedPickupDirectory pickupDirectoryLocation="C:\email"/>
         </smtp>
      </mailSettings>
   </system.net>
</configuration>

You’ll also need to create a new directory, “C:\email”. Once you’re done with this step, you’re application should successfully create an email file in C:\email that should contain the reset URL. The reset URL will still not work as we’ll need to

Step 4: Reset Password Page View Model

The final part is to create a page that processes the username (un) and token (rt) to allow the user to enter a new password.  This isn’t too difficult. First I create a view model for the reset page that will ensure that a return token is entered and that a new password is entered and confirmed (AccoundModels.cs):

public class ResetPasswordModel
{
   [Required]
   [Display(Name = "New Password")]
   [DataType(DataType.Password)]
   public string Password { get; set; }

   [Required]
   [Display(Name = "Confirm Password")]
   [DataType(DataType.Password)]
   [Compare("Password", ErrorMessage = "New password and confirmation does not match.")]
   public string ConfirmPassword { get; set; }

   [Required]
   public string ReturnToken { get; set; }
}

Step 5: Create the GET Action and Page

The actions are quite simple because Simple Membership exposes a handy method for reseting the password (WebSecurity.ResetPassword) that takes two parameters: 1. the generated token and 2. The new password. First, however, we’ll need to create the GET action that will taken in the necessary query parameter and assigns it to the ReturnToken of the ResetPasswordModel model (AccountController.cs):

// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string rt)
{
   ResetPasswordModel model = new ResetPasswordModel();
   model.ReturnToken = rt;
   return View(model);
}

From this create the view based on the ResetPasswordModel model view. Everything here is pretty standard except for the hidden field on line 25. This hidden field is passed in through the GET action that assigns it from the query parameter and allows the field to be entered in as a regular form to the POST method (ResetPassword.cshtml):

@model PasswordResetApp.Models.ResetPasswordModel

@{
   ViewBag.Title = "ResetPassword";
}

<h2>Reset Password</h2>

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()
   @Html.ValidationSummary()

   <fieldset>
      <legend>Resetting password form</legend>
      <ol>
         <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
         </li>
         <li>
            @Html.LabelFor(m => m.ConfirmPassword)
            @Html.PasswordFor(m => m.ConfirmPassword)
         </li>
         @Html.HiddenFor(m => m.ReturnToken)
      </ol>
      <input type="submit" value="Reset" />
   </fieldset>
<h2>@ViewBag.Message</h2>
}

Step 6: Create the POST action for ResetPassword

For the final step we’ll use the WebSecurity.ResetPassword method to change the users password. One line. Simple as that (AccountController.cs):

// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ResetPassword(ResetPasswordModel model)
   {
   if (ModelState.IsValid)
   {
      bool resetResponse = WebSecurity.ResetPassword(model.ReturnToken, model.Password);
      if (resetResponse)
      {
         ViewBag.Message = "Successfully Changed";
      }
      else
      {
         ViewBag.Message = "Something went horribly wrong!";
      }
   }
return View(model);
}

Notice a few things here. The expected parameter is the model being returned, which is the view model we created for the ResetPage. Next, notice the one line that does all the work here–line 9.

Step 7: Test

So now that you have a working password reset, it’s time to test it. If you don’t have a user created yet, then create one. Test it out with one password and log-out. The go to /Account/LostPassword and type in the email that you registered the account with. Check “C:\email” for the email (go by last modified) and copy the URL into your client. … well you know the rest.

Net Monetization and Micro Payments

Some of you may have noticed the latest web trend: content monetization. Content that used to be free such as on NYT and WashPo is now limited to only so many articles, and in some cases entirely closed off. This is the new Web. Unfortunately, the future will only bring more of this.

While I like free content as much as anyone, I know that’s it’s not really a viable option. “There is no free lunch,” as the old saying goes. Advertisements may pay the bills for some content providers, but it will not suffice for most. However, how does this affect the access to a multitude of opinions and sources that we’re so used to. That is, I may dish out the cost for a NYT subscription, but I will probably not buy a subscription to other papers I may rely on: WashPo, HuffPo, Guardian (yes, I’m left leaning)… Here is what I propose: Micro Payments for content on an on-demand basis.

Imagine a system where you pay in some amount of money (such as PayPal) and then I can use it in multiple places on the internet to purchase only the content I would like. The prices would be very low (say between .05 to .25 C per article) which would require a system with very low transaction costs. In the end I may spend more than the subscription fee on my news consumption, but I would spread out over many newspapers.

From an end-user perspective I would enjoy using this system because of:

  1. No subscriptions\contracts
  2. Pay only for what I consume
  3. Make premium content more approachable–not an all or nothing approach
  4. I feel in control of my expenses. I can setup a system where I only put in so much money in my account to ensure I don’t’ go over per month.
  5. True competition among content providers might bring prices down

From a corporation stand point, this system is ideal in even more ways:

  1. Access to a larger market
  2. Can compliment existing subscription-type system (IE, micro payments for non-subscribers)
  3. I can accurately judge what content is more valuable to make better decision by reading the market
  4. Overall, the pie gets bigger. People might spend more money on content if they didn’t feel pressured by a subscription\contract.
  5. Transaction costs will be very low

iTunes revolutionized the way we pay for music. This system would do the same but across the whole web.

There is a significant hurdle to overcome in trying to make system like this viable: buy in from well established content providers. Let’s go back to my newspaper example: it may be hard to get buy in from the NYT that may already have a large subscription pool for fear of revenue canabolism. Imagine paid-for subscribers leaving for a micro-payment system. Subscription\contract revenue has some major advantages, which I don’t want to get into at this point. Mainly, contract revenue is more stable even when the quality your product falters.

This becomes a chick-and-egg game. Without great content, there are no users; with out users, there is no micro-payment system; without a micro-payment system, there is no content…

Eventually, I think the greed for more revenue will win out large, established content providers. They’ll concede having a smaller piece of a much larger pie.

Until then, I think we should create this system for the rest of us. PayPal would be an ideal candidate to get this system out…

https://www.paypal-forward.com/innovation/

 

 

Implementing Password Reset in MVC 4 EF Code First using Simple Membership – Part 1

Visual Studio Logo
So everyone by now knows that I’m a big fan of Entity Framework Code First approach: I’m a developer and not a DBA so I appreciate anything that allows me to abstract my task away from the SQL world. A previous post explained how to setup an MVC 4 EF-Code First application. That application comes with a baked in user authentication system using Simple Membership; however, it lacks one necessary function for it to be truly usable–a password reset.

I’m not sure what the Microsoft guys were thinking when they created the starting sample application without a password reset since Simple Membership has all the functionality to easily create one. Perhaps it’s a liability thing.

Throwing caution to the wind, this post will explain–step by step–all that is necessary to create a usable password reset using the framework that’s already there.

Part I – Create an MVC Application with Email in the User Profiles

The following steps show how you can add email (or any other parameter) to the UserProfile of Simple Membership. This useful especially when you want to get more information on your users. For example, you may want their email, mobile, twitter, facebook, etc. this may be useful to have in either the UserProfile table or table(s) associated there. Either way, the following should help you understand on the required steps to make such changes. It’s also happens to be the preliminary step to implementing a password reset; after all, we’ll need the users’ email to send them their reset link!

Step 1 –  Create a MVC 4 Razor Application

I call my application “PasswordResetApp” but you call it whatever your want. Ensure that you are using the sample application that’s provided with VS2012 without playing around with any of the settings.

Step 2 – Adding Email to the UserProfile Class

Before we even create anything, we’ll need to ensure that our account stores users’ email, which we’ll use to send out a password reset link. This is a little tricky because of how Simple Memberships is setup.

First, we’ll need to turn off the default way that Simple Membership is initialized by removing the following line from AccountController:

[Authorize]
//[InitializeSimpleMembership] /**COMMENT OUT OR DELETE THIS LINE**/
public class AccountController : Controller
{

Next we’ll need to create a Database Context (step 3) of the setup tutorial. Here you can add your model (but do it later). For now, we’ll just add the UserProfile object. Create a new class that extended the DbContext class called MyDbContext and add the UserProfile object (I put this in a new file called MyDb.cs in Models).

public class MyDbContext : DbContext
{
   public MyDbContext(): base("DefaultConnection") {}
   public DbSet<UserProfile> UserProfiles { get; set; }

Next add the Email string object to the UserProfile class of AccountModel.cs:

public class UserProfile
 {
   [Key]
   [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
   public int UserId { get; set; }
   public string UserName { get; set; }
   public string Email { get; set; }  // Add this
 }

We’ll need to initialize Simple Membership (since we turned it off) when we run our db initialization code. So create a new class DbInit that inherits from DropCreateAlways and put it in your Models folder. This is step 5 of the setup tutorial. I put this in the DbInit.cs in Models:

public class DbInit : DropCreateDatabaseAlways<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
       SeedMembership();
    }

    private void SeedMembership()
    {
       WebSecurity.InitializeDatabaseConnection("DefaultConnection",
          "UserProfiles", "UserId", "UserName", autoCreateTables: true);
    }
 }

By putting the SeedMembership() function at the end of all your Db Seed code, we ensure that Simple Membership is initialized after DB creation.

Next we simply initialize the database and ensure that it is run when the app is started. I do this at the end of the Application_Start() function in Global.asax:

Database.SetInitializer<MyDbContext>(new DbInit());
new MyDbContext().UserProfiles.Find(1); // This ensures that DbInit is run.

Step 3 – Modifying the Registration View to Accomodate for Email Input

First add the email string to the RegisterModel so you can pass in the information and validate the form (at this point you can have two email inputs for mis-type validation similar to password entry, which is what I do here). This is what I add to the RegisterModel class of AccountModels.cs:

[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }

[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[Compare("Email", ErrorMessage = "The emails you've entered do not match.")]
public string ConfirmEmail { get; set; }

Then we’ll need to edit the ~\Views\Account\Register.cshtml view to account for our new variable. I add the following right below the list <li> element:

 <li>
   @Html.LabelFor(m => m.Email)
   @Html.TextBoxFor(m => m.Email)
 </li>
 <li>
   @Html.LabelFor(m => m.ConfirmEmail)
   @Html.TextBoxFor(m => m.ConfirmEmail)
 </li>

Next we’ll need to edit the controller for Register post-back  ([HttpPost]). This is the Register(RegisterModel model) function in AccountController.cs. All you need to do is modify the following line:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

To:

WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });

And now we have a working application that gathers the user’s email upon registration and then stores it in the UserProfile object and the UserProfiles database.

End of Part I

There’s still a whole lot more to implement the password reset so hold tight for Part II of this post where I will provide the source files of my PasswordResetApp, the references (useful links), and a graphical summary much like I did in the setup tutorial.

PART 2 NOW AVAILABLE

Using Vim in Windows

I have a love affair with Vim. It’s the programmers text editor: with just a few key-strokes you can do just about anything. This is what programmers live for! We share a collective belief that the answer to all of the world’s problems, lay just a few key-strokes away. Vim–ever so slightly–confirms our mutual delusion. Without moving your hands away from the keyboard, you can edit, paste, search, replace, undo, redo, automate, and this and more, and so much more.

Vim is especially popular among the Unix\Linux crowd where Vi(m) originated. However, there’s no need for windows power-users to lag behind. gVim (graphical vim) is a great port of Vim for windows. In this article I will go over my _vimrc (windows version of .vimrc) and my basic setup.

I based my vimrc file on Yan Pritzker’s, and I recommend you check his setup up (especially if you’re running on a mac).

  • The first thing you want to check is to ensure that your $HOME directory is set to C:/Users/[username]. If it’s not, then some of the features in this setup may not work properly.
  • Next you’ll want to create the folder $HOME/vimfiles/, $HOME/vimfiles/backups, $HOME/vimfiles/ftplugin, $HOME/vimfiles/views
  • Finally, you’ll want to create a “_vimrc” in the $HOME directory

 

_vimrc Contents with Detailed Comments

” Begin with ensuring that we are running in vim mode not vi
set nocompatible” Set the color scheme of choice.
” In vim ‘:colorscheme [tab]‘ to see more options
colorscheme pablo

” Start in documents folder [WINDOWS specific]
” (this is not as useful if you start vim from cmd line since
” in that case you may want the pwd to be the dir where you
” loaded vim from; however, since most of us start gVim from
” the start menu then starting off in yoru documents folder
” is a good choice)
cd ~\Documents

” The following two lines turn on highlight for search (1st
” line) and allow you to use to turn off highlight
” for that search. The highlight will return on your next
” search.
set hlsearch
nnoremap :nohlsearch:echo

“Line numbers are good–turn them on
set number

“Allow backspace in insert mode
set backspace=indent,eol,start

“Store lots of :cmdline history
set history=1000

“Show incomplete cmds down the bottom
set showcmd

“Show current mode down the bottom
set showmode

“No sounds
set visualbell

“Reload files changed outside vim
set autoread

“Modeline option enabled for custom vim settings per file
set modeline

” This makes vim act like all other editors, buffers can
” exist in the background without being in a window.
” http://items.sjbach.com/319/configuring-vim-right
set hidden

“turn on syntax highlighting
syntax on

” ================ Turn Off Swap Files ==============
set noswapfile
set nobackup
set nowb

” ================ Persistent Undo ==================
” Keep undo history across sessions, by storing in file.

set undodir=~/vimfiles/backups
set undofile

” ================ Indentation ======================

set autoindent
set smartindent
set smarttab
set shiftwidth=2
set softtabstop=2
set tabstop=2
set expandtab

filetype on
filetype plugin on
filetype indent on

set list listchars=tab:\ \ ,trail:·

set nolist

“Don’t wrap lines
set wrap

“Wrap lines at convenient points
set linebreak

” ================ Folds ============================

set foldmethod=indent “fold based on indent
set foldnestmax=3 “deepest fold is 3 levels
set nofoldenable “dont fold by default

” The following lines save the view of the file including
” the folds and automatically saves and opens them. The
” next time that you open up the same file it will
” remember where you closed and open all the folds!
set viewdir=~/vimfiles/views
autocmd BufWinLeave *.* mkview!
autocmd BufWinEnter *.* silent loadview

” ================ Completion =======================

set wildmode=list:longest
set wildmenu “enable ctrl-n and ctrl-p to scroll thru matches
set wildignore=*.o,*.obj,*~ “stuff to ignore when tab completing
set wildignore+=*vim/backups*
set wildignore+=*sass-cache*
set wildignore+=*DS_Store*
set wildignore+=vendor/rails/**
set wildignore+=vendor/cache/**
set wildignore+=*.gem
set wildignore+=log/**
set wildignore+=tmp/**
set wildignore+=*.png,*.jpg,*.gif

” ================ Scrolling ========================

“Start scrolling when we’re 8 lines away from margins
set scrolloff=8

set sidescrolloff=15
set sidescroll=1

References

http://yanpritzker.com/2012/01/20/the-cleanest-vimrc-youve-ever-seen/

That’s it.

The NSA Broke the Social Contract with the Tech World

Dilma Rousseff, the president of historically US-friendly Brazil, lashed out against the US government for their intrusion of her personal privacy, on the privacy of her government’s corporations, and on the privacy of Brazil’s citizens. She’s proposing some interesting and real-world solutions that will take some of the power away from the U.S. and possibly back into the hands of world internet users. Despite this, I believe that the biggest fallout that the NSA faces is their loss of trust with young technocrats, technologists, and engineers.

Perhaps Rousseff’s idea of a UN branch to deal with internet freedom will materialize and help create the political pressure to change privacy intrusion programs prevalent in the US and around the world. However, that will take decades with strong oppositions from many UN countries, not just the USA. It would put the “free world” in alliance with some of the most oppressive, autocratic countries to fight against such loss of sovereignty. Can you imagine Russia, Iran, Syria, or China, agreeing to an international body to promote internet freedom? Putin seems to flip-flop on the issue even if ministers in his own cabinet are clearly against it. However, it’s indisputable that china is against internet freedom, which they don’t deny in the slightest. Muslim countries feel the need to protect their citizenry from pornography, even in semi-secular, semi-democratic Turkey.

So why am I still optimistic that the Snowden leaks will produce significant, long lasting change?

It’s simple. Up until now, the tech world worked with with such bodies as the NSA and the British GCHQ (the good guys, they thought). In a way there was an unwritten, unspeakable contract: “you guys catch the real bad guys–the terrorists–and we won’t make your life too hard for you.”  As it turned out, the US government has broken this contract. While the phone number meta-data collection of US citizens may be most legally incriminating, what really broke this contract with the Tech World is the NSA’s complete disregard for privacy, oversight, and checks against their own system. Something that still haunts me, for example, is the screen shot of the tool used to track email communications. There’s a web-form that an analyst will fill out begin the query. That web-form contained a one-line input box (<input type=”text”>) for the justification for spying on that individual. That’s right, to spy on any email address you simply fill out a web-form similar to that when creating a new twitter account! Justification? Keep it under 30 characters, please!

48

Of course I’m entirely over simplifying this, but that screenshot is symbolic of the NSA’s approach to spying. They’ve grown lazy, complacent, and–I’m afraid–incompetent in the worst way possible. On the one hand, they built this incredibly powerful system capable on spying on internet traffic, but on the other hand, the gateway to accessing this powerful tool seems negligible. Snowden claims–and there is no reason to distrust his statements–that as a mid to low level 3rd party contractor, he could spy on who he wanted. His statements are substantiated by evidence of abuse: employees spying on their significant others. … I wonder what they typed in the small justification input box, “Frnd tld me she’s a cheating whore. Need proof.” But perhaps it’s not a required field.

If lack of oversight and evidence of abuse is not enough, there’s also substantial evidence that this tool is misused officially. The Tech World is fine with the NSA going after Al-Qaeda and violent terrorists. However, leaks clearly indicate that this tool is used for targeting journalists, protesters, publicly owned corporations, and politicians. This disclosure, I’m sure, is the last nail, the final straw for most of us.

But wait, there’s more! (As any as-seen-on-TV salesman will say)

The NSA, working with such government bodies as NIST  as insiders, have undermined our internet infrastructure. Suggestions of intentional back-doors in cryptographic systems takes this game to a new low. Read this Wired article for details.

The US government will claim that Snowden has caused them insurmountable damage; in a way, they are right. The disclosure of these practices have caused great damage, but only because they are true. It’s like the cheating husband who blames the divorce on his wife’s friend who disclosed his extra marital affair. The reason why the Snowden leaks are so damaging, is because they show that the US government broke the social contract with the Tech world. It has turned a semi-friendly group against the NSA just it turned a semi-friendly country against the US.

The consequences? I think that in the next few years cryptography standards will increase, privacy-protection products will flourish, and the Tech world will not make it so easy for PRISM-like programs to function.

http://www.wired.com/threatlevel/2013/09/nsa-backdoor

 

Choosing an ASP.NET MVC 4 Book

MVC 4 Books Rating Graph

(the above graph takes the public review statistics from amazon.com on 6/21/2013)

I find that choosing the right book is as important as going through the exercises and tutorials in it. If I am to invest 40+ hours into consuming it, I better choose the right one. The above info graphic represents the user review statistics from amazon.com as of 6/21/2013 (see references below).

I don’t always follow Amazon reviews when picking out my books, and sometimes a really good review will sway me over many negative reviews; however, Freeman’s Pro ASP.NET MVC 4 (978-1430242369) had overwhelming positive reviews written by individuals who sound like they know what they are talking about.

I hope to digest this book in a few weeks and then I’ll write a full review.

References:

 

Sketch Wireframe Kit

Sketch Wireframe KitI have used wireframe kits such as this one in the past, but I was never 100% happy with any. The one I used most is the Jaws Sketching Kit but it didn’t have that “sketch” feel to it–the lines were just too perfect and I’m not as into rounded corners anymore. For that reason, I’ve decided to build my own. I’m still missing a few items that I don’t use often for wire-framing, but if I ever do create them, I will update the kit.

UPDATE 6-14-2013: I didn’t really have time to write about the sketch kit the first time around because I was really busy, but I wanted to explain why I wanted it to have a very rough feel. The reason for this, it is to remind the person reading it that wireframes is all about layout and nothing about final look and feel. It’s supposed to symbolize a very unfinished and incomplete design. When wireframes have such things as rounded corners or any type of styling, it may be interpreted as the design or look and feel of the final product. By having a sketch feel to the wireframes, the reader knows that this is an unfinished product and the placement\location of elements is more important than how they may look\feel (at this point in the design process, anyway).

Adobe Illustrator CS5 File  and PNG (for backward compatibility) - dgSketchWireframeKitV0-1 (download link)

Licence: Attribution, No Mods, Share Alike (can be used commercially)

Creative Commons License

This work is licensed under a Creative Commons Attribution-NoDerivs 3.0 Unported License.

In Response to the Supporters of PRISM

PRISM Slide

Perhaps I am sensitive to privacy intrusion after my family enjoyed some of the “benefits” of a totalitarian-esque communist state. Perhaps my hatred of big-brother solidified after reading (and re-reading) George Orwell’s 1984. Or, perhaps, it’s just common sense.

Last week validated the vilified Assange and his Cyberpunks thesis: big-brother is watching your every step. Yes, you’ve all read the details about how the NSA has agreements with (at least) Verizon, Google, Microsoft, Yahoo, Facebook, Pal Talk, Youtube, Skype, AOL, and Apple. But I’m not writing this article to go over the details of the program nor how expansive it is. I wanted to respond to some of arguments that support PRISM that I have seen in response to all the news media critiques.

(Credulous) Arguments Supporting PRISM

The Eric Schmidt argument

He didn’t invent this argument, but he is the most famous and consequential head to have been caught saying it. On CNBC in 2009, Eric said, “If you have something that you don’t want anyone to know, maybe you shouldn’t be doing it in the first place.” And that’s the argument. What have you got to hide that you’re so concerned about privacy? This argument scares me. It’s more than just Eric’s hypocrisy (he had a bunch of information published, which he wanted to keep … aghem… secret), this is the go to argument of every totalitarian state (including the state in 1984).

To respond to this childish argument, I can think of a few things that one may be doing in secrecy:

1. Researching about their own health. Health is a touchy subject, and if Joanne wants to go on Web-MD to research genital warts, should that information not be private?

2. Someone wants to battle their daemons without facing prosecution. If a drug addict wants to fight his or her disease on their own terms by researching it on-line  should that information not be kept away from the government?

3. High risk\high profile users. What about high profile users (such as Eric Schmidt who experienced this himself!) who do not want their personal information known for reasons such as black mail? (More on this in my response to the next argument)

4. Cases of government (non-violent) protest. This is the most important case, and one that’s a little tougher to swallow by non-disaffected groups. But imagine that in the 19th century the government had such access into our brains. Would the women’s suffrage movement have happened if the government could quash activism at the grass-roots level? The only reason why Eric’s argument holds any bearing is because we somewhat agree with the current powers. We would have a different view if Verizon, Microsoft, and Google shared information with Iran.

The Technocrat (Obama’s) Argument

Obama (and other technocrats) have told us that the information they collect is simply used by an algorithm to identify patterns that looks suspicious (I hope they mean terrorist activity). Anyone who works with big-data and analytics knows that in order to get meaningful results, the whole data set needs to be available for computation. That is, if you input only partial information such as the data obtained from a limited warrant, your results will be skewed and, most likely, flawed. I agree. I agree with the fact that (for now) the administration is using this data in an innocent way to go after only the most extreme elements in our society. I also agree that the whole data set needs to be available.

What I don’t agree is the short sightedness of this argument. PRISM takes away a certain level of user control and opens up a door for corruption or negligence. Sure the data that is collected is currently only used to feed into PRISM’s algorithm, but what if (a) the algorithm changes based on a change in the administration or (b) the data is stolen. In the first scenario, what if some far right-wing evangelical Christian gets elected into power and wants to go after all the scientists who support the “theory” of global warming (basically, ALL of the scientists). PRISM allows them to do that. For the second scenario, what if some part of the administration is corrupted to steal the information being funnelled into PRISM in order to gain some sort of power. Imagine House of Cards meets big-brother. Not likely you say? What about, then, negligence? Surely, opening up another feed of our personal information only makes it less safe. If hackers get control of this funnel, they don’t only have access to personal information of one corporation (which has happened on many occasions), suddenly they have access to a slew of them at once!

Bill Maher’s Argument for Safety

Bill Maher and I agree on almost everything, except for this. I’m sure I can attribute this argument to a different person, but since I so closely identify with Bill, I’m going to name it after him. He makes the point in his last episode (6/7/2013) that perhaps the trade-off between privacy is worth the extra security we have. To make his point, he quotes Obama who says that it was only after he had access to privileged information that he realized how important such programs as PRISM are. He also points to one thing: Nukes. He points out that the founding fathers could not have foreseen a bomb that could obliterate a whole metropolitan area and the millions of people that it holds.

This is a valid argument as is the technocrat one, but again I feel that it lacks foresight. I guess since Bill already dismissed those who could not foresee the nuclear weapon, it would not suffice to quote Benjamin Franklin who said that, “Those Who Sacrifice Liberty For Security Deserve Neither.” It’s true that times have changed and now we have true technology of mass destruction. It’s scary to think of a dirty bomb scenario (or biological weapons). However, I don’t know whether this argument stands the test of reason and logic. If a terrorist is intelligent enough to build or procure a nuclear weapon, would they be caught in PRISM’s net? I’m sure their every communication and footprint would be encrypted. I don’t think that even the least savvy Anonymous hacker would get tripped up by PRISM. It’s a very simple thing to maneuver around: VPNs, proxies, encryptions, and care. Every decent drug dealer knows to use a “burner” and dispose of it every so often. Every hacker knows to utilize VPNs and proxies. Every spy knows to encrypt their communications. Surely PRISM can’t crack PGP or AES quickly enough.

So in reality we don’t even have the option to trade privacy for security. Sure, stupid terrorists like the Boston Marathon bombers might have been caught, but–wait!–they weren’t. Perhaps that was a miss. But because the PRISM program lacks any sorts of transparency, we cannot compare the hits versus misses. That is, we cannot judge the programs efficacy. Whether, like Schroedinger’s cat, the outcome is affected by this observance is another question.

In Conclusion

In July 2012, I wrote an article encouraging users not to use Kaspersky because of the governments strong-hold on power and freedom (and the fact that their laws clearly mandated back-doors and compliance). What can I say, then, about America’s biggest tech companies? Sure our ideals are more closely aligned with Google than the Kremlin, but for how long? To tell you the truth, I don’t know what to say. Perhaps we should all move to the Netherlands to enjoy TRUE civil liberties.

Hyperbole aside, the reason why America has been held as a beacon of light in the fog of political corruption, state totalitarianism, and abuse of power is because of one thing: checks and balances. One branch of government watches the other while elections and news media lubricate the whole process. No one branch has all the power. And on the day that the Patriot Act passed congress (with W’s signature a sure guarantee) I knew that the beacon of light dimmed if not extinguished completely. Last week was proof of that fact. The question is, where do we go from here? Will the once greatest nation in history overcome this great test of theirs or will the people fall complacent to the abuses of their government?

UPDATE (6/10/2013): The most important link w.r.t. to this scandal as written by Daniel Ellsberg (the man who leaked the Pentagon Papers 40 years ago). He calls Edward Snowden and the PRISM leak as the most important example of whistle blowing in history (including his own leak). As well, he goes into detail why it’s such an atrocity. When I have time I will include the link in my actual blog post. Please read the article and watch the video interview with Snowden: http://www.guardian.co.uk/commentisfree/2013/jun/10/edward-snowden-united-stasi-america?CMP=twt_gu

 

 

Code First Entity Framework with MVC4 and Visual Studio 2012

I am a huge fan of ADO.NET’s Entity Framework (EF) that bridges the gap between modelling entities\business logic and data engines. It allows web-programmers like myself to focus on the solution instead of worrying about properly setting up databases, keys, foreign-keys, constraints, and indexes. Because of it’s quick turn-around, EF is perfect for prototyping and proof of concepts. For enterprise sized solutions, code-first created databases may require some greater optimization, but that can always be achieved after the fact if not in the solution itself. Querying and operations are a simple endeavour–simply work with the abstracted model and let EF worry about performing the correct database transactions for you.

 

Visual Studio Logo

 

Setting up a Code First EF MVC4 project is simple enough, but because I don’t do it often, I sometimes forget some steps. After all, most of my time is spent working with the solutions, and not setting them up. For this reason, I have decided to make a graphical guide as well as this blog post, which I hope helps my readers as much ad it helps me. In this tutorial, I create a simple model that goes over many of the features that you might use.

Step 1 – Create a new Project

First create the project in VS2012 by going to new project, giving it a name, selecting ASP.NET MVC4, selecting Internet Application, and ensuring Razor is selected. This will give you the base for a Code First EF MVC4 application. In fact, the Accounts Model is already set up with Entity Framework!

Step 2 – Define the Model

Simple Model UML

Next we create a very simple model that exemplifies how a 1 to many relationship using ICollection. The UML diagram above is coded in code example below entitled, “TestModels.cs.” The model is a little inconsistent to illustrate different techniques and annotation of the entity framework: custom db table names, custom KEY, and custom FK name; as well, it illustrates that traditional EF naming, which doesn’t require the annotation described.

    [Table("dbUsers")] // Use this to use a different table name other than "Users"
    public class User
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int DbUserId { get; set; }
        public string Name { get; set; }

        public virtual ICollection Purchases { get; set; }
    }

    // This table will be called "Purchases" automatically
    public class Purchase
    {
        // Because standard naming is used, no need for [Key] ...
        public int PurchaseId { get; set; } 
        public int UserId { get; set; }
        public int ProductId { get; set; }

        [ForeignKey("UserId")] // Use this if the name of FK is different
        public virtual User User { get; set; }
        // No need to use ForeignKey because FK name is same as Key of Product
        public virtual Product Product { get; set; }

    }

    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public virtual ICollection Purchases { get; set; }
    }

Step 3 – Create the DbContext

In the same model file, I create a the DbContex object that tells EF which classes are going to be stored in the database. In this case, I name this “TestContext” as seen in code segment below. It may be useful to note that other options are available here such as turning off pluralization, pointing to a specific db connection, etc.

    public class TestContext : DbContext
    {
        public DbSet Users { get; set; }
        public DbSet Purchases { get; set; }
        public DbSet Products { get; set; }

    }

Step 4 – Add a Connection String

Next open up your “Web.config” and add a connection string in the <connectionStrings> node. If you followed the steps above, you should already have one named “DefaultConnection.” Whatever your choice of storage system, make sure you name your connection, “TestContext.” Entity framework will automatically associate this connection with the db context we created in step 3.

Step 5 – Add a Data Initializer

Entity Framework provides a very useful feature: the ability to initialize your tables with some sample data whenever the model changes. To do this create a new class that inherits from DropCreateDatabaseifModelChanges<DbContext>. Next we override the Seed(context) function where we add our products, purchases, and users. The method SaveChanges() in the DbContext object is run whenever you want to update the DB.

    public class TestInitializer : 
                    DropCreateDatabaseIfModelChanges 
    {
        protected override void Seed(TestContext context)
        {            
            var products = new List
            {
                new Product { Name = "Widget", 
                              Description = "A widget is a widget." },
                new Product { Name = "Crank", 
                              Description = "A crank for the  widget." }
            };
            products.ForEach(p => context.Products.Add(p));
            context.SaveChanges();

            var users = new List
            {
                new User { Name = "Joe" },
                new User { Name = "Lillith" }
            };
            users.ForEach(u => context.Users.Add(u));
            context.SaveChanges();

            var purchases = new List
            {
                new Purchase {  
                    Product = 
                        products.Where(p => p.Name == "Widget").First(),
                    User =
                        users.Where(u => u.Name == "Joe").First() }
            };
            purchases.ForEach(pr => context.Purchases.Add(pr));
            context.SaveChanges();
        }
    }

Step 6 – Set the Initializer in Global.asax.cs

Next we set the initializer in the Global.asax.cs file to ensure that it runs when it needs (when the model changes and the context is used).

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer(new TestInitializer());

...

Step 7 – Add the DbContext Object to a View in Order to Test

Usually I add the dbContext to the HomeController first (without even touching the Home View) in order to test out the implementation inside an ActionResult that I know I will run (visit with browser after running); I also add something to the data to ensure proper functionality and saving.

 public class HomeController : Controller
    {
        private TestContext db = new TestContext();

        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            db.Products.Add(new Product { Name = "asdf" });
            db.SaveChanges();
            return View();
        }

   ...

The last step is to verify that the database, tables, and sample data were created properly in the DB. For this I usually run SQL Managment Studio and inspect the DB directly. If you did everything correctly, you should see a new database with the name that you’ve described in the connection string.

Below is the graphical Guide:

A graphical guide to the tutorial above

References

MSDN, Entity Framework Overview - http://msdn.microsoft.com/en-us/library/bb399567.aspx
Creating an Entity Framework Data Model for an ASP.NET MVC Application - www.asp.net

Using LESS with ASP.NET MVC

There are several option in implementing LESS (the dynamic style sheet language) with your asp.net MVC application. While MVC 4.5 provides bundling and, with that, minification, it still does not provide the same dynamism as LESS; that being said, you can take advantage of both using the following technique.

WinLess Logo

An aside for those unfamiliar with LESS: it’s a dynamic stylesheet language that allows you to extend CSS to allow variables, “mixins,” operations and function. It’s a powerful tool that can help decrease dev time while making your style code more robust. It allows you, for example, to declare a variable for your main and accent colors at the top of the style sheet so that when you want to change the palette of your entire site, you can do that by editing three or four lines. That alone deserves great props. More info on http://lesscss.org/

So if you’re familiar with LESS you’ll know that you have 3 options: implement LESS on the client-side, dynamically on the server-side, or compile to CSS. There may already be some Asp.net LESS compilers our there (and if there isn’t, there should be), but my favorite option is the simplest: compile to CSS.

I use the program winless to watch the content folder of my MVC application where I have my .less file. I then add the compiled .css to the bundle(s). That’s it! Now anytime I make a change to the .less style it will automatically get compiled to the CSS file which my bundles use. No mess; no fuss.

Perhaps the most elegant solution would be if we have a LESS parser with the bundling implementation, but this is a pretty painless solution as well.

Reference:

 

 

 

Open Menu Button

Menu