Tutorial Programming

Tutorial ASP.NET C# Membuat Login, SESSION, MD5, SQL SERVER

Asalammualaikum, sahabat kali ini saya akan membahas tentang Tutorial ASP.NET C# Membuat Login, SESSION, MD5, SQL SERVER, kali ini saya akan membuat login.
Baiklah bismillah.

Berikut adalah struktur database pada sql server.



Pertama sahabat buat file dengan nama Login.aspx di server ASP.NET kalian.


Kedua buatlah coding design pada ASP.NET kalian dengan code;

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="Tutorial_1.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form" runat="server">
    <div>
        <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtPass" runat="server"></asp:TextBox>
        <asp:Button ID="BtnLogin" runat="server" Text="BtnLogin" OnClick="BtnLogin_Click" />
    </div>
        
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        
    </form>

</body>
</html>


Ketiga copy code untuk server side nya;

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Tutorial_1
{
    public partial class Login : System.Web.UI.Page
    {
        string connStr = "Integrated Security=SSPI; Persist Security Info=True; Initial Catalog=coba; Data Source=(LOCAL)";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] != null) // if it will not find Session user it will redirect to login page.
            {
                Response.Redirect("Editor/Home.aspx");
            }
        }


        private string md5(string sPassword)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(sPassword);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }

        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            

            string str = "select * from user_web where username =@username  and password =@password";
            SqlConnection con = new SqlConnection(connStr);
            SqlCommand cmd = new SqlCommand(str, con);

            string Pass = md5(txtPass.Text);

            try
            {
                con.Open();
                cmd.Parameters.AddWithValue("@username", txtUsername.Text);
                cmd.Parameters.AddWithValue("@password", Pass);

                SqlDataReader sdr = cmd.ExecuteReader();
                if (sdr.Read())
                {
                    
                    // If Username Password found in Database It will
                    // Storee Session
                    Session["User"] = txtUsername.Text;
                    Session.Timeout = 15; //15min
                    // now Storing Cookies & config.
                    HttpCookie LoginCookies = new HttpCookie("LoginCookies");
                    LoginCookies.Value = txtUsername.Text;
                    LoginCookies.Expires = DateTime.Now.AddHours(1); // Making Cooki for 1 hour
                    Response.Cookies.Add(LoginCookies);
                    // Redirecting to Welcomepage.
                    Response.Redirect("Editor/Home.aspx");
                    
                }
                else
                {
                    Label1.Text = "Invalid Username OR Password";
                }
                con.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message + "<br/>" + ex.StackTrace);
            }
            finally
            {
                con.Close();
            }
        }    
    }
}

Keempat buatlah folder bernama, Editor/Home.aspx;

Kelima copy code desain Home.aspx;


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="Tutorial_1.Editor.Home" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="LogoutButton" runat="server" Text="LogoutButton" OnClick="LogoutButton_Click" />
    </div>
        
    </form>
</body>
</html>


Keenam copy code untuk C# Home.aspx tersebut;

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Tutorial_1.Editor
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] == null) // if it will not find Session user it will redirect to login page.
            {
                Response.Redirect("~/Login.aspx");

                if (Request.Cookies["LoginCookies"] != null)
                {
                    Response.Redirect("~/Login.aspx");
                }
            }
            else // if it will find Session it will write message on WelcomeLabel.
            {
                Label2.Text = "Hello, " + Session["User"].ToString() + "!";
                // it will display on  WelcomeLabel
                // Hello, MahadTECH!
                // Now Taking Value From cookie as u wish..
                Label1.Text = "Its Taking from Cookies, Your name is " + Request.Cookies["LoginCookies"].Value;
                // it will display on Label1
                // Its Taking from Cookies, Your name is MahadTECH
            }
        }

        protected void LogoutButton_Click(object sender, EventArgs e)
        {
            Session.Remove("User");
            Session.Contents.RemoveAll();
            Session.RemoveAll();
            if (Request.Cookies["LoginCookies"] != null)
            {
                Response.Cookies["LoginCookies"].Expires = DateTime.Now.AddDays(-1);
                // its trick it will expire yesterday next time when will login it will be expired..
                // because date was before 1 day from today..
            }
            Response.Redirect("~/Login.aspx");
        }
    }
}



Jika coding benar, akan seperti gambar dibawah ini:



Jika sahabat mengalami error pada coding kalian, jangan segan untuk mengirim email dan komen.

Sekian tutorial saya mengenai Tutorial ASP.NET C# Membuat Login, SESSION, MD5, SQL SERVER mengunakan ASP.NET di C#, Semoga bermanfaat yah sahabat.
Maaf jika pemahaman saya ada yang salah, terimakasih.


3 comments:

  1. mau nanya untuk kasus lain nih kawan.
    Untuk nge get konten data base (materi belajar) berdasarkan lokasi dengan bantuan google MAP untuk mendapatkan posisinya gmn kawan?

    ReplyDelete
    Replies
    1. Ambil aja (latitude longitude) untuk algoritma nya, tergantung kita masing-masing. Mslh parameter get ataupun post, itu balik lagi ke algoritma kita.

      Delete
  2. mohon responnya ke email : muletasim@gmail.com
    terima kasih kawan

    ReplyDelete

Tutorial Programming Designed by Templateism | Ary EJFA Copyright © 2015

Theme images by richcano. Powered by Blogger.