Configure and Deploy ASP.NET MVC 3 Web Application Using Git to AppHarbor from Scratch!

by aherrick 1. March 2011 11:24

Today I want to walk through from configuring and deploying your environment so that you are able to successfully publish your web application to AppHarbor from the ground up.  With the recent addition of AppHarbor to the community, the process of configuring, building, and deploying a web application can now be fun, and possibly more importantly a completely free experience.

I am going to assume that you have a version of Visual Studio 2010 installed.  If not, the Express version (free) can be downloaded here.

Also, I will be deploying an ASP.NET 3 web application for this demo.  However, AppHarbor has full support for both ASP.NET MVC 1 and 2 web applications, as well as Web Forms.

With that out of the way, let’s begin.  I have already installed my copy of Visual Studio 2010.  Next I am going to grab a copy of Git Extensionswhich is a free download.  This will install Git on your Windows machine, as well as extensions which can be used in Visual Studio.  Let’s walk through the install below:

Install and Configure Git Extensions

1) Download and run the executable from the link above.  The version used at the time of this tutorial is 2.11

2) On the first options screen, it asks you to install MSysGit and Kdiff3.  Follow the recommendation and install both.

3) Install to the default directory recommend: C:\Program Files\GitExtensions\

4) Next screen is Custom Setup.  Leave all options as selected as default.

5) Next screen ensure “Putty” is selected.

git2

6) Finally click “Install” the first sub installation process we have is to install Kdiff3 since we selected that earlier.  Install by clicking “Next” all the way through the process, without changing any settings.

7) Next, it prompts us to actually install Git.

8) Click and and install in to the default recommended location. 

9) Next, it asks us to select the components we want to install.  Ensure you select “Context menu entries”  This will make it easier for you in the future when spinning up a fresh Git shell.  See below:

git3

10) Click next to install shortcuts.  Next it will prompt you on adjusting your PATH.  This is more of a UNIX thing which in UNIX will allow you to always use the Git command from Terminal/Bash.  Being on a Windows box, we aren’t really focused on that, we will just spin up a Git Bash console when we want to work with Git and leave Windows Command prompt untouched.  More on that later, for now, ensure you “Use Git Bash only.”

git4

11) Line Breaks – By default Windows and UNIX end lines differently.  Git can handle this for us, ensure “Check out windows style, commit Unix style” is selected.  I have not had any issues deploying to AppHarbor with this selection.  If you don’t want Git messing with any of your line endings and you plan only working on Windows projects, select “Checkout as-is, Commit as-is”.

git5

12) At this point, congratulations Git should be installed!

Spin up our ASP.NET MVC 3 Web Application!

If you already have a web application that you would like to push out to App Harbor, use that!  If not, we are going to spin up a quick one for demo purposes.

1)  Assuming at this point Visual Studio 2010 and ASP.NET MVC 3 are installed, Open Visual Studio: File-> New –>Project –> ASP.NET MVC 3 Web Application.  Create an “Empty” Template from the next dialog.

aspnetmvc1

2) Inside Visual Studio, we are going to spin up a Controller which will handle our incoming requests.  Right Click on the “Controller” folder on the right side and select Add –> Controller.  Call it “HomeController” as seen below.  By convention, ASP.NET MVC uses the Home Controller to handle incoming requests to the root of your site “/”

image

3) You should now see a file similar to the one below.  Right click anywhere inside the “Index” method and select “Add View”

image

4) Your solution now should look similar to mine, where you have a fresh Home Controller and an “Index” view sitting in your Views/Home/ folder.

image

5) Change the <h2> text to say “Hello ____” and click the green play button at the top.  You now have a fully functioning website!

Deploy your ASP.NET MVC web application to AppHarbor

1) If you have not already done so, head over to http://appharbor.com and register for an account.  It is completely free!

2) Once registered, sign in and you should be presented with your existing Applications.  If you just signed up, you will now need to create an Application.  This tells creates the seed that tells AppHarbor that you want to publish a new site.

3) I called my Application “ajondeck”.  Click create!  You will now see a screen similar to below.  This is the details you need in order to actually push your site to AppHarbor.  Take note of your “Repository URL” it will be important in a moment.

image

4) Let’s hop back into Visual Studio Right click on the Solution and say “Open Folder in Windows Explorer”

image

5) In Windows Explorer now, lets navigate up one more directory, so we are sitting in the root of the directory that our MVC Web Application is in.  Right click on the Folder you named your web application and select “Git Bash Here”  This will spin up a fresh Bash client in which we will be able to interact with Git.

image

6) If you haven’t used Git before, the steps following are going to be the minimum required to get off the group with App Harbor.  Git is much more powerful and could deserve diving deeper into.

7) Let’s first initiate a Git Repository.  This will spin up a repository for us that we we can add/commit to.  Inside your Bash Console, type: git init

image

8) Now that our repository is initialized, let’s add our files.  This will add all our files to the queue, ready to commit.  type: git add .

9) All our files our added, finally we need to actually commit them to the repository!  type: git commit –m “initial commit”

10) Our web application is now versioned locally!  Almost there.

11) Let’s refer back to the App Harbor site and grab our “Repository URL”.  In this case, mine is https://ajcool123@appharbor.com/ajondeck.git

12) Now let’s add AppHarbor as a remote repository.  This will give us the ability to push to it!  You will obviously use YOUR specific “Repository URL” that we talked about above.  type: git remote add appharbor https://ajcool123@appharbor.com/ajondeck.git

13) At this point, simply type: git push appharbor master

14) Enter your password at the prompt, and all your files will be pushed automatically to the servers of AppHarbor!

15) You should be able to view your application live @ http://YourApplicationName.apphb.com in my case, check out the one built for this demo here!  http://ajondeck.apphb.com

Enjoy playing around with building and deploying your sites!  Have fun!

Tags:

jQuery Dynamically Create Table

by aherrick 24. June 2010 10:47

Use jQuery objects to build up your table instead of using string concatenation.  How many time have you seen code similar to the following to build up a table?

        $(function () {

            var content = '';
            content += '<div id="tableWrap">';
            content += '<table id="basicTable">';

            for (var i = 0; i < 200; i++) {


                content += '<tr>';
                content += '<td>';
                content += i;
                content += '</td>';
                content += '<td>';
                content += 200 - i;
                content += '</td>';
                content += '</tr>';
            }

            content += '</table>';
            content += '</div>';

            $('body').append(content);
        });

Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.

        $(function () {

            var $wrap = $('<div>').attr('id', 'tableWrap');

            var $tbl = $('<table>').attr('id', 'basicTable');

            for (var i = 0; i < 200; i++) {

                $tbl.append(
                            $('<tr>')
                                    .append($('<td>').text(i),
                                            $('<td>').text(200 - i))
                           );
            }

            $wrap.append($tbl);
            $('body').append($wrap);
        });

View the live code here!

Tags:

Javascript Regular Expression Allow Alphanumeric KeyUp

by aherrick 22. January 2010 04:13

Working on an application I needed to write a script to only allow Alphanumeric characters (Letters and Numbers only) for dynamic XML generation.  We wanted the solution to be smart enough that when the user is typing in a textbox, any character other than Alphanumeric is automatically removed while they are typing into the input.  Using a combination of jQuery and regular Javascript the solution becomes simple. 

Take a look at the Javascript used below.

    <script type="text/javascript">

        $(function() {

            $('#basicInput').keyup(function() {

                // cache input and value
                var input = $('#basicInput');
                var value = $('#value');

                // only allow letters, numbers, don't allow spaces
                var tempVal = input.val().match(/[A-Za-z0-9]+/g);
                tempVal = tempVal == null ? "" : tempVal.join("");

                // display formatted input
                input.val(tempVal);
                value.html(tempVal);
            });
        });
        
    </script>

First we attach a jQuery keyup event to the text input. We then get the value of the input and run it through a basic regular expression to get the match. We then update the input with the array of matched values.

Great! Check out the example page to see it in action!

Tags:

Hard Drive No Sleep v1.0

by aherrick 29. November 2009 07:13

I wrote this little Windows Forms application a while back as an answer to a small issue I was having with my external hard drives.  I wanted to prevent them from spinning down and entering a sleep mode after a certain period of time.  This application simply attempts to write a text file to the root of each configured drive in order to keep activity on the drive and prevent it from spinning down.  I wanted to learn how to do some of the different configurations but mainly wanted to write a working Windows application.  Tested in Windows Server 2003/2008, Windows XP, and Windows Vista.

hdns

It is fully customizable to allow for multiple hard drives, and has different configuration settings such as how often (in minutes) to write a file, minimize to tray on start, monitor automatically on start, and run on Windows start up.  Once a configuration is saved, settings are saved even if the application is restarted.  I wanted to take a look at some of these basic configurations that can be reused across other applications that I build.

hdns-config

Below is an EXE of the application and the full source in case you are interested in checking it out!

HardDriveNoSleepV1.0-EXE.zip (91.46 kb)
HardDriveNoSleepV1.0-SRC.zip (422.66 kb)

Tags: ,

JavaScript Determine Valid Integer

by aherrick 13. October 2009 05:02

I need a simple function to determine if a value was a valid integer.  Meaning that the value is a whole number (positive or negative) and doesn’t contain decimals. 

Below is what I came up with.

// check valid integer
function IsValidInt(s) {

    var valid = false;
    if (s != null && s != "" && !isNaN(s)) {
        valid = parseInt(s, 10) == s;
    }
    return valid;
}

Breaking it down we assume that the value is invalid.  We verify the value is not null, not an empty string, and use JavaScript’s built in NaN() (Not a Number) function to determine if it is a valid number.

Then use other JavaScript built in function, parseInt() and compare it to the original passed in value.  parseInt() will evaluate the value and return an Integer.  By comparing the returned integer and our passed in value, we can determine if the passed in value is valid.

I came up with this basic test suite function to show it validating.

function TestIsValidInt(){
    var results = ''
    results += (IsValidInt('-1')?"Pass":"Fail") + ": IsValidInt('-1') => true\n";
    results += (IsValidInt('-1.5')?"Pass":"Fail") + ": IsValidInt('-1.5') => false\n";
    results += (IsValidInt('0')?"Pass":"Fail") + ": IsValidInt('0') => true\n";
    results += (IsValidInt('asdf')?"Pass":"Fail") + ": IsValidInt('asdf') => false\n";

    alert(results);
}

Check out the example page to see it in action!

Enjoy!

Tags:

Check It Out http://www.theholidaycountdown.com Is Live!

by aherrick 8. August 2009 02:44

This past week I took live the project I have been working on over the past month, The Holiday Countdown.  The premise is simple, I wanted to create a basic, clean site where you can easily find out how many days until an upcoming holiday. 

From the technology side of things, the site is built completely on the ASP.NET MVC 1.0 framework with a LINQ to SQL backend.  Custom Javascript code is used for the countdown timers. I would call this version 1.0, in the future I may end up making it more dynamic by allowing users to add their own Holiday Countdowns and add favorite Holidays to their account homepage. 

It was a fun little side project to work on so check it out today to find out how long until your next favorite Holiday!

http://www.theholidaycountdown.com

image

Tags:

Validate Username Using jQuery AJAX, JSON, and ASP.NET Web Method

by aherrick 11. February 2009 08:59

As of late, I have been working on using AJAX in my code to call ASP.NET Web Methods and Web Services.  There are a couple of different ways to accomplish this, including using the ASP.NET Script Manager, (see here) however there is a lot of overhead with instancing the Script Manager that is not always necessary.

The method below using the jQuery.AJAX call which even includes built in error checking functionality.  In this example, I am going to call a Web Method in the code behind that will validate the username text field input and return a boolean regarding if the username is valid. 

In a normal production environment, in your Web Method you would want to hit a database to validate the input, however for this demo I am going to simulate that.  If the username entered equals “testuser”, the method will return false, otherwise return true resulting in a valid username.

First we are going to add our html to the page:

<div>
    Username:
    <input id="tbUsername" type="text" />
    <span id="valid"></span>
</div>
<!-- preload -->
<div style="display: none">
    <img src="images/available.gif" alt="available" />
    <img src="images/taken.gif" alt="taken" />
    <img src="images/waiting.gif" alt="waiting" />
</div>

Here I am creating a simple html textbox and span tag.  We will use the Javascript code to change the html of the span tag.  It is a place holder for now.  Also I add an image preload div using CSS so the necessary images are loaded at runtime.  display: none ensures the images will not be visible on the screen.  This ensures a smooth effect when hiding/showing the images dynamically.

Next we are going to create our simple Web Method in the code behind.

using System.Web.Services;
[WebMethod]
public static bool IsUserAvailable(string username)
{
    // simulating db call here
    if ((!username.Contains(" ") || !username.Contains("")) && username != "testuser")
        return true;
    else
        return false;
}
 
All we are doing is creating a simple method to return if the user is valid. 

Now lets take a look at the Javascript required to make this all happen.

<script type="text/javascript" src="scripts/jquery-1.2.6.min.js"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("#tbUsername").blur(function(event) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/IsUserAvailable",
                data: "{'username': '" + $('#tbUsername').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#valid').html("<img src='images/waiting.gif' alt='Checking username!'>");                       
                    var delay = function() {
                        AjaxSucceeded(msg);
                    };
 
                    setTimeout(delay, 2000);
                },
                error: AjaxFailed
            });
        });
    });
    function AjaxSucceeded(result) {
        if (result.d == true)
            $('#valid').html("<img src='images/available.gif' alt='Username available!'>");
        else
            $('#valid').html("<img src='images/taken.gif' alt='Username taken!'>");
    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }    
</script>

Here is where the magic happens.  Using jQuery we are getting a reference to tbUsername and adding blur event.  Adding the event through jQuery leads to better cross browser compatibility. 

Using jQuery.ajax we define our variables:

  1. type: “POST” – this ensures we are posting to the server
  2. url: “Default.aspx/IsUserAvailable” – sets the page and method we are calling
  3. contentType: “application/json; charset=utf-8”
  4. dataType: “json” – using JSON as the data type, this could be XML, etc.
  5. success: – here we are creating a function to determine what to do with the Response from the server i fit was successful
  6. error: – allows us to define an error method if something goes wrong.

Here is what our POST/RESPONSE looks like in debug mode with Firebug

POST:

usernamePost

You can see what we are sending, username defines the argument name and test is the value entered into the textbox.

RESPONSE:

usernameResponce

After successfully validating the username in the Web Method, it sends back a true.  For more information on what the d value is, give this blog post esconia a read.

Finally if the response was true, we set the html of the span to the success image, otherwise set it to taken!

I hope this code is a jump-off point to get you started with jQuery AJAX, JSON, and ASP.NET and gives you a glimpse at how powerful it can really be!  Posted below is the code in its entirely, please test it out and let me know what you think!

jQueryAJAXValidateUsernameWebMethod.zip (39.30 kb)

Tags:

ASP.NET 2.0 SubSonic Project Template With SQL Server 2005 Northwind DB

by aherrick 29. December 2008 01:39

I created this template mostly for myself so that when I am creating web demos/test projects I have a wired up SubSonic project ready to go.  Hopefully it will be useful for someone interested in getting started with SubSonic.  Setup is currently running SubSonic 2.0.3.  I have found this to be the most stable version to date.  I will be putting up a version 2.1 (and hopefully 3.0) template soon.

Rob Conery, SubSonic creator, has some great videos on getting started as well.  Check it out at http://subsonicproject.com

This solution is completely wired using ASP.NET 2.0 and SQL Server 2005.  I broke the solution up to into two projects (DAL and WEB).  This way seems to work well and allows for abstraction.  In order to run, make sure you are running the Northwind database (just run ins). 

Good luck and let me know if you have problems running the solution.

SubSonicSMall

SubSonicNorthwindDBTemplate.zip (869.28 kb)
InstallNorthwind.zip (274.19 kb)

Tags:

ASP.NET Programmatically Control MasterPage and CSS

by aherrick 22. December 2008 07:14

Working on a project I need the ability to programmatically change the web application's associated master page (and associated CSS).  Most of the pages in the application were content pages (derived from the content page) however some were just static pages.  Since there was no MasterPage assoicated with these static pages, dynamically assigning the CSS was the next best option.

I created a BasePage for ALL pages in the application to derive from. 

For the ContentPages (pages that point to a MasterPage) I created a method in the BasePage to assign the necessary master page.  This method is called in the Page_PreInit method of the content page.  See below.

        protected void Page_PreInit(object sender, EventArgs e)
        {
            // set master page
            this.SetMasterPage();
        }

SetMasterPage is a simple method to dynmically change the MasterPage...

        public void SetMasterPage()
        {
            // change master page

            // will return random number between 1-3...      
            int masterPage = RandomNumber(1, 4);

            string fullMaster = ResolveUrl(string.Format("~/Site{0}.master", masterPage));
            this.MasterPageFile = fullMaster;
        }

Dynamically set the CSS on the static pages in a similar matter.  In the code behind of the specific page, , call SetCSS in the Page_Init method.  Dynamically setting the CSS is very easy too...

        public void SetCSS()
        {
            // set CSS

            // ALL CSS has to be set programatically... 
            HtmlLink css = new HtmlLink();
            int cssNum = RandomNumber(1, 3);

            css.Href = ResolveUrl(string.Format("~/StyleSheet{0}.css", cssNum));
            css.Attributes["rel"] = "stylesheet";
            css.Attributes["type"] = "text/css";
            css.Attributes["media"] = "all";
            Page.Header.Controls.Add(css);
        }

Really that's all there is to it.  This code can be tweaked to suit your needs.  This gives a lot more flexibility than simply dynamically changing your CSS file.

Attached is the code

ControlMasterPagesProgramatically.zip (34.59 kb)

Tags:

C# Directory List Application

by aherrick 9. December 2008 11:11

I am releasing this application I created to help me organize my music collection.  It takes multiple paths and combines ever directory under each path into a single txt/csv file sorted alphabetically.  I had a little fun with some of the validation and colors to make it work a little more smoothly. 

dl

Usage:

  1. Select paths using Add
  2. Select output format (txt or csv)
  3. List is generated to same directory .exe is located

Attached is the .exe and full source code.  It is free for distribution and please feel free to tweak to your needs!

If I tweak this in the future I will post the updated code, consider this V1.0

Enjoy!

DirectoryListV1.0-FullSRC.zip (73.37 kb)
DirectoryListV1.0EXE.zip (12.18 kb)

Tags: ,



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008