Single Sign-On In ASP.NET Core With Azure Active Directory

8. May 2017 15:21

.NET Core ASP.NET ASP.NET MVC Azure C# Cloud 

Visual Studio has made integrating of Azure Active Directory authentication in web applications very simple. If you are creating the application and want to integrate the AD authentication then it is a pretty easy task given that you have an Active Directory in Azure. But what if you have an application and it is out there running and now you want to change the authentication medium of your application so you can have better control and security of your web application. I already have an application and I want to integrate Azure AD authentication, hence I will not be able to change the authentication just like that. I have to manually make the changes to do so. So here it is what I have done to integrate Azure Active Directory in my ASP.NET Core web application.

 

Step 1: Create Azure Active Directory

When provisioning a new Azure Active Directory you have to go to the old portal manage.windowsazure.com. At the time of writing this blog post, the product team is still in a process of migrating the complete AD feature sets from the old portal to the new portal. Therefore, to create a new AD in Azure, click the Active Directory in the left pane and you will be able to see all the active directories. In the below screen shot you can see that I am a part of Microsoft Active Directory as a User.

If you are planning to use any of the current Active Directory out of the one listed, you can click on it and register your application and users. Note that you have to be a Global Administrator to do that. If you want to create a new Active Directory, then click the NEW button at the bottom left corner to create a new Active Directory.

Click on CUSTOM CREATE and a new dialog box will appear in front of you to enter the name of your Active Directory.

The green check box in the DOMAIN NAME denotes that the name you have chosen for your active directory is available. When done click the tick button or icon at the bottom right corner of the dialog box to create a new active directory.

Step 2: Add a user

After the creation of active directory is successfully completed, you can see the new created active directory in the list. Notice the ROLE as Global Administrator. Click on the active directory name to view the details. First, I am going to add a new user to the directory. When inside the active directory, click the USERS which in the top of the page.

I can see a default user added to my new created active directory here which is my official Microsoft user. I cannot delete this user neither I can change much of the roles and other information of this user because it something which is being managed by Microsoft. So to add a new user, click the ADD USER button at the bottom of the page. This will open up a dialog box which allows you to add or create a new user to the active directory. In my case I am going to add a normal user not an administrator, I will keep the the default prompts. The whole process of adding a new user will take 3 steps to complete.
In the next screen enter the details about the user. I want to add this user as a normal user hence I am selecting User as a ROLE.
In the last step, click the create button to add a new user and generate a temporary password for the new user. 
Make a note of this password somewhere as you will need it to log in to the account. After the first login, user is prompt to change the password.

Step 3: Add an application to the Active Directory

To add a new application, click on the APPLICATION link. Click the ADD button at the bottom of the page to add a new application and then click Add an application my organization is developing.
In the next step enter the name of the application and select the type of application you are building. In my case, it is a web application.
In the next step, you add a sign-in URL and app ID URI. The app ID URI I have added is in this format: http://<directoryname>.onmicrosoft.com/adauth. Replace the directoryname with your directory name. The adauth is the name of my application.
Once the adding of application is successful, click the USERS link. I can see the new user I have created in the user lists but it is not being assigned to the application yet. To do that, click the ASSIGN button at the bottom of the page and click YES. The ASSIGNED status will be changed from No to Yes.

Step 4: Setting up the web application

The easy way to set the application up for AD authentication is to create a new "demo" application and select Change Authentication from the new project dialog box. Select Work or School Accounts and enter the domain name. This will create a new application with all the things set up for your domain. The reason I said "demo" application because I want to just get the changes that Visual Studio does it for me when I select the AD authentication. This application will now act like a sample application from where I can take the implementation and add it to my existing application.
 
 
Here are the changes I have made to my existing application. As of now my existing application does not have user authentication and now as I want to implement, I will add the account controller and two views which will handle the authentication. In my case this is the account controller, you can name the controller as per your choice. Add two new views in the Views directory for your controller. Call them AccessDenied.cshtml and SignedOut.cshtml respectively.
 
Note that all the changes I am making to my existing application are exactly the same as the sample application.
Code for AccessDenied.cshtml view.
@{
   ViewData["Title"] = "Access Denied";
}

<header>
    <h1 class="text-danger">Access Denied.</h1>
    <p class="text-danger">You do not have access to this resource.</p>
</header>
Code for SignedOut .cshtml view.
@{
   ViewData["Title"] = "Sign Out";
}
<h2>@ViewData["Title"].</h2>
<p class="text-success">You have successfully signed out.</p>
Add below NuGet packages for AD authentication support in the application.
Install-Package Microsoft.AspNetCore.Authentication
Install-Package Microsoft.AspNetCore.Authentication.Cookies
Install-Package Microsoft.AspNetCore.Authentication.OpenIdConnect
In the .NET Core project, you will also see a new file called appsettings.json. Add the below configuration to it. Your configuration will than mine.
"Authentication": {
  "AzureAd": {
    "ClientId": "0d9h56ba-ccfd-42f2-9a75-64d8e96756e6",
    "AadInstance": "https://login.microsoftonline.com/",
    "CallbackPath": "/signin-oidc",
    "Domain": "dominicdomain.onmicrosoft.com",
    "TenantId": "d58e5363-f09c-4d65-9808-cd88396529f0"
  }
}
In the Startup.cs file, configure the request pipeline by adding the below code in the Configure method. I have added this code just after the UseStaticFiles() functions. This enables the application to use the cookie authentication and OpenId authentication.
app.UseCookieAuthentication();

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"]
});
In the ConfigureServices method, add the below code.
services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
In the AccountController.cs, add the below code.
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
        new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}

[HttpGet]
public IActionResult SignOut()
{
    var callbackUrl = Url.Action(nameof(SignedOut), "Account", values: null, protocol: Request.Scheme);
    return SignOut(new AuthenticationProperties { RedirectUri = callbackUrl },
        CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
}

[HttpGet]
public IActionResult SignedOut()
{
    if (HttpContext.User.Identity.IsAuthenticated)
    {
        return RedirectToAction(nameof(HomeController.Index), "Home");
    }

    return View();
}

[HttpGet]
public IActionResult AccessDenied()
{
    return View();
}
Add a new partial view in the Shared folder and name it _LoginPartial.cshtml just like we have in new default scaffold project.
@using System.Security.Principal
@using System.Security.Claims

@if (User.Identity.IsAuthenticated)
{
    var claims = ((ClaimsIdentity)User.Identity).Claims;
    var username = claims.FirstOrDefault(c => c.Type == "name")?.Value;

    //Uncomment the below code to see the complete email address of the user.
    @*<li class="navbar-text">Hello @User.Identity.Name!</li>*@  
 
    <ul class="nav navbar-nav navbar-right">
        <li class="navbar-text">Hello @username!</li>
        <li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign Out</a></li>
    </ul>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
    </ul>
}
Open _Layout.cshtml page, add the below line of code to render this partial view so users can sign in and sign out.
@await Html.PartialAsync("_LoginPartial")
And we are done! This is a minimalistic implementation that you can get start with. Azure Active Directory also provides groups and roles which you need to work with if you are working with the enterprise scale application where security is a major concern. You also have to tweak the code for that. Let's try executing the application and see what happens when I try to authenticate the user for the first time.
 
When you land on the home page you can see the Sign in link at the top right of the web page.
 
 
When you click on the sign in link, you will be redirected to the login.microsoftonline.com where you will be prompted for the user name and password. After the first successful login, you will be prompted to change the current password.
 
 
 
After the successful change of the password, you will be re-directed to the application with your user name as displayed at the top right corner.
 
 
 No Rating

.NET Projects You Should Be Follwing On Github

19. July 2015 04:51

API ASP.NET ASP.NET MVC C# Musings Web 

Open-source has entirely change the programming and developers world. Today you can create any application, game, mobile app without spending a single penny. Thanks to open-source software and awesome community of developers and people behind them. As a .NET developer I have been developing enterprise applications for quite a long time and now I have shifted my focus towards developing products and understanding what it takes to make a successful product launch.

Back then, I used to spend most of my time in investigating the new technologies and what technology we should be using to get this thing done. I still do that today, not because it is the requirement of the project but because I have been asking a lot of questions. The list of projects I have compiled below are the projects that have helped me in learning lots of new things and insights of the programming and I hope this does the same for you as well.  Here is the list of awesome open-source project that you should be following on Github.

Pinta


We all know about Paint.net, it is an awesome tool and a complete replacement of Photoshop (at least for me). And yet there is another project which is almost the same and open-source and it works on Linux and Mac. It uses Gtk# (Gtk sharp) to run on both Window and Linux platforms. This project is a must have if you are a .NET guy and want to get yourself into some serious programming. You will learn about the insights of using gtk# in your projects. Though Microsoft already took the steps to have .NET FX on Linux but still this project is a great learning source.

Official site: http://www.pinta-project.com/

Github: https://github.com/PintaProject/Pinta

 

ShareX


I take a lot of screen shots and record screen casts as well for my personal use. But I used to use two different tools to get the work done. This is one of the tools that will not just take screen shots or just let you record your screen casts easily, it will also allow you to upload them to the 40 different image storing cloud services. Dive into the source code and see the awesomeness under the hood. Here is the project description as seen on Github.

ShareX is an open source program that lets you take screenshots or screencasts of any selected area with a single key, save them in your clipboard, hard disk or instantly upload them to over 40 different file hosting services. In addition to taking screenshots, it can upload images, text files and all other different file types.

Official site: https://getsharex.com/

Github: https://github.com/ShareX/ShareX

 

StackExchange - Data Explorer


You got a programming question, you Google it and it redirects it to StackOverflow. StackOverflow needs no introduction among programmers. StackOverflow is one of the Q&A site dedicated to the developers to get the answers for their problems. But it is just one site. In the recent years StackExchange has grew up and not just providing support for programmers but also helping folks from other fields. Now the data StackExchange has is available for anyone out there for free under creative-commons. If you are interested in looking into the source code that powers the user to query that immense amount of data bank then head over to Github and fork this project. StackExchange is all about Microsoft stack and this tool is also written in ASP.NET MVC3.

Official App: https://data.stackexchange.com/

Github: https://github.com/StackExchange/StackExchange.DataExplorer

 

Mini Blog


This is the minimalistic blog engine written in ASP.NET web pages by the author of BlogEngine.NET, Mads Kristensen. I started my bog with BlogEngine.NET and I had an amazing experience with it. MiniBlog is totally different in terms of features that are offered by BlogEngine.NET. This project will tell you the power of web pages and how you can write your own simple site without wasting much time.

Demo: http://miniblog.azurewebsites.net/ (with user name and password as demo).

Github: https://github.com/madskristensen/MiniBlog

 

Fluent Scheduler

If you want to run cron jobs or automated jobs in your application quietly, then this is the library you should be using. The documentation is pretty sleek and get you started in no time. But other than that you should take a look at the source code and see how nicely this has been done.

Github: https://github.com/jgeurts/FluentScheduler

 

Dapper

A Micro-ORM used by StackExchange sites. This is a perfect replacement for EF. This is just a single file that you can drop in your project and get started.

Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.

Github: https://github.com/StackExchange/dapper-dot-net

 

LINQ-toWIKI

A .NET library to access MediaWiki API. The library is almost 3 years old but the source code will worth the look. Excerpt from Github:

LinqToWiki is a library for accessing sites running MediaWiki (including Wikipedia) through the MediaWiki API from .Net languages like C# and VB.NET.

It can be used to do almost anything that can be done from the web interface and more, including things like editing articles, listing articles in categories, listing all kinds of links on a page and much more. Querying the various lists available can be done using LINQ queries, which then get translated into efficient API requests.

Github: https://github.com/svick/LINQ-to-Wiki

 No Rating

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 

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

Recurring Tasks Inside ASP.NET Applications Using HangFire

15. June 2014 22:46

ASP.NET ASP.NET MVC C# SQL Server Web 

This is open-source at its best. Running background task to work in context with ASP.NET was and is still a big deal for few developers. I user QueueUserWorkItem to schedule emails when a new comment is added on my blog. This makes sure that the UI is responsive and the user can close or navigate to other post. I have been working on enterprise applications for many years now and most of the long running tasks are running in the background i.e. windows services.

HangFire is not limited to ASP.NET applications, you can even use it in your console applications.

HangFire is an open-source project which allows us to run recurring tasks within the ASP.NET application. No need of scheduling tasks and windows services. Everything will be within the ASP.NET application. When a new comment is added on my blog, an email is sent to my inbox as a notification to moderate it. In a normal scenario it will take a bit more than a normal time to add a comment because an email is also being sent to my inbox. To overcome this problem, I queued the mail process in the background like so:

bool commentSave = _db.AddComment(comment);
if (commentSave)
{
    System.Threading.ThreadPool.QueueUserWorkItem(s=> BlogEmail.SendEmail(comment));
    return Json(new { message = "Thanks for your comment. The comment is now awaiting moderation" });
}
else
    return Json(new { message = "There is an error while saving comment. Please try again later" });

As soon as a comment is added, user will be prompted that comment is added in the DB but the process of sending the email is scheduled in the background. But this approach has a drawback. What if the email sending is failed? As the admin of my blog, will I be able to see the status of the process? HangFire resolves all these questions and it comes with an awesome HangFire monitor which displays the status of all the background tasks in real-time. I will discuss about the HangFire monitor later in this post, but first let's get started with HangFire.

Installing HangFire

HangFire is available on NuGet. Firing the below command will automatically add the references in your project and takes care of all the configuration.

Install-Package HangFire
Attempting to resolve dependency 'HangFire.SqlServer (= 0.9.1)'.
Attempting to resolve dependency 'HangFire.Core (= 0.9.1)'.
Attempting to resolve dependency 'Common.Logging (= 2.1.2)'.
Attempting to resolve dependency 'Newtonsoft.Json (= 5.0.0)'.
Attempting to resolve dependency 'ncrontab (= 1.0.0)'.
Attempting to resolve dependency 'Dapper (= 1.13)'.
Attempting to resolve dependency 'HangFire.Web (= 0.9.1)'.
Attempting to resolve dependency 'CronExpressionDescriptor (= 1.10.1)'.
Attempting to resolve dependency 'WebActivatorEx (= 2.0.1)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (= 1.0.0.0)'.
Installing 'Common.Logging 2.1.2'.
Successfully installed 'Common.Logging 2.1.2'.
Installing 'ncrontab 1.0.0'.
Successfully installed 'ncrontab 1.0.0'.
Installing 'HangFire.Core 0.9.1'.
Successfully installed 'HangFire.Core 0.9.1'.
Installing 'Dapper 1.13'.
Successfully installed 'Dapper 1.13'.
Installing 'HangFire.SqlServer 0.9.1'.
Successfully installed 'HangFire.SqlServer 0.9.1'.
Installing 'CronExpressionDescriptor 1.10.1'.
Successfully installed 'CronExpressionDescriptor 1.10.1'.
Installing 'WebActivatorEx 2.0.1'.
Successfully installed 'WebActivatorEx 2.0.1'.
Installing 'HangFire.Web 0.9.1'.
Successfully installed 'HangFire.Web 0.9.1'.
Installing 'HangFire 0.9.1'.
Successfully installed 'HangFire 0.9.1'.
Adding 'Common.Logging 2.1.2' to HangfireDemo.
Successfully added 'Common.Logging 2.1.2' to HangfireDemo.
Adding 'ncrontab 1.0.0' to HangfireDemo.
Successfully added 'ncrontab 1.0.0' to HangfireDemo.
Adding 'HangFire.Core 0.9.1' to HangfireDemo.
Successfully added 'HangFire.Core 0.9.1' to HangfireDemo.
Adding 'Dapper 1.13' to HangfireDemo.
Successfully added 'Dapper 1.13' to HangfireDemo.
Adding 'HangFire.SqlServer 0.9.1' to HangfireDemo.
Successfully added 'HangFire.SqlServer 0.9.1' to HangfireDemo.
Adding 'CronExpressionDescriptor 1.10.1' to HangfireDemo.
Successfully added 'CronExpressionDescriptor 1.10.1' to HangfireDemo.
Adding 'WebActivatorEx 2.0.1' to HangfireDemo.
Successfully added 'WebActivatorEx 2.0.1' to HangfireDemo.
Adding 'HangFire.Web 0.9.1' to HangfireDemo.
Successfully added 'HangFire.Web 0.9.1' to HangfireDemo.
Adding 'HangFire 0.9.1' to HangfireDemo.
Successfully added 'HangFire 0.9.1' to HangfireDemo.

I am using HangFire with ASP.NET MVC application. Here are the few things that you need to configure before you dive in. When installing HangFire via NuGet, it adds HangFireConfig.cs under App_Start folder. HangFire supports Redis, SQL Server, SQL Azure or MSMQ. I am using SQL Server in this demo. The reason we require this storage because it is being used by the HangFire monitor to display the real-time data of the jobs. To configure HangFire to use SQL Server, open HangFireConfig.cs file and change the connection string as per your SQL Server installation.

JobStorage.Current = new SqlServerStorage(
    @"Server=GHOST\SERVER; Database=Jobs;user id=sa; password=pass#w0rd1;");

When the application first starts, all required database objects are created. 

You can find the scripts inside the downloaded package HangFire.SqlServer.0.9.1\Tools\install.sql. The jobs and monitor will be using this database to show me the real-time status of the jobs running in the background. To view the HangFire monitor, simply navigate to http://<sitename>/hangfire.axd. As it is a handler, you can see it in your web.config file. Let's see it in action:

The navigation pane on the right, lets you see the jobs and their status. It let's you even see the queues which are currently running. 

Scheduling the Jobs

Scheduling jobs using HangFire is easier then I thought it would be. Talking about the same example from my blog which sends email in my inbox when a new comment is added. If I want to schedule the mail send process as a background job I can do it easily using the BackgroundJob class.

bool commentSave = _db.AddComment(comment);
if (commentSave)
{
    BackgroundJob.Enqueue(() => BlogEmail.SendEmail(comment));
    return Json(new { message = "Thanks for your comment. The comment is now awaiting moderation" });
}
else
    return Json(new { message = "There is an error while saving comment. Please try again later" });

As I require it to run only once I just have queue it using the BackgroundJob.Enqueue() method. I can also delay the execution of the job using the Schedule method of the BackgroundJob class.

bool commentSave = _db.AddComment(comment);
if (commentSave)
{
    BackgroundJob.Schedule(() => BlogEmail.SendEmail(comment), TimeSpan.FromMinutes(60));
    return Json(new { message = "Thanks for your comment. The comment is now awaiting moderation" });
}
else
    return Json(new { message = "There is an error while saving comment. Please try again later" });

What if the email sending is failed? The SendMail method throws an exception that the mail sending is failed. HangFire will handle this by default and it will retry automatically 3 more times after a consecutive delay after each retry. But if I want to retry it more than 3 times then I can make use of the AutomaticRetry attribute and pass the number of retries I want, something like this:

[AutomaticRetry(Attempts = 5)]
public bool SendEmail(Comment comment)
{
    //Email code
}

Let's say if I do have another method that I want to run every minute (it's an overkill for my blog) then I will make use of RecurringJob class.

RecurringJob.AddOrUpdate(() => Storage.PunchIt(), Cron.Minutely);

Cron enum allows me to schedule a job daily, weekly, monthly, yearly, hourly and minutely. Now as my job is schedule in the background, time to take a look at HangFire monitor.

I have no idea why my Recurring Jobs screen is showing Next and Last execution time as 44 years ago. But you can see the Succeeded Jobs with a minute interval (#5 and #4). HangFire uses persistent storage and therefore you can trigger the job at your will or remove it when you feel like it. That means you configure the job in the code and manage it from the HangFire monitor.

What else you can do with HangFire

I just showed you how easy it can be scheduling jobs using HangFire. But there are more advanced topics which you should be looking into for more complex implementation. HangFire supports logging, dependency injection using Ninject, multiple queue processing and more.

References

Currently rated 3.3 by 6 people

MSDN Style Syntax Highlighting In ASP.NET

30. June 2013 01:03

ASP.NET 

There are many syntax highlighting plugins available on the web right now. Majority of the sites are using javascript based Syntax Highlighter from Alex Gorbatchev. I am using it for my current blog and BlogEngine.NET has it as a default syntax highlighter. It is good because it has a lot of themes to offer and you can also customize according to the look and feel of your blog or site. Moreover it has support for multiple languages which makes it acceptable among most of the bloggers and developers.

I also like the way MSDN and Codeplex style their code. Although it has some flaws like moving the code to the next line if it exceeds the length of the pre or div tags. The library MSDN and Codeplex are using for syntax highlighting is ColorCode. ColorCode is open-source and supports every language specific to Microsoft. The way ColorCode works is totally different than that of any other syntax highlighting library. Javascript based syntax highlighter use CSS for different styles whereas ColorCode uses in-line CSS to  set styling for the code.

To install ColorCode you can use NuGet command or add ColorCode reference as a library downloadable from Codeplex. NuGet command:

PM> Install-Package ColorCode

Only Microsoft stack languages are supported by ColorCode. Here is the complete list:

  • XML
  • Java
  • JavaScript
  • SQL
  • C#
  • VB.NET
  • ASPX (C#)
  • ASPX (VB.NET)
  • C++
  • PHP
  • PowerShell
  • Typescript
  • FSharp

As I mentioned earlier that this library uses in-line CSS and therefore you cannot use it in the windows forms application. You can use the webbrowser control in windows forms application if you want code to render correctly.

This is a sample basic usage of ColorCode.

string code = File.ReadAllText(Server.MapPath("~/Test.txt"));
string finalCode = new CodeColorizer().Colorize(code, Languages.CSharp);
codediv.InnerHtml = finalCode;

First line of the code will read all the text from a file. The second line will initialize a new CodeColorizer class Colorize method which will take 2 parameters, first is the code for which we want the syntax highlighting for and the second parameter is language. I now have the finalCode string which has the code with syntax highlighting. This is the output I have in my browser window.

It looks pretty good from the front but behind the scenes it’s not that pretty.

ColorCode is an open-source library and is hosted on Codeplex.

Reference:

 No Rating