<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nathan Bridgewater &#187; ASP.Net</title>
	<atom:link href="http://www.integratedwebsystems.com/category/dotnet/aspnet-dotnet/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Thu, 19 Jan 2012 20:37:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Get Started with Amazon EC2, Run Your .NET MVC3 (Razor) Site in the Cloud with Linux Mono</title>
		<link>http://www.integratedwebsystems.com/2011/12/get-started-with-amazon-ec2-run-your-net-mvc3-razor-site-in-the-cloud-with-linux-mono-2/</link>
		<comments>http://www.integratedwebsystems.com/2011/12/get-started-with-amazon-ec2-run-your-net-mvc3-razor-site-in-the-cloud-with-linux-mono-2/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 21:30:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[MVC3]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=1325</guid>
		<description><![CDATA[I’ve recently been getting pretty excited about Amazon EC2 once I realized...]]></description>
			<content:encoded><![CDATA[<p>I’ve recently been getting pretty excited about <a href="http://aws.amazon.com/ec2">Amazon EC2</a> once I realized you can setup a micro linux server for free to learn and test out their services. I know, a couple years behind the curve right? I’ve just never really looked into it. Now that I’m familiarizing myself with the whole cloud concept with Amazon, it’s really cool to think of small business growth potential in the web market without the restraint of building a heavy infrastructure upfront. I realize after reading some other articles that in the long run, it is probably more expensive than hosting your own solution. But as a startup, it still seems to me that it’s a pretty good deal at least for short term events or just taking their infrastructure out for a spin to test some ideas. Pay for what you use; that’s Amazon’s big pitch with their <a href="http://aws.amazon.com">Amazon Web Services (AWS)</a>. </p>
<p>So if you want to play around with <a href="http://aws.amazon.com/free">AWS for free</a>, you have to roll Linux. If you want to host ASP.NET MVC3 on AWS Linux, there’s a few steps you need to take. For this post, I’ll talk about some of the AWS services that can get you started along with how to install and configure your environment for hosting ASP.NET MVC3 applications with Linux and Mono.</p>
<p><span id="more-1325"></span><br />
<h2>Disclaimer:</h2>
<p>Before you try any of this, carefully read all the terms and conditions regarding <a href="http://aws.amazon.com">Amazon Web Services</a>. Review their pricing structure for every service you plan to use and the qualifying restrictions for the <a href="http://aws.amazon.com/free">free tier</a>. While their pricing structure is very competitive, it’s also very complicated. Be sure to fully understand what services you enable before doing it. Payment information is required to setup your AWS account, but you will only be charged when you use services that are not free. I am not responsible for any fees you may incur while using AWS services.</p>
<p>&#160;</p>
<h2>Conventions Used in This Article</h2>
<h3>Intended Audience</h3>
<p>I’m writing this post for people who are mostly familiar with Windows environments and maybe have some experience with Linux. I may over-explain a few concepts like using SSH or tab completion, which mainly target the Windows folks who may have never seen this before. Otherwise, this post can be used as a reference guide to AWS and using Mono Web hosting in general. We will be using the default MVC 3 application as our sample, which might be interesting if you haven’t worked with it yet. If you’ve never worked with Mono web hosting before, always start with something simple and familiar. I wouldn’t recommend trying to take your massive, enterprise, e-commerce solution and running it straight up on Mono without expecting a few hiccups.&#160; The <a href="http://mono-framework.com/MoMA">MoMA tool</a> will be useful for migrating assemblies since it identifies functionality not yet supported by Mono in your assemblies.</p>
<h3>Keystrokes</h3>
<p>There are a few conventions used throughout this tutorial. I’ll indicate keystrokes with {} characters, like in the example: {Ctrl} for a Control keystroke. I’ll hyphenate key combos like {Ctrl-D} for Control and D pressed simultaneously. And I’ll separate them for consecutive keystrokes: {Ctrl}{D} for Control then D.</p>
<h3>Tab Completion</h3>
<p>Another useful tip I’ll sometimes mention is when using the bash shell, you can type a segment of a directory or file name and press {TAB} to complete it. It will complete to the next unique segment. So if there are two files with similar names, it will complete the statement for the common portions of the names and wait for input. You can add the next unique character and press {TAB} again to make it go further. This is very useful when entering long paths or filenames from the command line. For example to script named install_mono-2.10.5.sh you can simply type:</p>
<p>./in{TAB}</p>
<p>Wait for the completion, then if it’s correct, {ENTER} to execute it.&#160; Sometimes you’ll have to add a few extra characters to help it out.&#160; Any path or git branch argument (and probably many other things) in Linux use this functionality.</p>
<h3>Linux Command Line</h3>
<p>As always with Linux command line, if you want to know how a specific command works, you can always check its manual pages by entering: “man &lt;command&gt;”&#160;&#160; For example to see the manual for ssh, you can enter “man ssh”.&#160; To exit the manual, just hit {Q}.</p>
<p>&#160;</p>
<h2>Amazon Web Services</h2>
<p>Amazon Web Services (AWS) is a lot like an Ad-hoc enterprise infrastructure. You pick and choose the components you want and put them together in the arrangement of your choice. Every service comes with a cost, so you weigh how you design your infrastructure based on your needs. The main two services we’ll use to get started include <a href="http://aws.amazon.com/ec2">EC2 (Elastic Cloud Computing)</a> using <a href="http://aws.amazon.com/ebs/">EBS (Elastic Block Storage)</a> for its local file system and <a href="http://aws.amazon.com/s3">S3 Storage Service</a> as our static content storage (and delivery).</p>
<h3><a href="http://aws.amazon.com/ec2">Elastic Cloud Computing (EC2)</a></h3>
<p>EC2 is simply server that and provide any service we want. It’s computing on demand and you pay by the hour. For smaller environments (like this walkthrough), we’ll fire up one micro instance for both database and web server; while in larger environments, you might setup a pool of database servers, a pool of application servers with horizontal scaling in mind. With EC2 you have the option of using the built-in instance storage (usually about 160GB for paid servers) or using the <a href="http://aws.amazon.com/ebs/">Elastic Block Storage (EBS)</a> service. EBS allows for a persistent (shared) storage for your instances. You can clone them into new servers or snapshot instances on existing servers.</p>
<h3><a href="http://aws.amazon.com/s3/">Amazon Simple Storage Service (S3)</a> &amp; <a href="http://aws.amazon.com/cloudfront">CloudFront</a></h3>
<p>The S3 service provides centralized storage for all your applications. S3 is accessible from outside the Amazon network and the price is pretty competitive starting roughly around <a href="http://aws.amazon.com/s3/#pricing">$0.14 USD/GB/month</a>. Using this service is not required, but if you have an application with a lot of local assets, this is a pretty good option to keep them on the AWS network. You can also expose your files in S3 to the public essentially turning it into a static file web server. If you need a more responsive edge network, then S3 will serve as a data source for the CloudFront service and deploy your assets to edge locations around the world.</p>
<p>&#160;</p>
<h2>Tools</h2>
<p>In order to use AWS on Linux, you’ll need an interactive SSH client and some common Linux utilities like tar, gzip, etc. For those of you Linux/Mac users, these tools are likely already setup on your machines. However, those of you Windows folks (like me) will need to install a few things.</p>
<p><a href="http://code.google.com/p/msysgit/downloads/list">MsysGit</a> comes with all these utilities nicely packaged. <a href="http://www.mingw.org/wiki/MSYS">Msys</a> is a set of recompiled GNU utilities for Windows. It enables a nearly identical bash command line shell for Windows as Linux, and they run natively. It also comes with openSSH and SCP which come in extremely useful when connecting to servers or moving files around between Windows and Linux.</p>
<p><a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">Putty</a> is another great interactive SSH utility, and <a href="http://filezilla-project.org/download.php">FileZilla</a> is a great graphical file transfer client, which works with SSH. I commonly bounce between all these tools in my environments. If you want to use Putty with your AWS server, you’ll also need the PuttyGen utility available on Putty’s website. This will create a private key that wraps your openSSH based key for use with Putty and FileZilla.</p>
<p>Finally, if you want to use AWS services programmatically, you of course will need to download the <a href="http://aws.amazon.com/sdkfornet/">AWS SDK</a>.&#160; Mac/Linux users can scroll to the bottom of the screen and download the “DLLs and Samples” version that is packaged in a ZIP for Mono.</p>
<h4>Required Windows tools for this walk-through:</h4>
<ul>
<li><a href="http://code.google.com/p/msysgit/downloads/list">MsysGit installer</a>&#160; &#8211; During install, make sure you <strong>enable</strong> the Windows Explorer shell context menu for<strong> Git Bash Here</strong>. </li>
</ul>
<p>&#160;</p>
<h2>Setup EC2 Instance</h2>
<p>Before you get started setting up a new EC2 instance, you need to register an AWS account. This will require a credit card. If you’re a new customer or comply with their terms and conditions for the <a href="http://aws.amazon.com/free">free tier</a>, then you don’t need to worry about being charged fees for usage. Registration takes a little while. Eventually, you’ll receive an email stating your account is active and ready to go.</p>
<h3>Launch New Instance</h3>
<p>Sign into your AWS Management Console and enter the EC2 section.&#160; When creating a new EC2 instance, we’re first going to find the Amazon Machine Image (AMI) that we want to use for our new server. Canonical provides a few pre-built ones for different versions of Ubuntu and they occasionally release updated AMI’s as updates are released.&#160; I chose to use the most recent (at the time of this post) Lucid (10.04 LTS) build.</p>
<p>To get started, click Launch New Instance in the top left. First, choose the Community AMI’s tab and then search for <em>ami-61be7908</em>.&#160; Also, watch for the star that indicates &quot;free tier” server. Make sure you choose a free tier AMI!</p>
<p>Step through the setup wizard for your new AMI. I used mostly defaults to ensure the free tier shown here. Click each image for an enlarged screenshot.</p>
<div class="gallery"><a title="Setup EC2 Step 1 - Choose an AMI from the Community AMI&#39;s tab. Ensure selected AMI is Free Tier indicated by star." href="http://assets.integratedwebsystems.com/1.png"><img alt="Setup EC2 Step 1" src="http://assets.integratedwebsystems.com/thumbs/1.png" /></a> <a title="Setup EC2 Step 2 part 1" href="http://assets.integratedwebsystems.com/2a.png"><img alt="Setup EC2 Step 2 part 1" src="http://assets.integratedwebsystems.com/thumbs/2a.png" /></a> <a title="Setup EC2 Step 2 part 2" href="http://assets.integratedwebsystems.com/2b.png"><img alt="Setup EC2 Step 2 part 2" src="http://assets.integratedwebsystems.com/thumbs/2b.png" /></a> <a title="Setup EC2 Step 2 part 3 - Enter a name for your instance. This will be shown in the EC2 instance list." href="http://assets.integratedwebsystems.com/2c.png"><img alt="Setup EC2 Step 2 part 3" src="http://assets.integratedwebsystems.com/thumbs/2c.png" /></a> <a title="Setup EC2 Step 3 - Setup your public key authentication. Don&#39;t forget to download the key." href="http://assets.integratedwebsystems.com/3.png"><img alt="Setup EC2 Step 3" src="http://assets.integratedwebsystems.com/thumbs/3.png" /></a> <a title="Setup EC2 Step 4 - Configure your firewall. Enable 80 and 22. WHen using Security Groups, you can re-use these permission sets on other instances." href="http://assets.integratedwebsystems.com/4.png"><img alt="Setup EC2 Step 4" src="http://assets.integratedwebsystems.com/thumbs/4.png" /></a> <a title="Setup EC2 Step 5 - Review and launch your new instance." href="http://assets.integratedwebsystems.com/5.png"><img alt="Setup EC2 Step 5" src="http://assets.integratedwebsystems.com/thumbs/5.png" /></a></div>
<p>&#160;</p>
<p>The important thing here is that we’re choosing a micro (free tier instance). Starting out, I would open up just your web ports 80 and 22. When you finish the wizard, your instance will automatically start up.</p>
<p>During step three, you will create a new key pair if you haven’t already created one. You will need to download the key file to your local machine and place it somewhere easily accessible for you to use from a command line. (In my case, I saved to the ~/.ssh folder which translates to <em>C:\Users\&lt;username&gt;\.ssh </em>in Windows 7.</p>
<h3>Setup an Elastic IP</h3>
<p>Before we connect to the new server, we also need to setup an Elastic IP.&#160; Elastic IPs act similar to static IPs except when you’re done using them, Amazon will release it back into the pool for someone else to use.&#160; This will allow you to shutdown your server or reboot your server and still maintain the same IP. Using this service is free as long as you have a running instance associated with it; otherwise, Amazon will charge for its use to discourage wasting unused IP allocations on their network.</p>
<p>Since we have a new EC2 instance available and running, go ahead and allocate an Elastic IP. To do this, make sure you’re still in the EC2 section of AWS dashboard and click the Elastic IPs link under the left navigation labeled: Network &amp; Security.&#160; Click the button on the to, “Allocation New Address”. Select the EC2 option and click “Yes, Allocate.”&#160; You will now have a dedicated IP in your list. Select the row and then click “Associate Address.” Choose the instance we just setup, and you’re done! One caveat to take note of is that shutting down the server will disassociate the address. So when you boot it back up, you will need to re-associate the address.&#160; Rebooting the server will not disassociate the address.</p>
<p><img title="Setup elastic IP step 1" alt="Setup elastic IP step 1" src="http://assets.integratedwebsystems.com/elasticIP-1.png" /></p>
<p><img title="Setup elastic IP step 1" alt="Setup elastic IP step 2" src="http://assets.integratedwebsystems.com/elasticIP-2.png" /></p>
<p>&#160;<img title="Setup elastic IP step 1" alt="Setup elastic IP step 3" src="http://assets.integratedwebsystems.com/elasticIP-3.png" /></p>
<p>&#160;</p>
<h2>Connect to Your Server</h2>
<p>Now that you’ve setup your new EC2 instance and you’ve configured your Elastic IP to route to your instance, you can now make a connection to your new server.</p>
<p><em>NOTE: Typically you can setup a DNS host record to resolve to your Elastic IP simplifying communication with your server. Naturally, this is what you would do when setting it up as a web server.&#160; In this case since we’re just experimenting, you can setup an easy unknown name like test.yourdomain.com just so you don’t have to continually refer to your IP address in command line. </em></p>
<p>SSH in the Linux world is like the Swiss army knife for admins.&#160; You can use SSH to connect to an interactive terminal, transfer files, or even tunnel traffic through its connection. It’s also encrypted with a public/private key pair (typically RSA). When you created the key on Amazon, you essentially generated the public/private key pair and you downloaded the public key.&#160; SSH will use that public to authenticate your connection against a pre-setup user account on the server.</p>
<p>Have your key file handy. Earlier I suggested you place this in your home .ssh directory ~/.ssh or on Windows 7, C:\Users\&lt;username&gt;\.ssh\.&#160; Right click on any directory with Windows Explorer and open an Git Bash. Then go to your .ssh directory by entering: “<em>cd ~/.ssh”</em>.<em>&#160; </em>This should place you in the same directory that we stored the key file for AWS making it very easy to refer to during this walkthrough. In the sample below, we called this file “mykey.pem”. Call it whatever you want.</p>
<p>Enter:</p>
<pre class="brush: bash; gutter: false;">ssh aws.yourdns.com –l ubuntu -i mykey.pem</pre>
<p>&#160;</p>
<p><em>NOTE: Don’t forget the tab completion here. A shortcut for this is to enter the command below. (Of course this is assuming you’re in the same directory as the mykey.pem file.&#160; </em></p>
<pre class="brush: bash; gutter: false;">ssh aws.yourdns.com –l ubuntu -i my{TAB}</pre>
<p>&#160;</p>
<p>You should see a busy welcome screen informing you about some basic info about your server. It will also let you know if you’re running the most recent AMI.&#160; Having the most recent AMI is not very important. With the built-in aptitude package manager, your server can easily stay current even running an older AMI.</p>
<pre class="brush: bash; gutter: false;">Linux domU- 2.6.32-318-ec2 #38-Ubuntu SMP Thu Sep 1 17:54:33 UTC 2011 i686 GNU/Linux
Ubuntu 10.04.3 LTS

Welcome to Ubuntu!
 * Documentation:  https://help.ubuntu.com/

  System information as of Tue Nov  8 19:48:48 UTC 2011

  System load:  0.0               Processes:           68
  Usage of /:   37.6% of 7.87GB   Users logged in:     0
  Memory usage: 41%               IP address for eth0: 10.208.195.158
  Swap usage:   0%

  Graph this data and manage this system at https://landscape.canonical.com/
---------------------------------------------------------------------
At the moment, only the core of the system is installed. To tune the
system to your needs, you can choose to install one or more
predefined collections of software by running the following
command:

   sudo tasksel --section server
---------------------------------------------------------------------

8 packages can be updated.
7 updates are security updates.

A newer build of the Ubuntu lucid server image is available.
It is named 'release' and has build serial '20110930'.
Last login: Mon Nov  7 21:31:53 2011 from 75.81.113.113</pre>
<p>&#160;</p>
<p>As you can see, I have a few packages that are available for update. So the first thing I like to do is immediately update the server. Do that with two commands. Apt-get update and apt-get upgrade. Update will re-sync the package cache for the local repositories. Upgrade will actually download and install the updated packages onto your system. Dist-Upgrade, another form of upgrade, will force update all new packages regardless of dependencies. This is typically something you’ll use when you start with a fresh server. After that, the normal “upgrade” should work fine. You can combine these commands into one by concatenating them with “&amp;&amp;”.</p>
<pre class="brush: bash; gutter: false;">sudo apt-get update &amp;&amp; sudo apt-get dist-upgrade -y</pre>
<p>&#160;</p>
<p>This will update the repositories; and if successful, will continue to the upgrade command and install the updates.&#160; The option “-y” simply instructs the upgrade to automatically answer yes to installing package updates.&#160; We’re running the command with sudo to temporarily enable root privileges. We’re “su” “doing” the command.</p>
<p>&#160;</p>
<h2>Install Mono &amp; Apache</h2>
<p>Now that we’ve updated the system we can continue to install all the necessary packages for the web server. I’m choosing to use Badgerports for the Mono install. Optionally, you can compile and install your own (sometimes more recent) version of Mono, but Badgerports is very convenient and easy to use.&#160; At the same time, we’ll install Apache.&#160; Enter these commands sequentially (one per line)</p>
<pre class="brush: bash; gutter: false;">wget http://badgerports.org/directhex.ppa.asc
sudo apt-key add directhex.ppa.asc
sudo apt-get install python-software-properties
sudo add-apt-repository 'deb http://ppa.launchpad.net/directhex/ppa/ubuntu lucid main'
sudo apt-get update
sudo apt-get install mono-apache-server4 mono-devel libapache2-mod-mono </pre>
<h3>&#160;</h3>
<h3>Setup Web Folder</h3>
<p>Now configure the directory where we’ll place the web files. Enter the following commands to create the directory and set its ownership and permissions.</p>
<pre class="brush: bash; gutter: false;">cd /srv
sudo mkdir www
cd www
sudo mkdir default
sudo chown www-data:www-data default
sudo chmod 755 default</pre>
<p>&#160;</p>
<h3>Configure Apache &amp; Virtual Host</h3>
<p>Finally, setup the apache virtual host to run our website.&#160; We’ll start by creating our virtual host configuration file that enables the 4.0 mono server for the web directory we just setup. We’ll than set it up nicely with the debian/ubuntu environment so we can easily disable and enable it.&#160; For this sample, I used mono-project’s <a href="http://go-mono.com/config-mod-mono/">mod_mono configuration tool</a> as a starting point. I then switched its server command to mod-mono-server4 (for 4.0 runtime), and I also changed its DocumentRoot to use the directory we setup.</p>
<p>&#160;</p>
<pre class="brush: xml;">&lt;VirtualHost *:80&gt;
  ServerName my-mono-server.somewhere.com
  ServerAdmin web-admin@my-mono-server.somewhere.com
  DocumentRoot /srv/www/default
  MonoServerPath my-mono-server.somewhere.com &quot;/usr/bin/mod-mono-server4&quot;
  MonoDebug my-mono-server.somewhere.com true
  MonoSetEnv my-mono-server.somewhere.com MONO_IOMAP=all
  MonoApplications my-mono-server.somewhere.com &quot;/:/srv/www/default&quot;

  &lt;Location &quot;/&quot;&gt;
    Allow from all
    Order allow,deny
    MonoSetServerAlias my-mono-server.somewhere.com
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI &quot;\.(?:gif|jpe?g|png)$&quot; no-gzip dont-vary
  &lt;/Location&gt;
  &lt;IfModule mod_deflate.c&gt;
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
  &lt;/IfModule&gt;
&lt;/VirtualHost&gt;</pre>
<p>&#160;</p>
<p>We’re going to use the local clipboard to copy and paste the contents into VIM through the msys window. With the default MSysGit client, it uses a Windows “cmd” shell so you can right click, “Paste” or enable quick edit mode to paste into the window.&#160; While working in VIM, if you have an problems with keystrokes, just hit {Esc} a couple times and you should be able to re-enable insert mode by pressing {i} once. Enter the following to open a new file in VIM.</p>
<pre class="brush: bash; gutter: false;">cd /etc/apache2/sites-available
sudo vi mono-default

#copy the contents above and paste them into the new file
{i}{Then paste - right click the window and select paste}
{Esc}:wq{Enter}</pre>
<p>Now we can create a symbolic link to this file from the enabled directory.</p>
<pre class="brush: bash; gutter: false;">cd /etc/apache2/sites-enabled
sudo rm 000-default
sudo ln -s /etc/apache2/sites-available/mono-default 000-mono</pre>
<p>&#160;</p>
<h3>Install Trusted Certificate Authorities</h3>
<p>If we want to use the AWS tools in our application, we’ll need to first install the trusted keys. We’ll use the mozroots tool to do that. We’ll use “sudo –u www-data” to run mozroots as the www-data user.</p>
<p>Enter:</p>
<pre class="brush: bash; gutter: false;">sudo –u www-data mozroots --import –sync </pre>
<p>&#160;</p>
<p>As a simple test to ensure the basic configuration is working, we can move the normal default web page into our new directory and then make a request against it.</p>
<pre class="brush: bash; gutter: false;">sudo mv /var/www/index.html /srv/www/default
sudo vi /srv/www/default/index.html 

# arrow down a couple lines to content
# press {i} then enter something. just to make it a little different
{Esc}:wq{enter}

# restart the web server sudo service apache2 restart </pre>
<p>If the web server restart reported “OK” then make a request against your server (from your local machine) to test the web server configuration. Open a browser and browse to <em>http://&lt;your-host-name/index.html</em>.&#160; You should see your slightly modified default page. Now we can continue on to building out the default MVC3 web application and test that.</p>
<p>If the web server did not restart okay, read the messages that were reported. Also, if you’re not seeing anything there you can always refer back to the apache logs located at: /var/log/apache2/error.log.&#160; If anything goes wrong throughout this entire process, always check the end of that file.</p>
<p>&#160;</p>
<h2>Deploy your first site</h2>
<h3>Create and Publish a New MVC 3 Project</h3>
<p>Finally… We’re ready to deploy a real .NET MVC3 application on Linux. We’re going to be doing a typical BIN deployment of MVC 3. I have detailed this out in another blog post and covered some of the potential issues you could run into while <a href="http://www.integratedwebsystems.com/2011/06/get-mvc3-razor-running-on-mono/">BIN deploying an MVC 3 project to Mono</a>.&#160; Feel free to refer to that post if you having any problems. Lets get started here by creating a new project.</p>
<p>Open Visual Studio and create a new Project. Choose .NET Framework 4, then ASP.NET MVC 3 Web Application. Choose Internet Application template. Then select the Razor view engine and optionally the HTML5 semantic markup.&#160; We’re just going to roll this application as-is. You do not need to create the unit test project.</p>
<p><img style="display: inline; float: right" align="right" src="http://assets.integratedwebsystems.com/publish.png" /></p>
<p>Under the Solution Explorer, expand the References node. We need to enable Copy Local on a few necessary assemblies for this to work in Mono. Go to properties of the following assemblies and set their <strong>Copy Local</strong> option to <strong>True</strong>: System.Web.Helpers, System.Web.Mvc, System.Web.Routing, and System.Web.WebPages.</p>
<p>Now publish the project. Select the Build menu, then Publish AWSMonoSample.Web. Choose Publish Method: File System and select a local directory for copying the published files. I also typically select “Delete all existing files prior to publish” to ensure a clean publish directory.&#160; Then click Publish. (In my sample, I’m publishing to C:\temp\AWSMonoSample.Web).</p>
<p>To deploy an MVC 3 site, we’ll also need to collect a few more MVC 3 and Razor dependencies. Browse to: Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies directory and grab System.Web.WebPages.Deployment.dll, System.Web.WebPages.Razor.dll, and System.Web.Razor.dll. DO NOT grab any other assemblies. Place all these assemblies in your published folder’s bin directory.&#160; You should only have to do this once, but it’s always a caveat of deploying MVC 3 to Mono on a new server.</p>
<p>&#160;</p>
<h3>Deploy Published Files to Your Server</h3>
<p>Now we can upload the files.&#160; Since AWS by default is public key authenticated, we’re going to use the manual command-line method. Once you understand public key authentication a little better, tools like FileZilla or WinSCP will work a little easier (if you like the GUI interface thing).</p>
<p>So to start, open My Computer / Windows Explorer and browse to your published directory (C:\temp\AWSMonoSample.Web for this example). Then right click on that directory and select Git Bash Here from the context menu. You should now be looking at a local BASH command line with your working directory being the deployment folder we just setup.</p>
<p>For this deployment, we’re going to first package the files into a gzipped tarball, then we’re going to “scp” upload it to our server. From that point, we’ll ssh back into our server and extract the files in the web directory we setup earlier.</p>
<p>So enter:</p>
<pre class="brush: bash; gutter: false;">$ tar -zcvf aws.tar.gz *
$ scp aws.tar.gz ubuntu@your-aws-hostname: -i ~/.ssh/mykey.pem</pre>
<p>&#160;</p>
<p><em>NOTE: Replace the hostname with the one you have setup for your AWS EC2 instance. Also replace your keyfile path with the one you have setup locally for AWS. </em></p>
<p>You should see a successful transfer. Now you can connect to your server and extract the files in place. Open a new (or use an existing SSH connection if you still have one open). Start from your home directory with the command: “cd ~/”.</p>
<pre class="brush: bash; gutter: false;">ssh ubuntu@your-aws-hostname -i ~/.ssh/mykey.pem
mv aws.tar.gz /srv/www/default
rm index.html   #remove test from earlier
tar -zxvf aws.tar.gz
rm aws.tar.gz   #optional cleanup

sudo service apache2 restart      #for a fresh start</pre>
<p>&#160;</p>
<p>That’s it! Now make a request against your server, and you should see the new MVC 3 sample website displayed! Keep in mind the membership is not wired up and the registration form may blow up on you (as it also would in Windows); but otherwise, the basic MVC stuff works including model validation.</p>
<p>&#160;</p>
<h2>Useful Links</h2>
<ul>
<li><a href="http://aws.amazon.com">Amazon Web Services</a> </li>
<li><a href="http://mono-project.com">Mono Project</a> </li>
<li><a href="http://go-mono.com/config-mod-mono/">Mono Configuration Tool</a> </li>
<li><a href="http://code.google.com/p/msysgit/">MsysGit</a> </li>
<li><a href="http://www.hanselman.com/blog/BINDeployingASPNETMVC3WithRazorToAWindowsServerWithoutMVCInstalled.aspx">Hanselman’s BIN Deploy MVC3 post</a> </li>
<li><a href="http://badgerports.org/">Badgerports</a> </li>
<li><a href="http://ubuntu.com">Ubuntu</a> </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2011/12/get-started-with-amazon-ec2-run-your-net-mvc3-razor-site-in-the-cloud-with-linux-mono-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Running Mono MVC3 Razor and Solving the InvalidOperationException of &#8216;The view &#8216;name&#8217; or its master was not found&#8217;</title>
		<link>http://www.integratedwebsystems.com/2011/09/running-mono-mvc3-razor-and-solving-the-invalidoperationexception-of-the-view-name-or-its-master-was-not-found/</link>
		<comments>http://www.integratedwebsystems.com/2011/09/running-mono-mvc3-razor-and-solving-the-invalidoperationexception-of-the-view-name-or-its-master-was-not-found/#comments</comments>
		<pubDate>Wed, 28 Sep 2011 16:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[Mono]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[razor]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/2011/09/running-mono-mvc3-razor-and-solving-the-invalidoperationexception-of-the-view-name-or-its-master-was-not-found/</guid>
		<description><![CDATA[I’ve been fighting my system the past day or so trying to...]]></description>
			<content:encoded><![CDATA[<p>I’ve been fighting my system the past day or so trying to figure out why all the views in one of my controllers return this silly exception. The file indeed exists. Permissions are correct. Other controller views works. Other non-view (like json or file content) actions work within this controller. This works on Windows but not in Mono. Why doesn’t it work? To find this, I ended up using my source control to identify the commit that caused the break. Then line by line, I started toggling the changes within that commit until I found it.</p>
<blockquote><p>System.InvalidOperationException: The view &#8216;Index&#8217; or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Areas/Manage/Views/Dashboard/Index.aspx ~/Areas/Manage/Views/Dashboard/Index.ascx ~/Areas/Manage/Views/Shared/Index.aspx ~/Areas/Manage/Views/Shared/Index.ascx ~/Views/Dashboard/Index.aspx ~/Views/Dashboard/Index.ascx ~/Views/Shared/Index.aspx ~/Views/Shared/Index.ascx ~/Areas/Manage/Views/Dashboard/Index.cshtml ~/Areas/Manage/Views/Dashboard/Index.vbhtml ~/Areas/Manage/Views/Shared/Index.cshtml ~/Areas/Manage/Views/Shared/Index.vbhtml ~/Views/Dashboard/Index.cshtml ~/Views/Dashboard/Index.vbhtml ~/Views/Shared/Index.cshtml ~/Views/Shared/Index.vbhtml</p>
</blockquote>
<p>I’m saying this purely by observation. But MVC3 (or maybe the Mono runtime) seems to group compiled view code by controller. I was able to figure out that ALL ViewResult actions failed under this specific controller. It turns out I had one character out of place in my Razor syntax. With that one syntactical flaw, all the views under that controller could not compile and the only reasonable exception that could be thrown was the one above. The windows runtime seems to ignore this (maybe because it compiles them individually; I don’t know). In my case, I was trying to render one view when another view was causing the problem. </p>
<p>So if you see this exception and everything seems to be correct, start sifting through your recent View changes to see if anything you did broke the view syntax. So you can get a little laugh, here’s my goof up: </p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2011/09/goof.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Extra @ symbol not needed when continuing a code block" border="0" alt="Extra @ symbol not needed when continuing a code block" src="http://www.integratedwebsystems.com/wp-content/uploads/2011/09/goof_thumb.png" width="322" height="63" /></a> </p>
<p>The indicated ‘@’ symbol is not necessary when continuing additional statements. </p>
<p>Enjoy! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2011/09/running-mono-mvc3-razor-and-solving-the-invalidoperationexception-of-the-view-name-or-its-master-was-not-found/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get MVC3 Razor Running on Mono</title>
		<link>http://www.integratedwebsystems.com/2011/06/get-mvc3-razor-running-on-mono/</link>
		<comments>http://www.integratedwebsystems.com/2011/06/get-mvc3-razor-running-on-mono/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 05:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[MVC 3]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[razor]]></category>
		<category><![CDATA[xsp]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=1156</guid>
		<description><![CDATA[Updated 10-18-2011 &#8211; added some more common issues I dug around a...]]></description>
			<content:encoded><![CDATA[<h4>Updated 10-18-2011 &#8211; added some more common issues</h4>
<p>I dug around a little to figure this out. Hopefully this will clarify all the steps required to get an MVC 3 Razor site running on Mono. The main pitfall I ran into was gathering the additional dependencies and excluding Microsoft.Web.Infrastructure assembly from my deployment. Overall though it’s not too difficult to deploy your MVC3 app.</p>
<p>In Summary:</p>
<ol>
<li>Install Mono</li>
<li>BIN Deploy Website</li>
<li>Configure Apache (or Xsp environment)</li>
<li>Fire Up Your Server</li>
<li>Errors You Might See</li>
</ol>
<p><span id="more-1156"></span></p>
<h2>Install Mono</h2>
<p>If you haven’t done this yet, go grab it from the <a href="http://www.go-mono.com/mono-downloads/download.html">Mono downloads page</a>. You need to run at least Mono 2.10, preferably the latest release (2.10.2). For Ubuntu you can use the <a href="http://badgerports.org/">badgerports</a>; or for Ubuntu, compile from source using a <a href="/2011/05/install-mono-2-10-2-and-monodevelop-2-6-beta-3-on-ubuntu-or-fedora-with-a-bash-script/">bash script</a> I created. (Skip the MonoDevelop install).</p>
<p>&nbsp;</p>
<h2>BIN Deploy Your Website</h2>
<p>For this, I just performed a traditional “Publish” from Visual Studio to a file system directory. Be sure to set these references to “copy local.”</p>
<ul>
<li>System.Web.Mvc</li>
<li>System.Web.Helpers</li>
<li>System.Web.Routing</li>
</ul>
<p>&nbsp;</p>
<h2>BIN Deploy Additional MVC3/Razor Dependencies</h2>
<p>Just like Scott Hanselman mentions in his <a href="http://www.hanselman.com/blog/BINDeployingASPNETMVC3WithRazorToAWindowsServerWithoutMVCInstalled.aspx">BIN deployment</a> post, add these additional libraries found in the MVC3 RTM. On Windows, they install to C:\Program Files\Asp.Net.</p>
<ul>
<li>System.Web.Razor</li>
<li>System.Web.WebPages</li>
<li>System.Web.WebPages.Razor</li>
<li>System.Web.WebPages.Deployment</li>
</ul>
<p>&nbsp;</p>
<p><em>NOTE: Do <strong>NOT </strong>copy the <strong>Microsoft.Web.Infrastructure</strong> assembly.  This assembly has been rebuilt in the mono library and will already be available to your app.  </em></p>
<p><em> </em></p>
<h2>Configure Apache/XSP</h2>
<p>Once you have Mono runtime installed, setup your apache virtual host configuration. Setup a virtual host to use <em>mod-mono-server4</em>. If you installed Mono with a custom prefix (like my script above), then be sure and setup your virtual host environment. Here’s a sample virtual host configuration using the Mono install prefix of, “/opt/mono-2.10”.</p>
<pre class="brush: xml; gutter: false;">&lt;VirtualHost *:80&gt;
  ServerName yourhostname

  DocumentRoot /srv/www/mvc3

  &lt;Directory /&gt;
    Options FollowSymLinks
  &lt;/Directory&gt;

  MonoServerPath mvc3 "/opt/mono-2.10/bin/mod-mono-server4"

  #optional debug mode
  MonoDebug mvc3 true 

  #be sure and set the prefixed mono paths here
  MonoSetEnv mvc3 MONO_IOMAP=all;PATH=/opt/mono-2.10/bin:$PATH;LD_LIBRARY_PATH=/opt/mono-2.10/lib:$LD_LIBRARY_PATH;  

  MonoApplications mvc3 "/:/srv/www/mvc3"
  &lt;Location /&gt;
    Allow from all
    Order allow,deny
    MonoSetServerAlias mvc3
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
  &lt;/Location&gt;
  &lt;IfModule mod_deflate.c&gt;
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
  &lt;/IfModule&gt;
&lt;/VirtualHost&gt;</pre>
<p>For running XSP manually, setup your shell environment with the correct prefix. Here’s a sample bash script.</p>
<pre class="brush: bash; gutter: false;">#!/bin/bash
MONO_PREFIX=/opt/mono-2.10
GNOME_PREFIX=/usr
export DYLD_LIBRARY_FALLBACK_PATH=/lib:
export LD_LIBRARY_PATH=/lib:/opt/mono-2.10/lib:
export C_INCLUDE_PATH=/include:/include
export ACLOCAL_PATH=/share/aclocal
export PKG_CONFIG_PATH=/lib/pkgconfig:/lib/pkgconfig
export PATH=/bin:/opt/mono-2.10/bin:$PATH</pre>
<p>&nbsp;</p>
<p>When you’re ready to fire up Xsp4: save the script above to a file (in this case env.sh), enter a terminal, change your working directory to the web directory and enter the following:</p>
<pre class="brush: bash; gutter: false;">$ source env.sh
$ xsp4</pre>
<p>&nbsp;</p>
<h2>Fire It Up</h2>
<p>Once everything has been deployed, fire up xsp4 or restart your apache2, all should be working.</p>
<p>&nbsp;</p>
<h2>Errors You Might See</h2>
<ul>
<li>System.Security.SecurityException: No access to the given key.
<ul>
<li>Delete Microsoft.Web.Infrastructure.dll from you bin directory.</li>
</ul>
</li>
<li>No response from web server on request, but you do see errors in the log /var/log/apache2/error.log
<ul>
<li>Check to make sure all your dependencies are present in the bin folder and apache has read/execute access to them. (Ubuntu: www-data group).  Also read through the errors at the end of the file and see if something else is causing the problem. Sometimes I rename/delete error.log and then restart the server for a fresh log.</li>
</ul>
</li>
<li>File request returns a 404 or asp.net missing assembly exception (but the file(s) actually exists)
<ul>
<li>Check your file permissions and make sure www-data group has read access to the files and read/execute to the directories involved.</li>
<li>find web-directory -type f exec chmod 664 {} \;</li>
<li>find web-directory -type d -exec chmod 775 {} \;</li>
</ul>
</li>
<li>Cannot find View&#8230;  (but it really does exist&#8230;)</li>
<li>
<ul>
<li><em>There are a few things that cause this. </em></li>
<li>File permissions; make sure www-data can read the web files</li>
<li>missing Web.config (especially under ~/Views); this is what informs the compiler how to build the view templates.</li>
<li>Syntax error in a view (may cause other views not to render returning this error).</li>
<li>Missing assemblies (make sure you bin deploy the site with all the necessary Razor and WebPages dlls. Do not deploy Microsoft.Web.Infrastructure.</li>
<li>Layout/Master page being used doesn&#8217;t exist.</li>
<li>Getting: &#8220;The classes in the module cannot be loaded&#8221;,   Just delete System.Web.WebPages.Administration.dll from your local bin directory. (not required for this).</li>
</ul>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2011/06/get-mvc3-razor-running-on-mono/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Setting up Mono 2.8 with Asp.Net 4.0 and MVC2 on Ubuntu with MySql Membership</title>
		<link>http://www.integratedwebsystems.com/2010/11/setting-up-mono-2-8-with-asp-net-4-0-and-mvc2-on-ubuntu-with-mysql-membership/</link>
		<comments>http://www.integratedwebsystems.com/2010/11/setting-up-mono-2-8-with-asp-net-4-0-and-mvc2-on-ubuntu-with-mysql-membership/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 06:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[4.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MySql]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=1024</guid>
		<description><![CDATA[I’ve had a few requests to write a full walk-through installing Mono...]]></description>
			<content:encoded><![CDATA[<p>I’ve had a few requests to write a full walk-through installing <a href="http://mono-project.com">Mono 2.8</a> w/ Asp.Net 4.0 since I posted an <a href="/2010/10/mono-2-8-install-script-for-ubuntu-fedora/">install script for Mono 2.8 on Ubuntu and Fedora</a>.  So here it is! We’re going to be setting up a new server from scratch then installing just the basics of Mono 2.8 (Mono, GTK, GDI, XSP, &amp; Mod_Mono). Then we’ll use that to setup a new Apache server with a basic Asp.Net 4.0 MVC2 application w/ MySql Membership.  That sounds like a lot, but it’s really very straight forward. So lets get started!</p>
<p><span id="more-1024"></span></p>
<h4>Update! 1/30/2011</h4>
<p>Mono 2.8.2 has become available since this article was posted and is highly recommended due to security enhancments. Refer to <a href="/2011/01/mono-2-8-2-script-updated-for-ubuntu-and-fedora/">install script for Mono 2.8.2</a> instead of 2.8. Pay close attention to your virtual host config so you use the correct mono install prefixes. Check MonoServerPath and MonoSetEnv directives below.</p>
<h2>Setup Your Server</h2>
<p>For our server, we’re going to setup a VM of 32 bit <a href="http://www.ubuntu.com/server/get-ubuntu/download">Ubuntu Server</a> 10.04 LTS using <a href="http://www.virtualbox.org/wiki/Downloads">VirtualBox</a>. You can use whichever VM software you want or setup a physical server. This is just an easy sandbox system for this walkthrough. I noticed VirtualBox requires hardware virtualization for 64bit guest systems; keep that in mind if you test with a 64bit server.</p>
<p>I applied default configuration settings to my VM with 512 RAM and a bridged network interface so I could communicate with it directly from another machine. After that, I mounted the Ubuntu Server install ISO to the disc drive and booted it into installation.  During installation, the only package option I enabled was the OpenSSH Server (use arrows, spacebar, and tabs to move around the installer).  I’m not going to worry about other things like a web server since the Mono installer script will do that for us. Once you’ve completed the installer, unmount the ISO, boot up, and login. It defaults to using DHCP for ethernet, so find the current IP using:</p>
<pre class="brush: bash; gutter: false;">ifconfig eth0</pre>
<p>Using the IP Address listed here, connect to the box with an SSH client of your choice (I tend to use <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">Putty</a> or the OpenSSH client built into <a href="http://code.google.com/p/msysgit/downloads/list">msysGit</a> on Windows).  Immediately update your server. If you haven’t used “sudo” before, it will request your sudo password, which is just your normal account password you setup during install.</p>
<pre class="brush: bash; gutter: false;">ssh nathan@ubuntu
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get upgrade -y</pre>
<p>&nbsp;</p>
<h2>Install Mono</h2>
<p>Once you’re updated, we can download the install script and install Mono, Apache, and dependencies.</p>
<pre class="brush: bash; gutter: false;">wget --no-check-certificate https://github.com/nathanb/iws-snippets/raw/master/mono-install-scripts/ubuntu/install_mono-2.8.shchmod 755 install_mono-2.8.sh./install_mono-2.8.sh</pre>
<p>This will re-run another update and then download, compile, and install everything required to run Mono 2.8. It will also compile and install other Mono-related items like: GTK, GDIPlus, XSP, and Mod_mono. <del>Once it completes, update your system path and reboot.</del> <del>Edit “/etc/environment” and insert “<em>/opt/mono-2.8/bin</em>:” to the beginning of the PATH value.</del></p>
<p><del></del>Once completed, refer to this more recent post about setting up MVC, which also includes information about setting up your <a href="/2011/06/get-mvc3-razor-running-on-mono/">environment for the new install</a>. You can test it with “mono –V”.</p>
<pre class="brush: bash; gutter: false;">nathan@ubuntu:~$ mono -V
Mono JIT compiler version 2.8 (tarball Mon Nov 15 14:39:28 CST 2010)
Copyright (C) 2002-2010 Novell, Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  x86
        Disabled:      none
        Misc:          debugger softdebug
        LLVM:          supported, not enabled.
        GC:            Included Boehm (with typed GC and Parallel Mark)
nathan@ubuntu:~$</pre>
<p>&nbsp;</p>
<p>So now we just need to configure Apache. The install process copied a mod_mono.conf to the directory: /etc/apache2.  You’ll need to enable this by moving it to /etc/apache2/mods-available and creating a link to that file at /etc/apache2/mods-enabled.</p>
<pre class="brush: bash; gutter: false;">cd /etc/apache2
sudo mv mod_mono.conf mods-avail*
sudo ln -s /etc/apache2/mods-available/mod_mono.conf /etc/apache2/mods-enabled/mono.conf

#optionally restart apache server. more changes coming
sudo service apache2 restart</pre>
<p>&nbsp;</p>
<h2>Configure Website</h2>
<p>We’re using <a href="http://mono-project.com/Mod_mono">Mod_Mono</a> to handle Asp.Net requests with Apache. I’ve mentioned before that I’m a big fan of the Mono website’s <a href="http://go-mono.com/config-mod-mono/">Mod_Mono configuration tool</a>. We can use that tool to build our initial VirtualHost configuration. Then change the MonoServerPath to be the one we installed at: “/opt/mono-2.8/bin/mod-mono-server4”  When you’re done, upload (or move) this folder to your home directory on the server.</p>
<p><em>NOTE: We’re using mod-mono-server<strong>4 </strong>for Asp.Net 4.0 runtime. You can use mod-mono-server2 for 2.0-3.5 Asp.Net and mod-mono-server for 1.0-1.1 Asp.Net. </em></p>
<p><em>NOTE: If you’re unfamiliar with copying files from your Windows box to a Linux one, you can use </em><a href="http://filezilla-project.org/download.php"><em>FileZilla</em></a><em> with an SSH (SFTP) connection. Connect to something like: “sftp://username@host” then treat it like any other FTP connection. </em></p>
<p>Here we’ll setup our web folders, permissions, move our configuration file, link it, and restart the web server. Our generated configuration file is named <em>ubuntu.conf</em> and was uploaded to my home folder.</p>
<pre class="brush: bash; gutter: false;">sudo mkdir /srv/www
sudo mkdir /srv/www/ubuntu
sudo chown root:www-data /srv/www/ubuntu -R
sudo chmod 775 /srv/www/ubuntu -R
mv ~/ubuntu.conf /etc/apache2/sites-available
cd /etc/apache2/sites-en*
sudo ln -s ../sites-available/ubuntu.conf "000-ubuntu.conf"
sudo service apache2 restart</pre>
<p><em>NOTE: I prefixed the link name with “000” since Apache loads configuration files in alphabetical order. It’s not necessary for this scenario, but if you’re running multiple virtual hosts and want a “default”, this is good to know. Make your default VirtualHost load first.</em></p>
<p>You might also want to give yourself permissions to write to the new web directories for publishing sites. The easy way to do this (maybe not best practice), would be to add yourself to the www-data group used by apache &amp; mono, which we just setup with full access.</p>
<pre class="brush: bash; gutter: false;">sudo usermod -a -G www-data your_username</pre>
<p>Later when we upload the site, this will be a factor. The alternative will be to upload your published site to your home directory and then with an ssh console, <em>sudo mv</em> the published files to the web directories if you choose not to add yourself to the www-data group.</p>
<p>For this sample, we used all the default parameters in our configuration. Take note that debugging is enabled. I also left IO Mapping enabled to allow Mono to treat file system paths as case insensitive. You can improve performance by disabling IO Mapping. The VirtualHost configuration looks like this:</p>
<pre class="brush: xml; gutter: false;">&lt;VirtualHost *:80&gt;
  ServerName ubuntu
  ServerAdmin web-admin@ubuntu
  DocumentRoot /srv/www/ubuntu
  # MonoServerPath can be changed to specify which version of ASP.NET is hosted
  # mod-mono-server1 = ASP.NET 1.1 / mod-mono-server2 = ASP.NET 2.0
  # For SUSE Linux Enterprise Mono Extension, uncomment the line below:
  # MonoServerPath ubuntu "/opt/novell/mono/bin/mod-mono-server2"
  # For Mono on openSUSE, uncomment the line below instead:
  MonoServerPath ubuntu "/opt/mono-2.8/bin/mod-mono-server4"

  # To obtain line numbers in stack traces you need to do two things:
  # 1) Enable Debug code generation in your page by using the Debug="true"
  #    page directive, or by setting &lt;compilation debug="true" /&gt; in the
  #    application's Web.config
  # 2) Uncomment the MonoDebug true directive below to enable mod_mono debugging
  MonoDebug ubuntu true

  # The MONO_IOMAP environment variable can be configured to provide platform abstraction
  # for file access in Linux.  Valid values for MONO_IOMAP are:
  #    case
  #    drive
  #    all
  # Uncomment the line below to alter file access behavior for the configured application
  MonoSetEnv ubuntu MONO_IOMAP=all;LD_LIBRARY_PATH=/opt/mono-2.8/lib:$LD_LIBRARY_PATH;PATH=/opt/mono-2.8/bin:$PATH
  #
  # Additional environtment variables can be set for this server instance using
  # the MonoSetEnv directive.  MonoSetEnv takes a string of 'name=value' pairs
  # separated by semicolons.  For instance, to enable platform abstraction *and*
  # use Mono's old regular expression interpreter (which is slower, but has a
  # shorter setup time), uncomment the line below instead:
  # MonoSetEnv ubuntu MONO_IOMAP=all;MONO_OLD_RX=1

  MonoApplications ubuntu "/:/srv/www/ubuntu"
  &lt;Location "/"&gt;
    Allow from all
    Order allow,deny
    MonoSetServerAlias ubuntu
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
  &lt;/Location&gt;
  &lt;IfModule mod_deflate.c&gt;
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
  &lt;/IfModule&gt;
&lt;/VirtualHost&gt;</pre>
<p>&nbsp;</p>
<h2>Create and Publish Asp.Net MVC2 Application</h2>
<p>In Visual Studio 2010, select the File menu –&gt; New –&gt; Project. In the new project dialog near the top center, select the .NET Framework 4.  Then on the left, select Web (under C#), and choose ASP.NET MVC2 Web Application.  There are a few key items we’ll need to remove to make this compatible with Mono.</p>
<p>First, open the <em>~/Models/AccountModels.cs</em> file and remove all data annotations attributes from the three model classes’ properties. You may leave “DisplayName”. I’ve found (without investing a lot of time in this), that the data annotations doesn’t seem to work out of the box. Removing these attributes will allow it to run properly under Mono. Keep in mind, this also means, you’ll need to write your own server-side validation. It’s not too painful; we’ve been doing this for  years anyway.</p>
<p>Finally, build and test-run the site from visual studio. It should work fine with the built-in Casini test web server. If all is well, right click on the project (in solution explorer) and Publish the site. Publish it to the file system and choose a destination folder. You don’t need to include the App_Data folder, and you can delete all files before publish if you want.</p>
<p>Upload the published files to the server using FileZilla, and copy them to <em>/srv/www/ubuntu</em>.  Apache doesn’t need to be restarted when you update web files and assemblies. You should now be able to browse the site at <em>http://your_test_server_host/</em>.  All should work except membership since we haven’t configured the database yet.</p>
<p>&nbsp;</p>
<h2>Setup Membership with MySql</h2>
<p>Awhile back, I wrote a <a href="/2010/02/how-to-setup-and-configure-mysql-membership-provider-6-2-2-porting-to-mono-part-2-of-3/">post dedicated to MySql Membership</a> with a simple <a href="/tools-source/">config generation tool</a> do this for you. Checkout the post for more details after setting up your database server. Setting up membership is identical between Asp.Net MVC and web forms. Install and configure MySql Server first. Then setup a placeholder database for the membership data. The first time you use membership during runtime will automatically generate the database schema.</p>
<h3>Install MySql and Setup Empty Membership Database</h3>
<pre class="brush: bash; gutter: false;">sudo apt-get install mysql-server</pre>
<p><em>NOTE: The default install will lock it down to localhost access only, which is good for a server. But for test, if you want to access it from your machine, you’ll have to tell it to bind to a LAN address (instead of 127.0.0.1). Take a peek at /etc/msyql/my.cnf file to update this setting. The comments describe the change.</em></p>
<p>I’m giving application user full access (including schema change privileges) to the membership database. MySql Memebrship provider updates its own schema as you update the provider.  Checkout the <a href="http://dev.mysql.com/doc/">MySql docs</a> if you want to limit account privileges.</p>
<pre class="brush: bash; gutter: false;">nathan@ubuntu:~$ mysql -h localhost -u root -p
mysql: create database membership;
mysql: grant all privileges on membership.* to 'aspnet_user'@'localhost' identified by 'secret_password';
mysql: quit</pre>
<h3>Configure Membership</h3>
<p>I used my configuration tool and generated a simple membership config.  Copy the membership sections to your into the “system.web” section of your root web.config and setup a connection string with the same name as the one used in membership. (“Default” is used here).</p>
<p>Next, if you’re using a factory default version of MySql Connector/NET, you’ll need to download its source and recompile it with .NET 4.0 profile. I found while doing this that the published 2.0 version seemed to blow up when referencing transaction methods. I found that it was a known bug and should be resolved in upcoming versions of the connector. For now, you’ll need to recompile MySql.Web and MySql.Data with a 4.0 profile if you want it to work under Mono with membership.  The sample version packaged here has that done already.</p>
<p><em>NOTE: The version of MySql .NET Connector I was using at the time I wrote this tool (6.3.5) didn’t support hashed passwords with Mono runtime. I made a minor tweak to this version that will disable the Mono runtime check for hashed passwords and will allow it (since it does work in the current version of Mono).  </em></p>
<pre class="brush: xml; gutter: false;">&lt;authentication mode="Forms"&gt;
    &lt;forms
      loginUrl="~/Account/Logon"
      timeout="30"
      name="6ad58f32-93d5-463f-9d99-835942aca8f5"
      path="/"
      requireSSL="false"
      slidingExpiration="true"
      defaultUrl="Default.aspx"
      enableCrossAppRedirects="false"/&gt;
&lt;/authentication&gt;

&lt;membership defaultProvider="MySqlMembershipProvider"&gt;
    &lt;providers&gt;
        &lt;clear/&gt;
        &lt;add name="MySqlMembershipProvider"
              type="MySql.Web.Security.MySQLMembershipProvider, mysql.web"
                connectionStringName="Default"
                enablePasswordRetrieval="false"
                enablePasswordReset="true"
                requiresQuestionAndAnswer="false"
                requiresUniqueEmail="true"
                passwordFormat="hashed"
                maxInvalidPasswordAttempts="5"
                minRequiredPasswordLength="6"
                minRequiredNonalphanumericCharacters="0"
                passwordAttemptWindow="10"
                applicationName="/"
                autogenerateschema="true"/&gt;
    &lt;/providers&gt;
&lt;/membership&gt;

&lt;roleManager enabled="true" defaultProvider="MySqlRoleProvider"&gt;
    &lt;providers&gt;
        &lt;clear /&gt;
        &lt;add connectionStringName="Default"
            applicationName="/"
            name="MySqlRoleProvider"
            type="MySql.Web.Security.MySQLRoleProvider, mysql.web"
            autogenerateschema="true"/&gt;
    &lt;/providers&gt;
&lt;/roleManager&gt;

&lt;profile&gt;
    &lt;providers&gt;
        &lt;clear/&gt;
        &lt;add type="MySql.Web.Security.MySqlProfileProvider, mysql.web"
              name="MySqlProfileProvider"
              applicationName="/"
              connectionStringName="Default"
              autogenerateschema="true"/&gt;
    &lt;/providers&gt;
&lt;/profile&gt;</pre>
<p>&nbsp;</p>
<p>Also for Mono, I added the DbProviderFactories section for MySql data in case it wasn’t already setup. Insert this adjacent to the <em>&lt;system.web&gt;</em> section.</p>
<pre class="brush: xml; gutter: false;">&lt;system.data&gt;
    &lt;DbProviderFactories&gt;
        &lt;clear/&gt;
        &lt;add name="MySQL Data Provider"
            description="ADO.Net driver for MySQL"
            invariant="MySql.Data.MySqlClient"
            type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data"/&gt;
    &lt;/DbProviderFactories&gt;
&lt;/system.data&gt;</pre>
<p>Once updated, you should now be able to run the MVC app and register/authenticate user accounts. If you have any problems, double-check your data source value, username and password. Make sure you can connect to it with a mysql client and your app credentials.  Also I find the Asp.Net Configuration Tool built-in to Visual Studio helpful when testing Membership configuration. It will show you a number of users and roles if membership is configured properly.</p>
<p>&nbsp;</p>
<h2>Sample</h2>
<p>Grab the sample from <a href="/resources/p1024/sample-asp4-mvc2.zip">here</a> or <a href="https://github.com/nathanb/iws-snippets/tree/master/sample-asp4-mvc2/">github</a>. Includes: Web App, dependencies, &amp; virtual host config. Comments, enhancements, pull requests, are welcome!</p>
<p>&nbsp;</p>
<h2>Wrap-Up</h2>
<p>So now we’re done. The next thing you should checkout is how to use <a href="http://msdn.microsoft.com/en-us/library/aa973811.aspx">inversion of control</a> with MVC2. I’ve been writing applications lately using <a href="http://www.subsonicproject.com/">SubSonic3</a> (<a href="http://subsonicproject.com/docs/Using_SimpleRepository">repository mode</a>) and <a href="http://unity.codeplex.com/">Unity Application Block 2.0</a> for dependency injection. Coupled with <a href="http://mvccontrib.codeplex.com/">MvcContrib</a> test helpers and <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>, this is a powerful combination for writing rock solid, testable applications that run on Windows AND Mono.</p>
<p>Here are a few useful links for this post:</p>
<ul>
<li><a href="https://github.com/nathanb/iws-snippets/raw/master/mono-install-scripts/ubuntu/install_mono-2.8.sh">Install script for Mono 2.8 on Ubuntu</a></li>
<li><a href="https://github.com/nathanb/iws-snippets/raw/master/mono-install-scripts/fedora/install_mono-2.8.sh">Install script for Mono 2.8 on Fedora</a></li>
<li><a href="/resources/p1024/sample-asp4-mvc2.zip">Sample application built here</a>. Includes: Web App, dependencies, &amp; virtual host config.</li>
<li><a href="http://dev.mysql.com/downloads/connector/net/">MySql .NET Connectors w/ Data Provider and Membership Provider</a></li>
<li><a href="/tools-source/">MySql membership configuration generation tool</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/11/setting-up-mono-2-8-with-asp-net-4-0-and-mvc2-on-ubuntu-with-mysql-membership/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Cross-domain JsonP using Asp.net MVC and jQuery</title>
		<link>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/</link>
		<comments>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 05:27:01 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[jsonp]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=897</guid>
		<description><![CDATA[So there are a couple great walkthroughs out there that talk about...]]></description>
			<content:encoded><![CDATA[<p>So there are a couple <a href="http://abcoder.com/javascript/jquery/jsonp-first-timer/">great walkthroughs</a> out there that talk about using <a href="http://api.jquery.com/jQuery.ajax/">jquery jsonp</a> in cross-domain scenarios.  They talk a lot about the requesting and server side, but not so much about how to use the callback. So to clarify, I’ll step through what I did to make this work including providing my implementation for a new ActionResult called JsonPResult for <a href="http://www.asp.net/mvc">MVC</a>.</p>
<p><span id="more-897"></span></p>
<p>Starting out, client-side on the calling page, I setup my script. This function makes a request to the server and expects a jsonp response back. The default “success” handler is optional here and will be invoked along-side the one you specify for jsonp.</p>
<pre class="brush: js; gutter: false;">$.ajax({
    url: 'http://other-domain/api/GetInformation',
    data: { key: 'some data key, this parameter is optional' },
    type: "GET",
    dataType: "jsonp",
    jsonpCallback: "localJsonpCallback"
});

function localJsonpCallback(json) {
    //do stuff...
}</pre>
<p>We need to setup the server side.  I’m using Asp.Net MVC, so I built this new ActionResult for handling Jsonp GET requests. I copied most of the code from the original JsonResult class in System.Web.MVC Ms-Pl code. Before I show you that, you should see it in action. Here I have a controller action that uses JsonpResult:</p>
<pre class="brush: js; gutter: false;">public JsonpResult GetInformation(string key)
{
    var resp = new Core.Model.CustomObject();
    if (validateKey(key))
    {
        resp.Data = "some custom message";
        resp.Success = true;
    }
    else
        resp.Message = "unauthorized";

    return this.Jsonp(resp); //using extension method
}</pre>
<p>This automatically handles all the fancy Jsonp work that goes on behind the scenes.  It serializes the custom object into Json and wraps it with the callback function. So your response appears something like this:</p>
<pre class="brush: js; gutter: false;">localJsonpCallback({"Data":{"Success":true, Message: "some custom message"}});</pre>
<p>I setup an extension method to use<em> controller.Jsonp(object)</em> just as you do the existing <em>controller.Json(object)</em> method already available. This should make it a lot easier to handle. It will inspect the call for the json callback itself so you also don’t have to manually pull it from the request.  It will also work with the two different types of callback requests parameters in use out there like: “jsoncallback” and “callback.”</p>
<pre class="brush: csharp; gutter: false;">/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 *
 * Content of this class was mostly derived from the original
 * JsonResult class in the System.Web.Mvc 2.0 RTM Assembly. This
 * has beeen slightly extended for use with JSONP calls.
 *
 * This software is subject to the Microsoft Public License (Ms-PL).
 * A copy of the license can be found in the license.htm file included
 * in this distribution.
 *
 * You must not remove this notice, or any other, from this software.
 *
 * ***************************************************************************/

namespace System.Web.Mvc
{
    using System;
    using System.Text;
    using System.Web;
    using System.Web.Mvc.Resources;
    using System.Web.Script.Serialization;

    public class JsonpResult : ActionResult
    {

        public JsonpResult()
        {
        }

        public Encoding ContentEncoding
        {
            get;
            set;
        }

        public string ContentType
        {
            get;
            set;
        }

        public object Data
        {
            get;
            set;
        }

        public string JsonCallback { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.JsonCallback = context.HttpContext.Request["jsoncallback"];

            if (string.IsNullOrEmpty(this.JsonCallback))
                this.JsonCallback = context.HttpContext.Request["callback"];

            if (string.IsNullOrEmpty(this.JsonCallback))
                throw new ArgumentNullException("JsonCallback required for JSONP response.");

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                response.Write(string.Format("{0}({1});", this.JsonCallback, serializer.Serialize(Data)));
            }
        }
    }

    //extension methods for the controller to allow jsonp.
    public static class ContollerExtensions
    {
        public static JsonpResult Jsonp(this Controller controller, object data)
        {
            JsonpResult result = new JsonpResult();
            result.Data = data;
            return result;
        }
    }
}</pre>
<p>When the response is downloaded from the client, it’s invoked and you handle it just as you normally would with any other getJSON success handler. So hopefully this helps clear up any confusion with using JsonP.  There’s about a thousand suggestions I found on doing cross domain JSON and this was just one of the many. I also wrote a simple JsonWebClient class in .Net that will permit the server-side proxy POST to another domain if anyone is interested. I did that before I learned about CORS (preflight post) or this, JsonP. Comments are welcome!</p>
<h3>Sample Code</h3>
<p>Additionally, here is a simple, working demo showing how this works. Be sure to start both websites. Then browse the ClientWebsite and click Test JSONP. This will perform a JSONP GET to the second website.</p>
<p><a href="/resources/p897/JsonPDemo.zip">Download the sample</a></p>
<p>This project is also in the <a href="https://github.com/nathanb/iws-snippets/tree/master/JsonPDemo">IWS Snippets project</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/07/cross-domain-jsonp-using-asp-net-mvc-and-jquery/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>MVC2 on Mono &#8211; Tips and Tricks for Windows Developers</title>
		<link>http://www.integratedwebsystems.com/2010/07/mvc2-on-mono-tips-and-tricks/</link>
		<comments>http://www.integratedwebsystems.com/2010/07/mvc2-on-mono-tips-and-tricks/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 17:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[MVC2]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=886</guid>
		<description><![CDATA[So lately, I&#8217;ve been pretty wrapped up with kids and family so...]]></description>
			<content:encoded><![CDATA[<p>So lately, I&rsquo;ve been pretty wrapped up with kids and family so I haven&rsquo;t had much time to post anything new.&nbsp; However, I did start a new project, which I&rsquo;ll detail out more as I go. It&rsquo;s been quite the experience so far since I decided to build this one from the ground up using MySql and Linux/Mono.&nbsp; I&rsquo;ve never designed apps like that before. For one, I&rsquo;ve had to learn a new set of design tools for MySql as opposed to my comfortable Sql Management Studio. And I&rsquo;ve also had to very incrementally test different programming technologies and methods that were questionably supported in Linux/Mono.&nbsp; The beauty of this is that no matter what I do to make it work for Mono, the app will always work on Windows, and there&rsquo;s little development time lost if I have to fall back to its native platform.</p>
<p><span id="more-886"></span></p>
<p>So about this project&hellip;&nbsp; Well it&rsquo;s a simple project really: web based, MVC2 with a MySql database. So here&rsquo;s a few technical issues I ran into while building the beginnings of this application.</p>
<h3>Choosing a Data Framework</h3>
<p>I know some of you purists would say stick to vanilla ADO.NET; it works every time, and you have no conversion problems. Well, that&rsquo;s right, but I&rsquo;m a lazy typist, and I really dig LINQ. So I tested several LINQ data frameworks on mono and found that <a href="http://code.google.com/p/dblinq2007/">Dblinq</a>&nbsp;and <a href="http://www.subsonicproject.com/">SubSonic3</a>&nbsp;were the most functionally supported frameworks. I tested it with Linq to NHibernate, but it&nbsp;didn&#39;t work. SubSonic3, after a recent bug fix, now does work in Mono!&nbsp;</p>
<h3>MVC2 Works on Mono?</h3>
<p>Yeah it does! Well mostly and only if you pull from the trunk code or the daily tarballs. <strike>Unfortunately, it does not work with the latest public release 2.6.4 and definitely not 2.4.4 which is the latest deployed version on Ubuntu 10.04.</strike>&nbsp;MVC2 now is officially supported by the Mono 2.8 release. MVC1 does work out of the box on older versions of Mono (2.6). So what do you have to do to get it working? &nbsp;Until Mono 2.8 gets pushed into the packaging system, you&#39;ll need to learn a little bit about compiling Mono on your own and installing it, which sounds more painful that it really is. I wrote a script that works (most of the time) on Ubuntu.&nbsp; There&rsquo;s no guarantee that it will work for you of course. <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Checkout one of my recent posts about manually getting&nbsp;<a href="/2010/10/mono-2-8-install-script-for-ubuntu-fedora/">Mono 2.8 installed</a>.</p>
<p>Using MVC2 is the easy part. Just setup a new MVC2 project and ensure your reference options for the System.Web.Mvc and System.Web.Routing assemblies are set to Copy Local. Data annotations will not work, so you&rsquo;ll need to rip out the model validation in the default MVC2 project; otherwise, the rest of it works like a charm.</p>
<h3>xUnit and Dependency injection with Unity works too!</h3>
<p>Yup, believe it or not, some of the components in the Enterprise Library do work in Mono including <a href="http://unity.codeplex.com/">Unity</a>, which works great for swapping out mock classes in test projects. I chose to use <a href="http://xunit.codeplex.com/">xUnit</a> as my testing framework since it seemed to work pretty nicely in the <a href="http://www.subsonicproject.com">SubSonic project</a>. I also found a real nice <a href="http://xunit.codeplex.com/wikipage?title=Comparisons&amp;referringTitle=Home">breakdown</a> of how they compare to other testing frameworks. The xunit command line runs on vanilla Ubuntu 10.04 (mono 2.4.4). However, my preferred method of running some of these tests is using the <a href="http://www.testdriven.net/">TestDriven.net runner</a> on Windows/VS.</p>
<h3>System Agnostic Gotchas</h3>
<p>I&rsquo;ve built and tested most of it on Windows. Which sometimes creates problems when deploying to non-Windows servers. Especially when it comes to I/O pathing.&nbsp; As you go through and design it, you always have to build it in a platform agnostic manner. Duh right?&nbsp; This includes simple things like case senstive paths, using the correct directory separators, etc. Typically as lazy Windows programmers (not all of us) <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &nbsp; we would rather hard code the path separator like this.&nbsp;&nbsp; string.Format(@&ldquo;..\files\{0}&rdquo;, filename);&nbsp;&nbsp;&nbsp; But unfortunately that breaks Linux pathing. So by using Path.DirectorySeparator, it will automatically decide which is the correct character to use on either platform.<br />
	<em>string.Format(&ldquo;..{0}files{0}{1}&rdquo;, Path.DirectorySeparator, filename);</em></p>
<p>The later versions of windows also support both slashes, so you could get away with using forward slashes in windows I/O on Vista and 7.</p>
<p>It can be advantageous (if working with a web application) to use <em>System.Web.HttpContext.Current.Server.MapPath</em> or <em>System.Web.Hosting.HostingEnvironment.MapPath</em> to get your native local path from a virtual one. So store your paths as virtual ones and let the framework convert it to a native/local one.</p>
<h3>Image Rendering</h3>
<p>Well, I haven&rsquo;t completely dug into this, but I have briefly tested simple things like resizing images and writing them back out with Jpeg encoding. I have to say that the Mono built-in implementation of the GDI works just fine.&nbsp; I even tested some other things like rendering speed as far as resizing a jpeg and writing it out. It seems using the System.Drawing as opposed to Mono&rsquo;s GDK/Cairo actually works faster (only by observation; nothing official). I&rsquo;ll have more detailed results on this as I get to that piece.</p>
<h3>Wrap-Up</h3>
<p>So if you&rsquo;re interested in starting a new Mono project, I hope some of these tips will keep you out of trouble. Good Luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/07/mvc2-on-mono-tips-and-tricks/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How to Setup and Configure MySql Membership Provider 6.2.2 &#8211; Porting to Mono Part 2 of 3</title>
		<link>http://www.integratedwebsystems.com/2010/02/how-to-setup-and-configure-mysql-membership-provider-6-2-2-porting-to-mono-part-2-of-3/</link>
		<comments>http://www.integratedwebsystems.com/2010/02/how-to-setup-and-configure-mysql-membership-provider-6-2-2-porting-to-mono-part-2-of-3/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 06:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Configuration Tool]]></category>
		<category><![CDATA[Membership]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[MySql]]></category>
		<category><![CDATA[MySql.Web]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=448</guid>
		<description><![CDATA[As the second part of this series, I’ll look at building a...]]></description>
			<content:encoded><![CDATA[<p>As the second part of this series, I’ll look at building a website that can use the MySql Membership Provider. This is one of the main hang-ups I’ve run into while porting one of my ASP.NET applications to Mono. With the latest MySql Connector, this turns out to be a very easy thing to do. It’s nearly as simple as setting up your web.config with the correct parameters and getting the right connector version.</p>
<p> <span id="more-448"></span><br />
<h3>Download the MySql Connector</h3>
<p>Fortunately now, the MySql.Web assembly comes with the prebuilt versions of the <a href="http://dev.mysql.com/downloads/connector/net/" target="_blank">MySql Connector/Net</a>. If you don’t have it, <a href="http://dev.mysql.com/downloads/connector/net/" target="_blank">go get it</a>.&#160; I recommend the Mono build, even for the Windows folks, because it’s a simple zip file with the assemblies. If you would like to see additional samples, download the Source version of their connector. When you have it downloaded, <strong>add a reference to MySql.Web</strong> in your web project.</p>
<h3>&#160;</h3>
<h3>Database</h3>
<p>As with the Microsoft Sql Server membership provider, you have a choice to place your database tables in an existing application database or in its own database. I prefer to use its own just to keep it separated in case I want to share the Membership component among several applications. If you build upon my <a href="http://www.integratedwebsystems.com/2010/01/installing-opensuse-11-2-with-mono-2-6-1-and-apache-using-text-mode-configuration-porting-to-mono-part-1-of-3/" target="_blank">last post</a>, you can simply create an empty database for your membership data.&#160; Don’t create any tables yet. Just create an empty shell and create a user account for the application to connect your database and has access to create and alter tables. If you’re new to MySql, the <a href="http://dev.mysql.com/downloads/workbench/5.2.html" target="_blank">MySql Administration Tools</a> are extremely handy for this.</p>
<p>&#160;</p>
<h3>Configuration</h3>
<p>The configuration options are mostly the same as the ones you’ve seen in the Microsoft Sql Server membership provider. This one has one added feature, which is an autogenerateschema flag.&#160; This flag instructs the membership provider to actually push schema updates based on the version you’re running. To enable it, simply set it to true.&#160; As with other membership configuration, once you have it enabled and configured to connect to your database, it should work immediately.</p>
<p>There are a few caveats that I ran into while configuring this. For example, hashed passwords only works on Windows .Net; not Mono. Encrypted passwords takes a little more configuration and also (through practice here) only seemed to work on Windows .Net.&#160; There may be some bugs in my version of Mono 2.6.1 or maybe another configuration oddity I couldn’t identify.</p>
<p>Nonetheless, the MySql providers work 100% on Windows. If you’re running on Mono, your main option is to use Clear Text passwords; or if you want to get a little creative, download the source code to the MySql Connector and rewire how it runs its encryption through the framework and roll your own instead.</p>
<p>&#160;</p>
<h3>Configuration Tool</h3>
<p>So moving forward, I built a tiny little configuration tool that you can use to generate the web.config sections you need for this. It takes into account some of my experiences with the things I mentioned like Hashed and Encrypted passwords. It will also auto-generate your MachineKey section if you choose to use encrypted passwords on the Windows side.</p>
<p><a class="launch_tool" href="#" jquery1265988263049="49" jquery1265988344594="2">Launch Configuration Tool</a></p>
<p>Here is the default, Windows based configuration that is generated. You may use this and tweak it or generate your own. </p>
<pre class="brush: xml; gutter: false;">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
    &lt;connectionStrings&gt;
        &lt;add name=&quot;MySqlMembershipConnection&quot;
            connectionString=&quot;Data Source=server_name;user id=username;password=password;database=database_name;&quot;
            providerName=&quot;MySql.Data.MySqlClient&quot;/&gt;
    &lt;/connectionStrings&gt;

    &lt;system.web&gt;

        &lt;authentication mode=&quot;Forms&quot;&gt;
            &lt;forms
              loginUrl=&quot;~/Account/Logon&quot;

              timeout=&quot;30&quot;
              name=&quot;.ASPXFORM$&quot;
              path=&quot;/&quot;
              requireSSL=&quot;false&quot;
              slidingExpiration=&quot;true&quot;
              defaultUrl=&quot;Default.aspx&quot;

              enableCrossAppRedirects=&quot;false&quot;/&gt;
        &lt;/authentication&gt;

        &lt;membership defaultProvider=&quot;MySqlMembershipProvider&quot;&gt;
            &lt;providers&gt;
                &lt;clear/&gt;
                &lt;add name=&quot;MySqlMembershipProvider&quot;
                      type=&quot;MySql.Web.Security.MySQLMembershipProvider, mysql.web&quot;
                        connectionStringName=&quot;MySqlMembershipConnection&quot;
                        enablePasswordRetrieval=&quot;false&quot;
                        enablePasswordReset=&quot;true&quot;
                        requiresQuestionAndAnswer=&quot;false&quot;
                        requiresUniqueEmail=&quot;true&quot;
                        passwordFormat=&quot;Hashed&quot;
                        maxInvalidPasswordAttempts=&quot;5&quot;
                        minRequiredPasswordLength=&quot;6&quot;
                        minRequiredNonalphanumericCharacters=&quot;0&quot;
                        passwordAttemptWindow=&quot;10&quot;

                        applicationName=&quot;/&quot;
                        autogenerateschema=&quot;true&quot;/&gt;
            &lt;/providers&gt;
        &lt;/membership&gt;

        &lt;roleManager enabled=&quot;true&quot; defaultProvider=&quot;MySqlRoleProvider&quot;&gt;
            &lt;providers&gt;
                &lt;clear /&gt;
                &lt;add connectionStringName=&quot;MySqlMembershipConnection&quot;
                    applicationName=&quot;/&quot;
                    name=&quot;MySqlRoleProvider&quot;
                    type=&quot;MySql.Web.Security.MySQLRoleProvider, mysql.web&quot;
                    autogenerateschema=&quot;true&quot;/&gt;
            &lt;/providers&gt;
        &lt;/roleManager&gt;

        &lt;profile&gt;
            &lt;providers&gt;
                &lt;clear/&gt;
                &lt;add type=&quot;MySql.Web.Security.MySqlProfileProvider, mysql.web&quot;
                      name=&quot;MySqlProfileProvider&quot;
                      applicationName=&quot;/&quot;
                      connectionStringName=&quot;MySqlMembershipConnection&quot;
                      autogenerateschema=&quot;true&quot;/&gt;
            &lt;/providers&gt;
        &lt;/profile&gt;
    &lt;/system.web&gt;
&lt;/configuration&gt;
</pre>
<h3>Testing Membership</h3>
<p>So once you have your membership configured, you’ll need to test it out. First, don&#8217;t forget to update your connection string credentials. Then the easiest way to test your membership configuration (if you are using Visual Studio) is to use the ASP.NET Configuration Tool (appears when selecting your web project). <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="Solution Toolbar" border="0" alt="Solution Toolbar" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/01/Toolbar.jpg" width="368" height="86" />When membership configuration is working properly the landing page will show you how many users are configured in the system. If there are none, it will still show you zero. You will also have access to add, remove, and update users from this screen.&#160; If it doesn’t show you anything, then there’s likely something wrong in your configuration.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="aspnetConfig" border="0" alt="aspnetConfig" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/01/aspnetConfig.jpg" width="512" height="180" /></p>
<p>&#160;</p>
<p>After the first time testing your membership, you’ll notice all the schema in the database will have been generated and is now filled with data. This was caused by the<em> autogeneratechema</em> flag being set to “true”.&#160; As new versions of MySql.Web assembly are released from MySql, any schema changes new to each version will automatically be applied with this flag enabled. It should also alleviate that “Schema is missing or incorrect” error.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="database" border="0" alt="database" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/01/database.jpg" width="602" height="266" /></p>
<p>&#160;</p>
<h3>Wrap Up</h3>
<p>So with that, you should have your ASP.NET application configured to run membership to a MySql database. If you’re using Mono, this configuration should work with the default ASP.NET MVC web application (after you reference the MySql assemblies and setup the configuration of course).&#160; Look forward to my next post, which will be the final part of this series about porting an ASP.NET MVC application to Mono. We’ll be taking a very simple MVC application called <a href="http://sitemanager.codeplex.com" target="_blank">SiteManager on CodePlex</a> and convert it to run on Mono and MySql.</p>
<p>&#160;</p>
<h3>Useful Links</h3>
<ul>
<li><a href="http://dev.mysql.com/downloads/mysql/" target="_blank">MySql Community Server</a>&#160; &#8211; Installing on OpenSuse Linux? <a href="http://www.integratedwebsystems.com/2010/01/installing-opensuse-11-2-with-mono-2-6-1-and-apache-using-text-mode-configuration-porting-to-mono-part-1-of-3/#InstallMonoAndApache">Refer to my last post</a>. </li>
<li><a href="http://dev.mysql.com/downloads/workbench/5.2.html" target="_blank">MySql GUI Tools</a> </li>
<li><a href="http://dev.mysql.com/downloads/connector/net/" target="_blank">MySql Connector/NET</a> </li>
<li><a class="launch_tool" href="#">My Cool Configuration Tool</a> </li>
</ul>
<p><div id="dialogContent"></div>
<link href="/tools/css/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" />
<link href="/tools/css/p448.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="http://www.google.com/jsapi"></script><br />
	<script type="text/javascript">
		google.load("jqueryui", "1.7.2");
	</script><br />
	<script language="javascript" type="text/javascript" src="/tools/js/p448.js"></script><br />
	<script src="/tools/js/MicrosoftAjax.js" type="text/javascript"></script><br />
	<script src="/tools/js/MicrosoftMvcAjax.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/02/how-to-setup-and-configure-mysql-membership-provider-6-2-2-porting-to-mono-part-2-of-3/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Using jQuery Modal Dialog Confirmation with an ASP.NET Server Control</title>
		<link>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/</link>
		<comments>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 22:07:07 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[dialog]]></category>
		<category><![CDATA[modal]]></category>
		<category><![CDATA[postback]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=413</guid>
		<description><![CDATA[So the other day, I wanted to build a confirmation dialog using...]]></description>
			<content:encoded><![CDATA[<p>So the other day, I wanted to build a confirmation dialog using jQuery with an existing Asp.Net web forms Button control.  I wanted this dialog to be modal; and upon confirmation, I wanted it to postback using the Button&#8217;s server-side click event.  After toying with the jQuery dialog, I realized that its dialog doesn’t suspend the process while waiting for user input. So it also causes problems with confirmation since clicking the original button will always postback. So with a few tweaks, you can prevent the postback and emulate the click event pretty easily.</p>
<p><span id="more-413"></span></p>
<h3>Setup the Dialog and Postback Script</h3>
<p>In my application, we may click the button multiple times. So you’ll need to initialize it on load and actually open it later. As you can see below, we&#8217;re making our dialog modal and setting its autoOpen to false to prevent it from opening during initialization.  The dialog contains two buttons, and in this initialization, we can define their handler code. The confirmation button “Yes, I Understand and Agree” runs a chunk of code emulates the server control Click event on Button1. Notice I used the inline server-side script to gain access to the Page.ClientScript object, which contains a nice handful of helper functions for javascript.</p>
<pre class="brush: js; gutter: false; toolbar: false;">$().ready(function() {
    $("#ConfirmPanel").dialog(
    { autoOpen: false,
        modal: true,
        bgiframe: true,
        width: 400,
        height: 300,
        buttons: {
            'Youbetcha': function() {
                &lt;%=this.Page.ClientScript.GetPostBackEventReference(new PostBackOptions(this.Button1))%&gt;;
            },
            'No Thanks': function() {
                $(this).dialog('close');
            }
        }
    })
});</pre>
<h3>Open the Dialog with OnClientClick</h3>
<p>Next we’ll open the dialog each time our original server control button is clicked. You use the OnClientClick property to do this.</p>
<pre class="brush: js; gutter: false; toolbar: false;">$("#ConfirmPanel").dialog('open'); return false;</pre>
<p>We always return false here. Since the dialog doesn’t suspend the process, it will always finish and immediately postback. So by returning false, we’re preventing the button from posting back and allowing the jquery dialog to appear.</p>
<p>Here’s the full Asp.Net markup:</p>
<pre class="brush: xml; gutter: false; toolbar: false;">&lt;asp:Label ID="lblClicked" runat="server" /&gt;
&lt;asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Test" OnClientClick="javascript: $('#ConfirmPanel').dialog('open'); return false;"/&gt;
&lt;div id="ConfirmPanel" style="width: 400px; height: 200px;"&gt;
    &lt;h2&gt;Terms and Conditions&lt;/h2&gt;
    &lt;p&gt;By accepting, you agree to the following:
        &lt;ul&gt;
            &lt;li&gt;Are you really, really sure???? &lt;/li&gt;
        &lt;/ul&gt;
    &lt;/p&gt;
&lt;/div&gt;</pre>
<h3>The Result</h3>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image_thumb.png" border="0" alt="image" width="534" height="325" /></a></p>
<p>Clicking Youbetcha fires the Click event for our Button1.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image1.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/12/image_thumb1.png" border="0" alt="image" width="126" height="36" /></a></p>
<p>Updated: 2/16/2010</p>
<p>To answer Matt’s question, I setup a simple web forms page with a data grid and a button within its rows. All the buttons are wired to one event handler and their command argument property is used to provide identifying data to the event handler.  Having said that, here’s the same solution using dynamic confirmation dialog. If you click OK, it will postback using the original button’s information which is displayed on postback.  Noticed I placed a <em>ClientScript.GetPostBackEventReference(uxGrid, string.Empty)</em> within the PageLoad event. Every time the page loads, postback or not, I want it to do this so it will render the __doPostBack client-side function. Without that, it will only work the first time. Subsequent clicks after the first postback will break.</p>
<p>So essentially the solution is to use __doPostBack(clientside_input_name_attribute, &#8221;).  Using the javascript function below we rebuild the buttons for the dialog each time and rewire it to the appropriate location.  So for this, if you didn&#8217;t want to use a grid, you could still use it the same way via OnClientClick with &#8220;this.name&#8221; and pass that to __doPostBack.</p>
<p>Here’s the markup source.  You can also <a href="/resources/p413/jquery_dynamic_confirmation.zip">download the full source code here</a>.</p>
<p>Thanks Matt.</p>
<pre class="brush: xml; gutter: false;">&lt;%@ Page Language="C#" AutoEventWireup="true"  %&gt;
&lt;%@ Import Namespace="System.Collections.Generic" %&gt;

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
    &lt;title&gt;&lt;/title&gt;

    &lt;script type="text/C#" runat="server"&gt;
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.GetPostBackEventReference(uxGrid, string.Empty);

            if (!Page.IsPostBack)
            {
                List&lt;int&gt; test = new List&lt;int&gt;();
                test.Add(2);
                test.Add(3);
                test.Add(32);
                test.Add(223);
                test.Add(5);
                test.Add(8);
                uxGrid.DataSource = test;
                uxGrid.DataBind();

            }
        }
        protected void uxRowAction_Click(object sender, EventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                uxTest.Text = "clicked " + b.CommandArgument;
            }
        }

    &lt;/script&gt;

    &lt;link href="smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" /&gt;
    &lt;script src="jquery-1.3.2.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script src="jquery-ui-1.7.2.custom.min.js" type="text/javascript"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;
        $().ready(function() {
            $('#dialogContent').dialog({
                autoOpen: false,
                modal: true,
                bgiframe: true,
                title: "MySql Membership Config Tool",
                width: 800,
                height: 600
            });
        });

        function rowAction(uniqueID) {

            $('#dialogContent').dialog('option', 'buttons',
                {
                    "OK": function() { __doPostBack(uniqueID, ''); $(this).dialog("close"); },
                    "Cancel": function() { $(this).dialog("close"); }
                });

                $('#dialogContent').dialog('open');

            return false;
        }

    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div id="dialogContent"&gt;
        &lt;h3&gt;confirm&lt;/h3&gt;
        &lt;p&gt;Click ok to accept&lt;/p&gt;
    &lt;/div&gt;
    &lt;asp:Literal ID="uxTest" runat="server" /&gt;
    &lt;div&gt;
        &lt;asp:DataGrid ID="uxGrid" runat="server" AutoGenerateColumns="false"&gt;
            &lt;Columns&gt;
                &lt;asp:TemplateColumn&gt;
                    &lt;ItemTemplate&gt;
                        &lt;asp:Button ID="uxRowAction" runat="server" CommandArgument='&lt;%#Container.DataItem.ToString() %&gt;' Text="Row Action" OnClick="uxRowAction_Click" OnClientClick="javascript:return rowAction(this.name);" /&gt;
                    &lt;/ItemTemplate&gt;
                &lt;/asp:TemplateColumn&gt;
            &lt;/Columns&gt;
        &lt;/asp:DataGrid&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/12/using-jquery-modal-dialog-confirmation-with-an-asp-net-server-control/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Announcing SiteManager &#8211; A Simple Open Source, MVC Based CMS</title>
		<link>http://www.integratedwebsystems.com/2009/10/announcing-sitemanager-a-simple-open-source-cms/</link>
		<comments>http://www.integratedwebsystems.com/2009/10/announcing-sitemanager-a-simple-open-source-cms/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 06:00:36 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[CMS]]></category>
		<category><![CDATA[CodePlex]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[SiteManager]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=370</guid>
		<description><![CDATA[While playing and learning with MVC, I designed a simple little CMS...]]></description>
			<content:encoded><![CDATA[<p>While playing and learning with MVC, I designed a simple little CMS (content management system). My goals for the project were to keep it simple, use MVC, and make it SEO optimized as possible. Well finally the first version of that application is published on <a href="http://sitemanager.codeplex.com" target="_blank">CodePlex</a>. Feel free to go check it out. Don’t forget to peek at the <a href="http://sitemanager.codeplex.com/wikipage?title=setup%20instructions&amp;referringTitle=Documentation" target="_blank">setup documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/10/announcing-sitemanager-a-simple-open-source-cms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Connecting to Sql Server using Impersonation from Asp.Net</title>
		<link>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/</link>
		<comments>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 16:13:03 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Active Directory]]></category>
		<category><![CDATA[Delegation]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=276</guid>
		<description><![CDATA[So you have an Asp.Net application that needs to authenticate its users...]]></description>
			<content:encoded><![CDATA[<p>So you have an Asp.Net application that needs to authenticate its users to Active Directory, and you also want to use their credentials for connecting to a database server. It&#8217;s pretty logical thing to do in an enterprise environment where you would normally control all your user privileges using Active Directory. This is especially nice since you also don&#8217;t have to put sensitive credentials in your web.config file. </p>
<p> <span id="more-276"></span>Before I begin, here are a few links worth mentioning:
</p>
<p>How To: Use Impersonation and Delegation in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998351.aspx" href="http://msdn.microsoft.com/en-us/library/ms998351.aspx">http://msdn.microsoft.com/en-us/library/ms998351.aspx</a></p>
<p>How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998355.aspx" href="http://msdn.microsoft.com/en-us/library/ms998355.aspx">http://msdn.microsoft.com/en-us/library/ms998355.aspx</a></p>
<p>How To: Use Windows Authentication in ASP.NET 2.0    <br /><a title="http://msdn.microsoft.com/en-us/library/ms998358.aspx" href="http://msdn.microsoft.com/en-us/library/ms998358.aspx">http://msdn.microsoft.com/en-us/library/ms998358.aspx</a></p>
<p>This turns out to be a very easy thing to do; it&#8217;s just hard to find any simple information about it. Authenticating to Asp.Net using Windows and using impersonation gives us the ability to let the worker process inherit privileges of the authenticated user. All it takes is a few web.config changes.</p>
<p>First, you need to change authentication mode to Windows. under &lt;system.web&gt; set &lt;authentication mode=&quot;Windows&quot;/&gt;</p>
<p>It&#8217;s also a good idea to force anonymous users to authentication. Do that by changing the &lt;authorization&gt; config.</p>
<p>Now we have users authenticating to the Windows network. Now lets enable impersonation so the worker process will adopt privileges for their requests. Set &lt;identity impersonation=&quot;true&quot;/&gt;</p>
<p>When you’re done, your web.config file should resemble this.</p>
<pre class="brush: xml; toolbar: false;">&lt;system.web&gt;

    &lt;authentication mode=&quot;Windows&quot;/&gt;

    &lt;identity impersonate=&quot;true&quot;/&gt;

    &lt;authorization&gt;
        &lt;deny users=&quot;?&quot;/&gt;
    &lt;/authorization&gt;

&lt;/system.web&gt;</pre>
<p>All that’s left is putting the proper delegation rules in place for your web server to hand out Windows tokens (at least that’s my understanding). In Active Directory Users and Computers from a domain controller or accessible machine, right click and go to the properties of the web server that will be using impersonation.&#160; Click the Delegation tab and select the third option. Trust this computer for delegation to specified services only.&#160; Select Use any authentication protocol.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/image10.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" border="0" alt="image" align="right" src="http://www.integratedwebsystems.com/wp-content/uploads/image_thumb.png" width="408" height="470" /></a>Then browse for a machine account for the database server you want to access with the impersonated accounts. Choose the MSSQLSvc with the port number next to it. (Ours had two services).&#160; Then click OK to apply the changes.</p>
<p>You may need to reset IIS or wait a few minutes for the AD changes to propagate. We reset ours from a command line with “iisreset”.</p>
<p>That should be it!&#160; You should now be able to browse your web app and access the database using your AD Windows Account.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/06/connecting-to-sql-server-using-impersonation-from-asp-net/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

