DucDigital for ( $girl = 1; $girl < $required; $girl++ ) { echo “I love DucDigital”; }

14Jan/100

Cache individual object in asp.net mvc

Upon writing a controller for exporting image on the fly, I struggled with the problem that: "Output cache does not cache HttpHeader (in this case, "Location" header)". Which lead me to despair since each time i called the controller to output image, it will have to connect to database and do a couple of query, which is not practical in real life. So finally, i found out that i can easily cache objects into a cache provider in Asp.net Mvc. Very useful, all my queries go back to 0 (traced through Ling2sql profiler).

You can use this piece of code in anywhere of your code where you want to cache any object.
(Notice: this code was used in a controller, so I used HttpContext.Cache. But if you use else where that make this code not working, try HttpContext.Current.Cache)

1
2
3
4
5
6
7
8
9
10
            if (HttpContext.Cache["ObjName"] != null)
            {
                link = (string)HttpContext.Cache["ObjName"];
                return link;
            }
            else
            {
                HttpContext.Cache.Add("ObjName", link, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(30, 0, 0, 0, 0), System.Web.Caching.CacheItemPriority.High, null);
                return link;
            }

What it did was to check if the ObjName exist in the context, if not, create one and dump the data into it. Remember when you call back from HttpContext, it's an object so you always need a cast. If you don't know about argument, let the intellisense do the work for you.

Time to exand further about the topic: HttpContext.Cache.Add

  • Share/Bookmark
24Dec/090

Builtin Async Controller in ASP.net MVC 2

Well, it's Christmas Eve at the time I post this post in my place. I hope you enjoy your Christmas with your family and happy new year to all of you who read this post of mine.

------------------------

One thing that make me feel more powerful when using ASP.net MVC is the newly introduce Asynchronous Controller Action.

Imagine, you have a front page with multiple widget, like news, weather, personal information, new forum thread etc... You are going to run it from top to bottom, query, query... Your basic solution for this is to query news first since it's kinda important, then weather, etc...

Why it's not a good solution? Because if you going to query everything like that, your program need to wait for each query to finish before continue to work with the code behind...

Better Solution? I could suggest you using Async Controller in this case. Separate each query into different Data Context, query to the database, Close Current Data Context, and process the info with code behind, separately and process at the same time. This helps you bring down processing time twice or thrice as fast than the normal approach...

Asynchronous Process has been introduce to ASP.net long before, but now, apply it to asp.net MVC even easier than what you really expect.

  • Inherit to "AsyncController" instead of "Controller" class
  • Write async method
  • Write Complete method
  • Write functions to handle async request

First step:

Look out for the head of your controller, you will always see this:

public class MyController : Controller

change it to:

public class MyController : AsyncController

Don't worry because everything will work just as normal even if you don't use AsyncController.

2nd Step, write the MethodAsync and MethodCompleted. The important is the prefix in this case, Async and Completed.

  • Method is the action name, like Create, Delete, Details
  • Async is in Void type, and everything request first will come to this void method, you can get the input from form, url here in this method. Async will pass parameter to Completed using AsyncManager.Parameters that you can see later in this article
  • Completed is an ActionResult method. just like your normal Create, Delete action. You can return a View or RedirectResult here. The param of this method corresponding to the AsyncManager.Parameter that was used in MethodAsync
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 
// Http://local/Controller/Method/
// As you can see i am using the attribute that can be use in the normal Actions
[AcceptVerbs(HttpVerbs.Post), ActionName("Method")]
 
public void MethodAsync(int id, string hello) {
 
	// This Increment() use to identify how many async process are there, 
	// once everything is back to 0, MethodCompleted is fire-up
 
	AsyncManager.OutstandingOperations.Increment();
 
	// This used to handle functions that are not Async Ready
    // since they don't have any async event ready.
	// using this you can start with any method.
 
	// the first int, string is the parameter data type, the last bool is the return type.
	// DoTestAsync is the method name that we going to write later on
 
    Func<int , string, bool> doTestHandler = DoTestAsync;
 
	// Begin async
	// ID, Hello is the param passing to method DoTestAsync
    doTestHandler.BeginInvoke(id, hello, ar =>
    {
 
        var handler = (Func</int><int , string, bool>)ar.AsyncState;
 
		// AsyncManager.Parameters["returned"] now cantaining the result of 
		// method DoTestAsync after finish the process. The datatype is bool.
        AsyncManager.Parameters["returned"] = handler.EndInvoke(ar);
 
        AsyncManager.OutstandingOperations.Decrement();
    }, doTagHandler);
}
 
// This will process after the Async finished. The param of
// this method is what we have used with AsyncManager.Parameters,
// in this case, returned with type bool
public ActionResult MethodCompleted(bool returned)
{
	// You can actually make use of the param here to make some ViewData or something
	returned = !returned;
 
    // Since it's a ActionResult, i must return a View or something related.
	// return View(); -> will use the default view (Controller\Method.aspx)
 
	// i want to show some Content:
	return Content(returned.ToString());
 
}
 
// Now we will write the method for our async controller 
public bool DoTestAsync(int a, string b)
{
	// Everything you need to do with the param in here, 
	// include query to your database or anything you can
	// posibly think of. For me, i will just return something.
 
	return true;
}
</int>

The result of this is:

"False"

Isn't it simple, what you need is just to follow this and there you go, you can now have a Web application that run twice or thrice as fast.

Good luck...

  • Share/Bookmark