.NET Performance Blog

March 27, 2011

OpenFaq (Part 1): The beginning

Filed under: .NET,ASP.NET,ASP.NET MVC,DDD,General,TDD — Eric P @ 1:43 pm

It is time to learn some new technologies.

For this task I am going to write FAQ applicaton called OpenFaq.

OpenFaq – The future of FAQ

Whenever we buy any new product there is usually some questions or issues that come up, that may not be covered in manual or by asking the uncle who (supposedly) knows everything. How do I …? Why am I getting this f#$x error? etc…

In some cases you may go to product’s website and try to find an answer there. In about 5 minutes (depending on how quickly you reach the boiling point) you give up and just do a google search.

Why are so many sites so bad in helping you find what you need?

The problem(s) this application will try to solve is:
On many sites FAQ is created early on and not frequently updated. It quickly becomes forgotten.
The questions are grouped according to how website administrator feels like they should be grouped. Not based on frequency of asking.
User interaction is limited to reading an answer

The Solution
Make FAQ dynamic, so admin can edit questions and answers without doing rollout
Get users involved with asking, answering, voting and comments (similar to stack overflow)
Use voting and other statistics to determine which questions are frequent/popular and which are not

Some Business Requirements

Some preliminary requirements for this application are:
* User can login
* User can post question
* User can answer question
* User can comment on question and answer
* User can vote on question and answer
* User can use keyword search to quickly find questions, answers

Maybe a touch of Technology

In this series I will try out some new technologies from MS and use some of the latest methodologies in application development.

For a while now I have been reading about many new technologies and approaches for software development. Here is the list that I plan to use for OpenFaq.

Approaches

  • BDD – behavior driven development
  • TDD – test driven development

Principles

  • YAGNI – you are not going to need it
  • KISS – keep it simple stupid
  • DRY – don’t repeat yourself

Technology

For this project I am going to use Microsoft stack.

  • ORM – EF 4 Code First
  • Web Framework – MVC 3
  • Template Engine – Razor
  • Package/Dependecy Manager – NuGet
  • BDD – SpecFlow
  • UI Testing/Acceptance test – WatiN
  • Unit testing – MS Test
  • Version Control – Mercurial
  • Project Site – Codeplex.com
Advertisements

February 2, 2010

ASP.NET GridView – edit records using JQuery Dialog

Filed under: .NET,ASP.NET,JQuery — Eric P @ 6:25 am

There are many ways in which you could modify modular data in Grid View:
1. Inline by making rows editable when u click on Edit
2. By using separate pages for Edit
3. By using popups/dialogs for adding/editing

In this post I will show how to implement the 3rd approach using JQuery UI Dialog for editing/adding data in ASP.NET GridView.

The following features have been implemented:
1. List customers
2. Add customer – Save/Cancel
3. Edit customer – Save/Cancel
4. Delete customer
5. Server side validation
6. Edit dialogs appear next to trigger links

You can check out the demo here:
http://samples.entechsolutions.com/GridWithEditDialog

The code is available here:
http://samples.entechsolutions.com/Downloads/GridWithEditDialog.zip

Implementation

Data source

The grid lists customers which are stored in list which is initialized for each new session. This way each user trying out this sample will not affect other users.
CustomerService is a class wrapped around list of customers that allows to add/edit/list customers:

public class CustomerService
{
	private List<Customer> Customers
	{
		get
		{
			List<Customer> customers;
			if (HttpContext.Current.Session["Customers"] != null)
			{
				customers = (List<Customer>)HttpContext.Current.Session["Customers"];
			}
			else
			{
				//Create customer data store and save in session
				customers = new List<Customer>();

				InitCustomerData(customers);

				HttpContext.Current.Session["Customers"] = customers;
			}

			return customers;
		}
	}


	public Customer GetByID(int customerID)
	{
		return this.Customers.AsQueryable().First(customer => customer.ID == customerID);
	}


        ...
        //Add/Update/Delete/GetAll

Add/Edit dialog

There are two main operations that are handled using JQuery dialog
* Add Customer
* Edit Customer

In both cases the same dialog is used, as well as the same content div and Update Panel

	<div id="divEditCustomerDlgContainer">	
			<div id="divEditCustomer" style="display:none">
					
				<asp:UpdatePanel ID="upnlEditCustomer" runat="server">
					<ContentTemplate>
						<asp:PlaceHolder ID="phrEditCustomer" runat="server">
							<table cellpadding="3" cellspacing="1">
							<tr>
								<td>
									*First Name:
								</td>
								<td>
									<asp:TextBox ID="txtFirstName" Columns="40" MaxLength="50" runat="server" />
								        ...
								</td>
							</tr>
							<tr>
								<td>
									*Last Name:
								</td>
								...
							</tr>
							<tr>
								<td colspan="2" align="right">
									<asp:Button ID="btnSave" onclick="btnSave_Click" Text="Save" runat="server" />
									<asp:Button ID="btnCancel" onclick="btnCancel_Click" onClientClick="closeDialog()" CausesValidation="false" Text="Cancel" runat="server" />
								</td>
							</tr>
							</table>
								
						</asp:PlaceHolder>
					</ContentTemplate>
							
				</asp:UpdatePanel>
			
			</div>
		</div>	<!-- divEditCustomerDlgContainer -->

You may notice that there are two divs around UpdatePanel – divEditCustomerDlgContainer and divEditCustomer. The reason for that is that when JQuery dialog opens – it is added after FORM tag in dom. That disables any ASP.NET submits and server side validation. The issue is described here:
http://www.trentjones.net/index.php/2009/03/jqueryui-dialog-with-aspnet-empty-post-values

To fix the issue I added a handler for JQuery Dialog open event that takes JQuery dialog DOM object and inserts it as a child of “divEditCustomerDlgContaine”. Note that JQuery dialog references divEditCustomer.

	<script type="text/javascript">
		$(document).ready(function() {
			$("#divEditCustomer").dialog({
				autoOpen: false,
				modal: true,
				minHeight: 20,
				height: 'auto',
				width: 'auto',
				resizable: false,
				open: function(event, ui) {
					$(this).parent().appendTo("#divEditCustomerDlgContainer");    //This is where JQuery dialog is added to DlgContainer
				},
			});
		});
     ...

When user clicks on Add/Edit customer links the following steps are followed:
1. JQuery dialog is opened
2. Content of dialog is overlayed with AJAX indicator and white background – BlockUI is used for that purpose
3. AJAX call is made that triggers refresh of upnlEditContent
4. On server side – dialog content is cleared for adding or loaded for editing.
5. Server side uses RegisterStartupScript to trigger a javascript call to UnlockDialog
6. Dialog is unlocked and available to user for editing

With this approach user sees the dialog right away and indicator tells him that data is being loaded. In most cases it should be pretty fast from click to being able to edit.

Positioning Dalog

You may notice that dialog appears to the right of the link that you click on. For that JQuery position() functionality is used:

	function openDialog(title, linkID) {
	
		var pos = $("#" + linkID).position();
		var top = pos.top;
		var left = pos.left + $("#" + linkID).width() + 10;
		
		
		$("#divEditCustomer").dialog("option", "title", title);
		$("#divEditCustomer").dialog("option", "position", [left, top]);
		
		$("#divEditCustomer").dialog('open');
	}

linkID is the ClientID of the link. Using the position() u can display dialog anywhere on the page or in relation to another control.

Running Client Side code using RegisterStartupScript in Async

To run some javascript script when response comes back from asynchronous request – function ScriptManager.RegisterStartupScript can be used.

The issue is that the first parameter in:
RegisterStartupScript Method (Control, Type, String, String, Boolean)

must be a control in update panel that will be rendered on the current request. In the “List Customers” page there are two update panels -“upnlEditCustomers” and “upnlCustomers” (for grid view).
The first panel is always updated on any async request (UpdateMode=”Always” by default). Originally I though to make it conditional which would be more efficient, but there were some issues to resolve and I decided it wasn’t worth the trouble in this case. As for “upnlCustomers” – we definitely don’t want that re-rendered on every async request – like opening/canceling the dialog, so this one is set to update conditionally.

To get RegisterStartupScript to work without worrying that triggering conrol is rendered in current request, I added another UpdatePanel whose sole purpose is to facilitate JavaScript calls from Async requests. This panel has an empty placeholder that’s used as a control in RegisterStartupScript:


	<asp:UpdatePanel ID="upnlJsRunner" UpdateMode="Always" runat="server">
		<ContentTemplate>
			<asp:PlaceHolder ID="phrJsRunner" runat="server"></asp:PlaceHolder>
		</ContentTemplate>
	</asp:UpdatePanel>

On server side there is a function RegisterStartupScript(key, script) that uses update panel above:

	private void RegisterStartupScript(string key, string script)
	{
		ScriptManager.RegisterStartupScript(phrJsRunner, phrJsRunner.GetType(), key, script, true);
	}

        private void TriggerClientGridRefresh()
	{
		string script = "__doPostBack(\"" + btnRefreshGrid.ClientID + "\", \"\");";
		RegisterStartupScript("jsGridRefresh", script);   //Trigger async grid refresh on Save
	}

	private void HideEditCustomer()
	{
		ClearEditCustomerForm();
		RegisterStartupScript("jsCloseDialg", "closeDialog();");    //Close dialog on client side
	}

Clear data in dialog

When user clicks on “Add Customer” – data in dialog is cleared and all validators are reset to Valid. For this I wrote a function that loops through all the controls in dialog and then performs a certain action on the controls of certain type:

	private void ClearEditCustomerForm()
	{
		//Empty out text boxes
		var textBoxes=new List<Control>();
		FindControlsOfType(this.phrEditCustomer, typeof(TextBox), textBoxes);
		
		foreach (TextBox textBox in textBoxes)
			textBox.Text = "";

		//Clear validators
		var validators=new List<Control>();
		FindControlsOfType(this.phrEditCustomer, typeof(BaseValidator), validators);
	
		foreach (BaseValidator validator in validators)
			validator.IsValid = true;
	}


	static public void FindControlsOfType(Control root, Type controlType, List<Control> list)
	{
		if (root.GetType() == controlType || root.GetType().IsSubclassOf(controlType))
		{
			list.Add(root);
		}

		//Skip input controls
		if (!root.HasControls())
			return;

		foreach (Control control in root.Controls)
		{
			FindControlsOfType(control, controlType, list);
		}
	}

Right now it only handles TextBoxes and Validators, but it can be easily expanded to support Text Areas, Drop Downs, etc…

JQuery Includes

This sample doesn’t include the files for JQuery UI and JQuery base library. Instead those are referenced at the google AJAX CDN.
The approach for including JQuery UI from Google AJAX CDN is covered here: http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css" type="text/css" rel="Stylesheet" />
	
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

This makes the application and code download a lot smaller (a lot less files), so it is great for sample projects.

January 28, 2009

One class per file or multiple classes in one file

Filed under: ASP.NET,General — Eric P @ 9:10 am

I browsed the internet for an answer to this question and the best I could find was:

“The primary benefit of a class per file is for source control and concurrent access: Why deal with the inevitable human error of code merges if each developer is really dealing with the separate classes.”

In my case there are several really small classes that seem like they can go into one file or be separated. As a personal style it seems best to put each class into separate file. This way I can easily see/find all the classes through solution explorer.

On the other hand it seems more like a stylistic argument, since I couldn’t find any evidence that it actually improves performance. I could also use VS diagramming tool to create a nice diagram for all the classes in a module.

So some possible guidelines for development team that can come out of this are:

  1. Allow including several classes in file only if each class is max of 10 lines of code.
  2. Classes in the same file must belong to the same Module (DDD Module)
  3. Enums should go in .cs file that uses them. If there are several classes that use enum – pick one.

Found another good reason for keeping classes in separate files:

“Also you’ll find many errors/diagnostics are reported via file name (“Error in Myclass.cpp, line 22″) and it helps if there’s a one-to-one correspondence between files and classes. ”
From: http://stackoverflow.com/questions/28160/multiple-classes-in-a-header-file-vs-a-single-header-file-per-class

Blog at WordPress.com.