TRICK: methods in ASPX pages with <%%> code blocks

J

John Rivers

Hello,

What good reason there is for not allowing methods in ASPX pages I
can't imagine, but here is how to get around that limitation:

(START)
<body MS_POSITIONING="FlowLayout">

<form id="Form1" method="post" runat="server">
<%
MyMethod(__output);
%>
</form>
</body>
</html>
<%
}
void MyMethod(System.Web.UI.HtmlTextWriter __output) {
%><input type="text" name="Name" value="some html"/><%
%>
(END)

how this works:

ASP.NET takes your ASPX code and inserts it into a hidden Render
method that takes HtmlTextWriter as an argument

we use "}" to close the current render method
then declare a method that takes the same argument
we don't need to put a closing brace because ASP.NET will
do that for us
 
L

Lucas Tam

What good reason there is for not allowing methods in ASPX pages I
can't imagine, but here is how to get around that limitation:

It makes for messy code?
 
J

John Rivers

My Classic ASP isn't messy
it is a beautiful set of classes that render html
handles multi-branding
perform top-notch best-of-practice datasheets and forms
with full locking and security that run at full speed
and can be tested quickly and easily

what IS messy is a bunch of "UserControl" files
which miss out on all the benefits of object oriented programming
leave my ASPX pages full of messy register tags
and non-standardised property accesses

a UserControl is just a single method in a file
instead of in a class where it belongs

it is silly!
 
M

Marina

Who says you can't have methods in the page?

Just put your methods in <script runat="server"></server"

And as someone mentioned, even though you can do this, you shouldn't. There
is no reason you can't put it in a code behind file, or in a class library
DLL.
 
T

tom pester

I like my code and functions inside the aspx page itself unless the project
architecture tells you otherwise.
If you develop in a small team the separion isn't necessary and VWD now has
full intellisense support for this scenario.

The fact that you can't have pure html in a function annoyed me very much
too when coming from cASP but you get used to it.
I think they made it impossible for performance reasons cause mixing code
with HTML did have a noticable negative perfermance effect.
Maybe they wanted to eliminate a bad programming practice?

Cheers,
Tom Pester
 
M

Marina

Even when you develop in a small team, there are many advantages to not
putting your code right in the .aspx.
1) reusability - not unlikely your function will be useful elsewhere
2) compile time error checking
3) easier to read, as it's not mixed in with HTML

list goes on and on.

So yes, you can do it. But I still don't see why you would want to.
 
T

tom pester

Hi Marina,
1) reusability - not unlikely your function will be useful elsewhere

If its a common function it should be in a class file and not in the code
behind file right?
The cases where you can reuse a code behind file are rare and I haven't spotted
them in the wild.
2) compile time error checking

Doesn't asp.net version 2 solve this?
3) easier to read, as it's not mixed in with HTML

I am not saying to mix html with code. Thats a bad idea generaly.
If I do everything in 1 file I still seperate logic from presentation but
now I put all me code in the <script runat=server> block.
The only difference is that the code is now embeded in the page itslef. That
is the only difference.
It's crucial that you understand this.
list goes on and on.

What else?
So yes, you can do it. But I still don't see why you would want to.

The code behind model has been pushed very hard in VS 2002/3 and the main
reason I used it was the lack if intellisense in the aspx file.
Now that this restriction is taken away why would I use a code behind?

The question to ask is why would you put your code in a seperate file?

I can think of 2 reasons :

1) it _promotes_ (and nothing more) thinking where code is separated from
presentation (MVC model)
2) a designer can work on the aspx file while the programmer works on the
code behind (that's not an argument of mine. I read it in the ms docs)

I find these 2 arguments not good enough. Allthough the first point can be
helpful for beginners.

There is no reason for me to have 100 files in my project when I could have
50 instead (or 1000/500 for that matter). I like to work fast and scrolling
to the top of the page to alter some code is just that little faster.
I don't like switching files. I know it takes maybe 1 second but when I program
I switch betweeb files a lot. That argument doesn't hold on big monitors
or dual views.

I can't come up with any other reason that those 2 I mentioned.

Cheers,
Tom Pester
 
M

Marina

A code behind file is really a specialized class file. My point was, the
code should be in something that gets compiled into a DLL. Whether it's in
a class library that is unrelated to asp.net, or in a codebehind file - it
is really the exact same thing. It gets compiled into a DLL.

I don't know what 2.0 does, or how much it improved the IDE in that regard.

In my opinion, having code in <script> tags, is mixing it with HTML. As in,
there is HTML in that file, and there is code in that file. And it's all in
there together.

I find the 2 arguments you listed more then enough to support the reasons
for doing it. Except with the change, that it more the promotes thinking
about these 2 things as separate. There is a lot to be said from separating
your UI from the business logic.

And sorry, but your reasons for not doing just don't make sense to me. I
don't care if I have 100 files or 50 files. You still just see one icon in
VS, and you can either go to design view, or you can go to code. You don't
see twice as many files - so who cares if in reality there are?

It sounds like your UI and your business logic is all intermixed together.
This will make it very difficult to re-architect (not that it sounds like
there is a lot of architecture) or change things later on, since everything
is all over the place.

In any case, microsoft didn't limit anyone to any one model of how things
should be done. If this way works for you, go ahead.
 
T

tom pester

Hi Marina,
I find the 2 arguments you listed more then enough to support the
reasons for doing it. Except with the change, that it more the
promotes thinking about these 2 things as separate. There is a lot to
be said from separating your UI from the business logic.

I am all for the seperation of logic and presentation and business logic
should defenetily go into its own space regardless of how small the project
is.
But the little code you write for wiring things up, ie that are specific
to the GUI, don't need seperation cause its specific and thus not reasuable.

A function that gets all orders from a database should be in a class library
(and I mean not code behind).
IMO A function that wires up the result to a datagrid doesn't have to be
in a class.

BTW Everything in ASP.NET is a class. The aspx file too. It gets transformed
by a parser to a plain class :

http://dotnetdan.com/articles/aspnet/FirstPrinciples.htm
http://dotnetdan.com/articles/aspnet/DataBinding.htm

So by that rational I do everything in a class file so I must be doing it
right ;)
And sorry, but your reasons for not doing just don't make sense to me.
I don't care if I have 100 files or 50 files. You still just see one
icon in VS, and you can either go to design view, or you can go to
code. You don't see twice as many files - so who cares if in reality
there are?

I hear you but I like to keep everything KISS. So there must be a _good_
reason if I have to double the project in files.
In any case, microsoft didn't limit anyone to any one model of how
things should be done. If this way works for you, go ahead.

The arguments you make are all solid but for me the separation between markup
and wire up code (not Business Logic) is a logical one.
You can make it a physical separition by splitting the file in 2. But what
does it give you? IMO not more power, except for the 2 reasons that are only
a consequence of making it physical.

Cheers,
Tom Peste
 
K

Kevin Spencer

who has it?

People who have diligently sought it for many years. People who can accept
painful truth, especially about themselves, and who are willing to change in
response to those truths.
why not me?

No reason whatsoever. The sooner you get started seeking it, the sooner you
will find it. but it takes a great deal of time, patience, and persistence.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Paranoia is just a state of mind.
 
J

John Rivers

Thankyou for your friendly post,

could you please give me more specific benefits to this approach than
"not really object oriented"

what actual advantages (and disadvantages) does the approach you are
suggesting actually have in contrast to simply using html literals?

Do you think the advantages outweigh the disadvantages?

You see I think this approach has so many disadvantages it is unusable.

And if you read many of the posts in this newsgroups you will see
people struggling with a level of complexity and unpredictability that
is simply unecessary.

Please think it through fully and decide.
 
G

Guest

Look at the following code:

1: using System;
2: using System.Web.UI;
3: using System.Web.UI.WebControls;
4: using System.ComponentModel;
5: using System.Text;
6:
7: namespace markberck.UI.WebControls
8: {
9: [DefaultProperty("Url"),
10: ToolboxData("<{0}:IFrameControl
runat=server></{0}:IFrameControl>")]
11: public class IFrameControl : System.Web.UI.WebControls.WebControl
12: {
13: private Unit height;
14: private Unit width;
15: private bool border;
16: private string borderStyleString;
17: private string url;
18:
19: #region Properties
20: [Bindable(true), Category("Appearance"), DefaultValue("")]
21: public override Unit Height
22: {
23: get {return height;}
24: set {height = value;}
25: }
26: [Bindable(true), Category("Appearance"), DefaultValue("")]
27: public override Unit Width
28: {
29: get {return width;}
30: set {width = value;}
31: }
32: [Bindable(true), Category("Appearance"),
DefaultValue("false")]
33: public bool Border
34: {
35: get {return border;}
36: set {border = value;}
37: }
38: [Bindable(true), Category("Data"), DefaultValue("")]
39: public string BorderStyleString
40: {
41: get {return borderStyleString;}
42: set {borderStyleString = value;}
43: }
44: [Bindable(true), Category("Data"), DefaultValue("")]
45: public string Url
46: {
47: get {return url;}
48: set {url = value;}
49: }
50: #endregion
51:
52: protected override void Render(HtmlTextWriter output)
53: {
54: if (this.url != null)
55: {
56: StringBuilder sbOutput = new StringBuilder();
57: sbOutput.Append("<iframe");
58: sbOutput.Append(" src=\"" + this.url + "\"");
59: if (!height.IsEmpty)
60: sbOutput.Append(" height=\"" + buildUnit(height)
+ "\"");
61: if (!width.IsEmpty)
62: sbOutput.Append(" width=\"" + buildUnit(width)
+ "\"");
63: if (Border)
64: {
65: if(borderStyleString != null)
66: sbOutput.Append(" style=\"" +
borderStyleString + "\"");
67: else
68: sbOutput.Append(" frameborder=\"1\"");
69: }
70: else
71: {
72: sbOutput.Append(" frameborder=\"0\"");
73: }
74: sbOutput.Append(" id=\"" + this.ClientID + "\"");
75: sbOutput.Append(" name=\"" + this.ClientID + "\"");
76:
77: sbOutput.Append("></iframe>");
78: output.Write(sbOutput.ToString());
79: }
80: }
81:
82: private string buildUnit(Unit u)
83: {
84: switch(u.Type)
85: {
86: case (UnitType.Cm) :
87: return u.Value + "cm";
88: case (UnitType.Em) :
89: return u.Value + "em";
90: case (UnitType.Ex) :
91: return u.Value + "ex";
92: case (UnitType.Inch) :
93: return u.Value + "in";
94: case (UnitType.Mm) :
95: return u.Value + "mm";
96: case (UnitType.Percentage) :
97: return u.Value + "%";
98: case (UnitType.Pica) :
99: return u.Value + "pc";
100: case (UnitType.Pixel) :
101: return u.Value + "px";
102: case (UnitType.Point) :
103: return u.Value + "pt";
104: default:
105: return u.Value.ToString();
106: }
107: }
108: }
109: }

This is a simple user control to create an IFrame object. The advantage of
this solution, is the reusabiliy. If I need an a Iframe on a page, I can set
its properties from code (like border, borderstyle, src, etc). I don't have
to create a method that returns a string, I can read my properties back etc.

If you use you "inline" html, it is much harder to read the properties set
(by another method) or change anything from code.

I agree that this approach looks like a much more difficult way to create an
IFrame, it was much faster in classic ASP where you would create a simple
method for this. But once you get used to the .Net way of working, you will
see it's advantages. The IFrame object I described can now be used by many
different projects, they just need to know the location of the IFrame dll.

another big advantage, inheritance:
For example, If someone misses a property, they can create a new control
which inherits the current control. The new control just has to contain the
new property.
In classic ASP way of working, you will have to create a new method and
create a maintenance issue. You'll have to update all the methods that use
the same code , while I just have to update one control (the controls that
inherit just have to be recompiled)
 
K

Kevin Spencer

Programming power necessarily introduces complexity into the experience of
the developer, just as aircraft power introduces complexity into the
operation of an aircraft.

A paper airplane is easy to fly. Just throw it. But how high can it fly, and
how many people can fly in it?

A single-engine small aircraft is considerably more difficult to fly. It
propels itself, and must contain at least one human being. So, it must be
able to take off and land without injuring the human beings inside it. It
must have fuel inside it. It must have enough power to lift the plane the
engine, the fuel, and the human beings inside it. It must have controls for
navigation, a control interface to enable the pilot to control it, and an
instrument interface to enable the pilot to receive information from it. But
how high can it fly, how fast can it fly, and how many people can fly in it?

A Boeing 747 is considerably more complex that that. It can fly at high
altitudes, over very large distances, carry hundreds of people as well as
their baggage, fly at considerably higher speed than a single-engine small
aircraft, and even fly itself. But what sort of complexity does this add to
the design of the aircraft? At high altitudes, air pressure is much lower,
and air is much thinner. It must have enough power to fly in thin air, and a
system of cabin pressurization to provide enough air to the passengers, as
well as a system to protect passengers when the cabin loses pressure. It is
very large, so it must have enough power to lift an incredibly heavy
aircraft to high altitudes in thin air. It must have several jet engines,
rather than a single propeller engine. These engines must be coordinated to
make the plane fly correctly. In order to fly itself, it needs a computer
that can gather data about the state and location of the aircraft, and
calculus algorithms to calculate the trajectory and the amount of power, as
well as the state of the navigational devices on the aircraft, such as
flaps, rudder, ailerons, etc. It must have backup systems. that can take
over in the event of any system failure. It must have a bathroom for the
human beings inside it, as well as other human necessities that must be met,
such as thirst, hunger, etc. It needs a crew of human beings to fly it. And
each member of the crew must be fully trained to do their job and interact
successfully with the rest of the crew and passengers. And so on.

Back in the day, a computer could perform exactly one instruction at a time.
In fact, a computer can STILL only perform only one instruction at a time.
Back in the day, there were no networks, and no Internet. Computers were
safely contained within their own confines, and had very little memory and
procesing power. Computers are calculators that have electronic switches and
toggles in them. Back in the day, computers were programmed using binary
machine code. Punch cards were used to feed instructions to them. A hole was
a 0. No hole was a 1 (or was it the other way around?).

As computers became more powerful, the number of punch cards and binary
instructions became too large for humans to keep up with. Assembler language
was developed. It provided a human-readable language that was translated by
a computer into machine code, combining whole blocks of machine code into
single assembler language commands. Now people could type instuctions into a
file, and compile that file into machine language that the computer could
execute. At this point, a program interface was still lines of command-line
text.

As computers became even more powerful, programs became larger, and did much
more. Higher level languages such as COBOL, Fortran, Pascal, and C were
developed for the purpose of making programmers more productive. They
combined blocks of assembler code into functions that contained
commonly-used operations, and data types that contained larger blocks of
data in a single container. These functions and data types could then be
combined to create a large variety of applications, applications that had
graphical interfaces, could interact with a variety of peripheral devices,
and make life much easier for users, who could perform tasks in much less
time than before. These high-level languages were first compiled into
Assembler, and then compiled to machine code that the computer understands.
To write such an applicaton using assembler only, or worse yet, machine
language only, would take entirely too much time. Of course, with the advent
of new higher-level languages, developers had to learn them and adapt with
the changes.

Networks were introduced, and with them, the Internet, the largest computer
network in human history, a network of millions of computers across the
globe. And computer power continued to increase, doubling every 2 years
(more or less), according to Moore's law. With the increase of programming
power, programs became much more complex. Multi-tasking operating systems
were developed, which could seem to run more than one program at a time via
time-sharing, and Network protocols were developed to allow computers to
talk with one another and exchange data. The complexity of such programming
made procedural programming so complex that it was extremely difficult to
write, debug, and maintain. Security issues demanded that software have
accessible and inaccessible areas, and that these levels of accessibility be
configurable to an increasingly higher degree of precision.

Object-oriented programming was introduced some time around 15 years ago or
so, which included principles such as Inheritance (which cuts down on
redundant code, making program code leaner and simpler to debug, maintain,
and extend), Encapsulation (which provides the ability to hide or expose
data and functionality on a highly-configurable basis), Polymorphism (which
enables classes to be used for a variety of similar purposes), and
Abstraction (which enables developers to treat aggregates of data and
process as real-world "things" or objects). Rather than thinking of data and
process (the essential components of any program) as what they really are,
programmers could think of them as objects, engines, tools, etc. In essence,
this was a continuation of the process of combination that started with
Aseembler language. Functions and data were combined into classes, which
provided larger "blocks" of functionality to the developer. This made
developers able to write even larger and more powerful applications, the
"Boeing 747" of programming technology.

ASP is procedural in nature, and relatively simple to use. It is also simply
not capable of doing a whole lot. It is the "single-engine small aircraft"
of web developers. Note that single-engine small aircraft are still in use,
and useful today, for very limited purposes, just as ASP is still in use,
and useful today, for very limited purposes. ASP.Net is more powerful by an
exponential factor, faster, and has the ability to do anything that any
compiled programming technology can do. This makes it more complex, and
harder to learn. That is simply the way things are.

If you don't have "the right stuff" to learn it and deal with it, stick to
ASP. It will be around for a long, long time, just like small aircraft. But
realize this: ASP.Net is not designed to be used like ASP, any more than a
Boeing 747 is designed to be used like a single-engine small aircraft. It
doesn't need to be "dumbed down" to a procedural level. It is designed
extremely well for what it is. It doesn't need "fixing." If you don't like
to "hang ten" on the big waves, the swimming pool is still there. But if you
want to ride the curl, don't argue. Listen and learn.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
When you can snatch this pebble from my hand, you will have learned.
 
M

michaelcoleman72

John - You are a hack. Retire from computing and think about going
into another profession... such as farming... oh wait, they user
air-conditioned tractors now instead of horses. You probably wouldn't
like that.

In that case, buy a book on OO programming. Read up on the .Net
framework or the Java Enterprise framework... maybe you will get a
clue.

I'll let you get back to rubbing your sticks together so you can fire
up and cook breakfast.

Regards
Coleman
Senior Developer

"Matches...we don't need no stink'n matches!!!"
 
J

John Rivers

Hmmm,

maybe it isn't clear what i am suggesting:

I want to use the object oriented language features of C#
in conjunction with html literals to create a presentation class
library
which is predictable (ie: it outputs exactly the html that i expect -
not
some indeterminate output decided by microsoft and which changes
based on all sorts of external factors (http request headers etc.)

although i can do this using Response.Write(@"<html") this is
not acceptable as I lose: syntax coloring, code completion and
most importantly the ability to keep html and javascript in its
real format without double escaping.

the reason i am upset is because there is no reason for microsoft
to make it hard for me to do this, if it suits my needs, which it
does.

what i am suggesting has all the benefits of your approach
but with none of the drawbacks.

does somebody, please, understand my point?
 
A

Alvin Bruney - ASP.NET MVP

I couldn't see your original thread, but based on this thread, it isn't
particularly difficult to do. One approach is to write a Httphandler to sit
out front to prepare the context, or tie into the html renderer - a better
idea since what you are interested in is html presentation - to prepare the
outputted hmtl

--
Regards,
Alvin Bruney [MVP ASP.NET]

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ www.lulu.com/owc
Forth-coming VSTO.NET - Wrox/Wiley 2006
 
K

Kevin Spencer

There are 2 different and important reasons for avoiding "code blocks" in
the Page Template. The first is that "code blocks" are not object-oriented,
and therefore do not provide any of the advantages of object-orientation
(see my previous post). The second is that mixing code and presentation
content is bad practice, making the application more difficult (and
therefore more expensive) to maintain, upgrade, and extend.

There is absolutely no reason why ASP.Net cannot, as it exists now, produce
any HTML output you desire. It is not difficult to do, and many of us do it.
All you have to do is learn how to use it correctly to achieve this.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top