Wednesday 28 January 2015

ADO.NET

Haii, berikut saya mau bagi cara create model, stored procedure dll yang berhubungan dengan SQL Server yang dapat kita create otomatis di ASP.NET dengan menggunakan ADO.NET. :)
1. Create projek
2. klik kanan model -> pilih add -> pilih ADO.NET

3. Selanjutnya ketikkan nama model. (Contoh: TransaksiModel)

4. Selanjutnya pilih EF Designer from Database

5. Kemudian klik New Connection, lalu isikan kotak dialog New Connection seperti gambar dibawah ini.
(Ehhh jangan lupa disesuaikan ya, ini hanya contoh)




















6. Kemudian pada pada kotak dialog Entity Data Model Wizard, silahkan dipilih atau di centang yang ingin digunakan di aplikasi, apakah table, view, atau stored procedure. Centang semuanya jika semua nya perlu. :)

7. Klik Finish (Lihat apa yang berubah)
8. Perhatikan di model telang muncul model untuk masing-masing tabel dan stored prosedure nya juga

White

Stored Procedure in ASP.NET (MVC 5)

Ada banyak cara untuk memanggil Stored Procedure di ASP.NET yang dalam hal ini stored procedure nya tersimpan di SQL Server 2008.
Boleh dengan cara menggunakan ado.net, jadi secara langsung model, stored procedure yang tersimpan di SQL Server tersebut tergenerate secara otomatis di aplikasi kita.
Nah, sekarang saya mau membagi bagaimana cara nya jika tidak menggunakan ado.net.

Mungkin seperti ini sederhana nya..
1. Kalau saya, buat pemanggilan stored prodedure nya di model
Misal nya seperti code di bawah ini.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace WebAppSatisfactionOfCustomers.Models
{
    public class M_User
    {
        [Key]
        public string Username { get; set; }
        public string Password { get; set; }

      

        //method untuk update password user di tabel M_User
        public void updatePassword(string username, string password)
        {

            SqlConnection sqlConn;
            SqlCommand cmd;

            DBConnector objDBConnector = new DBConnector();
            sqlConn = objDBConnector.GetConn();

            cmd = objDBConnector.GetCommand();

            SqlDataReader rdr = null;

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].[usp_M_User#UpdatePassword]"; <== ini SP yang dipanggil

            cmd.Parameters.AddWithValue("@Username", username);
            cmd.Parameters.AddWithValue("@Password", password);


            try
            {
                if (sqlConn.State == ConnectionState.Closed)
                    sqlConn.Open();

                rdr = cmd.ExecuteReader();


            }
            catch (Exception exp)
            {

                throw (exp);
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }
    }
}


2. nahh, langkah selanjutnya kita tinggal memanggil method-method ini di controller
kira-kira seperti ini,

[HttpPost]
        public ActionResult gantiPassword(FormCollection Form)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (SatisfactionOfCustomersDBContext dc = new SatisfactionOfCustomersDBContext())
                    {
                        string Username = Session["LogedUserID"].ToString();
                        string password = Form["pass"].ToString();
                        if (Username != null && password != null)
                        {
                            string name = Username;
                            string passworduser = encrypt(password);
                            user.updatePassword(name, passworduser); <= Method yg dipanggil dari model
                            return RedirectToAction("Login", "M_User");
                        }
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                throw ex;
            }

            return View();
        }


Silahkan dimodifikasi sesuai kebutuhan masing-masing ya.. :) :)


White


Tuesday 27 January 2015

Pop Up Login Using PHP

Siapa tau ada yang butuh buat pop up login dengan PHP..
1. Code dibawah ini aku letakkin di file browser.php, bisa di modif sesuka hati ya
<style type="text/css">
        #loginbox{
        margin: 0;
        margin-left: 40%;
        margin-right: 40%;
        margin-top: 50px;
        padding-top: 10px;
        width: 20%;
        height: 150px;
        position: absolute;
        background: #FBFBF0;
        border: solid #000000 2px;
        z-index: 9;
        font-family: arial;
        visibility: hidden;
        }
    </style>


<script language="JavaScript" type="text/javascript">
        function login(showhide){
        if(showhide == "show"){
            document.getElementById('loginbox').style.visibility="visible";
        }else if(showhide == "hide"){
            document.getElementById('loginbox').style.visibility="hidden";
        }
        }
    </script>


<div id="loginbox">
        <form name="login" action="function/login_process.php?name=login" method="post">
        <center>Username:</center>
        <center><input name="username" size="20" /></center>
        <center>Password:</center>
        <center><input name="password" type="password" size="20" /></center>
        <center><input type="submit" name="submit" value="LOGIN" /></center>
        </form>
        <br />
        <center><a href="javascript:login('hide');">close</a></center>
    </div>
    <p><a href="javascript:login('show');">LOGIN</a></p>


2. nah trus aku buat file untuk memproses login nama nya login_process.php dan bisa disesuaikan dengan kebutuhan masing-masing ya. :)

<?php
include ('../config/config.php');
session_start();

if ($_GET['name'])
{
    $username = $_POST['username'];
    $password = $_POST['password'];

    // query untuk mendapatkan username dan password dari database
    $query = "select * from tbl_user where username = '$username' and password = '$password'";
    $hasil = mysqli_query($connection, $query);
   
    if (mysqli_num_rows($hasil) > 0)
    {
        $_SESSION['username'] = $username;
        if ($username == 'admin')
        {
            header("location:../browser.php?dir=/FILES&&username=admin" );
        }
        else
        {
            header("location:../browser.php?dir=/FILES&&username=$username");
        }
    }
    else
    {
        echo "User tidak terdaftar";
    }
}
?>

Kira-kira hasil nya seperti ini setelah kita klik link login


sekian dulu ya, semoga membantu

White

Sunday 25 January 2015

Pop UP Using PHP

Jadi gini, saya punya tugas untuk menampilkan detail dari suatu file (jika di klik) muncul detail file tersebut (data nya berasal dari database=> MySql) di dalam sebuah Pop Up..

Berikut caranya ya. (ini sesuai dengan yang aku kerjakan ya :) )
1. Pertama buat dulu link file nya.
 (ini sebagian dari isi fileku yang ku beri nama browser.php)

 <link rel="stylesheet" href="style/colorbox.css" />
 <script src="style/jquery.min.js"></script>
 <script src="style/jquery.colorbox-min.js"></script>

<?php $link_address = "function/detail_view.php?f=".$row["id_file"]."&dir=".$row["path_file"] ?>
 <td><?php echo "<a class ='iframe' href='".$link_address."'>Detail Pop Up</a>"; ?></td>

2. Aku buat file detail_view.php
(ini nih file yang mau aku pop up)

<?php
include('../config/config.php');

    $id = $_GET['f'];
    $dir = $_GET['dir'];
   
    $query = "SELECT * from tbl_file WHERE id_file = '".$id."'";
    $sql = mysqli_query($connection, $query);
    if(mysqli_num_rows($sql) > 0)
    {
        while($data = mysqli_fetch_assoc($sql))
        {
            echo '
           
            <tr>
                <td>Id File</td>
                <td>:</td><td>'.$data['id_file'].'</td></tr>
            <tr>
                <td>Nama File</td>
                <td>:</td><td>'.$data['nama_file'].'</td></tr>
            <tr>
                <td>Tipe File</td>
                <td>:</td><td>'.$data['tipe_file'].'</td></tr>
            <tr>
                <td>Path File</td>
                <td>:</td><td>'.$data['path_file'].'</td></tr>
            <tr>
                <td>Lokasi File</td>
                <td>:</td><td>'.$data['lokasi_file'].'</td></tr>
            <tr>
                <td>Upload Date</td>
                <td>:</td><td>'.$data['upload_date'].'</td></tr>
            <tr>
                <td>Ukuran File</td>
                <td>:</td><td>'.$data['ukuran_file'].'</td></tr>
            </div>';
           
        }
    }
?>

udah dehhh... :)
Hasil nya seperti ini, setelah kita klik link detail



ini untuk referensi nya ya http://www.formmail-maker.com/forum/index.php?p=/discussion/23/how-to-make-a-popup-form-using-jquery-and-colorbox-plugins/p1

Thursday 22 January 2015

How to donwload file from directory using PHP

1. First is we make a class download .php
<?php
/*
|-----------------
| Chip Download Class
|------------------
*/

require_once("class.chip_download.php");

/*
|-----------------
| Class Instance
|------------------
*/
$directori = $_GET['dir'];
$file = $_GET['f'];
$tipe = $_GET['tipe'];
$download_path = "C:wamp/www/FileManagerUsingPHP".$directori.'/';


$args = array(
        'download_path'        =>    $download_path,
        'file'                =>    $file,       
        'extension_check'    =>    TRUE,
        'referrer_check'    =>    FALSE,
        'referrer'            =>    NULL,
        );
$download = new chip_download( $args );

/*
|-----------------
| Pre Download Hook
|------------------
*/

$download_hook = $download->get_download_hook();
//$download->chip_print($download_hook);
//exit;

/*
|-----------------
| Download
|------------------
*/

if( $download_hook['download'] == TRUE ) {

    /* You can write your logic before proceeding to download */
   
    /* Let's download file */
    $download->get_download();

}

?>

2. See, that the download.php require a class, class.chip_download.php
This is the class.chip_download.php
<?php


class chip_download {
   
    /*
    |---------------------------
    | Properties
    |---------------------------
    */
   
    private $download_hook = array();
   
    private $args = array(
                        'download_path'            =>    NULL,
                        'file'                    =>    NULL,                       
                        'extension_check'        =>    TRUE,
                        'referrer_check'        =>    FALSE,   
                        'referrer'                =>    NULL,                   
                    );
   
    private $allowed_extensions = array(
                       
                        /* Archives */
                        'zip'    => 'application/zip',
                        '7z'    => 'application/octet-stream',
                   
                          /* Documents */
                          'txt'    => 'text/plain',
                        'pdf'    => 'application/pdf',
                          'doc'     => 'application/msword',
                          'xls'    => 'application/vnd.ms-excel',
                          'ppt'    => 'application/vnd.ms-powerpoint',
                     
                          /* Executables */
                          'exe'    => 'application/octet-stream',
                   
                          /* Images */
                          'gif'    => 'image/gif',
                          'png'    => 'image/png',
                          'jpg'    => 'image/jpeg',
                          'jpeg'    => 'image/jpeg',
                   
                          /* Audio */
                          'mp3'    => 'audio/mpeg',
                          'wav'    => 'audio/x-wav',
                   
                          /* Video */
                          'mpeg'    => 'video/mpeg',
                          'mpg'    => 'video/mpeg',
                          'mpe'    => 'video/mpeg',
                          'mov'    => 'video/quicktime',
                          'avi'    => 'video/x-msvideo'
                   
                    );
   

    /*
    |---------------------------
    | Constructor
    |
    | @public
    | @param array $args
    | @param array $allowed_extensions
    |
    |---------------------------
    */
   
    public function __construct( $args = array(), $allowed_extensions = array()  ) {
       
        $this->set_args( $args );
        $this->set_allowed_extensions( $allowed_extensions );
                       
    }
   
    /*
    |---------------------------
    | Print variable in readable format
    |
    | @public
    | @param string|array|object $var
    |
    |---------------------------
    */
   
    public function chip_print( $var ) {
       
        echo "<pre>";
        print_r($var);
            echo "</pre>";
   
    }
   
    /*
    |---------------------------
    | Update default arguments
    | It will update default array of class i.e $args
    |
    | @private
    | @param array $args - input arguments
    | @param array $defatuls - default arguments
    | @return array
    |
    |---------------------------
    */
   
    private function chip_parse_args( $args = array(), $defaults = array() ) {
        return array_merge( $defaults, $args );   
    }
   
    /*
    |---------------------------
    | Get extension and name of file
    |
    | @private
    | @param string $file_name
    | @return array - having file_name and file_ext
    |
    |---------------------------
    */
   
    private function chip_extension($file_name) {
        $temp = array();
        $temp['file_name'] = strtolower( substr( $file_name, 0, strripos( $file_name, '.' ) ) );
        $temp['file_extension'] = strtolower( substr( $file_name, strripos( $file_name, '.' ) + 1 ) );
        return $temp;
    }
   
    /*
    |---------------------------
    | Set default arguments
    | It will set default array of class i.e $args
    |
    | @private
    | @param array $args
    | @return 0
    |
    |---------------------------
    */
   
    private function set_args( $args = array() ) {
       
        $defaults = $this->get_args();
        $args = $this->chip_parse_args( $args, $defaults );
        $this->args = $args;   
    }
   
    /*
    |---------------------------
    | Get default arguments
    | It will get default array of class i.e $args
    |
    | @public
    | @return array
    |
    |---------------------------
    */
   
    public function get_args() {
        return $this->args;   
    }
   
    /*
    |---------------------------
    | Set default allowed extensions
    | It will set default array of class i.e $allowed_extensions
    |
    | @private
    | @param array $allowed_extensions
    | @return 0
    |
    |---------------------------
    */
   
    private function set_allowed_extensions( $allowed_extensions = array() ) {
       
        $defaults = $this->get_allowed_extensions();
        $allowed_extensions = array_unique( $this->chip_parse_args( $allowed_extensions, $defaults ) );
        $this->allowed_extensions = $allowed_extensions;   
   
    }
   
    /*
    |---------------------------
    | Get default allowed extensions
    | It will get default array of class i.e $allowed_extensions
    |
    | @public
    | @return array
    |
    |---------------------------
    */
   
    public function get_allowed_extensions() {
        return $this->allowed_extensions;   
    }
   
    /*
    |---------------------------
    | Set Mimi Type
    | It will set default array of class i.e $allowed_extensions
    |
    | @private
    | @param string $file_path
    ! @return string
    |
    |---------------------------
    */
   
    private function set_mime_type( $file_path ) {
       
        /* by Function - mime_content_type */
        if( function_exists( 'mime_content_type' ) ) {
            $file_mime_type = @mime_content_type( $file_path );
        }
       
        /* by Function - mime_content_type */
        else if( function_exists( 'finfo_file' ) ) {
           
            $finfo = @finfo_open(FILEINFO_MIME);
            $file_mime_type = @finfo_file($finfo, $file_path);
            finfo_close($finfo); 
       
        }
       
        /* Default - FALSE */
        else {
            $file_mime_type = FALSE;
         }
       
         return $file_mime_type;   
   
    }
   
    /*
    |---------------------------
    | Get Mimi Type
    | It will set default array of class i.e $allowed_extensions
    |
    | @public
    | @param string $file_path
    ! @return string
    |
    |---------------------------
    */
   
    public function get_mime_type( $file_path ) {
        return $this->set_mime_type( $file_path );   
    }
   
    /*
    |---------------------------
    | Pre Download Hook
    |
    | @private
    | @return 0
    |
    |---------------------------
    */
   
    private function set_download_hook() {
       
        /* Allowed Extensions */
        $allowed_extensions = $this->get_allowed_extensions();
       
        /* Arguments */
        $args = $this->get_args();       
       
        /* Extract Arguments */
        extract($args);
       
        /* Directory Depth */
        $dir_depth = dirname( $file );
        if ( !empty( $dir_depth ) && $dir_depth != "." ) {
            $download_path = $download_path . $dir_depth . "/";
        }
       
        /* File Name */
        $file = basename( $file );
       
        /* File Path */
        $file_path = $download_path . $file;
        $this->download_hook['file_path'] = $file_path;
       
        /* File and File Path Validation */
        if( empty( $file ) || !file_exists( $file_path ) ) {
            $this->download_hook['download'] = FALSE;
            $this->download_hook['message'] = "Invalid File or File Path.";
            return 0;
        }
       
        /* File Name and Extension */
        $nameext = $this->chip_extension($file);
        $file_name = $nameext['file_name'];
        $file_extension = $nameext['file_extension'];
       
        $this->download_hook['file'] = $file;
        $this->download_hook['file_name'] = $file_name;
        $this->download_hook['file_extension'] = $file_extension;

        /* Allowed Extension - Validation */
        if ( $extension_check == TRUE && !array_key_exists( $file_extension, $allowed_extensions ) ) {
          $this->download_hook['download'] = FALSE;
          $this->download_hook['message'] = "File is not allowed to download";
          return 0;
        }
       
        /* Referrer - Validation */       
        if ( $referrer_check == TRUE && !empty($referrer) && strpos( strtoupper( $_SERVER['HTTP_REFERER'] ), strtoupper( $referrer ) ) === FALSE ) {
            $this->download_hook['download'] = FALSE;
             $this->download_hook['message'] = "Internal server error - Please contact system administrator";
            return 0;
        }
       
        /* File Size in Bytes */
        $file_size = filesize($file_path);
        $this->download_hook['file_size'] = $file_size;
       
        /* File Mime Type - Auto, Manual, Default */
        $file_mime_type = $this->get_mime_type( $file_path );       
        if( empty( $file_mime_type ) ) {
           
            $file_mime_type = $allowed_extensions[$file_extension];
            if( empty( $file_mime_type ) ) {
                $file_mime_type = "application/force-download";
            }
       
        }       
       
        $this->download_hook['file_mime_type'] = $file_mime_type;
       
        $this->download_hook['download'] = TRUE;
        $this->download_hook['message'] = "File is ready to download";
        return 0;       
   
    }
   
    /*
    |---------------------------
    | Download Hook
    | Allows you to do some action before download
    |
    | @public
    | @return array
    |
    |---------------------------
    */
   
    public function get_download_hook() {
        $this->set_download_hook();
        return $this->download_hook;
    }
   
    /*
    |---------------------------
    | Post Download Hook
    |
    | @private
    | @return array
    |
    |---------------------------
    */
   
    private function set_post_download_hook() {
        return $this->download_hook;
    }
   
    /*
    |---------------------------
    | Download
    | Start download stream
    |
    | @public
    | @return 0
    |
    |---------------------------
    */
   
    public function set_download() {
       
        /* Download Hook */
        $download_hook = $this->set_post_download_hook();
       
        /* Extract */
        extract($download_hook);
       
        /* Recheck */
        if( $download_hook['download'] != TRUE ) {
            echo "File is not allowed to download";
            return 0;
        }
       
        /* Execution Time Unlimited */
        set_time_limit(0);
       
        /*
        |----------------
        | Header
        | Forcing a download using readfile()
        |----------------
        */
       
        header('Content-Description: File Transfer');
        header('Content-Type: ' . $file_mime_type);
        header('Content-Disposition: attachment; filename=' . $file);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . $file_size);
        ob_clean();
        flush();
        readfile($file_path);
        exit;
       
    }
   
    /*
    |---------------------------
    | Download
    | Start download stream
    |
    | @public
    | @return array
    |
    |---------------------------
    */
   
    public function get_download() {
        $this->set_download();
        exit;
    }

    /*
    |---------------------------
    | Destructor
    |---------------------------
    */
   
    public function __destruct() {
    }
}
?>

If you want to see the complete code klik here
For more information, before you upload your file into a directory, make sure that your file name does not consist of space (" ").
So, before uploading the file, replace all the file name which is consist of space (" ") with _, or anything.
Because, this download code only works well with file name which is not consist of space (" ").

Thank you..