ASP (VB, C#) / PHP code reference

ASP (vb.net and c#.net) and PHP are the most common language for web development environment. This are not the fully conversion of one to other but get a quick references. We could get the ASP Convertor for free from the net but this might help to the developer when we work in different cross language or want to learn the basic syntax of similar different languages.

1. General syntax
ASP VB Comments, inline

'This is my comments for the line

ASP C# Comments, inline

'This is my comments for the line

PHP Comments, inline

//This is my comments for the line

#This is my comments for the line

ASP VB Comments, block

'line1

'line2

'line3

ASP C# Comments, block

/*
This the multi command lines

For the pieces of code bellow.
*/

PHP Comments, block

/*
This the multi command lines

For the pieces of code bellow.
*/

ASP VB, Escaping quotes

""
"var text1=""<img src=\""blank.gif\"">"";"

ASP C#, Escaping quotes

""
string test = @"sally said ""Yes you may."" ";

PHP, Escaping quotes

\" or use ' like javascript

'var text1="<img src=\"blank.gif\">";';

ASP VB Command termination

None, but : can be used to separate commands
on the same line.

ASP C# Command termination

Each command must end with ;

PHP Command termination

Each command must end with ; but
multiple commands per line are allowed.

ASP VB Screen output

Response.Write ("hello, world")

ASP C# Screen output

Response.Write( "Hello, World!" );

PHP Screen output

echo "hello, world";

or print ('hello world');

ASP VB Newline characters

Response.Write("Hello," + System.Environment.NewLine + " World!

")

Response.Write("Hello," & vbCrLf " World! ")

ASP C# Newline characters

Response.Write("Hello," + System.Environment.NewLine + " World!

");

Response.Write(" Hello," + System. ControlChars.NewLine + " World!

");

PHP Newline characters

"\n" (must be inside "", not '')

ASP VB Variable Names

Not case sensitive,
so ‘using system’ is the same as

using System

ASP C# Variable Names

Case sensitive,
so using system; have to be only using System;  Response.Write("”);

PHP Variable Names

Case sensitive AND must begin with $
so $Var is NOT the same as $var

2. String Functions
VB String concatenation

Dim x As String = “Con” & “caten” & “ation”

‘ The preceding statements set both x and y to “Concatenation”.

C# String concatenation

string str = “Hello ” + userName + “. Today is ” + date + “.”;

System.Console.WriteLine(str);

PHP String concatenation

. and .=

$fname=$name1." ".$name2;
$emsg.="error!";

VB Change case

LCase(), UCase()

lowerName=LCase(chatName)
upperName=UCase(chatName)

C# Change case

string x = “Janene”;

Console.WriteLine(x);

x = x.ToLower();

Console.WriteLine(x);

x = x.ToUpper();

Console.WriteLine(x);

PHP Change case

strtolower(), strtoupper()

$lowerName=strtolower($chatName);
$upperName=strtoupper($chatName);

VB String length

Len()

n=Len(chatName)

C# String length

Strings.Len(YourVariable);

string str = “abcdefg”;

Console.WriteLine("1) The length of '{0}' is {1}", str, str.Length);

PHP String length

Strlen();

$n=strlen($chatName);

VB Trim whitespace

Dim instance As String

Dim returnValue As String

returnValue = instance.Trim()

C# Trim whitespace

string Trim()

temp=Trim(xpage);

PHP Trim whitespace

trim() and also ltrim(), rtrim()
$temp=trim($xpage);

VB String sections

Left(), Right(), Mid()

Left(”abcdef”,3)      result = “abc” Right(”abcdef”,2)     result = “ef”

Mid(”abcdef”,3)       result = “cdef”

Mid(”abcdef”,2,4)     result = “bcde”

C# String sections

Left(), Right(), Mid()

string myString = “This is a string”;

Console.WriteLine(Left(myString,4));

Console.WriteLine(Right(myString,6));

Console.WriteLine(Mid(myString,5,4));

Console.WriteLine(Mid(myString,5));

PHP String sections

substr()

substr(”abcdef”,0,3);     result = “abc”

substr(”abcdef”,-2);      result = “ef”

substr(”abcdef”,2);       result = “cdef”

substr(”abcdef”,1,4);     result = “bcde”

3. Control Structures
VB if statements

if x=100 then

x=x+5

elseif x<200 then

x=x+2

else

x=x+1

end if

C#  if statement

if (Condition_1)

Statement_1;

else if (Condition_2)

Statement_2;

else if (Condition_3)

Statement_3;

PHP if statements

if ($x==100) {

$x=$x+5;

} else if ($x<200) {

$x=$x+2;

} else {

$x++;

}

VB for loops

for x=0 to 100 step 2

if x>p then exit for

next

C# for loop

class ForLoopTest

{

static void Main()

{

for (int i = 1; i <= 5;  i++)

{

Console.WriteLine(i);

}

}

}

PHP for loops

for ($x=0; $x<=100; $x+=2) {

if ($x>$p) {break;}

}

Vb while loop

Do While i>10

some code

Loop

C# while loop

int n = 1;

while (n < 6)

{

Console.WriteLine(”Current value of n is {0}”, n);

n+

PHP  while loops

while ($x<100) {

$x++;

if ($x>$p) {break;}

}

VB Select

Dim myNum

myNum = 454

Select Case myNum

Case 2

Response.Write(”myNum is Two”)

Case 3

Response.Write(”myNum is Three”)

Case 4

Response.Write(”myNum is Four”)

Case Else

Response.Write(”myNum is ” & myNum)

End Select

C# Switch 

int cost = 0;

switch(n)

{

case 1:

cost += 25;

break;

case 2:

cost += 25;

goto case 1;

case 3:

cost += 50;

goto case 1;

default:

Console.WriteLine(”Invalid selection. Please select 1, 2, or 3.”);

break;

}

PHP branching

switch ($chartName) {

case “TopSales”:

$theTitle=”Best Sellers”; $theClass=”S”;

break;

case “TopSingles”:

$theTitle=”Singles Chart”; $theClass=”S”;

break;

case “TopAlbums”:

$theTitle=”Album Chart”; $theClass=”A”;

break;

default:

$theTitle=”Not Found”;

}

4. HTTP Environment
VB Server variables

Public Sub Page_Load(Sender As System.Object, E As System.EventArgs)

var.Text=Request.ServerVariables(”ALL_HTTP”)

End Sub

Request.ServerVariables(”SERVER_NAME”)

Request.ServerVariables(”SCRIPT_NAME”)

Request.ServerVariables(”HTTP_USER_AGENT”)

Request.ServerVariables(”REMOTE_ADDR”)

Request.ServerVariables(”HTTP_REFERER”)

C# Server variables

void Page_Load(Object Sender, EventArgs E){

var.Text=Request.ServerVariables[“ALL_HTTP”];

}

Request.ServerVariables(”SERVER_NAME”);

Request.ServerVariables(”SCRIPT_NAME”);

Request.ServerVariables(”HTTP_USER_AGENT”);

Request.ServerVariables(”REMOTE_ADDR”);

Request.ServerVariables(”HTTP_REFERER”);

PHP Server variables

$_SERVER[“HTTP_HOST”];

$_SERVER[“PHP_SELF”];

$_SERVER[“HTTP_USER_AGENT”];

$_SERVER[“REMOTE_ADDR”];

$_SERVER[“HTTP_REFERER”];

Vb page redirect

Response.Redirect(”~/page.aspx”)

Server.Transfer(”page.aspx”)

Response.Status=”301 Moved Permanently”

Response.AddHeader “Location”, “http:/prabirchoudhury.wordpress.com/

C# page redirect

Response.Redirect(”~/page.aspx”);

Server.Transfer(”page.aspx”);

Response.Status=”301 Moved Permanently”;

Response.AddHeader “Location”, http://prabirchoudhury.wordpress.com/ ;

PHP Page redirects

header(”Location:page.php”);

VB, GET and POST variables

Request.QueryString("variable")
Request.Form("variable")

C#, GET and POST variables

Request.QueryString("variable");
Request.Form("variable");

PHP, GET and POST variables

$_GET["variable"];    $_POST["variable"];

$_REQUEST["variable"];

ASP, prevent page caching

Response.CacheControl = “no-cache”

Response.AddHeader “Pragma”, “no-cache”

Response.Expires = -1

C# prevent page caching

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetAllowResponseInBrowserHistory(false);

PHP, prevent page caching

header("Cache-Control: no-store, no-cache");
header("Pragma: no-cache");

VB Limit script execution time, in seconds

Server.ScriptTimeout = 60

C# Limit script execution time, in seconds

Server.ScriptTimeout = 60

PHP, Limit script execution time, in seconds

set_time_limit(240);

5. File System Functions
VB create a file system object

'Required for all file system functions
fileObj=Server.CreateObject
("Scripting.FileSystemObject")

C# create a file system object

//Required for all file system functions
fileObj=Server.CreateObject
("Scripting.FileSystemObject");

PHP create a file system

$filename = ‘test.txt’;

$ourFileHandle = fopen($ourFileName, ‘w’) or die(”can’t open file”);

fclose($ourFileHandle);

VB  check if a file exists

pFile="data.txt"
fileObj.FileExists(Server.MapPath(pFile))

C# check if a file exists

pFile="data.txt";
fileObj.FileExists(Server.MapPath(pFile));

PHP, check if a file exists

$pFile="data.txt";
file_exists($pFile);

VB file upload

<form id=”Form1″ method=”post” enctype=”multipart/form-data” runat=”server”>

<INPUT runat=”server” />

<br>

<input type=”submit” id=”Submit1″ value=”Upload” runat=”server” />

</form>

File1.PostedFile.SaveAs(SaveLocation)

Response.Write(”The file has been uploaded.”)

C# file upload

<form id=”Form1″ method=”post” enctype=”multipart/form-data” runat=”server”>

<INPUT runat=”server” />

<br>

<input type=”submit” id=”Submit1″ value=”Upload” runat=”server” />

</form>

File1.PostedFile.SaveAs(SaveLocation);

Response.Write(”The file has been uploaded.”);

PHP file upload

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

echo "The file ".  basename( $_FILES['uploadedfile']['name']).

" has been uploaded";

} else{

echo "There was an error uploading the file, please try again!";

}

VB check if a file exists

pFile="data.txt"
fileObj.FileExists(Server.MapPath(pFile))

C# check if a file exists

pFile="data.txt"
fileObj.FileExists(Server.MapPath(pFile));

PHP check if a file exists

$pFile="data.txt";
file_exists($pFile);

VB Read a text file

pFile=”data.txt”

xPage=fileObj.GetFile(Server.MapPath(pFile))

xSize=xPage.Size  ‘Get size of file in bytes

xPage=fileObj.OpenTextFile(Server.MapPath(pFile))

temp=xPage.Read(xSize)  ‘Read file

linkPage.Close

C# Read a text file

pFile=”data.txt”

xPage=fileObj.GetFile(Server.MapPath(pFile))

xSize=xPage.Size  ‘Get size of file in bytes

xPage=fileObj.OpenTextFile(Server.MapPath(pFile))

temp=xPage.Read(xSize)  ‘Read file

linkPage.Close

PHP, Read a text file

$pFile=”data.txt”;

$temp=file_get_contents($pFile);  //Read file

VB Delete file

Set ScriptObject = Server.CreateObject(”Scripting.FileSystemObject”)
ScriptObject.DeleteFile(filename)

C# Delete file

Set ScriptObject = Server.CreateObject(”Scripting.FileSystemObject”);
ScriptObject.DeleteFile(filename);

PHP Delete file

$myFile = “testFile.txt”;

unlink($myFile);

VB Server Time or Date

Now(), Date(), Time()

C#Server Time or Date

DateTime myDateTime1 = new DateTime();

PHP Server Time or Date

Date() ; DateTime();

6. Session Variable
VB create session

Dim name = “Jeff Smith”

Dim userName = “Smith”

Session.Add(”Name”, name)

Session.Add(”UserName “, userName)

Session(”name”) = txtname.Text;

Session(”address”)=txtaddress.Text;

C# create session

string name = “Jeff Smith”;

string userName = “Smith”;

Session.Add(”Name”, name);

Session.Add(”UserName “, userName);

Session[“name”] = txtname.Text;

Session[“address”]=txtaddress.Text;

PHP create session

session_start();
session_register("sessFirstName");
$sessFirstName = $HTTP_POST_VARS['txtFirstName'];

VB Session timeout

Session.TimeOut = 240

VB Session timeout

Session.Timeout = 240;

PHP Session timeout

ini_set(’session.gc_maxlifetime’,30);
ini_set(’session.gc_probability’,1);
ini_set(’session.gc_divisor’,1);

VB session remove

Session.RemoveAll()

//you can remove a single variable in the session

Session.Remove(”VarName”)

Session.Clear()

C# session remove

Session.RemoveAll();

//you can remove a single variable in the session

Session.Remove(”VarName”);

Session.Clear()

PHP session remove

//you can remove a single variable in the session
unset($_SESSION[‘session_name’]);

// or this would remove all the variables in the session, but not the session itself
session_unset();

// this would destroy the session variables
session_destroy();

7. Database Connection
VB Database (MSsql) Connection

‘   ||||| This is the Connections Object for an SQL DB

Dim MyConn As SqlConnection = New SqlConnection(”Data Source= server_name;Initial Catalog=database_name;User ID=user_name;Password=password”)

C# Database (MSsql) Connection

// Make a connection to the database

myConnection = new SqlConnection(”server=server_name; Initial Catalog=database_name; User; password=password”);

PHP Database (Mysql) Connection

define("HOST", "server_name");

define("USER", "user_name");

define("PASS", "password");

define("DB", "database_name");

$myConn=mysql_connect (HOST, USER, PASS) or die ('I cannot connect to the database because: ' . mysql_error());

@mysql_select_db(DB);

Vb Insert Data into database

Dim insertCmd = “insert into person (username ,firstname, lastname) values (@username,@firstname, @lastname)”

‘  |||| Set the Command Type (Stored Procedure, Text, etc)

MyCmd.CommandType = CommandType.Text

‘  |||||   Create Parameter Objects for values passed in

Dim objParam1, objParam2

‘  |||||   Add your parameters to the parameters Collection

objParam1 = MyCmd.Parameters.Add(”@UserName”, SqlDbType.VarChar)

objParam2 = MyCmd.Parameters.Add(”@Email”, SqlDbType.VarChar)

‘  |||||   Set the Parameter values to the passed in values

objParam1.Value = strUser

objParam2.Value = strEmail

‘  |||||   open database connection

MyConn.Open()

‘  |||||   execute query

result = MyCmd.ExecuteNonQuery()

‘   |||||   Close the Connection

MyConn.Close()

C# Insert Data into database

// |||| Create a sql command

String insertCmd = “insert into person (username ,firstname, lastname) values (@username,@firstname, @lastname)”;

SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);

myCommand.Parameters.Add(new SqlParameter(”@username”, SqlDbType.NVarChar, 50));

myCommand.Parameters[“@username”].Value = Server.HtmlEncode(userName.Text);

myCommand.Parameters.Add(new SqlParameter(”@firstname”, SqlDbType.NVarChar, 50));

myCommand.Parameters[“@firstname”].Value = Server.HtmlEncode(firstName.Text);

myCommand.Parameters.Add(new SqlParameter(”@lastName”, SqlDbType.NVarChar, 50));

myCommand.Parameters[“@lastName”].Value = Server.HtmlEncode(lastName.Text);

// open database connection

myCommand.Connection.Open();

// execute the query

myCommand.ExecuteNonQuery();

PHP feed into database

$sql  = "INSERT INTO person (username, fname, lname) ";

$sql .= "VALUES ('".$_POST['username']."', '".$_POST['fname']."', '".$_POST['lname']."') ";

mysql_query($sql)or die("cant execute tuatara: $sql");

Leave a Reply