Minggu, 13 Februari 2011

ASP.NET 4.0 - Referencing App_Code Classes

I am working to learn how to properly use custom code from within an ASP.NET project. I added an App_Code directory to an empty project. Within the App_Code directory I created a folder called DLL and a file called DLL.cs. Looking back, I would have done it differently. The path [ProjectName].App_Code.DLL is pre-pended to the file name, DLL, in this case. So, when I reference the object in my project, CachingTest, it is fully written as CachingTest.App_Code.DLL.DLL. The second DLL in the name makes it a little more confusing. What I would more likely do is name the .cs file after the Object I am working with instead of the Folder class. I figured out how to access the code from this link:
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/pages/code.aspx
As it notes, you do need to add a
<%Import Namespace="CachingTest.App_Code.DLL">
declaration to be able to access the class. In my .aspx page, I included the previous Import statement as well as a simple code block:

<% CachingTest.App_Code.DLL.DLL test = new CachingTest.App_Code.DLL.DLL();
test.ResponseWrite();
%>
My code-behind class is super simple:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CachingTest.App_Code.DLL
{
public class DLL
{
public void ResponseWrite()
{
HttpContext.Current.Response.Write("Test");
}
}
}>
In my test page, I had to add some extra code for the Response.Write() snippet. To get this right, I had to look at XIII's post:
http://forums.asp.net/p/1019346/1377641.aspx
As he noted, you have to use:
use HttpContext.Current.Response.Write()

When you use a custom class to perform some actions you should get into the current context of the currrent execution/request of your handler, which is most likely a Page or HttpHandler.

0 komentar:

Posting Komentar

 
Powered by Blogger