Getting Started With ASP.NET 5 On Ubuntu

16. June 2015 22:59

.NET Framework ASP.NET ASP.NET MVC C# Microsoft  Ubuntu Visual Studio Web  6 Comments

Ever since the .NET stack went open source last year, there is a huge excitement among the developers about the .NET stuff and developing apps using .NET which are no longer limited to Windows platform. I tried to install ASP.NET VNext on Ubuntu VM in which I terribly failed in the first go. Why? because the tutorial I used was quite old and I messed up the installation of pre-requisites. But I get everything working in the second try. So here are the steps and commands that will get you started with ASP.NET VNext on Ubuntu.

I am setting up a fresh VM for development on Ubuntu 14.04.2 LTS

Installing Mono

First thing is to install Mono. For folks who are new to Linux environment, Mono is a community driven project which allows developers to build and run .NET application on Linux platforms. Here is the set of commands that I have to execute to install Mono.

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF

echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
sudo apt-get update

Install the latest version of Mono available.

sudo apt-get install mono-complete

To check if Mono is successfully installed or to determine the version of Mono on you machine run the below command in the terminal.

mono --version

Installing LibUV

As stated on Github:

Libuv is a multi-platform asynchronous IO library that is used by the KestrelHttpServer that we will use to host our web applications.

Running the below command will install LibUV along with the dependencies require to build it.

sudo apt-get install automake libtool

Getting the source and building and installing it.

curl -sSL https://github.com/libuv/libuv/archive/v1.9.0.tar.gz | sudo tar zxfv - -C /usr/local/src
cd /usr/local/src/libuv-1.9.0
sudo sh autogen.sh
sudo ./configure
sudo make 
sudo make install
sudo rm -rf /usr/local/src/libuv-1.9.0 && cd ~/
sudo ldconfig

Here is a note at Githb repo that explains what the above set of commands are doing.

NOTE: make install puts libuv.so.1 in /usr/local/lib, in the above commands ldconfig is used to update ld.so.cache so that dlopen (see man dlopen) can load it. If you are getting libuv some other way or not running make install then you need to ensure that dlopen is capable of loading libuv.so.1

Getting .NET Version Manager (DNVM)

DNVM is a command line tool which allows you to get new build of the DNX (.NET Execution Environment) and allows you to switch between them. To get DNVM running fire the below command in the terminal.

curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh

To check if the DNVM is successfully installed on your machine, type DNVM in the terminal. The output should be something like this:

At any point of time if you want to list out the installed DNX runtimes, run the below command

dnvm list

The next step after this, is to upgrade the DNVM so you can use the dnx and dnu commands. Run the following command in the terminal

dnvm upgrade

Once this is done, we are all set to run ASP.NET VNext application on Ubuntu box. Clone the aspnet/Home repository from Github. If you don't have Git installed then install it with this simple command.

sudo apt-get install git

For simplicity, I have created a new directory on Ubuntu desktop named vnext. You can name the directory as you wish. Navigate to this directory in the terminal and clone the aspnet/Home repository.

git clone https://github.com/aspnet/Home.git

After cloning of repository is done, navigate to the 1.0.0-beta4 directory.

You can see three sample applications that you can test. For this tutorial I am going to checkout HelloMvc application. Get inside the HelloMvc directory and then, run the command 

dnu restore

This will take some time to execute. I didn't face this problem but there is a chance that someone will. When you run this command, the project.json.lock file gets created and the restore of the package will start. In the end when the restore is finalizing, it may say permission is denied. To resolve this error you can change the permission of the folder by running the following command.

sudo chmod -R 755 HelloMvc

You should always change permission to 755 for directories and 644 for files.

After the execution is completed, you can start the server by running the command.

dnx . kestrel

This command will work for both web and mvc application. If you plan to test out the console application then you can run the following command.

dnx . run

The server runs at port 5004. Fire up the browser and type in http://localhost:5004/

Hope this is helpful for the first time users of Linux.

Currently rated 5.0 by 1 person

ASYNC Controller In MVC 4

30. April 2013 22:17

.NET Framework ASP.NET MVC C# Visual Studio  0 Comments

I have build many small applications so far in MVC to help myself in understanding the framework more deeply. Now I am planning to write a blog engine on MVC. It will not be an easy task but I will be going to learn a lot of things. As I was planning things ahead I came across a problem where I have to load my blog stats like FeedBurner readers, Facebook page likes, Google +1 count, twitter followers inside a div on the page. The problem I see here is that I am going to make multiple cross-domain calls in order to get the stats. I can’t avoid that though but this will cause my blog to load slowly. I know about Async and Task Parallel Library(TPL) but the question is how do I implement this in my application? I do a quick web search and found something which is called Async controller in MVC4. You can also have AsynController in MVC3 but that is not pretty if you start comparing it with MVC4.

For the simplicity of the tutorial I am going to make 2 calls: get twitter followers count and facebook page likes. In MVC3, if you want to perform Async operations then you have to inherit your controller with AsyncController like this.

public class HomeController : AsyncController

But MVC4 is much cleaner. Let’s take a look at the default implementation of the calls I am making to Twitter and Facebook to get the follower count and page likes respectively. Here are my 2 methods in HomeController.

private string GetTwitterFollowersCount(string Username)
{
    XDocument xdoc = XDocument.Load("http://api.twitter.com/1/users/show.xml?screen_name=" + Username + "&include_entities=false");
    return (from item in xdoc.Descendants("user")
            select item.Element("followers_count").Value)
            .SingleOrDefault();
}
 
private string GetFacebookLikes(string FaceBookPageURL)
{
    string uri = "https://api.facebook.com/method/fql.query?query=select%20%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22" + FaceBookPageURL + "%22";
    return Convert.ToString((from elem in XElement.Load(uri).Descendants()
                   where elem.Name.LocalName == "like_count"
                   select elem).First<XElement>().Value);
}

Nothing fancy in the above two methods. When I call these 2 methods one after the other, they will just get the data from a different source and render the result in the view. That’s fine as it’s my requirement. Now when I run my application it now takes a longer time to render the view. Before I explain this further take a look at my Index().

public ActionResult Index()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    ViewBag.TwitterFollowers = GetTwitterFollowersCount("audi");
    ViewBag.FacebookLikes = GetFacebookLikes("http://facebook.com/audi");
    watch.Stop();
    Int64 elapsedTime = watch.ElapsedMilliseconds;
    ViewBag.Time = elapsedTime.ToString();
    return View();
}

This is because Controllers are synchronous by default and it will process the request one after the other i.e. it will wait for the first task to complete and then move on to the next task. In my case the controller will execute the GetFollowersCount method and only after the completion of this method it will shift to the next method GetFacebookLikes. This could be a long running task or just imagine if you are retrieving heavy data from different sources. The view or the page will not render till the execution of both the methods will not get completed. To get a rough idea of the time elapsed in making synchronous calls in the above controller, I have used StopWatch(System.Diagnostics) class. I don’t know how accurate, but I still used it to have an approximate idea of the time. This is the output of the above code.

It took 1588ms to complete 2 requests. Now if I implement async in the controller I will see a drastic improvement. It is not just the controller ActionResult which I have to change to support async calls but I also have to update the 2 methods which I am using to collect the stats. Here are my updated methods.

private Task<string> GetTwitterFollowersCountAsync(string Username)
{
    return Task.Run(() =>
    {
        XDocument xdoc = XDocument.Load("http://api.twitter.com/1/users/show.xml?screen_name=" + Username + "&include_entities=false");
        return (from item in xdoc.Descendants("user")
                select item.Element("followers_count").Value).SingleOrDefault();
    });
}
 
private Task<string> GetFacebookLikesAsync(string FaceBookPageURL)
{
    return Task.Run(() =>
    {
        string uri = "https://api.facebook.com/method/fql.query?query=select%20%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22" + FaceBookPageURL + "%22";
        return Convert.ToString((from elem in XElement.Load(uri).Descendants()
                                 where elem.Name.LocalName == "like_count"
                                 select elem).First<XElement>().Value);
    });
}

Pay attention to the GetTwitterFollwersCountAsync and GetFacebookLikesAsync return type. Previously they were only string, and now I have changed their return type to Task. I have put the code inside Task.Run() as it will queues the specified work to run on the Thread Pool and returns a Task(TResult) handle for that work. I have changed the ActionResult to handle the async feature. As you can see that this controller method does not return ActionResult instead it return Task. Here is my updated ActionResult.

public async Task<ActionResult> Index()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    Task<string> twitterFollowers = GetTwitterFollowersCountAsync("audi");
    Task<string> facebookLikes = GetFacebookLikesAsync("http://facebook.com/audi");
    await Task.WhenAll(twitterFollowers, facebookLikes);
    ViewBag.TwitterFollowers = await twitterFollowers;
    ViewBag.FacebookLikes = await facebookLikes;
    watch.Stop();
    Int64 elapsedTime = watch.ElapsedMilliseconds;
    ViewBag.Time = elapsedTime.ToString();
    return View();
}

The code is almost the same but 3 lines are making a difference (highlighted). Task will hold the value returned from the updated async methods. MSDN defines the await operator as:

The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

Task.WhenAll() will creates a task that will complete when all of the supplied tasks have completed. This actually parallelize the request. Lets check the output and compare both.

The difference is noticeable…607ms!! is half way down and a huge performance benefit. This is a small example and the real performance can be noticed when you work with real scenarios. I have used MVC4 with .NET 4.5 to use awesomeness of asynchronous controller. I hope this gives you an idea on how you can use async controllers in MVC4.

 No Rating

Pretty Paste - Visual Studio Extension Which Makes Pretty Paste

31. March 2013 16:52

Utils Visual Studio  0 Comments

This is a much needed extension for every developer out there. How many times you have been yelling when you paste the code from a blog post or from an article which eventually turns out to be a nightmare for you to re-format it? I came across a VS extension that can actually get this done for me. The good thing about this extension is that it is open-source and you can extend and contribute to it to make it more awesome.

Pretty Paste - Visual Studio Gallery

Source Code - Github

 No Rating

Visual Studio 2012 Features Comparison Chart

4. September 2012 02:25

Visual Studio  0 Comments

Visual Studio 2012 is now available and here is a chart that compares the features of different versions of Visual Studio 2012.

 

Currently rated 4.0 by 1 person

Death Of Visual Studio Installer Projects After Visual Studio 2010 And NSIS & Inno Setup Installers

8. March 2012 03:36

Microsoft  Visual Studio  3 Comments

I came across an announcement made by Candy Chiang at MSDN Forums at ClickOnce and Setup & Deployment Projects forums.

In Visual Studio 2010, we have partnered with Flexera, makers of InstallShield, to create InstallShield Limited Edition 2010 just for Visual Studio 2010 customers. The InstallShield Limited Edition 2010 offers comparable functionality to the Visual Studio Installer projects. In addition, you can build your deployment projects using Team Foundation Server and MSBuild. For more information, see here.

With InstallShield available, the Visual Studio Installer project types will not be available in future versions of Visual Studio. To preserve existing customer investments in Visual Studio Installer projects, Microsoft will continue to support the Visual Studio Installer projects feature that shipped with Visual Studio 2010 and below as per our product life-cycle strategy. For more information, see Expanded Microsoft Support Lifecycle Policy for Business & Development Products.

The question here is how we are going to create a setup within Visual Studio? How we are going to install the Windows service? How the application gets deployed in the production environment? The in-built Setup and Deployment template was extremely useful and I have no idea at the moment what is the best alternative Microsoft will come up with in Visual Studio 11 which is flexible enough to provide all what the developer needs. Well, in time we'll see but this is for sure that we are not going to have project templates for Setup and Deployment in the next release for Visual Studio. Microsoft also confirms that InstallShield will be available in the future versions of Visual Studio, but again it will be a limited edition (as what we have in Visual Studio 2010). Let's hope we are going to see more advanced version of InstallShield in next release of Visual Studio.

What are the alternatives?

With Setup and Deployment gone from Visual Studio, there is an excellent Visual Studio extension which allows you to create setup packages. This extension will let you create NSIS and Inno Setup installers for your application. At the moment this extension supports Visual Studio 2005, 2008 and 2010 and as I see excellent potential in this extension and the people behind the extension, I hope we will be able to see this extension for Visual Studio 11 soon. The current/latest version is still in beta and is only available for Visual Studio 2010.

Note: Before you start installing the add-in make sure you have few of the pre-requisites installed in your machine. Read for the pre-requisites here.

The best part about this extension is that alike traditional Setup and Deployment projects it gives you a complete wizard to create a setup package for your application. For folks who have never put their hands on NSIS, I would like to tell them that is a scriptable installer and that means that you can write your own custom scripts to get more out of the box.

Let's see what this add-in has to offer us in future. 

Related Links: 

Currently rated 5.0 by 1 person

«1234»

Visit blogadda.com to discover Indian blogs Computers Blogs