Tag Archives: CLASS

Using two Way Adding “active” tag to your navigation list in an asp.net mvc Layout page

Recently my task need convert this website http://www.royalecoach.com.au/royale.asp (this is wrote by using classic asp) into asp.net MVC.

First I need to create a layout.cshtml for my the new version of this website.Then navigation need add a class named active to it when the action method has been called.

The first way is very simpley, you could wirte a logic to your view, here is one solution:

addClassNametoLi

But the rule of MVC is the view must be simply as possible, I don’t like this nasty and yuck c# code sit in there. So there is a way just by write a CustomHtmlHelpers to improve it.

here is my class file:

htmlHelper

 

Then in your layout page ,your could use it like:

layoutMenu

That’s it. By the way, I am using asp mvc4. Hope that could help some one else.

Have fun:)

Use PHP Check all the field in form is not empty,here is the php page–continues with previous post

Use PHP Check all the field in form is not empty,here is the php page–continues with previous post

<?php
/*  Program name: checkBlank.php
 *  Description:  Program checks all the form fields for
 *                blank fields.
 */
 if(isset($_POST[‘sent’]) && $_POST[‘sent’] == “yes”)        #6
 {
/* check each field except middle name for blank fields */
  foreach($_POST as $field => $value)                        #9
  {
  if($value == “”)                                          #11
    {
      if($field != “middle_name”)                           #13
      {
         $blank_array[] = $field;                           #15
      } // endif field is not middle name
    } // endif field is blank
    else                                                    #18
    {
      $good_data[$field] = strip_tags(trim($value));
    }
  }  // end of foreach loop for $_POST
  /* if any fields were blank, create error message and
     redisplay form */
  if(@sizeof($blank_array) > 0)                             #25
  {
    $message = “<p style=’color: red; margin-bottom: 0;
         font-weight: bold’>
         You didn’t fill in one or more required fields.
         You must enter:
         <ul style=’color: red; margin-top: 0;
             list-style: none’ >”;
    /* display list of missing information */
    foreach($blank_array as $value)
    {
      $message .= “<li>$value</li>”;
    }
    $message .= “</ul>”;
    /* redisplay form */
    extract($good_data);                                     #40
    include(“form_phone_values.inc”);                        #41
    exit();                                                  #42
  } // endif blanks
  echo “All required fields contain information”;            #44
 } // endif submitted
 else                                                        #46
 {
  include(“form_phone_values.inc”);
 }
?>

Use PHP Check all the field in form is not empty–continues

First use class create your php form page,here is your class, you could save as form_phone_values.inc

<?php
/*  Program name: form_phone_values.inc
 *  Description:  Defines a form that collects a user’s
 *                name and phone number.
 */
$labels = array( “first_name” => “First Name”,
                 “middle_name” => “Middle Name”,
                 “last_name” => “Last Name”,
                 “phone” => “Phone”);
$submit = “Submit Phone Number”;
?>
 <html>
 <head><title>Customer Phone Number</title>
    <style type=’text/css’>
    <!–
     #form {
       margin: 1.5em 0 0 0;
       padding: 0;
     }
     #field {padding-bottom: 1em;}
     label {
     font-weight: bold;
     float: left;
     width: 20%;
     margin-right: 1em;
     text-align: right;
     }
    –>
   </style>
 </head>
 <body>
<h3>Please enter your phone number below.</h3>
<?php
 echo “<form action=’$_SERVER[PHP_SELF]’ method=’POST’>    
      <div id=’form’>”;
  if(isset($message))                                         #36
  {
     echo $message;
  }
  /* Loop that displays the form fields */
  foreach($labels as $field => $label)
  {
    echo “<div id=’field’><label for=’$field’>$label</label>
          <input id=’$field’ name=’$field’ type=’text’
             size=’50%’ maxlength=’65’
             value='”.@$$field.”‘ /></div>\n”;                #46
  }
  echo “<input type=’hidden’ name=’sent’ value=’yes’ />\n”;     #48
  echo “<input style=’margin-left: 33%’ type=’submit’
          value=’$submit’ />\n”;
?>
</form></body></html>

finally, you just need create a php page read everything through your class

finally, you just need create a php page read everything through your class,here is the source code for one of the three shopping cart, for another two cart you just need to change the storeID, it make your job much easy.

<?php
session_start();
require_once(“class_OnlineStore.php”);
$storeID = “COFFEE”;
$storeInfo = array();
if(class_exists(“OnlineStore”))
{
    if(isset($_SESSION[‘currentStore’]))
    {
        $store = unserialize($_SESSION[‘currentStore’]);
    }
    else
    {
        $store = new OnlineStore();    
    }
    $store->setStoreID($storeID);
    $storeInfo =  $store->getStoreInformation();
    $store->processUserInput();
}
else
{
    $ErrorMsgs[]=”The OnlineStore class is not available!”;
    $store = null;
        
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title><?php echo $storeInfo[‘name’]; ?></title>
<link rel=”stylesheet” type=”text/css” href=”<?php echo $storeInfo[‘css_file’]; ?>” />
</head>

<body>
<h1><?php echo htmlentities($storeInfo[‘name’]); ?></h1>
<h2><?php echo htmlentities($storeInfo[‘description’]); ?></h2>
<p><?php echo htmlentities($storeInfo[‘welcome’]); ?></p>

<?php
    $store->getProductList();
    $_SESSION[‘currentStore’] = serialize($store);
?>
</body>
</html>

then you need create your class

here is the source code for your online stores class

<?php
class OnlineStore
{
    private $DBConnect = null;
    private $storeID = “”;
    private $inventory = array();
    private $shoppingCart = array();
    function __construct()
    {
        include(“inc_OnlineStoreDB.php”);
        $this->DBConnect = $DBConnect;
    }

    
    function __destruct()
    {
        if(!$this->DBConnect->connect_error)
        {
            $this->DBConnect->close();
        }
    }
    
    public function setStoreID($storeID)
    {
        if($this->storeID != $storeID)    
        {
            $this->storeID = $storeID;
            $string = “SELECT * FROM inventory WHERE storeID = ‘”.$this->storeID. “‘”;
            $result = @$this->DBConnect->query($string);
            if(!$result)
            {
                $this->storeID = “”;    
            }
            else
            {
                $this->inventory = array();
                $this->shoppingCart = array();
                while(($row = $result->fetch_assoc())!==null)    
                {
                    $this->inventory[$row[‘productID’]]=array();
                    $this->inventory[$row[‘productID’]][‘name’]=$row[‘name’];
                    $this->inventory[$row[‘productID’]][‘description’]=$row[‘description’];
                    $this->inventory[$row[‘productID’]][‘price’]=$row[‘price’];
                    $this->shoppingCart[$row[‘productID’]]=0;    
                }
            }
                
        }
        
    }
    
    public function getStoreInformation()
    {
        $retval = false;
        if($this->storeID != “”)    
        {
            $string = “SELECT * FROM store_info WHERE storeID = ‘”.$this->storeID . “‘”;
            $result = @$this->DBConnect->query($string);
            if($result)    
            {
                $retval = $result->fetch_assoc();    
            }
        }
        return($retval);
    }
    
    public function getProductList()
    {
        $retval = false;
        $subtotal = 0;
        if(count($this->inventory)>0)
        {
            echo “<table width=\”100%\”>”;
            echo “<tr><th>Product</th><th>Description</th><th>Price each</th><th># in Cart</th><th>Total Price</th><th>&nbsp;</th></tr>”;
            foreach($this->inventory as $ID => $Info)
            {
                echo “<tr><td>”    .htmlentities($Info[‘name’]).”</td>”;
                echo “<td>”.htmlentities($Info[‘description’]).”</td>”;
                printf(“<td class=\”currency\”>$%.2f</td>”,$Info[‘price’]);
                echo “<td class=’currency’>”.$this->shoppingCart[$ID].”</td>”;
                printf(“<td class=’currency’>$%.2f</td>”,$Info[‘price’]*$this->shoppingCart[$ID]);
                echo “<td><a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&ItemToAdd=$ID’>Add Item</a><br/>”;
                echo “<a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&ItemToRemove=$ID’>Remove Item</a></td>”;
                $subtotal += ($Info[‘price’] * $this->shoppingCart[$ID]);                
            }
            
            echo “<tr><td colspan=’4′>Subtotal</td>”;
            printf(“<td class=’currency’>$%.2f</td>”,$subtotal);
            echo “<td><a href='”.$_SERVER[‘SCRIPT_NAME’].”?PHPSESSID=”.session_id() .”&EmptyCart=true’>Empty Cart</a></td></tr>”;
            echo “</table>”;
            
        echo “<p align=’center’><a href=’Checkout.php?PHPSESSID=”.session_id().”&CheckOut=$storeID’>Checkout</a></p>”;    
        }
            
        return($retval);
    }
private function addItem()
{
    $ProdID = $_GET[‘ItemToAdd’];
    if (array_key_exists($ProdID,$this->shoppingCart))
    {
        $this->shoppingCart[$ProdID] += 1;    
    }
        
    
}

function __wakeup()
{
    include(“inc_OnlineStoreDB.php”);
    $this->DBConnect = $DBConnect;    
}

private function removeItem()
{
    $ProdID = $_GET[‘ItemToRemove’];
    if(array_key_exists($ProdID,$this->shoppingCart))
    {
        if($this->shoppingCart[$ProdID]>0)
            {
                $this->shoppingCart[$ProdID]-=1;                
            }
    }
    
}

private function emptyCart()
{
    foreach($this->shoppingCart as $key=>$value)
    {
        $this->shoppingCart[$key]=0;    
    }
    
}

public function processUserInput()
{
    if(!empty($_GET[‘ItemToAdd’]))
    {
        $this->addItem();    
    }
    if(!empty($_GET[‘ItemToRemove’]))
    {
        $this->removeItem();    
    }
    if(!empty($_GET[‘EmptyCart’]))
    {
        $this->emptyCart();    
    }
    
}

public function checkout()
{
        $ProductsOrdered = 0;
        foreach($this->shoppingCart as $productID =>$quantity)
        {
            if ($quantity > 0)
            {
                ++$ProductsOrdered;
                $SQLstring = “INSERT INTO orders ” .” (orderID, productID, quantity) ” .” VALUES(‘” . session_id() . “‘,” .”‘$productID’, $quantity)”;
                $QueryResult = $this->DBConnect->query($SQLstring);
            }
        }
        
        echo “<p><strong>Your order has been ” .”recorded.</strong></p>”;
}
}

?>

Use PHP create an program an online order form–continue

Use PHP create  an program an online order form

you could see what it look like,

http://www.sandywebdesigner.com/index.php?section=Final-Project

http://www.sandywebdesigner.com/con_str/stores/GosselinGourmetCoffee.php

http://www.sandywebdesigner.com/con_str/stores/OldTymeAntiques.php

http://www.sandywebdesigner.com/con_str/stores/ElectronicsBoutique.php

the 3 order form just use the same class, you don’t to rewrite it, just change the storeID, you could use for any shopping cart.

the following post i will write the source code.

Cleaning Up with Destructor Functions

A destructor function is commonly called in two ways: when a script ends or when you manually
delete an object with the unset() function. You generally do not need to use a destructor function, although many programmers use one to close previously opened fi le handles and database connections. To add a destructor function to a PHP class, create a function named
__destruct() (with two leading underscore characters). Th e following code contains a destructor function that closes the database connection opened with the constructor function:
function __construct() {
$DBConnect = new mysqli(“php_db”, “dongosselin”,
“rosebud”, “real_estate”)
}
function __destruct() {
$DBConnect->close();
}

Initializing with Constructor Functions

A constructor function is a special function that is called automatically when an object from a
class is instantiated. You defi ne and declare constructor functions the same way you defi ne other functions, although you do not include a return type because constructor functions do not return values. Each class defi nition can contain its own constructor function, named either __construct() (with two leading underscore characters) or the same name as the class.

garbage collection

With PHP, you do not need to
worry about reclaiming memory that is reserved for your variables or
objects. Although you can manually remove a variable or object with
the unset() function, there is usually no reason to do so—as with
variables, PHP will automatically clean up unused memory when
an object within a function goes out of scope, or at the end of the
script for global objects. Th e one exception involves open database
connections.because database connections
can take up a lot of memory, you should explicitly close a
database connection when you fi nish with it by calling the procedural
mysql_close() function or the close() method of the mysqli class.

Creating Classes, Attributes, and Operations in PHP

  • Structure of a Class

A minimal class definition looks like this:
class classname
{
}

  • Constructors

Most classes have a special type of operation called a constructor.A constructor is called
when an object is created, and it also normally performs useful initialization tasks such as
setting attributes to sensible starting values or creating other objects needed by this object.

class classname
{
function __construct($param)
{
echo “Constructor called with parameter “.$param.”<br />”;
}
}

  • Destructors

The opposite of a constructor is a destructor.They allow you to have some functionality
that will be executed just before a class is destroyed, which will occur automatically when
all references to a class have been unset or fallen out of scope.

Similar to the way constructors are named, the destructor for a class must be named
__destruct(). Destructors cannot take parameters.