Deploying .NET Application To Appharbor Using Git

7. August 2012 13:12

ASP.NET MVC Utils 

I have an account with Appharbor but never tried to deploy an application. Appharbor has an excellent integration with Github and Codeplex and if you are planning to showcase you application latest build then Appharbor is the best thing to do that. The Appharbor site has a detailed tutorial on how you can deploy your application from Github and Codeplex. But the question here is what will a programmer do if he just wants to deploy the application from his dektop or in other words if he wants to test his application which is not an open source application. Fortunately, it is possible and is pretty easy to use by using Git Bash. All a programmer need to to is to execute a bunch of commands to deploy the application. I have already deployed one of my application called MP3app to Appharbor (just for few days) which was previously hosted on sub-domain.

If you have an application and you want to showcase it then you can deploy the application to Appharbor. The application I have with me right now is an ASP.NET MVC application which demonstrates the use of Micro-ORM Dapper. This application is with me and is not hosted on Github or Codeplex and therefore I cannot take the advantage of deploying it from the code hosting service. 

Before you proceed I assume that you have an account with Appharbor and have Git bash installed on your machine. If you don't have Git bash installed on your machine, download it from here. After successfull login you can create a new application with the name of your choice. You can also select the datacenter location for your application, either United States or Europe.

Click Create New button to create your application, after which you will be shown with the application settings screen. On the right-hand side you can also see the links which will help you to get started with Appharbor using Bitbucket, Github and Codeplex. Moreover, you can also select add-on services like SQL Server with 20MB of space. You can see the complete list of add-ons and their charges here.

I am calling my application DapperTest which demonstrates the use of Micro-ORM with SQL ServerCE 4.0 in ASP.NET MVC3. On the left side under the application name and other configurations you can see two buttons, REPOSITORY URL and BUILD URL. Click on the REPOSITORY URL button and you will have the URL copied to your clipboard. Open any text editor and paste the copied URL over there as you will be need it afterwards.

Open Git bash and then navigate to the project/solution directory. This will be the original project/solution with source code and not the published version. Also you need to be sure that the project/solution has Visual Studio solutiuon (.sln) file. If the file is not present then you will not be able to deploy your application to Appharbor.

To navigate to the project directory fire the below command in the Git bash console:

cd D:\DapperApp

To initialize empty Git repository, execute the below command:

git init

If you navigate to your project folder, then you can see a folder named .git. By default, this folder is hidden. Now the repositiry is created, I can now add all the files to the repo using the below command:

git add .

It might be possible that you don't want to add certain files to the repository then you can add a .gitignore file. You can see an example here. After this, I can then commit it using the below command:

git commit -m "initial commit"

After the commit is successful, copy the repository URL that you saved initially in your text editor. Add the remote repository (in our case it is Appharbor) using the below command:

git remote add appharbor https://prashantkhandelwal@appharbor.com/dappertest.git

Make sure to replace the URL with the correct one. Once this command executed successfully, you can then deploy/push to Appharbor by using below command:

git push appharbor master

Before the application is being deployed, it will ask you for your Appharbor password. Make sure that you type it slowly because you will not be able to see the password being typed on the Git bash console.

This is it, enjoy the power of cloud.

Here is the list of few applications hosted on Appharbor:

Currently rated 3.0 by 1 person

Integrate Windows Live SignIn Support In ASP.NET

28. July 2012 12:35

API ASP.NET 

Last year I wrote a post on how you can integrate OpenID support in your ASP.NET application. Few days back as usual I was chasing Windows Live SDK updates on Twitter and yes the most awaited SkyDrive API was made available to all the developers. I will be writing a post later on how to upload files using SkyDrive API.

Setting up the application

To integrate Windows Live Sign-In support I have downloaded the LiveService samples from Github and take a look at ASP.NET sample. All the hard work has been done for you from before. First you need to create an application at https://manage.dev.live.com. Once you create an application, you will get the Client ID and Client secret for the application which we will be using in our application.

Now you have the Client ID and Client secret, you then need to update the same in the Callback.aspx code-behind. The redirect domain will be the name of the domain. In my case I have hosted the complete solution which you can try here. The pretty looking Sign In button rendered on the page is from the JavaScript code.

When you click on the button it will open a window which will ask your Live or Hotmail credentials.

After you successfully authenticated from Live service, it will return you the authentication code. For your ease I have made the authentication code (along with the URL that retrieves the user's image) available to you through a JavaScript alert.

Don't waste your time in looking into the alert message. Just press CTRL+C to copy the whole message and paste it into notepad. Now it's time to look into it carefully. If you quickly open a new tab in your browser and paste the copied URL, then you will get the image of the user who is authenticated. To get more information about the user, modify the URL in the notepad to this:

https://apis.live.net/v5.0/me?access_token=EwBAAq1DBAAUlbRWyAJjK5w968Ru3Cyt/6GvwXwAAf/Zr2CM5/qilrH.......

Note that from the URL above I have removed /picture. Now hit the new URL to the browser again, and this time the output has more information:

The question comes here is: What if I want to get the contacts of the authenticated user or want to get the list of folders in his/her SkyDrive? To understand this, consider that Windows Live is a big application which is built up with small applications like mail, SkyDrive, calendar etc. Now if someone wants to access any part of the application we need to specify which part of the application we need to access. For us (programmers) it is called Scope. The test application I am demonstrating here has the following scopes: wl.signin, wl.basic, wl.offline_access, wl.skydrive. To grant access to your application you should provide the correct scopes in your application. To know more about scopes read here

After everything went fine and I was successfully authenticated I get my picture with Windows Live (it's 2 year old) and the Sign in button changed to Sign out:

You can also display other user information, if you wish. I have compiled all the files under one hood for your ease and you only have to create a new application, get the Client ID and Client secret and update it into the application.

Download: Live-SignIn.zip (9.71 kb)

 No Rating

MP3APP - A Web Application To Get Lyrics, Album Name, Album Art and More

29. June 2012 20:53

ASP.NET MVC Utils Web 

I was busy in few of my freelance projects and got a very rough weekends this whole month. But still I get a bit of time to work on my so called in-house project and somehow I was able to get it completed after a bit of testing. The application I built is a simple web application which will allow you to enter artist name and the song name and let you search the lyrics, album art, artist image, album name and album release date. I hope this application help few people out there.

Now, something about the internals and history of the application. I created a windows application 2 years back and thought of porting the same application for the web. For the, web I used ASP.NET MVC 3 with jQuery but the internals of the application remains the same as it was for my windows app. To fetch the lyrics I use LyrDB and WikiLyrics web services and for album art, album name, artist image etc. I used Last.FM web service. I package the whole stuff and what I got is the application which I was running since 2 years on my machine and now the same application is out for you, use it and suggest me something new if you anything in your minds.

I am not yet finished with this application and you'll see more in coming days.

Try out the application here: http://mp3app.midnightprogrammer.net

 No Rating

Working With Micro-ORM Dapper In MVC

29. May 2012 12:50

ASP.NET MVC 

I love working with MVC but I do have a hard time working with complex data with EntityFramework (EF). I heard of using inline SQL queries in MVC but don't know how to use it and will it have any performance issues? Few month's back I downloaded the StackOverflow (SO) Data Explorer which is an open-source project built on MVC to explore data dump provided by SO. The thing that took my attention in that code was that they have been SQL queries to get the data from the database. This looks promising to me as the guys at SO will never compromise with performance. SO Data Explorer uses the micro-ORM called Dapper which is authored by Sam Saffron of Stack Overlfow.

Getting Dapper

Dapper is also available on NuGet or you can also drop this single file in your project which is hosted at Google Code. You can use the below NuGet command to install Dapper.

Usage

Performing CRUD operations in EF is simple for simple scenarios, but when the required data is complex I prefer using SQL queries with joins and other related stuff which make my work far much easier. To demonstrate how to use Dapper to perform CRUD operations, I am building a simple application to manage contacts. I started up with creating a model named ContactModel. You can copy the below code or you can have one for yourself.

public class Contacts
{
    [Key]
    public int ContactID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public string Skype { get; set; }
}

The model is ready but we are not using EF Code First which created the database for us on the fly and therefore I have a bit more work to do. I'll now create a database with a table which is same like my model. After the table has been created now I will add a new class to my project where I will write functions which will help me in performing CRUD operations. I will talk about view and controllers later when I am done with my DB access class. For this sample application I have used SQL CE 4.0 DB, but if you wish you can use SQL Server DB.

At the first, I just want to list down the contacts I have in the database. Practically this would have been the last thing to show in the example but I am showing this at first so you get an idea how Dapper works. As we have fresh database with no records, write down and insert query or just simply punch in the data in. Now in my data access class I will create a simple function which returns me the collection of contacts.

try
{
    using (SqlCeConnection con = new SqlCeConnection(ConStr))
    {
        con.Open();
        var contacts = con.Query<Contacts>("Select Name, Address, Email, Skype from Contacts");
        return contacts;
     }
}
catch (Exception x)
{
    throw x;
}

The above functions returns the collection of the contacts which I will use in my Index view where I am going to list down all the contacts I have with me (See the SQL query :) ). Add a new controller or use the existing Home controller and add the below ActionResult method ListContacts.

public ActionResult ListContacts()
{
    var db = new DB();
    return View(db.GetContacts());
}

I now must have a view which will display the list of all the contacts. Right-click on ListContacts() method and choose Add View. A pretty familiar dialog pops up like the one below.

Nothing fancy here, just select the model class as the Contacts and Scaffold template as List. Hit F5 and change the URL to {View}/ListContacts and you will be able to see the list of contacts.

Performing INSERT/UPDATE and DELETE operations

To insert the data in the database create the below method in the DB access class:

public bool CreateContact(Contacts contact)
{
    try
    {
        using (SqlCeConnection con = new SqlCeConnection(ConStr))
        {
            con.Open();

            string sqlQuery = "INSERT INTO Contacts([Name],[Address],[Email],[Skype]) VALUES (@Name,@Address,@Email,@Skype)";
            con.Execute(sqlQuery,
                                  new
                                  {
                                      contact.Name,
                                      contact.Address,
                                      contact.Email,
                                      contact.Skype
                                  });
        }
        return true;
    }
    catch (Exception x)
    {
        return false;
    }
}

I have a normal INSERT statement which will insert the records for me. The point that you need to note is that it is executed by the Execute extension method of the SqlCeConnection class. If you use SQL Server then the class will be SqlConnection class. Returning to controller and just to remind you that if we were working with EF which would have done the CRUD part for us then you must be aware that there are 2 ActionResult methods which were required for this purpose. One will just return the view and the other one with [HttpPost] attribute will create the record. I require a create view so I can add contacts. Follow the same steps you have followed above while creating the ListContacts view. For your further help here are the 2 ActionResult methods to create a new record (I am sure you can create a view!! Just right-click Create() method and click AddView and the scaffold is Create).

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Contacts contact)
{
    var db = new DB();
    bool isCreated = db.CreateContact(contact);
    if (isCreated)
    {
        return RedirectToAction("ListContacts");
    }
    else
    {
        return View();
    }
}

The process of updating a contact will be similar like we have done for the insert. Before updating a contact I need to get the details of the contact when the user clicks on the Edit link on the page. When the user clicks the Edit hyperlink on the list page, the contact ID will be paased as a parameter.

public Contacts GetContactByID(int ContactId)
{
    using (SqlCeConnection con = new SqlCeConnection(ConStr))
    {
        con.Open();
        string strQuery = string.Format("Select ContactID, Name, Address, Email, Skype from Contacts where " +
        "ContactID={0}", ContactId);
        var customer = con.Query<Contacts>(strQuery).Single<Contacts>();
        return customer;
    }
}

public bool UpdateContact(Contacts contact)
{
    try
    {
        using (SqlCeConnection con = new SqlCeConnection(ConStr))
        {
            con.Open();
            string sqlQuery = "UPDATE Contacts SET Name =@Name, Address =@Address, Address = @Address, " +
            "Email = Email, Skype = @Skype WHERE ContactID=@ContactID";
            con.Execute(sqlQuery, new
            {
                contact.Name,
                contact.Address,
                contact.Email,
                contact.Skype,
                contact.ContactID
            });
        }
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

The GetContactByID method will accept the contactId which is passed as a parameter to the Edit ActionResult method. I am calling this method from the Edit ActionResult. The main purpose of this method is to fetch the contact details on the basis of the ID passed to it. The returned Contacts serves as a model to the Edit view which then populates the details of the contact I want to edit. I assume here you know how to create a View. Here is my Edit and Edit with HttpPost which does the actual update work. The UpdateContact method will get called from the Edit ActionResult method which is attributed with HttpPost.

public ActionResult Edit(int ContactID)
{
    var db = new DB();
    return View(db.GetContactByID(ContactID));
}

[HttpPost]
public ActionResult Edit(Contacts contact)
{
    var db = new DB();
    db.UpdateContact(contact);
    return RedirectToAction("ListContacts");
}

Following the same procedure that I followed for insert and update I am going to implement the delete functionality. The below code will be used to delete the contact details.

public bool DeleteContact(int ContactID)
 {
     try
     {
         using (SqlCeConnection con = new SqlCeConnection(ConStr))
         {
             con.Open();
             string sqlQuery = "DELETE FROM Contacts WHERE ContactID=@ContactID";
             con.Execute(sqlQuery, new { ContactID });
         }
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }

And for your ease, here are the 2 ActionResult methods.

public ActionResult Delete(int ContactID)
{
    var db = new DB();
    return View(db.GetContactByID(ContactID));
}

[HttpPost]
public ActionResult Delete(int ContactID, FormCollection frm)
{
    var db = new DB();
    bool IsDeleted = db.DeleteContact(ContactID);
    if (IsDeleted)
    {
        return RedirectToAction("ListContacts");
    }
    else
    {
        return View();
    }
}

This is it. A simple application where you can perform CRUD operations using SQL queries with micro-ORM Dapper.

Performance

Another reason for using a micro-ORM, Dapper in my case, but if you check the documentation you can see the table which clearly state the difference between the different ORMs.

There are other ORMs that you can try like the Massive ORM and PetaPOCO.

 No Rating

Infinite Scrolling In ASP.NET With jQuery

28. April 2012 12:53

ASP.NET Jquery T-SQL 

I didn't create the whole solution by myself. The initial idea is from the All-In-One Code Framework sample. I was just customizing my BlogEngine and for one of the module I thought it would be nice not to use paging and I should go for infinite scrolling stuff. This idea seems cool to me and without wasting any time I just do a quick web search and I came across a solution which is a part of a All-In-One Code Framework. This was not the complete solution I was looking for but I can re-use the jQuery part in the sample.

Assembling jQuery Part

I just re-use the all jQuery script as it is without any major modification. The only change I made is the name of the web method in the url parameter of the Ajax method I have in page code behind and change the method name to InfiniteScroll:

function InfiniteScroll() {
    $('#divPostsLoader').html('<img src="images/loader.gif">');

    //send a query to server side to present new content
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetData",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            if (data != "") {
                $('.divLoadData:last').after(data.d);
            }
            $('#divPostsLoader').empty();
        }
    })
};

I already have 2 divs in the page where the data is being loaded when the user scrolls down at the bottom of the page. This is the simplest Ajax call written in jQuery and I assume you are aware of the syntax and methods and require no explanation. What I require here is to call this function when the user scrolls at the bottom of the page. So how to know when the user scrolls and reach at the bottom of the page? Here is the method which fires the InfiniteScroll() function:

$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        InfiniteScroll();
    }
});

Make sure you put the scroll function inside the document.ready function. Now when the user scrolls at the bottom of the page then it will call the InfiniteScroll() function which in turn loads new data in the divLoadData div.

The Code-Behind

In the code-behind create a WebMethod function that returns a HTML string. For this example I am loading all my blog posts title, post date and slug from my blog engine database which is a SQL Server CE 4.0. Here is the method:

[WebMethod]
public static string GetData()
{
    RecordCount = RecordCount + 10;
    string Sql = "SELECT Title, DateCreated, Slug FROM be_Posts ORDER BY Title OFFSET " + FirstCount + " ROWS FETCH NEXT 10 ROWS ONLY";
    FirstCount = RecordCount;
    StringBuilder sb = new StringBuilder();
    dt = new DataTable();
    da = new SqlCeDataAdapter(Sql, con);
    con.Open();
    da.Fill(dt);

    DataView dv = dt.DefaultView;

    foreach (DataRowView row in dv)
    {
        sb.AppendFormat("<p>Post Title" + " <strong>" + row["Title"] + "</strong>");
        sb.AppendFormat("<p>Post Date" + " <strong>" + row["DateCreated"] + "</strong>");
        sb.AppendFormat("<p>Slug" + " <strong>" + row["Slug"] + "</strong>");
        sb.AppendFormat("<hr/>");
    }

    sb.AppendFormat("<divstyle='height:15px;'></div>");
    con.Close();
    return sb.ToString();
}

Infinite scrolling is nothing but is a sort of automatic paging. Every time a user scrolls down at the bottom of the page, the query gets fired and gets the new set of data. As I am using SQL CE 4.0 the paging query is different than that of the SQL Server 2008.

Query for SQL CE 4.0:

SELECT Title, DateCreated, Slug FROM be_Posts ORDER BY Title OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

Change the OFFSET and FETCH NEXT to get the next result set.

Query For SQL Server 2008:

SELECT Title, DateCreated, Slug FROM ( 
     SELECT 
          ROW_NUMBER() OVER (ORDER BY title) AS row, Title, DateCreated, Slug
     FROM be_Posts
) AS a WHERE row BETWEEN 1 AND 10

I have changed the query in the above code to get me the set of next results every time a user scrolls at the bottom of the page. When the user scrolls down I increment the FirstCount with 10 which is a value of RecordCount variable. I have attached the complete solution so you can try. I don't have the database included in the solution as it is my blog database. You have to create one to test it out.

Download: InfiniteScroll.zip (2.28 mb)

Currently rated 2.0 by 1 person