ASP.NET Tutorial/Development/Assembly

Материал из .Net Framework эксперт
Версия от 14:56, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Adding an Assembly to the Global Assembly Cache

   <source lang="csharp">

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</source>


Adding comments to a component.

   <source lang="csharp">

/// <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;
   }

}</source>


Building Basic Components

   <source lang="csharp">

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">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   </form>

</body> </html></source>


Building Component Libraries by Using the C# Command-Line Compiler

   <source lang="csharp">

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.</source>


Components and Dynamic Compilation

   <source lang="csharp">

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.</source>


Component with Property

   <source lang="csharp">

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">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   </form>

</body> </html></source>


Declaring Fields and Properties

   <source lang="csharp">

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">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   </form>

</body> </html></source>


Declaring Methods

   <source lang="csharp">

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">
   <asp:Label
       id="lblMessage"
       Runat="server" />
   </form>

</body> </html></source>


Load server side assembly

   <source lang="csharp">

<%@ 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("
Location: "); sb.Append(assemblyInfo.Location); sb.Append("
FullName: "); sb.Append(assemblyInfo.FullName); sb.Append("
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( "

" + typeInfo.FullName + "

");
         sb.Append("Number of Constructors: ");
         sb.Append(typeInfo.GetConstructors().Length.ToString());
         sb.Append("
Number of Properties: "); sb.Append(typeInfo.GetProperties().Length.ToString()); sb.Append("
Number of Fields: "); sb.Append(typeInfo.GetFields().Length.ToString()); sb.Append("
Number of Events: "); sb.Append(typeInfo.GetEvents().Length.ToString()); sb.Append("
Number of Methods: "); sb.Append(typeInfo.GetMethods().Length.ToString()); sb.Append("
Is Class: "); sb.Append(typeInfo.IsClass); sb.Append("
Is Interface: "); sb.Append(typeInfo.IsInterface); sb.Append("
Is Enum: "); sb.Append(typeInfo.IsEnum); sb.Append("
Attributes: "); sb.Append(typeInfo.Attributes); sb.Append("
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>

<asp:label id="OutputClass" runat="server"></asp:label> </form> </body>

</html></source>


Make an assembly available to an ASP.NET application

   <source lang="csharp">

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.</source>


Mixing Different Language Components in the App_Code Folder

   <source lang="csharp">

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.</source>


Using ASP.NET Intrinsics in a Component

   <source lang="csharp">

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">

Show Preferences

   <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" />
   </form>

</body> </html></source>