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!

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.

PyArkansas: Small town, big tech!


DjangoEventsPeoplePython

Last weekend I flew out to to Little Rock, Arkansas, took a two hour crawl through a snarl of traffic, and arrived just in time for my Friday night pre-PyArkansas tutorial in Conway. Held on the stunning campus of Hendrix College, I wended my way around buildings, a massive fountain, inspiring structures, until I found the building where my tutorial was about to happen. Standing in the foyer with the beautiful Foucault pendulum, I could not help but to stop for a moment, exclaiming “Oooo!!!!” aloud, wishing I had gotten there thirty minutes earlier.

My tutorial was intended to encourage women in computer science by serving two purposes: discussing the source code and functionality of a particular project, and openly discussing some of the issues they faced in their current programs and surroundings. I was pleasantly surprised to discover that these women needed no technical or social encouragement. They are already enthused, technically and socially well prepared, and on their way to a very bright future in engineering or computer science. I was pleasantly surprised that they were very comfortable in the bash shell, and as comfortable in their current college curriculum. Like children at play, they picked up the moderate-levelled tutorial code quickly, made great strides in such a short time, and had a lot of fun doing it.

It was profoundly encouraging to see such a small computer science program achieve diversity as well as such a high level of skill. It made me wonder why larger colleges and universities cannot accomplish the same on bigger budgets, with larger staff, and a more diverse mix of students. It touched me to hear and see the enthusiasm, eagerness, and skill of the students in this program. Their learning experience under the Department Chair, Dr. Burch, comes as close to perfect as I have ever seen.

The next day’s events at PyArkansas were held at the also-very-nice campus of University of Central Arkansas, where an entire day’s worth of tutorials took place. Two Python 101 tracks were held: one for programmers and one for non programmers (a great concept). An all-day Django Track was given, where the advanced course was taught by Jacob himself. I held an afternoon tutorial addressing advanced Python concepts, with downloadable example code, where we compared and contrasted build and deployment tools, played with regex, and showed examples of some internal Python oddities involving static variables. I unfortunately missed the Python Blender tutorial, held at the same time as mine, and I heard it went quite well.

The campus facilities were very accomodating. Everything was well organized,and up and running for us when we arrived. This is a very welcome surprise to anyone who has travelled a bit to do tutorials. I was specifically told by Dr. Chenyi Hu, the Department Chair of UCA, that he really does care about diversity, and it is something they strive to achieve. This was truly touching, quite impressive, and a pleasant surprise from such a small town.

Kudos to Greg Lindstrom, Dr. Carl Burch of Hendrix College, Dr. Chenyi Hu of UCA, and everyone else involved. You induced a big technical “tremor” through your small town, which echoed far and wide. It is yet another example of the great people drawn to the Python community, and the amount of quality effort they are willing to give back. I feel honoured to have been part of this event, and I hope to be involved in many more to come.

Gloria