
Introduction
This article consists of two parts. The first part of the article explains how to use an ASP.NET script in a Windows Application. The ASP.NET script, when processed, basically generates HTML output, which is normally displayed by a web browser client like Internet Explorer or Netscape Navigator.
The second part of the article discusses use of Microsoft WebBrowser control in an application. This article does not cover this topic in very detail, but provides pointers to relevant information. This part of the article will display the HTML output generated in the first part.
Using ASP.NET Runtime
ASP.NET exposes a well-known interface that can be used to process a ASP.NET web page request. HttpRuntime, ApplicationHost and HttpWorkerRequest are important classes involved in this process.
The HttpRuntime is located in System.Web namespace. It is the entry point of the HTTP pipeline that transforms an aspx request to an HTML page. To transform an aspx page to HTML, its static method ProcessRequest is used. Following is the signature of the ProcessRequest function.
public static void ProcessRequest(
HttpWorkerRequest wr
);
Before using HttpRuntime, it should be passed all required information. The class HttpWorkerRequest class is used for this purpose. SimpleWorkerRequest is a simple implementation of HttpWorkerRequest that can be used to pass required parameters. Following shows constructor signature of the class.
public SimpleWorkerRequest(
string page,
string query,
TextWriter output
);
The following code snippet can be used to transform an aspx page to an HTML page and send the HTML page to the console. Remember, this code snippet should be run in a new AppDomain created by the client. As explained in the coming sections, the class ApplicationHost can be used for this purpose.
SimpleWorkerRequest = new SimpleWorkerRequest(aspxPage,
query,
Console.Out);
HttpRuntime.ProcessRequest(req);
It should be noted that the HttpRuntime can be used only in a new AppDomain. The caller of the ASP.NET runtime should create a new AppDomain for the ASP.NET runtime environment, and the ProcessRequest method of the HttpRuntime should be called in the newly created AppDomain. The new AppDomain can be created by using the AppDomain and the Assembly classes if the .NET framework. However, the ApplicationHost class is bundled with the .NET SDK exactly for this task, and simplifies the programming work involved. This article uses ApplicationHost class. The only method of this class, CreateApplicationHost, is used for this purpose. It's signature is given in the following code snippet.
public static object CreateApplicationHost(
Type hostType,
string virtualDir,
string physicalDir
);
Above call loads the assembly containing the class hostType in the new AppDomain created and returns a reference to it. Remember the hostType is created in the newly created AppDomain and only the reference (actually proxy) is returned. Its use is shown in the following code snippet.
MyHost host = new ApplicationHost.CreateApplicationHost(
typeof("MyHost"),
"/foo",
Environment.CurrentDirectory);
The following section summarizes the steps required to use the ASP.NET runtime in a Windows application.
- Create a new AppDomain to call the
HttpRuntime.PrecessRequest method on the web page to be processed. This results in HTML being generated from the ASP.NET web page. The output is sent to the StreamWriter passed as a third parameter in the function call, HttpRuntime.ProcessRequest.
- Either process the HTML page directly from the
StreamWriter or save the output generated to a file. The save file can be used later. This article saves the HTML output to a file, which is used later.
- Use the HTML output generated in your application. This article uses the Microsoft HTML
WebBrowser control to display the HTML output.
The following code snippet, from the code included with article, shows the steps 1 and 2.
host = (MyHost)ApplicationHost.CreateApplicationHost(
typeof(MyHost),
"/foo",
Environment.CurrentDirectory);
host.CreateHtmlPage(webPage, null, m_outFile);
CreateHtmlPage function of the MyHost class is given below. Note that the HTML output generated will be saved to a file specified by the third parameter. This file will be later displayed by the WebBrowser control.
public void CreateHtmlPage(String webPage,
String query,
String file)
{
StreamWriter stream = new StreamWriter(file);
SimpleWorkerRequest swr = new SimpleWorkerRequest(
webPage,
query,
stream);
HttpRuntime.ProcessRequest(swr);
stream.Close();
}
Using Microsoft WebBrowser Control
Using Microsoft WebBrowser control is explained in the article Using the WebBrowser Control in .NET by Nikhil Dabas in detail. The process is summarized in the following steps.
- Import the assemblies from the
WebBrowser control, SHDocVw.dll, using the command given below. It will generate two assemblies AxShDocVw.dll and SHDocVw.dll. aximp c:\windows\system\shdocvw.dll
- Use the imported
WebBrowser control in the .NET application. The control to be used is AxSHDocVw.AxWebBrowser.
To use the WebBrowser control in this article, following code is used.
private AxSHDocVw.AxWebBrowser m_Browser;
this.m_Browser = new AxSHDocVw.AxWebBrowser();
this.label = new System.Windows.Forms.Label();
this.txtFile = new System.Windows.Forms.TextBox();
this.cmdOpen = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)
(this.m_Browser)).BeginInit();
this.SuspendLayout();
this.m_Browser.Anchor =
((System.Windows.Forms.AnchorStyles)
((((System.Windows.Forms.AnchorStyles.Top
| System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_Browser.Enabled = true;
this.m_Browser.Location = new System.Drawing.Point(0, 72);
this.m_Browser.Size = new System.Drawing.Size(360, 232);
this.m_Browser.TabIndex = 0;
The ASP.NET runtime requires the binaries to be located either in GAC or in the bin sub directory of the web application. The build script included with the code automatically copies the required assemblies in the bin directory. If you get an exception like "System.IO.FileNotFoundException", check this point.
Running the Application
Use either the command line "UsingAspRuntime.exe AspxFileName" or specify the aspx file in the Filename Text Box and click open button. Two ASP.NET files, test.aspx and test2.aspx, are included with the code.
History
First Update
- Updated the source code to support PostBack.
- Update the source code to create only one AppDomain to process all the requests.
- Updated the source code to handle files other than ASP.NET.
|
|
 |
 | How to catch the error? vcpp2003 | 20:54 20 Dec '04 |
|
 |
Hi, The sample is wonderful,but how can i catch the error in the .aspx file,e.g. in test0.aspx,if i change "Current Time is: <%=Now%>" to "Current Time is: <%=NowError%>",a complier error raised in the browser.how can i catch the error in the program,but not in the aspx page.
Thanks
vcpp2000
|
|
|
|
 |
 | MFC/C++ sealspecop | 11:08 14 Nov '04 |
|
 |
How can I connect to the Runtime from within an MFC/C++ application?
|
|
|
|
 |
 | Very Good epoluodi | 5:10 8 Apr '04 |
|
 |
I am Studying.........
支持!!!!
|
|
|
|
 |
 | Call JScript function from C# embedded WebBrowser mrader | 1:11 8 Jan '04 |
|
 |
I have embedded a web browser into a windows form. How can I detect / call a script which is embedded in the loaded document? Actually, I know the name of the script and what the parameters would be, but have no clue who to actually execute it. All I find on MSDN are C++ COM samples that don't help me in my .NET environment. Regards, Michael
|
|
|
|
 |
|
 |
You have to use MSHTML COM library.
1. Add Reference to COM library 'Microsoft HTML object library' 2. Add the following code sample
void ExecuteScript(string script) { mshtml.IHTMLDocument2 doc = m_Browser.Document as mshtml.IHTMLDocument2;
if (null != doc) { mshtml.IHTMLWindow2 win = doc.parentWindow;
win.execScript(script, "javascript"); } }
Hope this help, Conrad
|
|
|
|
 |
|
 |
Thanks for that code snippet!
More than just, Senior Systems Programmer @ VoxTechnologies
|
|
|
|
 |
 | StrongName version? eric914 | 6:21 16 Dec '03 |
|
 |
I'm unable to completely strongname the web control. I'm getting: The located assembly 'SHDocVw' is not strongly named.
I have taken both SHDocVw.dll and AxSHDocVw.dll, decompiled them, and recompiled them w/ the strong name key. That has finally allowed me to instantiate the Ax object, but now it gives me the message above.
I've opened up the SHDocVw in ildasm and can see the key is there. Other than the original COM .dll itself, this is the only other file named SHDocVw.dll.
Any suggestions?
|
|
|
|
 |
|
 |
"Wrapper Assembly Key File" entry at the Properties of the project (General Tab).
|
|
|
|
 |
 | passing object to web service hnipak | 5:44 30 Jul '03 |
|
 |
Hello,
is there a way to pass an object (eg. callback delegate) to web service so that it can grab it from somewhere (HttpContext or so) from asp.net runtime hosting application?
Thank you!
Regards, Ales
|
|
|
|
 |
 | How to execute aspx content in a string? José Proença | 5:55 25 Jul '03 |
|
 |
Hi,
All ways that I know of running a aspx file, to produce HTML, use a file as the source code. Is there a way of feeding the aspx code from a string?
I've tried to extend the SimpleWorkerRequest class to find where the data is feed, so I could feed in my data from a string, but to no avail...
Please help,
ztp
|
|
|
|
 |
|
 |
Was there ever a solution for this problem, if so could it be posted. Thanks
PRH
|
|
|
|
 |
 | FileNotFoundException daDude | 19:07 23 Jun '03 |
|
 |
Hi,
I am getting the following error message: An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
on line: host = (MyHost)ApplicationHost.CreateApplicationHost(typeof(MyHost), "/foo", Environment.CurrentDirectory);
Which file is it trying to open?
Thanks.
|
|
|
|
 |
|
 |
Hi,
Its looking for a file containing MyHost class. It is included with the main program itself (UsingAspRuntime.exe). The ASP.NET runtime looks for all assembalies in the bin directory. So be sure that the bin directory has been created and it contain the UsingAspRuntime.exe. The build script does this automatically.
Thanks Shivpal
|
|
|
|
 |
|
 |
Is there any way to tell ASP.NET not to look in the bin directory before you set the application environment up? It would be really nice if it didn't do this, so you could use the executing copy of the executable, rather than a copy in the bin folder. There must be a way to do this. I see that HttpContext has a 'BinDirectory' property, but it's read only.
|
|
|
|
 |
|
 |
You could create a dummy web.config file in your app directory
<?xml version="1.0" encoding="utf-8" ?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin\.."/> </assemblyBinding> </runtime> </configuration>
Conrad
|
|
|
|
 |
|
 |
cant get this to work at all
charles black
|
|
|
|
 |
|
 |
I am getting the same error, and I have my output set to the /bin directory, so finding the EXE is definitely not the issue. I can manually create an instance of my object using Activator.CreateInstance, however CreateApplicationHost() fails every time...
|
|
|
|
 |
 | Memory / handle consumption Marc Sommer | 4:05 5 Jun '03 |
|
 |
Each page request leads to an increasing use of memory (approx. 1 to 3 MB additionyl per request). After 30 or 40 page requests and quitting the application, used handles decrease by 600 according to TaskManager WinXP.
Marc
|
|
|
|
 |
|
 |
The memory consumption is because for each request a new AppDomain is created. There are two solutions for it. The first one to create the AppDomain manually instead of using ApplicationHost.CreateApplicationHost and unload it when the HTML is generated. The second approach that should work fine here is to re-use the same AppDomain repeatedly. For this make the following changes.
1. make local variable 'MyHost host = null;' a class variable. 2. Modify the function InitBrowserComponent as given below. The change done is the the host is not created every time but only once. Remember, the host is actually created in a new ApppDomain.
private void InitBrowserComponent(String webPage) { Object obj = null; if (host == null) { host = (MyHost)ApplicationHost.CreateApplicationHost( typeof(MyHost), "/foo", Environment.CurrentDirectory); } host.CreateHtmlPage(webPage, null, m_outFile); m_Browser.Navigate("file://" + Environment.CurrentDirectory + "/" + m_outFile, ref obj, ref obj, ref obj, ref obj); // update the test box with the file name currently open in the // browser component txtFile.Text = webPage; } Since a new AppDomain is not created for every request, it should also boost performance.
|
|
|
|
 |
 | Speed Marc Sommer | 3:48 5 Jun '03 |
|
 |
I am totaly new to the ASP part of .net. I am amazed beeing able to handle web forms without the need of IIS. I tried the application with some aspx code behind samples and they work like a charm.
But speed seems not to be very satisfying. I takes approx. 5 seconds to render a simple page. For a win gui application this is really unacceptable. Is there a way to speed up things? Keep the asp.net engine in memory? How would this be handled through IIS? Requests are handled much faster, so there should be a way to do it.
Marc
|
|
|
|
 |
|
 |
Try the changes as suggested in Memory / Handle consumption. I think its speed will always be less than a gui desktop app.
|
|
|
|
 |
 | Postback Jochen Jonckheere | 1:08 3 Jun '03 |
|
 |
Nice piece of code!
I wan't to use it in my application, but it doesn't work with postback. Is there a way to solve this?
|
|
|
|
 |
|
 |
Thanks
While creating a new domain for processing new ASP.NET request, the physical and virtual directory is specified. For it to work, all the files must be located in the same physical directory. This is a limitation of this method. Other than this limitation, it should work fine.
|
|
|
|
 |
|
 |
Hi, I just updated the code to support the Postback. Please check it out.
Thanks
|
|
|
|
 |
|
 |
Hello shivpal,
You wrote: I just updated the code to support the Postback. Please check it out.
It seems that it do *not* work. can you give me any hint how to run the example below ?
Thanks in advance
Uwe ------ test.aspx ------ <html> <head>
<script language="C#" runat="server">
void Button1_Click(Object Sender, EventArgs e) { Label1.Text = System.Web.HttpUtility.HtmlEncode(Text1.Text); }
</script>
</head> <body> <form runat="server">
<asp:Label id="Label1" Text="Label1" Width="200px" runat="server"/>
<asp:TextBox id="Text1" Text="copy this text" Width="200px" runat="server" />
<asp:Button id="Button1" Text="Kopieren" OnClick="Button1_Click" Runat="server"/>
</form>
</body> </html> ------
|
|
|
|
 |
|
|
Last Updated 25 Jun 2003 |
Advertise |
Privacy |
Terms of Use |
Copyright ©
CodeProject, 1999-2010