ASP.NET Tutorial/Development/Assembly
Содержание
- 1 Adding an Assembly to the Global Assembly Cache
- 2 Adding comments to a component.
- 3 Building Basic Components
- 4 Building Component Libraries by Using the C# Command-Line Compiler
- 5 Components and Dynamic Compilation
- 6 Component with Property
- 7 Declaring Fields and Properties
- 8 Declaring Methods
- 9 Load server side assembly
- 10 Make an assembly available to an ASP.NET application
- 11 Mixing Different Language Components in the App_Code Folder
- 12 Using ASP.NET Intrinsics in a Component
Adding an Assembly to the Global Assembly Cache
All the assemblies that make up the .NET Framework class library are contained in the Global Assembly Cache.
Any assembly located in the Global Assembly Cache can be referenced by any application running on a server.
The Global Assembly Cache"s physical location is at the following path:
C:\WINDOWS\assembly
Before you can add an assembly to the Global Assembly Cache, you must add a strong name to the assembly.
A strong name is similar to a GUID. You use a strong name to provide your assembly with a universally unique identifier.
You can generate a strong name by using the sn.exe command-line tool like this:
sn.exe -k KeyPair.snk
Executing this command creates a new file named KeyPair.snk, which includes a new random public/private key pair.
You can compile an assembly that includes a strong name by executing the Visual Basic .NET command-line compiler like this:
csc /t:library /keyfile:KeyPair.snk /recurse:*.cs /out:MyLibrary.dll
Adding comments to a component.
/// <summary>
/// Represents an employee of Acme.ru
/// </summary>
public class Employee
{
private string _firstName;
private string _lastName;
/// <summary>
/// The employee first name
/// </summary>
public string FirstName
{
get { return _firstName; }
}
/// <summary>
/// The employee last name
/// </summary>
public string LastName
{
get { return _lastName; }
}
/// <summary>
/// Returns an employee from the database
/// </summary>
/// <param name="id">The unique employee identifier</param>
/// <returns>An instance of the Employee class</returns>
public static Employee getEmployee(int id)
{
return null;
}
/// <summary>
/// Initializes an employee
/// </summary>
/// <param name="firstName">First Name</param>
/// <param name="lastName">Last Name</param>
public Employee(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
}
}
Building Basic Components
File: HelloWorld.cs
public class HelloWorld
{
public string SayMessage()
{
return "Hello World!";
}
}
File: ShowHelloWorld.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
void Page_Load()
{
HelloWorld objHelloWorld = new HelloWorld();
lblMessage.Text = objHelloWorld.SayMessage();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Hello World</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblMessage"
Runat="server" />
</div>
</form>
</body>
</html>
Building Component Libraries by Using the C# Command-Line Compiler
The C# compiler is located at the following path:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe
The Visual Basic command-line compiler is located at the following path:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc.exe
You can use the csc.exe tool to compile any C# source file like this:
csc /t:library SomeFile.cs
The /t (target) option causes the compiler to create a component library and not a Console or Windows application.
When you execute this command, a new file named SomeFile.dll is created, which is the compiled assembly.
To compiling a single file, you can compile all the source code files in a folder (and every subfolder) like this:
csc /t:library /recurse:*.cs /out:MyLibrary.dll
The /recurse option causes the compiler to compile the contents of all the subfolders.
The /out option provides a name for the resulting assembly.
Components and Dynamic Compilation
Any component in the App_Code folder is compiled in the same way as an ASP.NET page.
App_Code folder are compiled into a new assembly and saved to the Temporary ASP .NET Files folder, located at the following path:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\[application name]
You can add as many subfolders to the App_Code folder as you need to organize your components.
Component with Property
File: HelloWorld.cs
using System;
public class PropertyHelloWorld
{
private string _message;
public string Message
{
get
{
return _message;
}
set
{
if (value.Length > 5)
throw new Exception("Message too long!");
_message = value;
}
}
public string SayMessage()
{
return _message;
}
}
File: Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
void Page_Load()
{
PropertyHelloWorld objPropertyHelloWorld = new PropertyHelloWorld();
objPropertyHelloWorld.Message = "Hello World!";
lblMessage.Text = objPropertyHelloWorld.SayMessage();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Property Hello World</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblMessage"
Runat="server" />
</div>
</form>
</body>
</html>
Declaring Fields and Properties
File: FieldHelloWorld.cs
public class FieldHelloWorld
{
public string Message;
public string SayMessage()
{
return Message;
}
}
File: Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
void Page_Load()
{
FieldHelloWorld objFieldHelloWorld = new FieldHelloWorld();
objFieldHelloWorld.Message = "Good Day!";
lblMessage.Text = objFieldHelloWorld.SayMessage();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Field Hello World</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblMessage"
Runat="server" />
</div>
</form>
</body>
</html>
Declaring Methods
File: StaticHelloWorld.cs
public class StaticHelloWorld
{
public static string SayMessage()
{
return "Hello World!";
}
}
File: ShowStaticHelloWorld.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
void Page_Load()
{
lblMessage.Text = StaticHelloWorld.SayMessage();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show Shared Hello World</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblMessage"
Runat="server" />
</div>
</form>
</body>
</html>
Load server side assembly
<%@ Page language="C#" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Reflection" %>
<html>
<head>
<script language="C#" runat="server">
private string GetAssemblyInfo()
{
StringBuilder sb = new StringBuilder();
try
{
string assemblyFile = @"C:\WINNT\Microsoft.NET\Framework\v1.0.3705\mscorlib.dll";
Assembly assemblyInfo = Assembly.LoadFrom(assemblyFile);
sb.Append("CodeBase: ");
sb.Append(assemblyInfo.CodeBase);
sb.Append("<br>Location: ");
sb.Append(assemblyInfo.Location);
sb.Append("<br>FullName: ");
sb.Append(assemblyInfo.FullName);
sb.Append("<br>Manifest Resource Names: ");
string[] resourceNames = assemblyInfo.GetManifestResourceNames();
for (int i=0; i<resourceNames.Length; i++)
{
string name = resourceNames[i];
if (i>0) sb.Append(",");
sb.Append(name);
}
Type[] types = assemblyInfo.GetTypes();
foreach (Type typeInfo in types)
{
sb.Append( "<h2>" + typeInfo.FullName + "</h2>");
sb.Append("Number of Constructors: ");
sb.Append(typeInfo.GetConstructors().Length.ToString());
sb.Append("<br>Number of Properties: ");
sb.Append(typeInfo.GetProperties().Length.ToString());
sb.Append("<br>Number of Fields: ");
sb.Append(typeInfo.GetFields().Length.ToString());
sb.Append("<br>Number of Events: ");
sb.Append(typeInfo.GetEvents().Length.ToString());
sb.Append("<br>Number of Methods: ");
sb.Append(typeInfo.GetMethods().Length.ToString());
sb.Append("<br>Is Class: ");
sb.Append(typeInfo.IsClass);
sb.Append("<br>Is Interface: ");
sb.Append(typeInfo.IsInterface);
sb.Append("<br>Is Enum: ");
sb.Append(typeInfo.IsEnum);
sb.Append("<br>Attributes: ");
sb.Append(typeInfo.Attributes);
sb.Append("<br>GUID: ");
sb.Append(typeInfo.GUID.ToString());
}
}
catch (Exception ex)
{
sb.Append( "Error: " + ex.ToString() ) ;
}
return sb.ToString();
}
private void RetrieveInfo_Click(object sender, System.EventArgs e)
{
OutputClass.Text = GetAssemblyInfo();
}
</script>
<title>Reflect Class</title>
</head>
<body>
<form id="ReflectClass" method="post" runat="server">
<asp:button id="RetrieveInfo" onclick="RetrieveInfo_Click" runat="server" Text=" Retrieve Assembly Info "></asp:button>
<br><br>
<asp:label id="OutputClass" runat="server"></asp:label>
</form>
</body>
</html>
Make an assembly available to an ASP.NET application
You can add the assembly to the application"s /Bin folder.
Or you can add the assembly to the Global Assembly Cache.
Adding an Assembly to the Bin Folder
The ASP.NET Framework automatically checks this folder for any assemblies.
If the folder contains an assembly, the assembly is referenced automatically by the ASP.NET.
When you add an assembly to an ASP.NET application"s Bin folder, the assembly is scoped to the application.
If you add an assembly to the Bin folder, then you can take advantage of XCopy deployment.
Mixing Different Language Components in the App_Code Folder
You need to place components written in different languages in different subfolders.
If you create two subfolders in the App_Code folder named VBCode and CSCode
Then you can use the web configuration file to use components written in both VB.NET and C#.
File: Web.Config
<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</codeSubDirectories>
</compilation>
</system.web>
</configuration>
When the contents of the App_Code folder are compiled, two assemblies are created.
one that corresponds to the VBCode folder and one that corresponds to the CSCode folder.
Using ASP.NET Intrinsics in a Component
using System.Web;
public class Preferences
{
public static string FavoriteColor
{
get
{
HttpContext context = HttpContext.Current;
context.Trace.Warn("Getting FavoriteColor");
if (context.Session["FavoriteColor"] == null)
return "Blue";
else
return (string)context.Session["FavoriteColor"];
}
set
{
HttpContext context = HttpContext.Current;
context.Trace.Warn("Setting FavoriteColor");
context.Session["FavoriteColor"] = value;
}
}
}
File: Default.aspx
<%@ Page Language="C#" trace="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
void Page_PreRender()
{
body1.Style["background-color"] = Preferences.FavoriteColor;
}
protected void btnSelect_Click(object sender, EventArgs e)
{
Preferences.FavoriteColor = ddlFavoriteColor.SelectedItem.Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<style type="text/css">
.content
{
width:80%;
padding:20px;
background-color:white;
}
</style>
<title>Show Preferences</title>
</head>
<body id="body1" runat="server">
<form id="form1" runat="server">
<div class="content">
<h1>Show Preferences</h1>
<asp:DropDownList
id="ddlFavoriteColor"
Runat="server">
<asp:ListItem Text="Blue" />
<asp:ListItem Text="Red" />
<asp:ListItem Text="Green" />
</asp:DropDownList>
<asp:Button
id="btnSelect"
Text="Select"
Runat="server" OnClick="btnSelect_Click" />
</div>
</form>
</body>
</html>