ASP.NET MVC sample application

Filed in ASP.NET MVC 6 Comments

Below is a fully functional asp.net mvc sample application project. Go ahead a download it, play with it, make suggestions, extend, etc. If you have any suggestions for improvements, just drop me a line or leave a comment.

The sample project assumes you have Visual Studio 2008 installed, the rest of the dlls and javascript files are included in the download (nHibernate, ActiveRecord, jQuery, plugins). Also included are scripts to create the sample table schema for both SQL Server and MySQL.

The following mvc sample projects are included:

  • Auto-Complete Using jQuery
  • Add a Row to a HTML Table
  • Dual Listbox in jQuery
  • TinyMCE Samples
  • Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures
  • Check username availability

IMPORTANT: You need to set the username and password for your database in the web.config file for the project to work.

Below is a video showing the sample in action:

, ,

Export to Excel or CSV from ASP.NET MVC with C#

Filed in ASP.NET MVC | C# 3 Comments

Since programming way back in the Classic ASP days, at some point a client always wants to export an html grid into an Excel grid. In c#, that need didn’t disappear, but got a lot easier with GridView and the HtmlTextWriter. Finally reached that point in my ASP.NET MVC programming world, and quite frankly, am surprised it took this long, for this same need! But I digress. To pull this off, all we are really going to do is add an export method to a controller, most of which will look very familiar to asp.net web forms.

Add using statements

using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

We are going to use our dear old friend the GridView from web forms as a placeholder for our data, which is why we need the second using statement.

Create Controller Method

This one is pretty easy, consisting of three parts:

  • Creating the GridView placeholder
  • Binding the query results to the GridView placeholder
  • Dumping the results back to the browser

This example queries all contacts that have not unsubscribed, but you can imagine how easy it is to extend.
var contacts = Contact.FindAll();
var grid = new System.Web.UI.WebControls.GridView();

grid.DataSource = from contact in contacts
where contact.Unsubscribe == false
select new
{
ContactID = contact.ID,
FullName = contact.FullName,
Email = contact.Email
};
grid.DataBind();

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=YourFileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

That’s it!

, , , ,

Initialize global asax in MVC for NHibernate ActiveRecord

Filed in ActiveRecord | ASP.NET MVC 1 Comment

Initializing your global.asax for MVC and NHibernate’s ActiveRecord is really easy. There are really only two sections you need to touch: the using section and Application_Start().

Configure using section

Out of the box, you don’t have to do anything if you are NOT using ActiveRecord for CRUD. If you want to use ActiveRecord, here are the using statements you need to add:

using System.Reflection;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;

Those namespaces are used in the next section, which is

Application_Start()

There are only three lines of code to initialize ActiveRecord to specify the settings are sitting in web.config:

IConfigurationSource source = System.Configuration.ConfigurationManager.GetSection("activeRecord") as Castle.ActiveRecord.Framework.IConfigurationSource;
Assembly asm1 = typeof(Certification).Assembly;
ActiveRecordStarter.Initialize(new Assembly[] { asm1 }, source);

Those lines should appear BELOW the RegisterRoutes() call. If you don’t include the above lines, you will receive the following nastygram:

An ActiveRecord class (Contact) was used but the framework seems not properly initialized. Did you forget about ActiveRecordStarter.Initialize() ?


, ,

How to add or delete a row to a html table using jQuery, MVC, and JsonResult

Filed in ASP.NET MVC | C# | jquery | json 3 Comments

This post covers a piece of functionality I’m always using, and just wanted a spot where I can do some quick copy/paste. There are a few pieces of functionality needed to make this happen, and the technology used, here are the assumptions about your environment:

  • ASP.NET MVC 1.0
  • jquery-1.3.2.js
  • nHibernate (optional)

You can download the code sample here.

Preparing your controller to process the post

1. Create a method that returns a JsonResult like the one below:

public JsonResult AddContact(FormCollection f)
{
Contact c = new Contact();
//your logic for adding your object, be sure to include some error handling!
c.CreateAndFlush();
int NewID = c.ID;
//return the new key
return Json(NewID);
}

You would also have an Update method similar to the Add. For this example we will also add a delete method:

public JsonResult DeleteContact(int ID)
{
//for this example, i'm using nhibernate to handle crud statements
Contact c = Contact.Find(ID);
if(null != c)
{
c.Delete();
}
//in a real example there would be error handling
return Json("Ok");
}

Create a simple table and form

1. This example will have two fields: first and last name:

First, Last Name: <input type="text" name="firstname" id="firstname" />&amp;nbsp;
<input type="text" name="lastname" id="lastname" />&amp;nbsp;
<input type="button" onclick="Add();" value="add" />

2. Next we create a table to hold existing contacts, and then prepare it for adding/deleting:

<table width="100%" id="contactsTable">
<tr>
<th></th>
<th>Contact Name</th>
</tr>
<%

foreach(var item in Model)
{
//we need to add an id which uniquely ties this entire row to this contact for jQuery
Response.Write("<tr id='c" + item.ID + "'>");%>
<td align="left">
<a href="#" onclick="javascript:Update('<%= item.ID %>');">Update</a>&amp;nbsp;&amp;nbsp;
<a href="#" onclick="javascript:Remove('#c<%= item.ID %>','<%= item.ID %>');">Delete</a>
</td>
<td>
<%
string _firstnametext = "txtfirstname" + item.ID.ToString();
Response.Write(Html.TextBox(_firstnametext, item.FirstName));
%>
</td>
<td>
<%
string _lastnametext = "txtlastname" + item.ID.ToString();
Response.Write(Html.TextBox(_lastnametext, item.LastName));
%>
</td>
</tr>
<%}%>
</table>

In the above example, the data is displayed in textboxes for convenience. If you have many fields, you may want to use either a dialog (which will be covered in a future post) or redirecting the user to another page…but I digress. Now that we have our table ready, all we have left is creating the jQuery Add, Update, and Delete functions.

jQuery functions

So the last part is creating three simple calls using jquery to send changes back to the server. First is the most “complex” function, which is adding a new record. It is more complex because this will actually append the new contact to the table. As you’ll see, it isn’t rocket science:

function Add()
{
$.post("/Contact/AddContact", $("#Form1").serialize(),
function(data) {
//this function fires after the post;
//the data variable will have the new contact's pk value;
//this is a great spot to see if there was an error and adjust accordingly
var myObject = eval('(' + data + ')');
var ID = myObject;
var FirstName = $('#firstname').val();
var LastName = $('#lastname').val();

var Remove = '&amp;nbsp;&amp;nbsp;|&amp;nbsp;&amp;nbsp;<a href="#" onclick="javascript:Remove(\'#c' + ID+ '\',' + ID + ');">Delete</a>';
var NewRow = "<tr id='c" + ID+ "'>" +
"<td><a href='#' onclick='Update(" + ID + ")'>Update</a>" + Remove + "</td>" +
"<td><input type='text' name='txtfirstname" + ID + "' value='" + FirstName + "''></td>" +
"<td><input type='text' name='txtlastname" + ID + "' value='" + LastName + "''></td></tr>";

//this portion appends the new record to the table
$('#contactsTable tr:last').after(NewRow);
//clear out the add form
$('#firstname').val("")
$('#lastname').val("");
});
};

You can read more on form posting using jquery here: http://docs.jquery.com/Post. The next function is deleting a contact. Like all the examples in the post, you want to include your own logic for error handling!

function Remove(rowid,id) {
//the first line makes the request to delete the contact, the second line removes the row from the html table
$.post("/Contact/DeleteContact", { id: id});
$(rowid).remove();
}

Finally we have our Update call. This will be just like the Add function, except you don’t have to append a new row because the record is already there.

Hope you enjoyed!

, ,

Using nHibernate, Castle ActiveRecord, and ASP.NET MVC Together

Filed in ActiveRecord | ASP.NET MVC | C# | Environment Setup | NHibernate 3 Comments

So this is my first post, with that this blog’s objective: to post all the code shortcuts, how-to’s, tips-tricks, etc. so they are handy whenever I need them. It always seems that at some point I need to do something that I did 5 projects ago, and forgot to save that snippet and can’t quite find it!

For this entry, we’re going to configure a new web application in the following sequence:

1. Create ASP.NET MVC 1.0 project in Visual Studio 2008

2. Copy and reference the required nHibernate dlls

3. Configure web.config

4. Initialize global.asax

Pre-requisites: If you haven’t already installed MVC, go here: http://www.asp.net/mvc/download/.

Create ASP.NET MVC 1.0 project in Visual Studio 2008

1. Open Visual Studio 2008

2. Click “File” –> “New Project” and select “ASP.NET MVC Web Application” under the c# menu

Select your location, project name, etc.

Copy and reference the required nHibernate files and dlls

1. Download the latest ActiveRecord release here: http://bit.ly/8HdvIU

For detailed documentation on ActiveRecord, visit the Castle Project site here: http://bit.ly/8pzxyb and here: http://bit.ly/8jzycs.

2. Unzip, copy and then reference the following assemblies into your bin folder:

  • Castle.ActiveRecord.dll
  • Castle.Core.dll
  • Castle.Components.Validator.dll
  • Castle.DynamicProxy.dll
  • NHibernate.dll
  • Iesi.Collections.dll
  • log4net.dll

Configure web .config

1. Add the following elements to configSections:

<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<section name="activeRecord" type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler, Castle.ActiveRecord"/>

2. Add the following elements right after /configSections:

SQLServer 2005/2008

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.connection_string">Server=localhost;initial catalog=<em>YOURDB</em>;uid=<em>YOURUSERNAME</em>;pwd=<em>YOURPASSWORD</em></property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="<em>YOURASSEMBLY</em>"/>
</session-factory>
</hibernate-configuration>

<activeRecord isWeb="true">
<config>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string" value="Server=localhost;initial catalog=<em>YOURDB</em>;uid=<em>YOURUSERNAME</em>;pwd=<em>YOURPASSWORD</em>"/>
</config>
</activeRecord>

MySQL

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">NHibernate.Dialect.MySQLDialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
<property name="connection.connection_string">Database=<em>YOURDB</em>;Server=localhost;User Id=<em>YOURUSERNAME</em>;Password=<em>YOURPASSWORD</em></property>
<property name="show_sql">true</property>
<property name="hbm2ddl.keywords">none</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="<em>YOURASSEMBLY</em>" />
</session-factory>
</hibernate-configuration>

<activeRecord isWeb="true">
<config>
<add key="hibernate.connection.driver class" value="NHibernate.Driver.MySqlDataDriver" />
<add key="hibernate.dialect" value="NHibernate.Dialect.MySQLDialect" />
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="hibernate.connection.connection_string" value="Database=<em>YOURDB</em>;Server=localhost;User Id=<em>YOURUSERNAME</em>;Password=<em>YOURPASSWORD</em>" />
</config>
</activeRecord>

For logging, you need to add the following elements, regardless of database type:

<log4net>
<appender name="NHibernateFileLog" type="log4net.Appender.RollingFileAppender">
<file value="Logs/nhibernate.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
<file value="Logs/general.txt" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="DataLog" type="log4net.Appender.RollingFileAppender">
<file value="Logs/data.txt" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<!-- levels: DEBUG, INFO, WARN, ERROR, FATAL -->
<root>
<level value="DEBUG" />
<appender-ref ref="GeneralLog" />
</root>
<logger name="NHibernate" additivity="false">
<level value="DEBUG" />
<appender-ref ref="NHibernateFileLog" />
</logger>
<logger name="Pushable.Data" additivity="false">
<level value="DEBUG" />
<appender-ref ref="DataLog" />
</logger>
</log4net>

Initialize Global.asax

1. Open global.asax in code view

2. Add the following using statements:

using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;

3. Update Application_Start so it looks like this:

protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);

IConfigurationSource source = System.Configuration.ConfigurationManager.GetSection("activeRecord") as Castle.ActiveRecord.Framework.IConfigurationSource;
Assembly asm1 = typeof(<em>ONE OF YOUR ASSEMBLIES, I.E. CONTACT</em>).Assembly;

ActiveRecordStarter.Initialize(new Assembly[] { asm1 }, source);
}

That’s it! So what we’ve done here is configure our environment, in upcoming posts, we’ll dig into actual code and do some fun things with jQuery. Also, I’ll be revisiting this post with some screenshots in the near future. Finally, if you know of better/more efficient ways to do some of these same tasks, I’m all ears!

, , ,

TOP