Embedding ASPX in ASP page - asp.net

I have an ASPX based component which I'd need to inlude into a plain ASP based
script. Scenario is, that I'm working within an LMS system (Angel to be exact)
and I wan't to create a new nugget within that framework. An Angel nugget is
pretty much what a portlet is in the Java world.
Now, the nugget spec. states that my starting point has to be a file called
default.asp. What I'd like to do is:
read relevant data from ASP session
pass data to ASPX component
have ASPX do it's job and display the results
My problem is that I fail to run / display my ASPX component without
using an iframe, which I want to avoid since that crushes the layout /
design of my nugget.
Is there a way to get this done properly or do I have to rewrite my
component in ASP to get this going?
Note: the component performs
web service queries and such and I'd like to avoid rewriting that.

Why don't you grab the .aspx content from the .asp page using the MSXML object?
url = "http://www.yoururl.com/YourPage.aspx?relevantData=YourRelevantData"
Set xml = Server.CreateObject("Msxml2.SERVERXMLHTTP")
xml.Open "GET",url,False
xml.send
html = xml.ResponseText
Set xml = Nothing
Response.Write(html)

Related

ASP.NET - Parse / Query HTML Before Transmission and Insert CSS Class References

As a web developer I feel too much of my time is spent on CSS. I am trying to come up with a solution where I can write re-usable CSS i.e. classes and reference these classes in the HTML without additional code in ASPX or ASCX files etc. or code-behind files. I want an intermediary which links up HTML elements with CSS classes.
What I want to achieve:
Modify HTML immediately before transmission
Select elements in the HTML
Based on rules defined elsewhere (e.g. in a text file relating to
the page currently being processed):
Add a CSS class reference to multiple HTML elements
Add multiple CSS class references to a single HTML element
How I envisage this working:
Extend ASP.NET functions which generate final HTML
Grab all the HTML as a string
Pass the string into a contructor for an object with querying (e.g. XPATH) methods
Go through list of global rules e.g. for child ul of first div then class = "navigation"
Go through list of page specific rules e.g. for child ul of first div then class &= " home"
Get processed HTML from object e.g. obj.ToString
ASP.NET to resume page generation using processed HTML
So what I need to know is:
Where / how can I extend ASP.NET page generation functions (to get all HTML of page)
What classes have element / node querying methods and access to attributes
Thanks for your help in advance.
P.S. I am developing ASP.NET web forms websites with VB.net code-behinds running on ISS 7
Check out my CsQuery project: https://github.com/jamietre/csquery or on nuget as "CsQuery".
This is a C# (.NET 4) port of jQuery. In basic performance tests (included in the project test suite) selectors are about 100 times faster than HTML Agility Pack + Fizzler (a css selector add-on for HAP); it's plenty fast for manipulating the output stream in real time on a typical web site. If you are amazon.com or something, of course, YMMV.
My initial purpose in developing this was to manipulate HTML from a content management system. Once I had it up and running, I found that using CSS selectors and the jQuery API is a whole lot more fun than using web controls and started using it as a primary HTML manipulation tool for server-rendered pages, and built it out to cover pretty much all of CSS, jQuery and the browser DOM. I haven't touched a web control since.
To intercept HTML in webforms with CsQuery you do this in the page codebehind:
using CsQuery;
using CsQuery.Web;
protected override void Render(HtmlTextWriter writer)
{
var csqContext = WebForms.CreateFromRender(Page, base.Render, writer);
// CQ object is like a jQuery object. The "Dom" property of the context
// returned above represents the output of this page.
CQ doc = csqContext.Dom;
doc["li > a"].AddClass("foo");
// write it
csqContext.Render();
}
To do the same thing in ASP.NET MVC please see this blog post describing that.
There is basic documentation for CsQuery on GitHub. Apart from getting HTML in and out, it works pretty much like jQuery. The WebForms object above is just to help you handle interacting with the HtmlTextWriter object and the Render method. The general-purpose usage is very simple:
var doc = CQ.Create(htmlString);
// or (useful for scraping and testing)
var doc = CQ.CreateFromUrl(url);
// do stuff with doc, a CQ object that acts like a jQuery object
doc["table tr:first"].Append("<td>A new cell</td>");
Additonally, pretty much the entire browser DOM is available using the same methods you use
in a browser. The indexer [0] returns the first element in the selection set like jquery; if you are used to write javascript to manipulate HTML it should be very familiar.
// "Select" method is the same as the property indexer [] we used above.
// I go back and forth between them to emphasise their interchangeability.
var element = dom.Select("div > input[type=checkbox]:first-child")[0];
a.Checked=true;
Of course in C# you have a wealth of other general-purpose tools like LINQ at your disposal. Alternatively:
var element = dom["div > input[type=checkbox]:first-child"].Single();
a.Checked=true;
When you're done manipulating the document, you'll probably want to get the HTML out:
string html = doc.Render();
That's all there is to it. There are a vast number of methods on the CQ object, covering all the jQuery DOM manipulation techniques. There are also utility methods for handling JSON, and it has extensive support for dynamic and anonymous types to make passing data structures (e.g. a set of CSS classes) as easy as possible -- much like jQuery.
Some More Advanced Stuff
I don't recommend doing this unless you are familiar with lower-level tinkering with asp.net's http workflow. There's nothing at all undoable but there will be a learning curve if you've never heard of an HttpHandler.
If you want to skip the WebForms engine altogether, you can create an IHttpHandler that automatically parses HTML files. This would definitely perform better than overlaying on a the ASPX engine -- who knows, maybe even faster than doing a similar amount of server-side processing with web controls. You can then then register your handler using web.config for specific extensions (like htm and html).
Yet another way to automatically intercept is with routing. You can use the MVC routing library in a webforms app with no trouble, here's one description of how to do this. Then you can create a route that matches whatever pattern you want (again, perhaps *.html) and pass handling off to a custom IHttpHandler or class. In this case, you're doing everything: you will need to look at the path, load the file from the file system, parse it with CsQuery, and stream the response.
Using either mechanism, you'll need a way to tell your project what code to run for each page, of course. That is, just because you've created a nifty HTML parser, how do you then tell it to run the correct "code behind" for that page?
MVC does this by just locating a controller with the name of "PageNameController.cs" and calling a method that matches the name of the parameter. You could do whatever you want; e.g. you could add an element:
<script type="controller" src="MyPageController"></script>
Your generic handler code could look for such an element, and then use reflection to locate the correct named class & method to call. This is pretty involved, and beyond the scope of this answer; but if you're looking to build a whole new framework or something this is how you would go about it.
Intercepting the content of the page prior to it being sent is rather simple. I did this a while back on a project that compressed content on the fly: http://optimizerprime.codeplex.com/ (It's ugly, but it did its job and you might be able to salvage some of the code). Anyway, what you want to do is the following:
1) Create a Stream object that saves the content of the page until Flush is called. For instance I used this in my compression project: http://optimizerprime.codeplex.com/SourceControl/changeset/view/83171#1795869 Like I said before, it's not pretty. But my point being you'll need to create your own Stream class that will do what you want (in this case give you the string output of the page, parse/modify the string, and then output it to the user).
2) Assign the page's filter object to it. (Page.Response.Filter) Note that you need to do it rather early on so you can catch all of the content. I did this with a HTTP Module that ran on the PreRequestHandlerExecute event. But if you did something like this:
protected override void OnPreInit(EventArgs e)
{
this.Response.Filter = new MyStream();
base.OnPreInit(e);
}
That would also most likely work.
3) You should be able to use something like Html Agility Pack to parse the HTML and modify it from there.
That to me seems like the easiest approach.

ASP script code inside ASP.NET page?

how to use ASP code inside ASP.NET ?
is it possible to run ASP script code inside ASP.NET page ?
If so, please give an example.
thanks
--
ASP code might look like this. So how do we such such script inside ASP.NET ?
Function changeColor(value, random)
Dim colorArray
colorArray = Split(value, ",")
divBlockColor = colorArray(random Mod (UBound(colorArray) + 1))
End Function
I'm affraid it isn't possible, as ASP Code runs in a different application environment as asp.Net. That's also why for example session("xyz") is not shared between Classic ASP and ASP.Net web pages in the same website.
What you could do is leave the asp code in a .asp page, and use forms with POST to go back and forth to the asp code. This way you will not have to rewrite the entire .asp environment, and you can migrate to .Net one bit at a time.
This way you can leave all your existing code, and use simple javascript to automatically submit the forms, posting the values back to .Net

how to use NVelocity from asp.net webforms?

I want to use "NVelocity" from plain ASPX pages without using any MVC framework. I don't want to use "NVelocity View Engine" thru' asp.net MVC framework. The only example that I got for "NVelocity" is for merging and writing onto console window (http://www.castleproject.org/others/nvelocity/usingit.html)
I am looking out for example on to integrating "NVelocity" into aspx web forms. Any pointers would be really helpful.
I found a way. The idea is the override Page.Render() method in an aspx page. Write the code in Render() method to transform the HTML template (I mean, *.html file or *.aspx file) using NVelocity. Pass HTMLTextWriter object while merging the template and context "template.Merge(context, writer);"
This will render the transformed HTML to web browser.

ASP.NET 2.0 -how do I include files containing server-side code?

I want to be able to load a customized log in page depending on a couple of parameters passed into the querystring.
Each customized login page needs to be able to dynamically display log in errors and possibly have other variables passed in.
Let's say the dynamic login page looks like this (over-simplification here):
<form>
<% if (has_errors) { Response.Write(error_msg); } %>
<input type="text" name="email">
</form>
If the aspx page loads the file like this:
Response.writefile("path/to/custom/page");
the code shows up in the output and doesn't get processed. I have tried other ways to load the file contents (something similar to classic ASP includes) but get the same results every time.
I could have all the custom pages set up as user controls, but I need 100% control over the css, js, and html - and the documentation I read here indicates that I won't have that level of granularity.
link text
PLUS - I'm stuck in a .net 2.0 environment - so .NET MVC is not available to me
Any help/suggestions?
but I need 100% control over the css,
js, and html
You won't get 100% over the page but you will have control inside the User Control instance. Also, many times, you can override these technologies like CSS, from within your control.
In the end because all controls are solified into one big HTML page you will have the same level of control as you would in any single web page with client-side technologies.
You can build a Web UserControl to represent log/in and then include an instance of that control onto any page, in any place, across multiple pages if you wish.
(See the Topics on that MSDN help page about how to create and use it).
Other useful references (these are various angles on the same subject).
Creating a Web user Control in .NET
ASP 101 - User Controls
This should provide a good start to keep looking, if this is the kind of info you think you need.
Internals
The User Control can have its own logic, access the browser querystring, access the page Session, Application, etc. pretty much anything it needs to know for itself to work.
Object Oriented
Additionally, because a User Control is also an object, you can add your own public methods and properties to it through which you can interact to communicate with the control intance on the page (just like you interact with other web controls like Button.Text="click", TextBox.BackColor = System.Drawing.Color.Blue, etc).
Other Options - Dynamic control loading
You might want to consider loading controls dynamically at runtime using the Page.LoadControl(..) method:
Loads a Control object from a file
based on a specified virtual path.
MyControl myControl1 = (MyControl)LoadControl("TempControl_Samples1.cs.ascx");
PlaceHolder1.Controls.Add(myControl1);

ASP.NET, XSLT and dynamic controls

I wish to use xml and xsl to generate controls on an asp.net page.
I currently have a asp.net content page that contains a xml control. When the page is loaded, an xml file is loaded and the required element is extracted and set as the xml control's DocumentContent and the xml control's TransformSource is set to the appropriate xsl file.
In the xsl file, I wish to use templates to create asp.net controls depending upon the contents of the xml. Is there an easy way of doing this with the xml control on the content page?
Register a namespace in your XSL so that you can put .NET server-side tags into it. Run your XSL transform against your XML. Run the result of your transform through Page.ParseControls(). This will give you a nice control hierarchy. Add the output of that function to your Controls collection (or the controls collection of your placeholder) and you're good to go.
There are LOTS of caveats to using dynamic controls in .NET, so beware.
The generated output of transform is not parsed to be added to the page as set of controls. Rather the generated output is sent to the response. Therefore you cannot apply a transform to an XML control that will generate new controls.
There may be a way to create the transform result and invoke some parsing that can be applied to the page but that would not meet your 'easy' requirement.
I don't know of any easy way to do it, but there are a few systems out there which generate the aspnet markup on the fly then send it to the aspnet runtime from a memory stream (or similar).
I think umbraco uses a system something like that, but the initial builder mechanism is probably a little more low level than an aspnet control. It might be achievable using an httpmodule or something else that gets hit earlier in the request pipeline.

Resources