27. august 2004 - 19:30Der er
24 kommentarer og 1 løsning
Egne klasse filer under asp.net
Jeg er i færd med at lege med den objektorienterede del af .net, men jeg har ét stort problem - hvordan i himlens navn refererer jeg til en fil med selskrevne klasser i ASP.NET? Jeg har tidligere fået svar på hvordan man gør i ren .net programmering ved at angive de enkelte sourcefiler som parametre til compileren. Men i ASP.NET bruger man jo ikke selv en compiler. Hvordan i hulen får jeg alle mine source filer kombineret, så klasserne i de enkelte fuier er til rådighed over alt? Jeg har læst mig frem til at man ikke længere anbefaler at bruge <!-- #Include - direktivet, hvilket alternativ er der i ASP.NET
Jeg laver f.eks en klasse
Class et { altmuligt }
Jeg gemmer denne klasse i en fil eks. et.vb
Jeg skriver en ny klasse, som f.eks skal arve eller anvende fra min "et klasse".
class to inherits from et { } Jeg gemmer denne klasse i en fil to.vb
to kender jo ikke klassen et, så der må da skulle laves en filreference til et.vb?
Jeg er klar over at jeg kan placere klasserne sammen i et namespace, men hvad nu hvis jeg har 2 namespaces i hver sin
I ASP.NET bliver du så vidt jeg ved nødt til at compile dine .cs/.vb filer til en assembly (.dll fil), kopiere den til bin dir og så kan din ASP.NET sider (.aspx filer) bruge klasserne.
Namespaces bør være ligegyldigt i denne sammenhæng.
Ja - men det burde være helt uafhængigt af det. I princippet kunne jeg find på, at arbejde med notepad eller et andet simpelt tekstprogram.
Når ASPX siden er ændret, vil den ved næste Load iværksætte en ny kompiilering, så de filer, som den afhænger af, må være specificeret et eller andet sted. Jeg har undersøgt <import namespace="" direktivet, men det er så vidt jeg kan se kun beregnet til kompilerede klasser?
hvis du bruger vs 2003 (ikke 2005 beta), vil der som standard bliver slået en dll over din formklasse også, så det er ikke helt ligegyldtigt med miljøet.
desuden er der nogle pagedirectives der spiller ind også... vs bruger f.eks. internt en code-behind="...", hvor du (hvis du arbejder i notepad) ville bruge en Src="...".
en googling på ord som asp.net codebehind vs src og inherits kan du finde mange gode forklaringer på, men du kan lige få lidt fra docs her :
Web Forms Code ModelSee Also Introduction to Web Forms Pages | Web Forms Page Processing | Compilation and Deployment of Web Projects A Web Forms page consists of two parts: visual elements (HTML, server controls, and static text) and the page's programming logic. Visual Studio stores each of these components in a separate file. The visual elements are created in an .aspx, and the code is in a separate class file, called the code-behind class file (.aspx.vb or .aspx.cs).
It is also possible to create the visual elements and code in the same file, which is sometimes called a "single-file" Web Forms page. This style of Web Forms page has limited support in Visual Studio. For details, see "Single-File Web Forms Pages" below.
Note Visual Studio does not support cross-language compiling in Web Forms pages and projects. This means it is not possible to include a Visual C# Web Forms page in a Visual Basic Web project, and vice versa. The ASP.NET Page Class Although a Web Forms page consists of two separate files, they form a single unit when your application is run. The code-behind class files for all Web Forms in a project are compiled into the dynamic-link library (.dll) file produced by the project. The Web Forms .aspx page file is also compiled, but somewhat differently. The first time a user browses to the .aspx page, ASP.NET automatically generates a .NET class file that represents the page and compiles it to a second .dll file. The generated class for the .aspx page inherits from the code-behind class that was compiled into the project .dll file.
This single .dll file is run at the server whenever the Web Forms page is requested. At run time, this .dll file processes the incoming request and responds by dynamically creating output and sending it back to the browser or client device.
If the page contains server controls, as is typical, the derived page class acts as a container for the controls. Instances of the controls are created at run time and likewise render output for the browser or client device.
For developers familiar with Active Server Pages (ASP), the ASP.NET page framework model represents something new. The ASP model is one of HTML extended with script code. The ASP page consists of script code, such as ECMAScript (JScript, JavaScript) or VBScript, coexisting with static HTML within the same file. The ASP parser reads the page, interprets it, and runs only the script code to get output results. ASP then merges the output of the script code with the static HTML output found in the page before sending the output back to the browser or client device.
In the ASP.NET Page class model, the entire Web Forms page is, in effect, an executable program that generates output to be sent back to the browser or client device. In this model, the page goes through a series of processing stages similar to those of other components — initialize, process, and dispose — with two differences:
The page class performs these steps each time the page is called. The page is initialized, processed, and disposed of every time a round trip to the server occurs. The page class has a unique stage —render— that occurs toward the end of the page life cycle, during which output is generated. For more information, see Control Execution Lifecycle. Note For efficiency, the information required to recreate the page may be cached, but this action is independent of its life cycle. Deriving from the Page Class When Visual Studio creates the page and class files for a Web Forms page, it generates code that inherits from the base Page class. For example, if you create a new Web Forms page and name it WebPage1, a new class named WebPage1 is derived from System.Web.UI.Page.
Depending on whether you have chosen Visual Basic or Visual C# for your development, Visual Studio generates either of the following lines of code:
' Visual Basic Public Class WebForm1 Inherits System.Web.UI.Page // C# public class WebForm1 : System.Web.UI.Page The .aspx page file in turn inherits from the derived WebPage1 class. The relationship of the base Page class, the derived class file, and the .aspx file is illustrated in the following diagram.
Web Forms Page Structure and the Page Base Class
Because the .aspx file is compiled dynamically when a user browses the page, its relationship to the class file is established with script directives at the top of the page. In Visual Studio, the relationship between .aspx files and class files is created and maintained automatically, even if you rename the Web Forms page. Specifically, the Inherits attribute of the @ Page directive is used to specify the class file from which the .aspx file is derived. A typical directive looks like this:
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1"%> The Codebehind, Inherits, and Src Attributes In Web Forms that use code-behind files, the @ Page directive (or @ Control in user control files) contains attributes that specify the relationship of the .aspx file and its code-behind file. These attribute are:
Codebehind In Visual Studio, this attribute references the name of a file that contains the class for the page. For example, if you create a Web Forms page in Visual Studio called WebForm1, the Codebehind attribute will point to WebForm1.aspx.vb or WebForm1.aspx.cs. This attribute is used only by the Visual Studio Web Forms Designer. It tells the designer where to find the page class so that the designer can create an instance of it for you to work with. The attribute is not used at run time. Inherits Identifies the class from which the page derives. In Visual Studio, this points to a class in the project assembly (.dll), as shown in the diagram above. The code-behind model illustrated above is the model used by Visual Studio. The ASP.NET Framework supports a slightly different code-behind model for Web Forms pages. In the ASP.NET code-behind model, the visual elements are in an .aspx file and the code is in a separate code-only file, as in Visual Studio. However, there is no project, and the code is not pre-compiled. Instead, the code in the .vb or .cs file is compiled at run time, when the page is first requested by a user.
The inheritance model works as illustrated above, with the difference that the Web Forms class (WebForm1 class in the diagram) is not part of a project assembly. Instead, each page is a separate assembly. There is no difference in how your code runs in the two models.
In the ASP.NET code-behind model, there is no Codebehind page attribute, since that attribute is unique to Visual Studio. To tie the .aspx file to its corresponding code, the page directive contains a Src attribute, which references the file containing the source code for the file.
The Src attribute is not supported in Visual Studio. If you import a Web Forms page into Visual Studio that contains the Src attribute, the designer will raise an error. For details, see The file could not be loaded into the Web Forms designer.
Single-File Web Forms Pages In addition to pages that are made up of an .aspx file and a separate class file, the ASP.NET architecture supports a "single-file" model in which the UI elements and code are in the same file. Single-file Web Forms pages are functionally very similar to pages consisting of two files. For example, you use the same controls on both types of pages. Users still request pages using the same .aspx extension for the file name, and the page is still run using server-side code and it streams HTML to the client. A single-file page has the advantage that it can be easier to deploy.
There are a few differences in the way single-file pages are processed:
The code for the page is not compiled into a separate class that the .aspx file then derives from. Instead, the .aspx file simply derives from the Page class. When the page is deployed, the source code is deployed along with the Web Forms page, since it is physically in the .aspx file. (The user does not see the code — only the results rendered when the page runs are sent to the user.) You can work with single-file Web Forms pages in Visual Studio, but because Visual Studio is oriented toward the two-file, code-behind model, there is more limited support for single-file pages. Differences include:
You cannot directly create a single-file Web Forms page in Visual Studio. When you create a new page, by default Visual Studio creates a separate .aspx file and class file. To create a single-file page, you must initially create it as a text file and then change its extension to .aspx. You cannot add non-visual components to the page (such as data components) by dragging them from the Toolbox, because the Web Forms Designer will not persist them in the page. Instead, you should add such components in code. You write code in HTML view, not in the Code Editor. When you are writing code, Intellisense is not supported — you do not get syntax checking or statement completion, tabbing, or code formatting. You must bind events to event handlers manually. For single-file Web Forms pages, Visual Studio does not support double-clicking to create the handler for a control's default event, nor the drop-down lists of classes and events in the Code Editor. Some debugging features, such as the ability to see a variable value by pointing the mouse at it, are not supported. Because the code in the page is not compiled into the project assembly, compile-time errors are not caught until the page runs. For more information about single-file Web Forms pages, see Working with Single-File Web Forms Pages in Visual Studio .NET.
See Also Introduction to Web Forms Pages | Web Forms Page Processing | Compilation and Deployment of Web Projects
Og denne her ville sikkert også være god... omhandlende hvordan du laver en multifile assembly: (denne her er på vb'sk, men hvis du bruger c# sakser jeg bare det ud istedet... bare sig til)
.NET Framework Developer's Guide
This section provides a complete example that illustrates the steps required to create a multifile assembly.
Step 1 — Compiling Files with Namespaces Referenced by Other Files This example starts with some simple code for the Stringer file. Stringer has a namespace called myStringer with a class called Stringer. The Stringer class contains a method called StringerMethod that writes a single line to the console.
[Visual Basic] ' Assembly building example in the .NET Framework SDK. Imports System Namespace myStringer Public Class Stringer Public Sub StringerMethod() Console.WriteLine("This is a line from StringerMethod.") End Sub End Class End Namespace
Use the following command to compile this code:
[Visual Basic] vbc /t:module Stringer.vb
Specifying the module parameter with the /t: compiler option indicates that the file should be compiled as a module rather than as an assembly. The compiler produces a module called Stringer.netmodule, which can be added to an assembly.
Step 2 — Compiling Modules with References to Other Modules This step uses the /addmodule compiler option. In this example, a code module called Client has an entry point Main method that references a method in the Stringer.dll module created in Step 1.
The following example shows the code for Client.
[Visual Basic] Imports System Imports myStringer 'The namespace created in Stringer.netmodule. Class MainClientApp ' Shared method Main is the entry point method. Public Shared Sub Main() Dim myStringInstance As New Stringer() Console.WriteLine("Client code executes") 'myStringComp.Stringer() myStringInstance.StringerMethod() End Sub End Class
Specify the /t:module option because this module will be added to an assembly in a future step. Specify the /addmodule option because the code in Client references a namespace created by the code in Stringer.netmodule. The compiler produces a module called Client.netmodule that contains a reference to another module, Stringer.netmodule.
Note The C# and Visual Basic compilers support directly creating multifile assemblies using the following two different syntaxes. Two compilations create a two-file assembly: [Visual Basic] vbc /t:module Stringer.vb vbc Client.vb /addmodule:Stringer.netmodule
One compilation creates a two-file assembly: [Visual Basic] vbc /out:Stringer.netmodule Stringer.vb /out:Client.exe Client.vb
Step 3 — Creating a Multifile Assembly Using the Assembly Linker You can use the Assembly Linker (Al.exe) to create an assembly from a collection of compiled code modules.
To create a multifile assembly using the Assembly Linker
At the command prompt, type the following command: al <module name> <module name> ... /main:<method name> /out:<file name> /target:<assembly file type>
In this command, the module name arguments specify the name of each module to include in the assembly. The /main: option specifies the method name that is the assembly's entry point. The /out: option specifies the name of the output file, which contains assembly metadata. The /target: option specifies that the assembly is a console application executable (.exe) file, a Windows executable (.win) file, or a library (.lib) file.
In the following example, Al.exe creates an assembly that is a console application executable called myAssembly.exe. The application consists of two modules called Client.netmodule and Stringer.netmodule, and the executable file called myAssembly.exe, which contains only assembly metadata . The entry point of the assembly is the Main method in the class MainClientApp, which is located in Client.dll.
al Client.netmodule Stringer.netmodule /main:MainClientApp.Main /out:myAssembly.exe /target:exe
You can use the MSIL Disassembler (Ildasm.exe) to examine the contents of an assembly, or determine whether a file is an assembly or a module.
Jo - men i det sidstnævnte omhandler det jo ikke ASP.net. Det er vel kun kompileringsmetoder som kan anvendes i forbindelse med VB.net og tilsvarende c#.net?
Eksemplet med webforms og codebehindform er ganske godt. Men jeg kan altså ikke forstå at codebehind-filen ikke kan opsplittes i flere filer. Jeg kan fint få det til at fungere med SSI, men jeg skulle mene at der måtte være en smartere og mere direkte implementeret metode - som kan kombinerer sourcekoder i ASP.NET.
du kan kun referere til én codebehind fil... men du kan sikkert godt proppe flere klasse ind i den. med asp.net 2.0 er der en mulighed for at lave partial classes, hvilket i praksis giver dig mulighed for at fordele en klasse på flere forskellige filer.
Jeg er bl.a. ASP-programmør, hvor jeg har arbejdet objektorienteret i det omfang, som vb-script nu tillod det. Her kunne jeg bruge <!-- include direktivet til at skabe adgang til mine ASP-filer og hermed til kildekoden. ASP.NET arbejder med compiler - byte-code o.s.v. Men det må kunne lade sig gøre at arbejde på en tilsvarende måde, hvor man kan vedligeholde forskellige sourcefiler, uden at det er nødvendigt at sikre sig, at de enkelte klasser er compileret først? <! -- Måske er det bare at bruge Include???
nej der er usercontrols er (bl.a.) erstatningen for includes, og lige en lille detalje. codebehind er udelukkende noget der bruges af visual studio, og du kan proppe alle de klasse ind i den som du vil.
Hej igen Nej Page går ikke, der kan kun være et direktiv/1 reference på hver side. Jeg fandt dog et andet i går aftet - så du er tæt på. @Assembly ser ud til at være løsningen.
Så vidt jeg kan se, så er @assembly beregnet til den "rå" vb kode eller c# kode. Hvis man forandrer i den, så bliver den kompileret i forbindelse med første page load. Det fungerer i hvert fald - lige som jeg gerne vil have det til.
@Register anvendes til user-controls. Nu er jeg ikke helt inde i terminologien endnu, men er en usercontrol ikke altid kode, som danner et visuelt objekt?
en usercontrol fungerer faktisk på samme måde som en form, og den måde du laver dem på er helt identisk med den måde du laver sider på. extension på filen der indeholder aspx-koden skal bare være ascx.
Ja, og det er netop forms, jeg gerne vil være foruden. I OO programmering bygger man som regel mange klasser, som intet har med formularer eller "skærmbilleder" at gøre.
Jeg synes at hele .net er et godt produkt - det har lært en del af java, måske oven i købet det meste. Jeg mener dog samtidigt, at hele ideen med code-behind-forms er en stor misforståelse fra microsofts side. Rent OO-programmeringsmæssigt burde konceptet være opbygget som Forms-behind-Code. I JSP anvender man servlets som leverer data og en form kan godt sammenlignes med det. Men man har gjort for meget ud af at fokusere på formularen som det centrale i en web-applikation. Det centrale er klasserne - forms er bare et hjækpemiddel til brugerinterfacet. Det ser dog indtil nu ud til, at man godt kan arbejde med Foms-behind-code i stedet, men @assembly er altså ét af de elementer, som jeg manglede, for at komme videre i det arbejde. Jeg regner med at lave en artikel på min side www.novra.dk, når jeg har fuldt overblik over ASP.Net strukturen og dens anvendelse i praksis.
Snepet - selv om du måske ikke lige gav det 100% præcise svar, så var det dialogen med dig, som skabte svaret, så pointsene er bestemt dine.
Mvh
Ole
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.