--- connessione
global.asa:
Session("provstr") = "DRIVER={SQL Server};SERVER=DARIXWIN;UID=sa;PWD=manager;DATABASE=parcol"
Session("provstr") = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("\parcolasp") & "\db\parcol.mdb;"
.asp:
inserire:
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Session("provstr")
--replace
include 'login.asp' con
con %>
print con response.write
$ con ''
.php con .asp
\" con ""
== con =
!= con <>
;\n con \n
; con :
// con '
if: mettere then, elseif () then , end if con : se una sola riga o togliendo { e }
". con " & (attenzione a ".jpg"!)
." con & "
query .= con = query &
commenti
cols++ con cols=cols+1
define('BTN_PREV', '<') con Const BTN_PREV="<"
\n vbCRLF
\t vbTab
--condizioni
if (isset($_GET['menu'])) $menu=$_GET['menu'];
else $menu="home";
con
menu = Request.QueryString ("menu")
if (menu="") then
menu="home"
end if
while ($i <= 10){
}
con
Do While counter i <= 10
Loop
--switch
switch ($i) {
case 0:
print "i equals 0";
break;
default:
print "i is not equal to 0, 1 or 2";
}
con
Select Case Number i
Case 0
Response.Write ("i equals 0")
Case Else
Response.Write ("i is not equal to 0, 1 or 2 ")
End Select
--recordset
$conn = db_connect();
$link1 = db_open($conn);
rs = db_query (link1,query)
While (row=db_fetch_array(link1,row,rs)){
a=row["id"];
}
con
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open Session("provstr")
Set rs = Server.CreateObject("ADODB.Recordset")
rs.open query, conn
DO While Not rs.EOF
a=rs("id")
rs.MoveNext
Loop
rs.Close
--sessioni
$_SESSION['s_okreg'] con Session("s_okreg")
$_GET["name"] con Request.QueryString ("name")
$_SERVER['HTTP_HOST'] con Request.ServerVariables("HTTP_HOST")
--for next
for($i=1;$i<=6;$i++){
}
con
For i = 1 To 6
Next
--sql mysql to access o mssql
select * from news order by date desc limit 1
con
select top 1 * from news order by date desc
--filesystem
if (file_exists($nomefile))
con
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If (fs.FileExists(nomefile))=true Then
--mail
Dim infoMail
Set infoMail = Server.CreateObject("CDONTS.NewMail")
infoMail.From = from_mail
infoMail.To = to_mail
infoMail.Subject = subject
infoMail.BodyFormat = 1
infoMail.MailFormat = 1
infoMail.Importance = 1
infoMail.Body = message
infoMail.Send
Set infoMail = Nothing
--conversioni
cstr()
--stringhe
response.write "
W.. " & _
" sfs "
--redirezione
header("Location: menu.asp"); exit; con Response.Redirect "login.asp"
--upload file
!!enctype="multipart/form-data" rende indisponibili gli oggetti request()
--permessi
oltre a abilitare il virtualhost a scrittura in iis, abilitare l'utente iis IUSR_ a scrivere sulla directory, su winxp per abilitare la visualizzazione dei permessi completi dececcare 'utilizza condivisione file semplice' in explorer
-------------------------------------------------------------------------------
--- REFERENCE
-------------------------------------------------------------------------------
Code Sample 3. Basic output in PHP
Code Sample 3. Basic output in Visual Basic .NET
<%
Dim Hello As String = "Hi how are you" & vbcrlf
Response.Write(Hello)
%>
However, these methods for sending output to the browser exist primarily for backwards compatibility with classic ASP. ASP.NET's new control-based, event-oriented model allows for data to be output to the browser by simply setting properties on server controls. This technique allows for clean separation of layout and code and can make maintenance easier, requiring significantly less code in complex situations than PHP.
The current date is:
This example declares a server-side Label control called TheDate, and during the page's Load event, sets the Text property of the label to the current date and time. The HTML output of this code is identical to the other two versions, except that the Label control renders itself as a span tag containing whatever was set as the label's text.
Conditional Processing
IF/ELSE
PHP has several conditional processing expressions such as for, while, switch, and foreach but the most common is the if/else expression. Visual Basic .NET has very similar constructs with similar syntax. Code Sample 4 provides a comparison of equivalent conditional logic in PHP and Visual Basic .NET.
Code Sample 4. Basic conditional logic in PHP
if ($a > $b) {
print "a is bigger than b";
} elseif ($a == $b) {
print "a is equal to b";
} else {
print "a is smaller than b";
}
Code Sample 4. Basic conditional logic in Visual Basic .NET
If a > b
Response.Write ("a is bigger than b")
ElseIf a = b Then
Response.Write ("a is equal to b")
Else
Response.Write ("a is smaller than b")
End If
Switch
Switch statements are common language constructs for most programming languages when you wish to test a single expression for multiple values. They are commonly used to replace if statements that contain multiple elseif/else blocks.
Code Sample 5 shows a comparison between PHP's switch statement and Visual Basic's Select Case statement.
Code Sample 5. A switch statement in PHP
switch ($i) {
case 0:
print "i equals 0";
break;
case 1:
print "i equals 1";
break;
case 2:
print "i equals 2";
break;
default:
print "i is not equal to 0, 1 or 2";
}
Code Sample 5. A Select Case statement in Visual Basic .NET
Select Case Number i
Case 0
description = "0"
Wesponse.Write ("i equals 0")
Case 1
description = "1"
Response.Write ("i equals 1")
Case 2
description = "2"
Response.Write ("i equals 2")
Case Else
description = " i is not equal to 0, 1 or 2"
Response.Write ("i is not equal to 0, 1 or 2 ")
End Select
Looping
Another extremely common control construct is the loop. There are several different commonly recognized types of loops that both PHP and .NET support.
Code Sample 6. For loop in PHP
for ($i = 1; $i <= 100; $i++) {
print $i;
}
Code Sample 6. For loop in Visual Basic .NET
Dim sum As Integer = 0
Dim counter As Integer
For counter = 1 To 100 Step 5
sum += counter
Next
For i = 1 To 100
Response.Write (i)
Next I
In Visual Basic, this type of loop is known as a For...Next loop, and in PHP it is simply called a For loop. In this example, the += operator is used as shorthand for sum = sum + counter. In PHP one may break out of a loop with the Break; statement. A For...Next loop can be broken out of with the Exit For statement.
Conditional Loop
A conditional loop iterates over a set of instructions as long as a condition evaluates to true. Code Sample 7 shows an example of a basic conditional loop in each language.
Code Sample 7. Conditional loop in PHP
$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
Code Sample 7. Conditional loop in Visual Basic .NET
Dim counter i As Integer = 1
Do While counter i <= 10
Response.Write(i)
counter i += 1
Loop
In Visual Basic, this type of loop is known as a Do...Loop statement, or a while loop. PHP also supports Do...While loops, which are very similar to while loops, except the truth expression is checked at the end of each iteration instead of at the beginning. The main difference from regular while loops is that the first iteration of a Do...While loop is guaranteed to run (the truth expression is only checked at the end of the iteration), whereas it may not necessarily run with a regular while loop. (The truth expression is checked at the beginning of each iteration; if it evaluates to FALSE right from the beginning, the loop execution ends immediately.)
Here is an example of this in PHP:
$i = 0;
do {
print $i;
}
while ($i>0);
This loop runs exactly one time, since after the first iteration, when the truth expression is checked, it evaluates to FALSE ($i is not bigger than 0) and the loop execution ends.
In Visual Basic .NET, you can do much the same thing:
Dim counter i As Integer = 0
Do
Response.Write (i)counter
Loop While counter i > 0
However, Visual Basic .NET supports a built-in looping capability that PHP does not support, which is to evaluate a condition until it is true.
Foreach Loop
PHP 4 (not PHP 3) includes a foreach construct, much like ASP.NET and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays and will issue an error when you try to use it on a variable with a different data type or on uninitialized variables. In Visual Basic .NET, the equivalent is the For Each...Next statement. Code Sample 8 shows an example of looping over an array in each language.
Code Sample 8. foreach loop in PHP
$i = 0;
foreach($a as $v) {
print "\$Key[$i]$v \n";
$i++;
}
Code Sample 8. For Each loop in Visual Basic .NET
For Each v In a
Response.Write a(v) (v & vbcrlf)
Next
Arrays
Arrays in PHP function very differently than arrays in Visual Basic .NET. In PHP, arrays are actually associative arrays but can be used like index or associative arrays. In Visual Basic .NET arrays are index arrays. Visual Basic .NET does not support associative arrays as such (although you can build them your self—see collections below). Other ASP.NET languages do support these types of arrays but Visual Basic .NET does not, and this can provide some challenges to PHP developers who are not used to working with the more common index array and might wish to model an associative array in Visual Basic .NET. Code Sample 9 shows an example of a simple array in PHP and Visual Basic .NET.
Code Sample 9. Example of array creation in PHP
$a = array (0,1,2);
Code Sample 9. Example of array creation in Visual Basic .NET
Dim MySingleArraya() As Integer = New Integer (2) {0,1,2}
In a Visual Basic .NET array, variables are declared the same way as other variables, using the Dim statement. You follow the variable name with one or more pairs of parentheses to indicate that it is an array rather than a scalar (a variable containing a single value).
Visual Basic .NET arrays also must be declared as holding a specific type of data when they are created. If the type specified is Object (the generic type underlying every object type in .NET), then the array can hold any type of data, but values must be converted to their original type when they are retrieved from the array.
Visual Basic .NET arrays can be either nested arrays-of-arrays, or multi-dimensional arrays. There are a variety of functions to manipulate arrays that are comparable to PHP, with one exception. Because Visual Basic .NET has no notion of associative arrays, there are no functions to access or index or doing anything by an array's "Key," which does not exist in Visual Basic .NET.
While we have made several references to Visual Basic .NET not supporting associative arrays, it is possible to create what is called a collection as an alternative to an array. Collections work somewhat like associative arrays in that they can be used to solve similar problems.
In some circumstances, it can be more efficient to store items in a collection than in an array.
You might want to use a collection if you are working with a small, dynamic set of items To create a collection all you need to do is declare and instantiate a Collection variable as shown in the sample code below:
Dim myCollection As New Collection()
You then can use the Add method to add members to the collection. In this example, we create four strings and add them to the collection. A unique String value may optionally be added as the key for the members of your collection. This value is passed to the collection as the second argument of the Add method.
Dim w, x, y, z As String
w = "key1"
x = "key2"
y = "key3"
z = "key4"
myCollection.Add(w, "1")
myCollection.Add(x, "2")
myCollection.Add(y, "3")
myCollection.Add(z, "4")
While this may seem a lot like creating an associative array in PHP, a collection is a very different animal in that it is an object in and of itself. For PHP developers moving to ASP, it is recommended that they look at the Microsoft Visual Basic .NET Language Specification before trying to model associative arrays in Visual Basic .NET.
Managing State
A common task in any Web application is the management of state, which is usually done using cookies or an application state management construct such as Session variables. Visual Basic .NET has similar methods to PHP for handling state.
Setting and Retrieving Cookies
Setting cookies in both environments is relatively trivial. Code Sample 10 shows an example of writing and then reading a cookie in each language.
Code Sample 10. Setting and retrieving cookies in PHP
/* and to retive the set cookie */
echo $_COOKIE["TestCookie"];
?>
Code Sample 10. Setting and retrieving cookies in Visual Basic .NET
Dim value as string = "something from somewhere"
Dim myCookie As New HttpCookie = New HttpCookie("Something from somewhereTestCookie")
Dim now as DateTime = DateTime.Now
myCookie.Value = now.ToString()value
myCookie.Expires = now.AddHour(1)
Response.Cookies.Add(myCookie)
'and to retrieve the set cookie
Response.Write(Request.Cookies["What we setTestCookie"].Value)
Setting and Retrieving Session Variables
Session variables in ASP.NET are very similar to PHP session variables. Session variables in both environments provide handling and cookie manipulation for you to provide persistence through a Web application visit.
The last important difference is that when a value is retrieved from the ASP.NET session object, it is returned as the generic System.Object type, which can hold any type of data. This value must be converted back to its original underlying type before it can be used. Code Sample 11 shows some examples of session variable usage.
Code Sample 11. Session variable usage in PHP
= $today ?>
Code Sample 11. Session variable usage in Visual Basic .NET
Session("Today") = DateTime.Now
Dim today As Date
today = CDate(Session("Today"))
Response.Write(today)
Response.Write (session("Today"))
ASP.NET also has another form of state management called Application State that is analogous to session variables but persists for the lifetime of an application. This allows you to store various things, such as configuration information or database connection strings that would not change while the application is running.
For more information on this subject check out the Application State section of the .NET Framework Development Guide.
Regular Expressions
ASP.NET supports most of the popular features of other regular expression implementations such as those in Perl and awk. It is designed to be compatible with Perl 5 regular expressions. ASP.NET also supports regular expression features not yet seen in other implementations, such as right-to-left matching and on-the-fly compilation. Since ASP.NET is compatible with Perl regular expressions and since most PHP developers use Perl-compatible regular expressions, there is usually no need for translating your syntax from one form to the other. For more information about .NET regular expression support, see .NET Framework Regular Expressions.
Exception Handling
The ASP.NET framework includes support for structured exception handling following familiar language constructs Try/Catch, which provides the ability to catch exceptions that may arise in code. This is something that is missing in PHP and will be added in PHP 5.
Below is an example of how this is done in Visual Basic .NET:
Try
' code that might cause an error here
Catch e As ExceptionType
' code to handle the error
' Optional: More Catch blocks here
Finally
' code that is always executed
End Try
It is worth noting that a Try block can have either one or more Catch blocks, or a Finally block, or both. In other words, in situations in which you know that there is no way to correct for an error, but you still need to clean up some objects regardless of whether an error occurs or not, you can use a Try...Finally block with no Catch statement.
Querying a Database
In PHP there are generally two common ways to access a database: by using a database specific extension or by using the database independent PEAR DB library.
In ASP.NET, database access is performed through a set of objects known as ADO.NET, which serves much the same function as the PEAR DB library. The actual execution of a database query is accomplished with a set of connection, command, parameter, and data-adapter objects. There are multiple versions of each of these objects, depending on the type of database being accessed. For example, there is a set for databases with OLE-DB drivers (such as Microsoft Access), as well as a set for databases that have ODBC drivers but lack OLE-DB drivers. There are also specialized data providers for both Oracle and Microsoft SQL Server that are optimized to provide high-performance access to each of those specific databases. Third parties also provide support for other databases such as MySQL. The examples in this section will use the SQL Server objects, as that is one of the most-commonly used databases with ASP.NET.
System.Data, System.Data.SqlClient, and System.Data.oledb are the namespaces that define data base access in ADO.NET. To give your page access to the classes, you need to import the System.Data and System.Data.SqlClient namespaces into your page.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
Code Sample 12 shows an example of executing a query in each language. With PHP we have shown a connection using PEAR, which is not only one of the most popular methods of connecting to a DB, it is the most analogous to ADO.NET.
Code Sample 12. Executing queries in PHP
getMessage());
$sql = "select * from mytable";
$q= $db->query($sql);
if (DB::iserror($q)) {
die($q->getMessage());
}
| = $row[0] ?> |
= $row[1] ?> |
= $row[2] ?> |
Code Sample 12. Executing queries in Visual Basic .NET
<%--- outputting the resutlt ---%>
In PHP, your query result is stored in a variable called a result set, while in ADO.NET it is called a Dataset object. result set is a read-only view of the data returned while the .NET Dataset is actually an in-memory and read-write view of the data allowing .NET developers to easily manipulate data returned from a data source.
When outputting data, ASP.NET offers several methods for display of data to the user or client. The first is similar to PHP, which is to loop through the result set using a SQLDataReader object to write out the data we wish to display from the query. The more common way, which does not have an analog in PHP, is ASP.NET's data binding. This allows developers to build User Interface and Display controls that can be used and reused throughout an application and allows for greater abstraction of display from data and logic. Data binding's flexible syntax allows you to bind not only to data sources, but also to simple properties, collections, expressions, and even results returned from method calls.
To use data binding, you need to assign some data source such as query results to the DataSource property of a data-aware server control (such as the DataGrid). Optionally, you can provide some additional formatting information for each column and call the DataBind() method. The server control will take care of the rest.
For example, in Code Sample 12 we used the data binding syntax to output the result of our query like this:
<%--- In page load event
---%>
myDataGrid.DataSource = myDataset
myDataGrid.DataBind()
<%--- outputting the resutlt ---%>
Data-aware server controls will provide additional functionality, such as support for paging or in-line editing of the data being displayed. For more information and examples, please refer to Data Binding Server Controls.
Data Caching and Page Caching
Caching frequently accessed data can dramatically improve the response time of a site, as the page processing doesn't need to wait on a database query. Caching the HTML generated by a page request can improve response time even more, as the cached page doesn't need to be processed at all. Both environments provide support for both caching strategies; however, ASP.NET has many more methods for caching and managing data than PHP allowing developers to pick which method and strategy suites the needs of their application performance need.
Page Caching
Caching the HTML output of a page request is a common method of reducing load on a Web application. PHP does not natively support Page Caching, but it can be performed programmatically or by downloading third party packages. Usually page caching is performed on the server in numerous ways, from caching the compiled code to actually writing out the output of the page to a separate file that is updated whenever the code is updated.
In ASP.NET, page caching can be performed via either the low-level OutputCache API or the high-level @ OutputCache directive. When output caching is enabled, an output cache entry is created on the first GET request to the page. Subsequent GET or HEAD requests are served from the output cache entry until the cached request expires.
The output cache respects the expiration and validation policies for pages. If a page is in the output cache and has been marked with an expiration policy that indicates that the page expires 60 minutes from the time it is cached, the page is removed from the output cache after 60 minutes. If another request is received after that time, the page code is executed and the page can be cached again. This type of expiration policy is called absolute expiration—a page is valid until a certain time.
In addition to output caching an entire page, ASP.NET provides a simple way for you to cache just specific portions of a page, which is called fragment caching. You delineate regions of your page with a user control, and mark them for caching using the @ OutputCache directive introduced in the previous section. This directive specifies the duration (in seconds) that the output content of the user control should be cached on the server, as well as any optional conditions by which it should be varied.
For more information about ASP.NET's output caching, see Caching ASP.NET Pages.
Data Caching
There are a variety of ways to cache query results in PHP programmatically but not natively to the environment. Building Data Caching classes or systems in PHP can be done simply for small amounts of information with Session variable and/or cookies or for larger and more complex information by building your own Data caching classes. The problem is that when you are working with large types of complex data this can be inefficient, error prone, and somewhat complex to program.
ASP.NET offers a system-wide method for caching data (DataSets, arrays, collections, XML objects, and so on.) through the Page.Cache object. For applications that need more sophisticated functionality, ASP.NET cache supports three specific types of cache: expiration, scavenging, and file and key dependencies.
* An expiration type allows developers control when a cached item expires. This can be defined as a specific time, such as 01:00, or it can be relative to an item's last use, such as expire 20 minutes after the item was last accessed. After an item has expired, it is removed from the cache and future attempts to retrieve it return the null value unless the item is reinserted into the cache.
* A scavenging type cache attempts to remove infrequently used or unimportant items when memory becomes scarce. Developers have the power to control how the scavenging occurs and can provide hints to the scavenger when items are inserted into the cache that indicate the relative cost of creating the item and the relative rate at which the item must be accessed to remain useful.
* A file and key dependencies type allow the validity of a cache item to be based on an external file or on another cache item. If a dependency changes, the cache item is invalidated and removed from the cache. An example of how you might use this functionality in an application is if you had a large report that is periodically updated and downloadable to your staff. The application processes the data in the file and the report. The application caches that data and inserts a dependency on the file from which the data was read. When the file is updated, the data is removed from the cache and the application can reread it and reinsert the updated copy of the data.
ASP.NET Data Caching provides programmers many different methods to manage their applications and make them more responsive and efficient. For more information, see the Cache Class documentation for the Cache object.
Sending E-mail
Both PHP and ASP.NET have built in support for doing e-mail programmatically. To send e-mail with ASP.NET in this example you need to setup the IIS SMTP service, which must be installed because the built-in mail objects in .NET depend on objects included with the service. .NET though allows you to work with any SMTP server or mail server like PHP. Code Sample 13 compares basic syntax of each environment.
Code Sample 13. Sending e-mail in PHP
$to = "test@atnoaddress.com";
$from = "me@nosuchaddress.com"; $subject = "hi";
$message = "just wanted to say hi";
mail($to,$subject,$message, $from)
Code Sample 13. Sending e-mail in Visual Basic .NET
Dim myMail As MailMessage = New MailMessage()
myMail.From = "me@nosuchaddress.com"
myMail.To = "test@atnoaddress.com"
myMail.Subect = "hi"
myMail.Body = "just wanted to say hi"
SmtpMail.Send(myMail)
XML Manipulation and Web Services
Built-in support for parsing and manipulating XML in PHP is rather poor. While developers can use it for parsing and traversing XML, it lacks support for DOM parsing, which while slower than PHP's SAX parser, is much easier to work with. PHP also does not support the ability to natively validate XML documents against a DTD or XML SCHEME, and PHP does not support XSL/XSLT, as well as numerous other technologies that are common to many Web application products on the market. While there are numerous PHP packages that allow PHP to accomplish many XML-related tasks .NET and ASP.NET have extensive built-in support for working with XML. XML is one of the technologies at the heart of the .NET platform. You can learn more about Web Services by reading How ASP.NET Web Services Work.
The .NET Framework has extremely comprehensive support for all XML recommendations as defined by the W3C and supports XSL/XSLT, XPath, XQuery, as well as a host of other technologies, such as UDDI, WSDL, SOAP for Web services.
While it is possible to create XML-RPC type mechanisms in PHP, it is much harder to create Web services, which allow developers to exchange data and procedures using common protocols and standards to provide for discovery, data binding, and description. .NET has extensive support for Web services and related technologies, such SOAP, WSDL and UDDI. .NET also makes the creation and development of Web services a trivial matter for the developer. For example, here is code to create a simple hello world Web service:
<%@ WebService Language="VB" Class="HelloWorld" %>
Imports System
Imports System.Web.Services
Public Class HelloWorld :Inherits WebService
Public Function SayHelloWorld() As String
Return("Hello World")
End Function
End Class
The .NET Framework SDK allows you to generate your proxy classes using the command-line Web Services Description Language tool (WSDL.exe). To create a proxy class called HelloWorld.cs for the above example, you could enter:
WSDL http://someDomain.com/someFolder/HelloWorld.asmx?WSDL
This class would look very similar to the class created in the previous section. It would contain a method called SayHelloWorld that returns a string. Compiling this proxy class into an application and then calling this proxy class's method results in the proxy class packaging a SOAP request across HTTP and receiving the SOAP-encoded response, which is then marshaled as a string.
From the client perspective, the code would be simple, as shown in the following example:
Dim myHelloWorld As New HelloWorld()
Dim sReturn As String = myHelloWorld.SayHelloWorld()
And that's all there is to creating a simple Web service. For more information on XML in general and Web services in specific, you can go to Employing XML in the .NET Framework.