Problems setting up ASP.NET 4.0 web on IIS 7


.NETASP.NETASP.NETFrameworksLanguagesServers

I was attempting to set up a new ASP.NET 4.0 web on my dev machine, running Windows 7 and IIS 7. I ran into several errors, that I suspect others may encounter, and I had to search all over the web to find all the answers. So I’ve written this post in the hopes it saves some other dev the same headache I had!

So, first I created the new website and app pool identity, but when I hit the site for the first time, I got the following error:
HTTP Error 500.19 – Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

After searching for solutions, I found most had to do with permissions to the web.config file or actual locking of sections of the web.config file. I confirmed that the app pool identity had permissions to the file, and there were no locking attributes in the file. So something else had to be the issue. Then I found this post:
http://stackoverflow.com/questions/9216158/the-requested-page-cannot-be-accessed-because-the-related-configuration-data-for
It turns out that ASP.NET had not been configured fully on my machine. So, according to one of the answers on the post, the solution is to do the following steps:
1. Open control panel
2. Click on “Programs and Features”
3. Click on ”Turn windows features on/off”
4. Locate ”Internet Information services IIS” in the pop up window and expand its node
5. Expand the ”World Wide Web Service” node
6. Expand “Application Development Features” node
7. Check the check box of”ASP.NET”
8. Then click ok button
9. You will need to restart your computer (go get a cup of coffee…)

After restarting, and hitting the site again, I got this new error:
HTTP Error 500.21 – Internal Server Error
Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list
Another web search revealed that even though the step above enabled ASP.NET, it was not fully installed. This article shows how to finish the installation: http://stackoverflow.com/questions/6846544/how-to-fix-handler-pagehandlerfactory-integrated-has-a-bad-module-managedpip
Basically, just open a command window and enter the command shown below (command is slightly different for 32-bit vs. 64-bit).
64-bit:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

32 bit:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

If you get a permissions error, you need to run the window as an administrator. To do this, go to start |run, and type ‘cmd’, but hit Ctrl-Shift-Enter, instead of just Enter.
After doing that, I hit the site again, and it worked! Hope this has helped!

Hello Meteor


Javascript/AJAX

(modified from http://asynchrotron.com/blog/2012/05/22/hello-meteor/)

This post is for the benefit of all those who are feeling like they might be missing a step with frameworks like Backbone, Ember, (and now Meteor), et. al. Read on for recommendations on what to read up on to understand more about the problems they’re solving.

First a brief note about MVC

The Model-View-Controller application architecture (MVC) is used in most modern applications to separate an application’s data from its business rules and user interface. Briefly, Models represent an application’s data and functions to access it. Views represent information presented to the user. Controllers represent intermediary resources required to generate Views. The MVC pattern isn’t new (it can be traced back to Smalltalk), but it was popularized, along with the REST style of client-server API design by server-side web frameworks such as Rails and Django.

So what’s all the fuss about JavaScript MVC frameworks (Backbone, Ember, et. al.)?

If you think of the screens – or pages – in your application as different “states” in your application, server-side frameworks require a round trip back to the server when the user goes from one application state to another. This is fine for content-heavy apps or websites. Or if you’re accessing the pages via an ethernet cable or 802.11. But when you move to high latency connections and along the continuum — and I believe it really is a continuum — from a web site to a web app, you can deliver a much better user experience if you avoid the server round trip for each state change, and instead switch from state to state on the client, within a single browser page load cycle.

This saves you all of the overhead of destroying and recreating the DOM tree, flushing browser context (JavaScript, CSS, etc.) on each new page load. You also are transmitting less data on the wire (or ether) since HTML is generated on the client, and only JSON passed over the network. Both of these factors (page refresh time and network traffic optimization) are significant when you consider the fact that more and more internet usage is taking place via mobiles and tablets.

You would still need a server to authenticate users and perform other privileged operations, and to store the “official” version of the data that different clients synchronize with, but instead of sending dynamically created HTML to the client (a la aforementioned server-side frameworks) the server would send as much data as needed (typically as JSON) to the client, and the client would create all of the different application states dynamically. The problem with this approach — and I’ve been writing apps this way since 2008, without the benefit of any client side frameworks — is that they quickly turn into a mass of spaghetti code.

This is where the likes of Backbone, Ember, etc. come in. They are a re-imagination of the MVC application architecture for JavaScript application development in the client, where all (or nearly all) application states are handled in the client, in JavaScript. They provide a way to structure your JavaScript applications in a more organized MVC style.

Addy Osmani’s articles, and especially his Backbone Fundamentals book are a great place to start reading more about this. Although it’s focused on one specific framework (Backbone), it has a good overview of MVC and how the pattern has moved from server side frameworks (like Rails, Django) to the client side (Backbone, et. al.).

I also wholeheartedly recommend his recent talks on providing structure to JavaScript apps.

And this is a useful comparison of various front-end frameworks, although the conclusions should be taken with a grain of salt (it’s one persons’s perspective, and things are not quite as quantifiable as the article suggests):
So, all of these are client side frameworks, which solve the problems of a) separating client side code into MVC, and b) optionally, allowing views to “observe” client side models, so that views get updated automatically as the data in the models is updated or as new data arrives from the server.

This gets you pretty far, but all of these applications have something else in common which the previously mentioned MVC frameworks don’t address: They need to send data back to the server and check in if data has changed on the server. In other words, they need to synchronize client side models with the server side models.

Enter Meteor.

Meteor is a full stack framework for end-to-end JavaScript applications. The beauty of coding it all in JavaScript is that you can easily implement the observer pattern (views watching for changes to the models) all the way to the server side. Meteor
apps can subscribe to models (or subsets of models) on the server, and meteor takes care of all of the plumbing. This really is the bleeding edge of JS today.

For more on the problems Meteor solves, read the Meteor docs from the intro section through to as many of the detailed concepts you’re interested in. Or come to my talk at JS.Chi() and we will work through it together. Here are the slides from the talk.

Have fun!

Pallavi

ASP.NET Membership.GetUserNameByEmail Error: “The E-mail supplied is invalid.”


.NETASP.NETC#LanguagesTips and Tricks

What the heck does this error message mean?? I had cause to find out when I was getting this error in a method that was simply updating the email address for an existing user. Mind you, I wasn’t creating a new user – I was just updating an existing user.  Since the error message is less than helpful, I thought I’d post this so anyone else getting this error won’t have to search as much as I did to find the solution.

Here’s how it came into play: I had created a secure web page to allow my client to manage some of their user accounts. They often had requests to change the email address for the account, so I created a simple form with a couple of text boxes (tbChangeEmail_Old and tbChangeEmail_New), a label to display the status of the attempt (lblChangeEmail_Status) and a Submit button.

Here’s the code I was using, when the user clicked the Submit button:

try
{
   string username = Membership.GetUserNameByEmail(tbChangeEmail_Old.Text);
   if (!string.IsNullOrEmpty(username))
   {
      MembershipUser user = Membership.GetUser(username, false);
      user.Email = tbChangeEmail_New.Text;
      Membership.UpdateUser(user);
      lblChangeEmail_Status.Text = "Email address successfully changed.";
   }
   else
   {
      lblChangeEmail_Status.Text = "Unable to find user with that email.";
   }
}
catch (Exception ex)
{
   lblChangeEmail_Status.Text = "Error: " + ex.Message;
}

It’s pretty straightforward – attempt to get the username using the ‘old’ email, and if the account isn’t found, display a message to the user. If we do find the username, then use it to get a MembershipUser object, set the Email property to the ‘new’ value, and update the user. Wrap that up in a try/catch block, and we’re good to go.

Everything worked fine, until today, when my client reported she was getting an error message for one user: “The E-Mail is invalid.” Huh. Did that mean the new email address wasn’t a valid email format? No, the new email was fine. Did it mean the old email didn’t work and the user wasn’t found? No, the test for !string.IsNullOrEmpty(username) catches that, and I verified that the account with the old email address was present. So what’s going on?

I did the usual trick of Googling for a solution, and found a lot of forum questions related to creating a new user, but then I finally found something about DUPLICATE emails, which, of course, are not allowed in the Membership database, based on our configuration. Aha! I did a quick SQL query of the DB, and sure enough, there was already an account with the ‘new’ email address, so it was not possible to update the ‘old’ account with the ‘new’ address!

So, since the existing error message is less than helpful in this case, I changed the logic in the catch block, so I could display a more helpful error on the web page:

catch (Exception ex)
{
   if (ex.Message.ToLower() == "the e-mail supplied is invalid.")
      lblChangeEmail_Status.Text = "There is another account with the 'new' email address, so the 'old' email account cannot be updated.";
   else
      lblChangeEmail_Status.Text = "Error: " + ex.Message;
}

Now, if we run across another case like this, my client will know exactly what’s going on. No more ambiguous error messages! J

So, not earth-shattering .NET stuff, but I figure what I learned might help someone else in the same situation. Happy coding!

Displaying another app’s data using HTTParty and Kaminari


RailsRuby

I needed to access some data from another app and display it to users. The api side was a Rails 2.3.11 app and used will_paginate. It returned the json of a model collection and an association along with paginator information. The client side was a Rails 3.1 app using HTTParty and Kaminari.

API Controller

Rails 2.3.11 doesn’t include associations in the json, which is a known bug. So I returned a collection with the two models’ information. I used an API key to authenticate, which I won’t describe in detail since it’s outside the scope of this post.

class Api::FoosController < ApplicationController
  before_filter :authenticate_api_key!

  def foos_index
    @foos = Foo.paginate(:order => "created_at desc", :per_page => 40, :page => params[:page], 
        :include => :bar)
    @records = @foos.collect { |foo| {:foo => foo, :bar => bar} }
    render :json =>  {:records => @records, :total_entries => @foos.total_entries, 
        :per_page => @foo.per_page }
  end
end

API Route

The route requires the page number.

  map.connect '/api/foos/foos_index/:page', :controller =&gt; "api/foos", :action =&gt; :foos_index

Client Model

FooIndex.foos_index returns itself, along with accessors for the response, records, total_count, current_page, and limit_value. The last three are important for Kaminari. When I parsed the JSON, I symbolized the keys. Much prettier than strings.

class FooIndex
  include HTTParty
  base_uri ENV['FOO_APP_URL']
  default_params :api_key =&gt; ENV['FOO_API_KEY']
  format :json
  attr_accessor :response, :records, :total_count, :current_page, :limit_value

  def initialize(response, records, total_count, current_page, limit_value)
    self.response = response
    self.records = records
    self.total_count = total_count
    self.current_page = current_page
    self.limit_value = limit_value
  end

  def self.foos_index(page)
    @current_page = page || 1
    response = get("/api/foos/foos_index/#{@current_page}")
    if response.success?
      json = JSON.parse(response.body, symbolize_names: true) 
      self.new(response, json[:records], json[:total_entries], page, json[:per_page])
    else
      raise response.response
    end
  end
end

Client Controller

I had to be creative with Kaminari using the paginate_array method. The options total_count and limit are used because the api doesn’t return the whole set of data, just the data for one page.

class FoosController &lt; ApplicationController
  def index
    params[:page] ||= 1
    @foos_index = FooIndex.foos_index(params[:page])
    @paginated_array = Kaminari.paginate_array(@foos_index.records, 
        total_count: @foos_index.total_count, 
        limit: @foos_index.limit_value).page(@foos_index.current_page)
  end
end

Client Route

Page number is optional in the route. The controller defaults it to page 1.

  match '/foos(/:page)', :controller =&gt; :foos, :action =&gt; :index

Client View in HAML

The json returned by the api doubles up the first part of the hash. I’m not sure of an elegant way to handle that.

= paginate @paginated_array

%table
  %thead
    %th Foo Name
    %th Bar Name
    - @foos_index.records.each do |record|
      %tr
        %td= record[:foo][:foo][:name]
        %td= record[:bar][:bar][:name]

= paginate @paginated_array

And that’s all it takes. Please comment with any comments or questions.

About Angel N. Sciortino

Ruby programmer. Sysadmin. Queer and polyamorous. Welder. Crocheter and darner. Chaotic good.

More Posts by Angel N. Sciortino - Author Website

Practicing Code with the DevChix


ApprenticeshipRailsRuby

In February I finally decided to do something I always wanted to do with DevChix. I wanted to lead a group project intended for those who wanted to learn and could commit to 2 hours a week. I had 3 volunteers.. then two.. and then one! But thats ok, I know people get busy and other things going on, so no big deal. But cool thing is, even those that left said they learned something. So, my goal was still reached!

The Project

I had this idea in my head for awhile. One thing with lists is, you need to write down something if you want to do it today. We all have todo lists, and there are somethings we want to do every day. You may try to remember them without a list, or maybe you write them out. I thought it would be cool to have a todo list app that will give your list, allow you to check them off, then next day you have the same list. Bonus to have a graph of how many you did each day of the week. I think its motivating to see a graph of my progress.

Getting Started

Its my experience, when I start an app, I add user login and I get hung up on the authentication, tests and stuff and never get to the meat of the app. So I wrote a simple login system with just a username (no password), threw it in the session and wrote some simple methods to check to see if logged in. Later we replaced it with Devise with not much trouble at all.

What we learned

  • git, making branches, push and pull
  • erb and haml
  • grid 960
  • HighCharts a javascript graphing library
    devise, we added a whitelist so we can have a beta with only certain email addresses allowed to sign up.

  • publishing with heroku
  • rails of course

Challenges

Summer got busy, including a cross country move for me and new job! We still managed to meet about every 2 weeks. We used github for our code. We put our tasks in Pivotal Tracker and that worked fine. We used Github wiki to record meeting notes, what happened since last meeting and who is doing what for the next week. We’ve been able to meet weekly the past month or so as the summer is winding down.

Whats next?

We are deploying the app to DevChix for beta testing. From there, not sure.