How to write to Windows Azure Website’s application log and more

We struggled with Windows Azure website because we couldn’t write logs. Using Log4Net to write to log file as we used to do, does not work for Azure Website because of the limited file permission. We had to resort to email notification or Virtual Machine when we needed to debug Azure Websites, which was a big headache!

Fortunately, it is all over now. To write to the Application Log of Azure Website, just use System.Diagnostics.Trace name space and use method like TraceInformation, TraceError, TraceWarning to record different levels of log!


Trace.Wrietline("Log Verbose level log");

Trace.TraceInformation ("Log Information level log");

Trace.TraceWarning("Log Warning level log");

Trace.TraceError("Log Error level log");

Then just turn on the Application Logging and select a logging level for that Azure Website.

4-16-2015 5-41-11 PM

With this feature, it becomes much easier to troubleshoot Azure websites. Even better, Microsoft provides this streaming log function from which you can view application logs in REAL-TIME! (New Azure portal only)

4-16-2015 5-29-27 PM

Furthermore, here is something developers will definitely like – this streaming log is also available in Visual Studio, and you can filter the result using Regular Expression! (Latest version Azure SDK is required)

4-16-2015 5-33-57 PM

4-16-2015 5-36-13 PM

Since file logging is supposed to be turned off automatically after 12 hours, if you also want to log into a table storage, not a problem. You can set up a Azure Storage to hold the log.

4-16-2015 5-42-41 PM

Click View settings of the Azure Website in Visual Studio.  In the Log tab, there  will  be a nice table view of the log. I do notice that it uses a lot of memory of the Azure Website. Just something to consider.

4-16-2015 5-43-48 PM

That’s what I know about logging to Azure Websites. Hopefully it is helpful. We use Azure on most of our web applications and I think it is just getting better everyday. Now with the ability to write application log for Azure Website, it just meets all of our needs, but there is still a huge set of exciting features we haven’t used. I look forward to exploring those someday!

Avoid client timeout on WebAPI call

If a WebAPI service takes a long time to complete, the caller, the client side, may timeout waiting for a response. There are several options to solve this issue, you can increase the timeout limit on the client side and web server side, or use a more persistent connection method like WebSocket and SignalR.

Here I propose a different way to avoid the timeout issue that allows the clients side to proactively check the result instead of passively waiting. The idea is pretty intuitive – since the client side times out on waiting for a response, why don’t just disconnect and check back the result later? So the solution is to disconnect with the client side as soon as the request is received and a WebAPI service is provided to enable client to check for the status of the processing. This way the client does not need to keep the connection open until the processing completes or times out. It can simply calls back every 5 seconds to check the result of the processing.

Here I am going to provide some sample code on how to achieve this. First, we create a Task class

public class Task
{
   public string TaskID;
   public Request Request;
   public Status Status;
   public Result Result;

   public void Execute(){
   // Do all sort of calculation and processing here
   // When done, sets the Status of the task to Finished.
   }
}

We then create a class to store tasks and to handle creation, retrieval, and deletion of tasks.

public class TaskManager
{
   private static List<Task> _TaskList = new List<Task>();
   // Create a new instance of Task object
   // and start a new thread to run this task
   public static Result CreateNewTask(Request request){
      var task = New Task(){
                TaskID =  System.Guid.NewGuid().ToString();
                .....
                };
      _TaskList.add(task);
      Thread thread = new Thread(task.Execute);
      task.Status = Status.Processing
      thread.start;
   }
   // This is also useful for purging tasks
   public static void RemoveTask(string taskID)
   public static Task GetTaskByID(string taskID)
}

Up to this point, we have our ‘backend’ built. Now we are going to create a WebAPI method to accept the request from the client side and a method for client side to check a task’s status:

[HttpPost]
public Result ProcessRequest(Request request){
// Submit a request which will be created as a task
// Return the TaskID back to client
}

[HttpGet]
public Result CheckStatus(String taskID){
// Call this every few seconds to check result
}

In this post I shared an idea to avoid client side timeout when calling WebAPI. We chose an approach that enables client side to check the result actively. Although it makes the client side a bit more complex, it is a reliable way to handle WebAPI calls that run a long time and also provides much more flexibility to the client side.

How to use soapUI 5.0 to post JSON to REST Service

I wrote an article on the same topic but with version 4.5.1 soapUI back in 2013. To post JSON with an 4.5.1 version soapUI, you almost have to trick the application by explicitly typing in the media type ‘application/json’, and there are also a few settings that don’t really make sense. I’ve always forgotten the steps and had to go back to check my blog post.

Since then I have tried a couple of newer versions of soapUI for the same task, hoping it got more intuitive, but eventually I stuck with the 4.5.1 version because I didn’t see much improvement in those versions. Today I get my hands on the latest 5.0 version of the tool. Still free, great!
First, I crate a new SOAP project. The ‘Opens dialog to create REST Service’ option is gone. OK. It is already simpler from the first step.
1

Now my project is created, I right click the project and select New REST Service from URI.

2

In the popup window, I put in the service endpoint where I am going to post my JSON to.

3

BOOM! It creates everything for me. No need to provide a Service Name, Parameter Name, or Method Name, everything is extracted from the endpoint provided. This is a great UI design because if out of nowhere it asks the user to provide a Service Name, she will be confused – What is the Service Name for?

4

It also automatically opens up Request1 where you can see it by default selects GET method.

5

I changed the Method to POST. It selects the correct Media Type for JSON posting. Just type in your JSON body and click the green arrow on the left top corner to post.

6

I am impressed by how easy the process becomes and glad that the development team is putting efforts on improving user experience, even though it is already a well-functional application. User experience is really a big part of software. A good UX can really change your life!

Use System.Windows.Forms.WebBrowser in a ASP.NET web application

There are certain scenarios where you would need to use some windows control in your web application server side. Taking a snapshot of a URL/web page is an example where you would need to use Windows.Forms.WebBrowser control to load up a URL/HTML and save the page to a Bitmap. However you may receive an error saying: ActiveX control ‘8856f961-340a-11d0-a96b-00c04fd705a2’ cannot be instantiated because the current thread is not in a single-threaded apartment.

This is because by default ASP.NET web application runs in Multi-Thread Apartment (MTA) mode, but WebBrowser control object is required to run in Single-Threaded Apartment (STA) mode as it does not handle its own threads synchronization, thus not thread safe.

Adding AspCompat=”true” to the page directive will force ASP.NET request thread to be in STA mode thus share a single thread with the COM object, e.g. WebBorwser control, it creates, and effectively resolve our issue:

<%@ Page AspCompat="true" Language="C#" %>

These links explain the concepts better than I do:
COM Component Compatibility
How to use System.Windows.Forms.WebBrowser in a web app?
What does AspCompat=”true” mean and when should I use it?

Session state is not available in this context

Who would know that HttpApplication.Session returns an null exception when the session is null, whereas HttpContext.Current.Session returns null when the session is null?

I have this ASP.NET MVC application that checks session status in Application_AcquireRequestState handler. If a session is a newly created session and a cookie containing session id has been included in the request header, the codes sign the user out (because the user’s session has expired).

The problem is that before checking whether the user’s session is a new session, I need to make sure that the session is not null. When doing this I first attempted using this.Session which is originally from base class HttpApplication.

 if (Session != null && Session.IsNewSession)

However, when later I deployed it to client’s environment I noticed that there were many Session state is not available in this context error thrown out. I also noticed an interesting thing – when Debug mode is on, the error is not being thrown out. Which is partly why I didn’t encounter this when development. However, this behavior seems not consistent – Today when I tested the same piece of code in a different environment, the same exception got thrown out only when in Debug mode.

So this issue can occur depends on the environment. What’s going on and what do we do?

The answer is – use HttpContext.Current.Session instead.

It turns out that the implementation of HttpApplication.Session will throw an exception when the session is null. So basically you cannot even check its value like what I did. According to an answer from Stackoverflow, the implementation is something like this:

[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public HttpSessionState Session
{
get
{
HttpSessionState session = null;

if (this._session != null)
{
session = this._session;
}
else if (this._context != null)
{
session = this._context.Session;
}

if (session == null)
{
throw new HttpException(SR.GetString("Session_not_available"));
}

return session;
}
}