Schubert's Blog

A biker and technology enthusiast's
view of the world

Returning JSON result in ASP.Net MVC 2

One ASP.Net MVC feature that I discovered and took full advantage of, whilst building Beta 2 was the ease with which JSON result could be returned for a web request.

It is as simple as calling the JSON function from the inherited Mvc.Controller class. The first parameter is the object or list of objects you would like to return in your JSON result. The second parameter is optional, but I had to set it to JsonRequestBehavior.AllowGet. This is because of the way GET request are secured in ASP.Net MVC 2. My final server side code to return events using JSON looked like:

//The parameters are as following:
//mo = mode, this can be 3 or 10. 3 returns short descriptions for the top 3 events,
// 10 returns a more detailed description of the first 10 events and supports paging
//y = year the user would like to find event in
//m = month
//d = day
//ctry = country
//reg = region
//cty = city
//pg = page number, this is obtained via the requested query string in code

public ActionResult GetJson(int mo, int y, int m, int d, string ctry,
string reg, string cty)
//Taking care of paging request
int pageNo = 0;
if (mo != 10)
//If the mode is not 10, set page number to 0
pageNo = 0;
//Getting page number from the requested query string
// and setting it to a safe value for later use
if (int.TryParse(Request.QueryString.Get("pg"), out pageNo))
pageNo = pageNo > 0 ? pageNo - 1 : 0;

//Create an instance of the Business logic class
BlEvents = new BlEvents();

//Returning JSON results based on the mode
case 10:
var shortResults = BlEvents.GetTop3Events(y, m, d, ctry, reg, cty);
return Json(shortResults, JsonRequestBehavior.AllowGet);
case 3:
var extResults = BlEvents.GetPagedEvents(y, m, d, ctry, reg, cty, pageNo);
return Json(extResults, JsonRequestBehavior.AllowGet);

The end result, two types of JSON results. The first url return the top 3 events with a short description for the 23 of August 2010 and the second url returns the top 10 events with a longer description and other fields for the 31 of September 2010. The last entry always has the Id set to 0, the Title to "Powered by". And the short description is set to the number of events that has for that date, useful for other website and users to making paged JSON request.

In the previous blog entry, I've discuss using TSQL with no lock. An insight I've used to performance tune the TSQL queries behind these JSON calls. In a future blog, I'll discusses how I've use JQuery to request and present these JSON reponses in the browser.

By Schubert on 03 January 2011 12:42

Categories: Development | Tags: , , , ,

Permalink | Comments (0)

Submit to DotNetKicks...

TSQL optimzation tricks

A question at the back of most System Architects and Enterprise Application Developer's mind is; will my software or website cope with the number of requests as it's user base grows?

One way I've optimized is by use NOLOCK in my select queries. Using NOLOCK politely asks MSSQL Server to ignore locks and read directly from the tables. This means you completely circumvent the lock system, which is a major performance and scalability improvement. However, using NOLOCK also means the code is reading data that might be partially written or in the process of being updated. On since the data is not critical, the user will see event data that is out of sync with the information in the database. If this were a banking or financial system, I would recommend using page or row level locks, depend on the number of rows being read and written.

Another optimization trick I've used is to page the data on the database server and only return page size of rows back, which can be 10, 20 or 50 rows. This not only reduces network bandwith between the web and database server, it also reduces stress and memory usage on the web server. This way the web server does not need to process large quanities of data for each database request and land up using only 10 or 20 rows of the 100 or so that get returned. Although it does introduce some stress on the database server and this subject is not a well covered subject on the internet, so tread carefully.

This is how most of Beta 2's search queries look like:

ALTER PROCEDURE [dbo].[ListEventsByKeywords] 
	-- Add the parameters for the stored procedure here
	@Keywords nvarchar(100) = '',
	@Year int,
	@Month int,
	@Day int,
	@PageNo int,
	@PageSize int
	SELECT [t1].*
desc, el.[Id]) AS [ROW_NUMBER], el.*
  FROM Events el WITH(NOLOCK) Where el.IsDeleted = 0 AND el.IsSuspended = 0 AND el.Status = 1 AND DATEPART(Year,el.StartTime) = @Year AND DATEPART(Month,el.StartTime) = @Month AND DATEPART(Day,el.StartTime) = @Day ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN (@PageNo * @PageSize) + 1
AND (@PageNo * @PageSize) + @PageSize ORDER BY [t1].[ROW_NUMBER] END END

I would like to hear the opinion of database programmers about the above tsql and how they go about returning only a subset of required rows, instead of returning 100+ result rows and leaving the web developer with the task of only showing 10 or 20 at a time to the user.

By Schubert on 05 December 2010 14:43

Categories: Database | Tags: ,

Permalink | Comments (0)

Submit to DotNetKicks...

CSS Getting links to look like buttons

On, I've had places where I wanted to give the user a HTML link and a button, side-by-side, but they look nothing alike. For example, at the bottom of the 'Create a New Event' page, the user can click a link that took them back to their home page or a button to add a new event. Although, through the magic of CSS, it is possible to get the both of them to look identical. In Beta 1, I let this be, but, in Beta 2, I had to find a way to improve the overall page and website appeal and this was one of the major changes.

A normal HTML link tag looks like

<a href="/">Back to Home page</a>

and a button tag looks like

<button type="button">Add an event</button>

giving us:

Back to Home page

Now, for some CSS. Start by adding a border of 1 pixel, solid black to the style attribute of both the link and button. This will give both the tags a border and make them look like a custom styled button. This giving us:

Back to Home page

Then add a color value to both the style attributes. This will give the text in both the link and button the same color. I'll use hex codes #034AF3, as this is one of the primary colors of the Beta 2 color scheme. This gives us:

Back to Home page

Next give the link and buttons padding, so that they fill up and the border is not sticking to the text. I've used 5 pixels all round. This give us:

Back to Home page

Finally, give the both of them a background color, I've used white. On the link remove the text decoration. And on the button, set the cursor type to pointer, this will give the user a pointer icon when they hover over the button. And I had to set the font size to 1em to get the button to size up, this might not be necessary and depends on the site design. All Done! The final button and link look like:

Back to Home page

And the final markup for the link tag looks like:

<a href="/" 
style="border: 1px solid black;
color: #034af3;
padding: 5px;
background-color: #ffffff;
text-decoration: none;"
>Back to Home page</a>

and the button looks like

<button type="button" 
style="border: 1px solid black;
color: #034af3;
padding: 5px;
background-color: #ffffff;
font-size: 1em;
cursor: pointer;"
>Add an event</button>

Even though I've used the style attribute here, on a professional site I would recommend using the class tag and move all the styles into a CSS file. Usually followed by using a tool like CSSTidy to clean and compress the CSS file. I'm always open to hearing suggestion, on how to make CSS more effective and cross-browser complaint. Look forward to hearing from some design gurus and novices like myself.

By Schubert on 05 September 2010 12:43

Categories: Designing | Tags: , ,

Permalink | Comments (0)

Submit to DotNetKicks... and TDD & Mocks Part 2

In this blog entry I present two of the four test cases I've used to test the base business logic class from Beta 1. I've used the NUnit testing framework, as it was the simplest to implement with Visual Web Developer 2008. And Rhino Mock to pass in fake anonymous and logged in users to the base class. The code for the base class being tested here, is covered in the previous blog, so head over there if you haven't read it yet. On with the testing, first create fake accounts:

public class BlBaseText
//Faking a normal user account
Mock<IIdentity> FakeLoggedInSpereIIdentity;
//Faking an admin account
  Mock<IIdentity> FakeLoggedInMapzeAdminIIdentity;
//Faking an anonmymous account
  Mock<IIdentity> FakeAnonIIdentity;

In the NUnit setup function, I initialze the fake accounts.

[TestFixtureSetUp] public void Setup() { //Setting up the user account SPere
FakeLoggedInSpereIIdentity = new Mock<IIdentity>(); FakeLoggedInSpereIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable(); FakeLoggedInSpereIIdentity.Setup(i => i.Name).Returns("SPere").Verifiable(); //Setting up the admin account MapzeAdmin
FakeLoggedInMapzeAdminIIdentity = new Mock<IIdentity>(); FakeLoggedInMapzeAdminIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable(); FakeLoggedInMapzeAdminIIdentity.Setup(i => i.Name).Returns("MapzeAdmin").Verifiable(); //Setting up the anonymous account
FakeAnonIIdentity = new Mock<IIdentity>(); FakeAnonIIdentity.Setup(i => i.IsAuthenticated).Returns(false).Verifiable(); FakeAnonIIdentity.Setup(i => i.Name).Returns("").Verifiable(); }

Now that we have fake accounts, we can go ahead and setup the acutal test. The four test cases are:

1. The user is authenticated and their username exist in the database. This is the normal scenario and should be the case 90% of the time.

public void ConstructorTest_UserIsAuthenticateAndValidUserName() { //Inject the fake user SPere
BlBase.FakeIIdentity = FakeLoggedInSpereIIdentity.Object; //The MVC state dictionary to store error and messages
ModelStateDictionary dictionary = new ModelStateDictionary(); //Initialise the base business logic class
BlBase blbase = new BlBase(dictionary, new L2SUserService()); //Make sure the current user variable is an instance of the IUser interface
Assert.IsInstanceOf<IUser>(blbase.currentUser); //Make sure the current user id is 1
Assert.AreEqual(1, blbase.currentUser.Id); //Make sure the user name is "SPere"
Assert.AreEqual("SPere", blbase.currentUser.UserName); //And finally make sure there were no errors or messages
Assert.AreEqual(0, dictionary.Count); }

2. The user is authenticated but the username does not exist in the database. Most likely cause of this is the user delete their account, but their authentication cookie is still valid as they were not logged out.

[Test] public void ConstructorTest_IsAuthenticateAndNotValidUserName() { //Create a fake account "NotValidUsername"
var FakeIIdentity = new Mock<IIdentity>();
FakeIIdentity.Setup(i => i.IsAuthenticated).Returns(true).Verifiable();
FakeIIdentity.Setup(i => i.Name).Returns("NotValidUserName").Verifiable();

//Inject the fake user "NotValidUsername"
BlBase.FakeIIdentity = FakeIIdentity.Object;
//The MVC state dictionary to store error and messages
ModelStateDictionary dictionary = new ModelStateDictionary();

//Initialise the base business logic class
BlBase blbase = new BlBase(dictionary, new L2SUserService());

//Make sure the current user variable is null
//Make sure there is an error in the model state dictionary
Assert.AreEqual(1, dictionary.Count);
//Make sure the Severe Error key is present in the dictionary
Assert.AreEqual("SevereError", dictionary.Keys.FirstOrDefault());
//Make sure the message value is 1, so we can show generic severe error
//message and log the user out
Assert.AreEqual("1", dictionary["SevereError"].Errors.First().ErrorMessage);

To prevent this blog from turning into the longest blog post on the internet, I've not posted test 3 and 4, but they are similar. 3. was to check the scenario when the user is authenticated but is suspended and 4. is the scenario when the user is not authenticated. Hope this helps someone. As always, I'm open to suggestion and sharing best practices when it comes to testing, coding, designing and motorbiking Laughing. and TDD & Mocks Part 1

This is my first foray into the world of writing code to test other code and have to admit, I enjoyed it. Ever since, I have tried to use TDD in every project, even if it only means testing a subset of the desired functionality. The finalized Beta 1 website had 490 test cases, 243 to test the Business logic layer, 121 to test the MVC Controllers and 126 to test the helper classes. The only disadvantage of TDD I've found so far is it almost doubles the development time. But the confidence of knowing that the website can cope with all the test cases, thought up during and after development, outweighs the cons.

In this blog entry, I'll discuss the BlBase class,'s base business logic class and cover how I've gone about using NUnit and Rhino Mocks to test it in the next blog entry. Having decided to use LinqToSql as the Data Access Layer, all the business logic classes will need an instance of the data context. They will also need an instance of the current user to carry out selects, inserts and updates against. Making the BlBase class look like:

public class BlBase
//Current user variable, all business logic code have access to the current user
public IUser currentUser;
//The datacontext initialised once per request
public RedStartDataContext currentDataContext;

//Only for testing, inject a fake user identity
public static IIdentity FakeIUser;
//Modelstate dictionary, all business logic code can store
//informative and error messages here
public ModelStateDictionary currentModelState;

The BlBase class has one constructor and no methods. And this constructor has code to intialise the current user and data context variable. The constructor looks like:

//Constructor to initialise the user and data context
public BlBase(ModelStateDictionary ModelState, IUserService UserService)
//save the model state and initialise the data context
currentModelState = ModelState;
currentDataContext = new RedStartDataContext();

//Get the current user

//A little trick here: when this code is live
//HttpContext.Current will never be null. When
//NUnit call this code the FakeIUser will be used
//instead. Mapze Beta 2 has a cleaner implementation.
IIdentity identity;
if (HttpContext.Current != null)
identity = HttpContext.Current.User.Identity;
identity = FakeIUser;

//is the request authenticated
if (identity.IsAuthenticated)
//get the user from db
currentUser = UserService.Get(identity.Name);

//Make sure there is a user with the identity name
//also make sure the user account is not suspended.
//The 1 in the ModelError is picked up by a custom
//MVC error trapping filter and logs out the user.
if(currentUser == null || currentUser.Suspended)
currentModelState.AddModelError("SevereError", 1);

I believe most social networking and user interactive website will have a similar base class for all their business logic classes to inherit from. Making sure this class works correctly is of utmost importance, especially to business that rely on their user base for sales and feedback. The next blog entry shows how I've used NUnit and Rhino Mocks to test this class.