Global.asax

Global.asax is a global event handling file in App_Start folder.  This file is read first, and you can specify events and actions at app level.

When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed. It completes all current requests for the application, sends the Application_OnEnd event to any listeners, and restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework reparses and recompiles the Global.asax file and raises the Application_OnStart event.

https://msdn.microsoft.com/en-us/library/1xaas8a2(v=vs.71).aspx

 

Join (Include) two or more models

You have a model which defines book, and another model which defines author of the book.  How do you link them show in one table at the view?  Here is how.

suppose you have models define like below;

How to compose Linq that join these two together so it shows, Book ID, Title, Author Name?

The answer is, Use .include to include the model within.

 

Done.

Adding WebAPI to your current MVC Project

Started off as regular web site in MVC, later you want to add Web API to the same project?  You can simply add Web API controllers, but to make it work you have to do few more steps.

inside your Global.asax, you have to make reference to System.Web.Http and also add  GlobalConfiguration.Configure(WebApiConfig.Register)

This should take care of API request routing properly and good to go.

Iko puts it all well at http://stackoverflow.com/questions/26067296/how-to-add-web-api-to-an-existing-asp-net-mvc-5-web-application-project

Migration, Code First Database (EF)

When you are developing your web service, and working with your data set, often you need to make modification to your data set, and definition of your data set.  We can simply initialize (aka, delete and start clean) or migrate to continue on with data you have.

There are two types of migration Automatic Migration and C0de-Based Migration.  I am a lazy guy and I typically choose Automatic Migration, but I do come across situation where I have to run Code-Base migration, so I ll cover both here.

First you have to enable migration. Go to package manager console and run,

Then you should see something like;

Now you should see Migration folder being created, and we check Configuration.cs within that folder.  Then we will edit value for AutomaticMigrationEnabled to true to enable Automatic Migration.

Then we just run command below to let them automatically update whatever and however they want.

 

Next, I will cover the manual migration process.

You can also refer to ; https://msdn.microsoft.com/en-us/data/jj591621.

Working on Custom Domain Name with Azure

When you make web app on Azure, it comes with yourname.azurewebsites.net , and if it’s demo site or for internal use, that’s fine as is.  But most of the time when you want to run your own web services you want to have your own domain names, and that’s what I cover today.

Now you can buy domain name from Azure and that may be the easiest way to map custom domain to your web app.

But, I have already purchase domain elsewhere, and your company may already have domain name.  Then we will need to work with DNS record to point domain name to appropriate place within Azure. (DNS, as a function, uses data records table and map domain name to IP addresses.)

Each DNS server provide different ways to edit, create record, so I will skip that part.

DNS has several record types, but for now, we just worry about A and CNAME record types.

To set A record, you need IP address of your web app.  I somehow came across bug?? with new Azure management portal site and had to use old portal in order to get IP address, and here is how;

Use this URL: https://manage.windowsazure.com/

and continue to ignore new Azure Portal links, and move to Configure > domain names, then manage domains, there you should see the IP address for you to use for your A type record.

I don’t know if it’s my environment or bug at new Azure management portal, but I ll just go with whatever works, for sake of saving my time.

After setting A name for your root domain, www for your CNAME (or whatever you desire), wait for 5-10 minutes, then you should be good to go.

 

Using Facebook Login to Registger

Registration is VERY important part of function in all web services.  ASP.Net come with great and easy way to register and manage registered users accounts.  Yet, using third party authentication system like Facebook, Twitter, Microsoft, Google, Linkedin accounts can even make the registration process easier.

Facebook has about 1.5 billion monthly active users (http://newsroom.fb.com/company-info/) as of Sep 2015, what would be the reason to not use such popular web service’s authentication system.

When you create project in ASP.Net in Visual Studio, and choose “individual authentication”, you get a set of code there to easily implement Facebook login.   You can refer to this document on how to to turn on Facebook, Twitter, Microsoft, Google login integration. http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on.

The built in third party authentication logic is OK, but I want to make it better (for me), fetch profile information and put that into my own table.

Continue reading “Using Facebook Login to Registger”

Using Filter

Filters are things you can do before or after the actual executable actions.

The order of filter goes like this,

IAuthenticationFilter > IAuthorizationFilter > iActionFilter > IResultFilter

and if during Action, exception occur then IExceptionFilter

You can set filter at web.config or by having bracket at the top of classes.

IExceptionFilter

One of the main attribute in IExceptionFilter is HandleError Attribute.  Here we want to tell the system what we want do when exception occurs.  (we want to tell what to do when an error happens.)

Custom Errors

You can do display error  page with detail message, with out much of message,  or redirect to custom page when the error occurs.

Usually you will choose RemoteOnly option, which is to display detail error message at local environment and hide detail error message at online environment.

I will cover about handling error more later.  I just let you know IExceptionFilter is here.

Handling Cache

You can specify how to use cache by having [OoutputCache(duration=240)] at the head of classes.  Or at Web.Config

You have create profile at Web.Config then you can use them like

When using partial views, you can specify cache rules to partial view only or both partial and main view.

Controller

View

 

and more to be continued.

ActionResult

ActionResult is an object used in ASP.Net MVC.  ActionResult returns or passes things like ViewResult to views and many more.

If you simply want to return view then

If you want to redirect user to other url

If you want to redirect user to another action

If you want to add some parameters to the action

If you just need to return https status code result, you can also use (include System.Web.Mvc).  Check https://msdn.microsoft.com/en-us/library/system.web.mvc.httpstatuscoderesult(v=vs.118).aspx for more detail.

There are more in HttpStatusCode, and you can return more precise and appropriate status code to the user;

  • Member – Status Code
  • OK – 200
  • Created – 201
  • MovedPermanently – 301
  • Found – 302
  • SeeOther – 303
  • BadRequest – 400
  • Unauthorized – 401
  • Forbidden – 403
  • NotFound – 404
  • MethodNotAllowed – 405
  • InternalServerError – 500

I haven’t use this myself, but you can return nothing too

You can also simply return contents like text

I ll introduce more about later.

 

Mastering Azure DocumentDB Part 1

If you are looking for a full coverage of DocumentDB and developing web services based on DocumentDB in ASP.Net C# MVC, you have come to the right place. well, almost, working on it.


Index

  • What is DocumentDB
  • Pricing
  • Using DocumentDB
    • Getting Started with .Net SDK
    • CRUD of Database
    • CRUD of Collection

 

What is DocumentDB

DocumentDB is the NoSQL database service from Azure.

DocumentDB is native in JSON, means you can post JSON format data and be able to query them like SQL.  This is convenient in modern web services, because the service is not tied to previously defined data schema, which has been a headache for all web service developers, because the service needs ever improvement and that often means data schema changes.

DocumentDB  is configurable to scale linearly.  This is important concept so I ll cover this fully later.

DocumentDB is manageable via REST API, or can be managed from SDK for JavaScript, Java, Node.js, Python and .Net. But I ll be covering SDK for .Net first.


Pricing

Pricing is applicable at collection level and charged per hour. (What is collection? I ll get to that later) There are 3 tiers, all same storage capacity, difference is how much request units they can handle per second.  Request unit is basically a transaction of the database.

  • S1 250 request unit / sec reserved and  $0.039 per hour (that is up to $29 per month)
  • S2 1,000 request unit / sec reserved and $0.076 per hour (that is up to $57 per month)
  • S3 2,500 request unit / sec reserved  and $0.154 per hour (that is up to $114 per month)

This sounds pretty reasonable for me.  Please be sure to refer to limitation of DocumentDB when you choose your service grade.


 

Using DocumentDB

In DocumentDB, there are 3 layers of structures

  • Database
  • Collection
  • Document

What are all these means?  Don’t worry about details for now-now, but these are containers and how each object exist within.  And I ll talk more about what each of these containers are and mean.


 

Getting Start with .Net SDK

I will be using SDK first, so ., once you create ASP.Net MVC project, the first step is to download SDK. You can nuget it or get it from github (https://github.com/Azure/azure-documentdb-dotnet).  You can also do same by calling REST API, but I will cover that when I use DocumentDB with other programming language later.


The top level container of DocumentDB is database.  So, first, let’s go over CRUD of database.

CRUD of Database

When you work with DocumentDB you need end-point URI and authorized key code.  I will store these values into my Web.config file like below.

If you already know which database to work with, you can also store database name to make your life simpler and easier.

Get A List of Databases

Controller

View

And now you should list of database you have in the account like below.

スクリーンショット_013116_064600_PM

I currently have one in my account already.  Let’s add another one and see.

Create Database

Database is simply a container of JSON document, with capability to have user access logic built in.  If you want to have different user access level at server side, then you can have separate that database and create collections within.  Creating database is free but you can only make up to 100 databases per account.  (see more at limitation of DocumentDB)

Controllers

View

This is what it looks like at input interface.

スクリーンショット_020116_124451_AM

After I run and create database, I am redirected to the list of existing databases and see SandBagDatabase which is database I just added. Super.

スクリーンショット_020116_125044_AM


Now that you can view and add databases, let’s take a look at collections.  Which is one below level container of DocumentDB Databases. Collection is where Azure charges and can choose performance levels and more.

CRUD of Collection

Get A List of Collections

List of collection can be obtained from building CollectionQuery (CreateDocumentCollectionQuery) and running it. That is;

I am totally trusting that databaseName which is passed variable to be rigid, but I may want to think about that later.

Controller

View

Right now I don’t have any collection so I should see nothing like below;

スクリーンショット_020116_020826_AM

Creating Collection

Now let’s create collection and see.

Controller

View

The input interface looks like below;

スクリーンショット_020116_111757_AM

After I type in collection name and click on Create Collection button, now I see new collection being added properly. Super!

スクリーンショット_020116_112448_AM

 

Please continue on to part 2 for reading more about working with Documents.

FormExtentions

Mastering form extension is very important because when you are writing modern web services, almost always you will be using form extension to take input from users.  You will be using form extensions frequently for ever, so better master this first.

You can refer to full class documentation here.
https://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(v=vs.118).aspx

The basic form is like this

which generate html code like below

We usually have two types of forms, one that link to the model and one that is not link to the model.

We will look more into how you can build model that work well with forms later.