荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: Jobs (温少), 信区: Visual
标  题:  Building a SQL Query Tool Using ASP+
发信站: BBS 荔园晨风站 (Sun Sep 17 03:55:13 2000), 转信



   Building a SQL Query Tool Using ASP+

    In pursuit of true code/presentation separation and cross
programming language interoperability, we now have ASP+ from Microsoft.
I will show how you can build a database application with a
user-friendly frontend using ASP+, ADO+ and C#. We will also examine how
this compares to a similar application written with ASP, ADO and VB. To
compile the code from this article you will need the Technology Preview
of the .NET Framework SDK.

    In my earlier article about the Scripting Object Model (SOM) found
in Visual InterDev 6.0, I mentioned that one of the goals of the SOM was
to bring an object-oriented framework to ASP. The SOM failed to live up
to expectations however; firstly it is implemented using script, and
secondly it didn't really feel as though it was part of the platform ?I
think most would agree that the ideas behind the SOM were good, but it
never became as popular as it could have been.

Out With the Old, In With the New
In comes ASP+. Although the name implies that it is ASP plus some new
features, ASP+ is a total rewrite, and part of Microsoft's larger .NET
initiative. Some of the things that are new to ASP+ include:

code is compiled
xcopy deployment (no component registration or locked binaries)
web forms for true code / presentation separation
and cross programming language interoperability.


ASP+ is based on the Common Language Runtime (CLR), which allows any
.NET compatible language to be used for programming your web
applications. Gone are the days where you needed to use different
languages for different tasks. If you are a C++ developer you will be
able to continue to use your skills and build your web applications
using the Managed Extensions for C++. And if you are a Visual Basic
developer ASP+ has you covered. At the time of writing Microsoft has a
commitment from a number of vendors for porting their languages to the
CLR ?I am aware of APL, CAML, Cobol, Eiffel, Haskell, Mercury, ML,
Oberon, Oz, Pascal, Perl, Python, Scheme and Smalltalk.

For the purpose of this article I will be using Microsoft's new language
C# (pronounced C Sharp). Slowly but surely papers are being written
describing this exciting language. I encourage everyone to view some of
the articles on MSDN (http://msdn.microsoft.com/net/).


The new state model in ASP+ frees the application developer from having
to request the values of HTML controls and then recreate the state of
those controls on the round trip. No longer will you need to sprinkle
code such as:

<input type="text" name="firstname" value="<%= request("firstname") %">

With ASP+

<asp:Textbox id="firstname" maintainstate="true" runat="server" />

Most people would agree that the declarative (code-less) method of ASP+
is cleaner. This declarative model really starts to shine when you are
able to leverage ASP+ editors such as Visual Studio.NET. With VS.NET you
will be able to drag-and-drop smart ASP+ web controls onto a form and
visually set its properties that dictate not only the appearance, but
the behavior as well. VB programmers have been able to do this for
years. But with these controls, the code runs on the server and outputs
standard browser-independent HTML.

As you can see from the code snippet above, ASP+ uses declarative
controls in place of the standard HTML elements. These controls provide
a consistent programming model. For example, in HTML you have <input
type="textbox"> and <textarea>, both being very similar except that a
textarea has multiline capabilities. ASP+ expresses these idiosyncrasies
in a consistent manner.

A textbox and a multiline textbox (textarea) are both created using:ng
conflicts.
For example, imagine importing two namespaces with identically named
classes such as TextBox, and writing the following code:

<TextBox id="mytext" runat="server" />

This syntax is invalid, as the namespace must be declared (there is no
default namespace). By forcing us to use the namespace, ambiguous
references are avoided. The code should be rewritten:

<CompanyX:TextBox id="myTextBox" runat="server" />

In addition to the HTML equivalent web controls, ASP+ provides a rich
framework for creating robust web controls that do much more than the
traditional HTML. One of these rich controls provided with ASP+ is the
DataList control, used to display a data-bound list. Not only does it
make rendering data simple, but it also leverages temormation and code into
the same file (primarily to aid the porting of existing ASP
applications). I am going to use the code-behind model of developing
ASP+ pages. Code-behind refers to the ASP+ programming model where all
of the implementation code resides in a separate source file that is
merged with the presentation file at compile time. This allows a
designer to design the ASP+ page using their HTML design tool of choice
while the developer codes his programming logic in a separate file.

SQL Query Tool built Using ASP+
To help contrast ASP+ with the older ASP model, I decided to port a
little web application that allows querying SQL Server over the web. The
original application can be found in the ASPToday article "SQL Query
Tool built with Virst request of the isql.aspx page is made. The IL is
persisted to the file system to survive machine reboots. The IL is then
JIT (Just-In-Time) compiled into native code and executed by the CRT
(Common Language Runtime).

The native code remains cached by ASP+ for subsequent requests. If a
source file is modified, the edited pages are then recompiled on the
fly. ASP+ takes care of monitoring file changes. When a file does
change, ASP+ starts the new version of the application, while gracefully
bringsql.cs" Trace="False" %>

Most of the line is pretty self-explanatory. Looking at this line you
can see that I am using C# as my scripting language (CS also works for C
Sharp). My page inherits from the ISQL class of the Scrilla namespace.
The source code can be found in a file named isql.cs, and tracing is
currently turned off.

If I preferred I could have chosen to pre-compile my isql.cs file into a
dll and place it into the bin directory within my application root. This
is where the compiler will look by default for <custom> assemblies.
Choosing this route I would need to remove the Src=isql.cs parameter and
replace it with Codebehind="isql.dll". Precompiling your code into DLLs
is a good idea if you want to hide your source code from people thaarea element
use <asp:TextBox TextMode="MultiLine"
runat="server" /> and to create an HTML input control for passwords use
<asp:TextBox TextMode="Password" runat="server" />. By default the
<asp:TextBox> webcontrol defaults to a standard <input type="text"> HTML
control.

The Runat="server" is another attribute that needs to be explained. If
you do not have it on an element the element will be treated as literal
text by the compiler and you will not have programmatic access to the
element. This however, does not mean that you should add runat="server"
to every element on the page. Instead only place the runat="server"
attribute on elements where programmatic access is needed. For example
in my page I have the tag:

<h2>WebSQL</h2>

I could have pla having to create, manage and cleanup the unused controls.


Other web controls in the asp namespace <asp:> have attributes such as
AutoPostBack and event handlers. Although the length of this article
doesn't allow me to go through all of the attributes I will explain some
of the more popular ones. The AutoPostBack attribute on a web control
tells the ASP+ page compiler to create a client-side mechanism (usually
a small snippet of JavaScript 1.0 code) to automatically post back the
page and its data when something of interest to the developer happens on
the client. For instance, in the case of one of my <asp:DropDownList>
web controls I am telling the compiler to automatically post back the
page and call my event handler named lstDatabases_Change ustate information
is then posted back to the ASP+ page for handling on the server.


On the server the lstDatabases_Change event handler is called when the
user changes the selected index of the lstDatabases drop-down list.

protected void lstDatabases_Change(object sender, EventArgs e)

The Change event handler for the lstDatabases control (
lstDatabases_Change ) of my sample application checks the value of the
selected item in the drop-down list to see if it is equal to the value
of my TEXT_REFRESH co
database of Microsoft抯 SQL Server using Microsoft抯 next generation
ADO, called ADO+. For an introduction to ADO+, take a look at
Introducing ADO+ on the MSDN.

string sql_conn_str = "server=" + _ServerName + ";uid=" + _UserName + _
                      ";password=" + _Password + ";database=Master";

The variables _ServerName, _UserName, and _Password are member variables
with values established in the Load event handler of the Page object.



public class ISQL : Page
{
   private string _DatabaseName;
   private string _ServerName;
   private string _UserName;
   private string _Password;

   protected void Page_Load(object sender, EventArgs e){
      ...
      _ServerName   = txtServer.Text;
      _UserName   = txtUser.Text;
      _Password   = txtP the
lines of what a RecordSet in ADO was.

A DataTable object consists of a single table, which can be the result
of a select, store procedure, view, etc. DataTable抯 contain the data
and DataSet抯 contain DataTable抯. For this application we are only
concerned with DataSet抯 and DataTables.

Next we begin a try/catch/finally block to handle any exceptions that
may be thrown.

try
{
   DataSet ds = new DataSet();

   myCommand.FillDataSet(ds,"Databases");

   lstDatabases.DataTextField   = ly name that it
will map to the table. This allows the developer to give the results of
a command a name that can be used later when working with the table.

The next few lines are used for binding the data in our "Databases"
DataTable to our lstDatabases <asp:DropDownList>. The DataTextField
property maps the text that is displayed to the user to the "Name"
column of our DataTable. The DataValueField maps the value of the HTML
<option> to the "Name" column also.

The DataSource property tells the runtime what the lstDatabases web
control is to bind to. DataBind() effectively says, "you have everything
you need, now do it". It should also be noted that I could just call
DataBind() without specifying the lstDatabases object. This is
synonymous to ct method called after any constructor in
the class. This is where you will do most of your setup work. Trying to
access post-back data, server controls, and so on from the constructor
will result in an exception because these items are not yet available.


In my Page_Load method I first set the values for my four member
variables ; _DatabaseName, _ServerName, _UserName, and _Password. Before
I can assign a value to _DatabaseName, I check to make sure that there
are some values in the lstDatabases <as load of the page (as opposed to a
post-back). If it is not a
post-back we set a few startup attributes on our ASP+ page. First we
select our BordersOn and HTML radio buttons. Then we create a new
ListItem object calling its constructor with the value of the TEXT_BLANK
constant and "". The TEXT_BLANK constant will be used for the display
text in the listbox, while the "" (empty) will be used for its value.
Next we Add the ListItem to the Items collection of our lstSave control.
We then remove the value from the txtPassword <asp:TextBox> if the user
chose not to have their password saved between roundtrips to the server.



if (!chkSavePassword.Checked)
{
txtPassword.Text = "";
}

The Click handler for our btnSave control is responsible for saving
whavailable on all string objects in the .Net classes. SubString works
like JavaScript抯 Substring and Visual Basic抯 Left$ functions. We take
a SubString of our QueryValue (up to the value of Length ) and use the
value for the display text of the listbox. We use the entire value of
QueryValue as the value of the listbox.

ListItem item = new ListItem(QueryValue.Substring(0,length),
QueryValue);

Lastly we Add the newly created ListItem ( item ) to the Items
collection of our lstSave object.

lstSave.Items.Add(item);

The Click handler for btnExecute is similar to the Change handler for
the lstDatabases control in that it too builds a connection string (
sql_conn_str ) and creates an SQLDataSetCommand object using a SQL
command ( sql_command ). The dof our txtXML <asp:TextBox> to the boolean true.
Then we simply
set the XML property of our 慺illed?DataSet ( ds ) to the Text property
of out txtXML <asp:TextBox> control:


In cases where the results are to be returned in grid form we set the
BorderWidth property of our DataList control ( grdResults ) to the
integer value of the boolean Checked property of our BordersOn radio
button. Next we leverage the power of ASP+ and ADO+ databinding to set
the DataSource property of the DataList to the DefaultView of our
"Query" DataTable. Then we call the DataBind method, which tells the
runtime that we are ready for it to populate our DataList.



Conclusion
Hopefully this article was successful in whetting your appetite for
diving into the .NET Framework with ASP+ and C#. I will be writing more
articles on working with the .NET framework in ASP+ in the coming
future.

Click here to download this article's support material.

To compile the code from this article you will need the Technology
Preview of the .NET Framework SDK. The SDK can be downloaded from the
MSDN



--

   好好学习,天天向上!!!!

※ 来源:·BBS 荔园晨风站 bbs.szu.edu.cn·[FROM: 192.168.18.211]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店