In this article, Carlos explains how to integrate XML into your applications using ASP.
Summary:
This article details an approach to integrating XML into database-driven applications or websites using classic ASP. The goal of this approach is to encapsulate database interactions into a reusable object that will handle data retrieval, including simple hierarchical data, by leveraging ADO and XML.
The result is the beginning of a framework that allows the separation of the data, business and data-access layers. This, in turn, facilitates the implementation of distributed application architectures.
Introduction:
By now most web developers have heard of XML and of its value to the web and distributed computing. In classic ASP, Microsoft has provided the pieces for developers to take advantage of XML in different ways. This article suggests a framework for making database driven ASP applications using only XML. It achieves this goal by encapsulating data retrieval into a VBScript class.
Prerequisites:
This article requires that the reader be familiar with the following:
• VBScript Classes and the advantages of OO design,
• XML, XSL, their use in ASP, and advantages, and
• ADO and its use in ASP, particularly persistence of Recordsets and Data-Shaping.
Overview:
Many articles have been written demonstrating object-oriented (OO) and XML features available in ASP including:
1. Creating a Datagrid Class in classic ASP - 2-Dimensional Arrays by Brian O'Connell 2. A Generic GetRows VBScript Class 3. Using Classes in ASP (OOP in ASP/VBScript - Part #2) by Marcus Brinkhoff 4. Converting Hierarchical Recordsets Into XML By Richard Chisholm 5. Increasing ConvertRStoXML() Performance By David O'Neill 6. An ASP Class for XML Data Transfer by Seth Juarez
These articles adequately explain the benefits of OO design and of XML use in ASP. The data access objects even show how OO design can help manage creation and destruction of precious ADO connection objects.
However, they still either bind the interface to the data (as in the DataGrid article) or they still looped through recordsets or arrays to create their XML. It was not until Transforming ADO Recordsets to XML with XSLT that we begin to see that we can piece the tools available in the classic ASP platform to create a reusable, extensible, and flexible framework with XML as the foundation.
XDO seeks to implement such a framework and makes it possible to retrieve XML data from the database. This allows the developer to have SQL Server-like XML capabilities with any database that can be accessed with ADO via OLEDB.
Design:
Current architectures for distributed applications recommend object models that follow object factory (or engine – collection – class) design patterns. XDO emulates this design pattern for the data access tier in n-tier architectures. Business rules, captured as function libraries or as other classes, can create an instance of the XDO object and return XML that matches the rule coded within the called function or object method. The resulting XML is then transformed with XSLT to render the user interface (See figure 1).
XDO is a custom data access object that encapsulates the functionality of MSADO objects. In a “real-world” implementation, no ASP page interfaces with ADO objects directly. Instead, ASP pages create instances of the XDO object, which in turn interacts with ADO. Instances of ADO Connections and Recordsets are managed by XDO. Furthermore, Business objects can encapsulate the instantiation of XDO objects.
Examples include a Customer XML Engine or a Catalog XML Engine. This adds another layer of abstraction in the object model thereby separating business rules from the presentation (display) code.
XDO is a custom data access object that encapsulates the functionality of MSADO objects. In a “real-world” implementation, no ASP page interfaces with ADO objects directly. Instead, ASP pages create instances of the XDO object, which in turn interacts with ADO. Instances of ADO Connections and Recordsets are managed by XDO. Furthermore, Business objects can encapsulate the instantiation of XDO objects.
Examples include a Customer XML Engine or a Catalog XML Engine. This adds another layer of abstraction in the object model thereby separating business rules from the presentation (display) code.
The required components of this framework are:
• IIS 4.0+ running VBScript 5.0+,
• MSXML parser 3.0+, and
• Microsoft’s ADO 2.0+
The main object used in the architecture is the XDO object. This object is a stateless component that returns an XML document object model (DOM’s) of data in the database. These XML DOMs are stateful representations of customers, employees, orders, and products. The XML DOM represents the data describing the object.
Implementation:
The sample code provided demonstrates the use of the XDO framework. It uses the Northwind Access database for the data-source but will work for and ADO accessible database. The default.asp page displays a drop-down list of customers by default and allows the user to click buttons to view either the selected customer’s details or their 3 most recent orders.
Execution of the typical ASP page in this framework involves adding the class references to the page through #include directives, validating the request, creating an instance of the business object engine, CustomerXMLEngine, calling the appropriate business object method, transforming the data with appropriate XSL, and returning the resulting HTML interface.
The demo is made up of:
• The default.asp page, that controls which business object method is called,
• The Class.CustomerXMLEngine.asp, that houses the business model’s logic, and
• XSL stylesheets, that are used to transform the returned XML. The default.asp determines which view is displayed based on the arguments submitted.
• XDO, with serves as the
Default.asp
This design allows the same ASP page to render 3 different interfaces (Figure 2). Looking at the code, one can see that the implementation code is reduced to a few lines of code.
The default.asp page interacts with the business object using the “new” statement, returning an instance of the business object.
'/// CREATE AN INSTANCE OF THE CustomerXMLEngine
dim engCustomer : set engCustomer = new CustomerXMLEngine
Data is retrieved from the CustomerXMLEngine object by calling its methods. The example below returns a simple list of customers (ID and CompanyName) and is transformed into a drop-down list using xsl.
'/// GET A STYLE SHEET
dim objXSL
set objXSL = loadStyleSheet("xsl/customerSimpleList.xsl")
'/// CALL THE getSimpleCustomerList AND TRANSFORM TO GET DROPDOWN LIST
dim sCustomerDropDown
sCustomerDropDown = engCustomer.getSimpleCustomerList().transformNode(objXSL)
Class.CustomerXMLEngine.asp
The CustomerXMLEngine contains the rules that define what data to retrieve from the database and applying any rules (like applying a customer discount) at that time. Each method has a SQL statement that determines the resulting XML. On initialization, the business object creates a single instance of the XDO object and sets the connection string.
'INITIALIZE OBJECT
Private Sub Class_Initialize()
m_sObjectTag = "Customer"
set m_oXDO = new CXDO
m_oXDO.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& Server.MapPath(".") & "\database\NWIND.mdb;"
End Sub
This instance of the XDO object is used in each method to execute their SQL and returns an XML dataset.
Public Function getCustomerList()
dim sSQL : sSQL = "SELECT * FROM Customers"
set getCustomerList = getDOM(sSQL)
End Function
…
'GET XML DOM FOR PROVIDED SQL
Private Function getDOM(SQL)
set getDOM = m_oXDO.getXMLDOM(m_sObjectTag, SQL)
End Function
The XML is returned as a DOM object to facilitate XSL transformation.
XDO
At the heart of this framework lies the XDO object. It is designed to convert Recordsets, including hierarchical (or shaped) Recordsets, into element-based xml. I chose element-based xml to facilitate the creation of XSL templates.
An XDO instance’s lifespan begins with the creation of an ADO Connection. This Connection is available to the XDO object until the terminate method is called. The primary method is getXML, which is exposed as a public method if only the xml string is needed. A secondary public function is getXMLDOM.
This method calls getXML, loads the xml string into an XML DOM object, and returns the DOM instance.
The getXML method, when called, executes the loadData() method. This calls openConnection() and the MSDataShape provider is set if the a shaped SQL statement is provided.
Private Sub openConnection()
dim sConn : sConn = m_sConn
if (Instr(1, UCase(m_sSQL), "SHAPE") = 1) then
if (m_Connection.State = adStateOpen) then m_Connection.Close()
m_Connection.Provider = "MSDataShape"
sConn = Replace(sConn, "Provider", "Data Provider")
end if
if (m_Connection.State <> adStateOpen) then m_Connection.Open(sConn)
End Sub
Next, loadData() executes the query and the Recordset is persisted as XML using the Recordset’s Save() method. At this point, the XML format is in the Microsoft ADO-specific markup. I have written a generic XSL template that transforms shaped and non-shaped Recordsets from the Microsoft markup to element-based markup. This XSL is coded as a string, instead of an external XSL file, to aid XDO’s portability. After the transformation, the resulting XML string is returned.
Though the demo is implemented as VBScript classes, this model is easily translated to COM or other platforms. I have used VBScript classes because some of my clients and my web-host do not support custom COM development.
XDO facilitates the creation of XSL templates by rendering element-based (also called tag-based) XML. Element-based XML, unlike attribute-based XML (like that of ADO), uses a simpler XSL syntax. This makes creation or updating of XSL templates, which render HTML, much easier. Also, the XML document object model (or DOM) still allows searching and sorting of data and requires less overhead than an ADO Recordsets.
Persistence to the database is not mentioned in this model. However, there are a number of ways to address this. One might extend the XDO object to support persistence to the database. Another method might be to create a separate database persistence object to handle this function. Either way this function would also be encapsulated by the business object and not directly called by the ASP page.
This framework separates web applications into different tiers, a data tier, a business rules tier, and the presentation tier. This delegation of duties is clearly delineated with XDO, ADO, and the database making up the data tier, the CustomerXMLEngine in the business rules tier, and XML, XSL and HTML in the presentation tier.
Extending a business object is as simple as adding the new method and altering the default page to process the inputs and render the appropriate interface with XSL. Adding a new Business object, like an EmployeeXMLEngine, is easy to create with the CustomerXMLEngine as a template. The result is a flexible architecture that is easy to expand and maintain.
Further Reading:
• Creating a Datagrid Class in classic ASP - 2-Dimensional Arrays by Brian O'Connell
• A Generic GetRows VBScript Class • Using Classes in ASP (OOP in ASP/VBScript - Part #2) by Marcus Brinkhoff
• Converting Hierarchical Recordsets Into XML By Richard Chisholm
• Increasing ConvertRStoXML() Performance By David O'Neill
• An ASP Class for XML Data Transfer by Seth Juarez
꼭 블로그가 아니더라도 XML RSS 는 이제 어느정도 대세가 되어가고 있는 듯합니다. 이제는 언론사나 커뮤니티 등에서도 RSS 가 나옵니다.. 그리고 #Reader나 Xpyder,FreeDemon 등의 RSS 구독기 또한 점차 넓게 사용되고 있습니다. 여기서는 이러한 XML RSS 를 구현하는 방법을 ASP 기반에서 XML 컴포넌트를 이용하여 구현하고자 합니다.
사실 RSS 를 구현할때 사실 단순히 텍스트 파일로 뿌려주고 ContentType 만 xml 로 선언해줘도 가능합니다. 그러나 조금은 다르게 해보고 싶다는 저의 호기심도 있고, 확장성과 향후 유지보수에 조금이라도 더 손쉽게 하기위해서 윈도우즈 2000 에 기본제공되어 있는 XML 관련 컴포넌트를 이용하여 구현해보았습니다. 물론 아래 소스는 지금 제 블로그 RSS 의 원형이 되고 있습니다.
한가지 주의 하실점은 XML 선언전에 어떠한 개행( ) 이나 문자가 들어가서는 안됩니다. PHP 에서의 쿠키과 마찬가지 입니다.
< ?xml version="1.0" encoding="EUC-KR" ? >
< %
Response.ContentType = "text/xml"
Set xmlPars = Server.CreateObject("Msxml2.DOMDocument")
' 여기서 부터 rss 정보를 담는다.
Set rss = xmlPars.CreateElement("rss")
rss.setAttribute "version", "2.0"
rss.setAttribute "xmlns:dc", "http://purl.org/dc/elements/1.1/"
rss.setAttribute "xmlns:sy", "http://purl.org/rss/1.0/modules/syndication/"
rss.setAttribute "xmlns:admin", "http://webns.net/mvcb/"
rss.setAttribute "xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlPars.AppendChild(rss)
'< channel> 시작
Set Channel = xmlPars.CreateElement("channel")
rss.AppendChild(Channel)
'< title>정보
Set title = xmlPars.CreateElement("title")
Channel.AppendChild(title)
Channel.childnodes(0).text = "블로그 제목"
'< dc:language>정보
Set language = xmlPars.CreateElement("dc:language")
Channel.AppendChild(language)
Channel.childnodes(3).text = "ko"
'< image>정보
Set image = xmlPars.CreateElement("image")
Channel.AppendChild(image)
'이미지 정보에 들어갈 것들
set i_title = xmlPars.CreateElement("title")
set i_url = xmlPars.CreateElement("url")
set i_width = xmlPars.CreateElement("width")
set i_height = xmlPars.CreateElement("height")
image.childnodes(0).text = "이미지 제목"
image.childnodes(1).text = "이미지 경로"
image.childnodes(2).text = "이미지 가로 사이즈"
image.childnodes(3).text = "이미지 세로 사이즈"
' 여기서 부터는 포스트에 대해서 출력
' 우선 데이터를 읽어오자
SQL = "해당되는 포스트에 대한 쿼리문"
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open SQL,접근문자열,adOpenForwardOnly,adLockPessimistic,adCmdText
' 여기서 부터 루프를 돌리자.
Do until rs.EOF
' 이라는 노드를 추가
Set item = xmlPars.CreateElement("item")
Channel.AppendChild(item)
' 여기서부터 해당 포스트의 세부 정보를 출력
set title = xmlPars.CreateElement("title") '
set link = xmlPars.CreateElement("link")
set description = xmlPars.CreateElement("description")
set dcdate = xmlPars.CreateElement("dc:date")
set dcsubject = xmlPars.CreateElement("dc:subject")
s = "서버측 코드 실행 성공"
print s
= s.split()
.reverse()
print ' 단어 역으로 바꾸기 '
print ' '.join(l)
print 'Testing..'
% >
< script language="JavaScript">
document.write("클라이언트측 코드 실행 성공")
< /script>
< script language="Python" runat="server">
print '다시 서버측 코드..'
< /script>
주의 ASP 내에 파이썬 스크립트를 삽입할 경우 들여쓰기에 주의해야 합니다. 파이썬 자체가 들여쓰기를 기준으로 단락을 구분하기 때문에 주의를 기울이지 않으면 생각보다 에러가 많이 발생합니다. 특히 조건문이나 for 문과 같은데에서는 더더욱 조심해야 하구요. - 박기석, 2001.12.03. -
인터넷 익스플로러에서 http://localhost/pythontest.asp 를 입력한다. 다음과 같은 실행결과가 나오면 성공!
서버측 코드 실행 성공
단어 역으로 바꾸기
성공 실행 코드 서버측 Testing..
클라이언트측 코드 실행 성공
다시 서버측 코드..
=====================================================Q Python2.4, IIS 5.1, WinXP환경입니다.
Win32all설치후에 Manual보고 그대로 실행했는데,
Internal Server Error : 500이 뜹니다.
그리고 pyscript.py를 그냥 실행시키면 python script가 IIS에 등록되는 것 같습니다.
위 옵션에 --unregister를 추가하면 실행자체가 안되구요.
ASPN에서도 --unregister란 옵션은 없던데... ^^;
위의 실행결과가 안 나오네요.
누구 혹시 아시는 분 Reply좀 부탁드립니다.
set objImage =server.CreateObject("DEXT.ImageProc")
if true = objImage.SetSourceFile(UploadPath) then
''FileNameWithoutExt 속성은 업로드한 파일의 이름을 리턴한다.(확장자 제외)
SourceFileName = uploadform("file").FileNameWithoutExt
''워터마크 처리(2)
UploadPathWaterMark = objImage.SaveAsWatermarkImage("/DEXTUploadProSamples/Image/WaterMark/watermark.bmp",FilePath,-10,-10,false)
Response.Write("Save as Watermark Image: " & UploadPathWaterMark & " ")
end if
if true = objImage.SetSourceFile(UploadPathWaterMark) then
''워터마킹 처리 된 이미지로 썸네일 처리 한다. (3)
UploadPathThumbnail = objImage.SaveasThumbnail(FilePath1, objImage.ImageWidth/2, objImage.ImageHeight/2, false)
Response.Write("Save as Thumbnail: " & UploadPathThumbnail & " ")
end if
%>
< %
set objImage = nothing
Set uploadform =nothing
%>