Friday, February 22, 2013

Browser back button issue after logout

[Reference from codeproject Articles...]

Introduction
Generally when any user login in any web application, we store some value in session. The session continues the user existence until logout. After logout we clear/abandon the session and redirect to login page. In that state the user is out of website and the secret information is now secure or nobody is authorized to view/access the information.
But the problem is now, from this redirect login page if user clicks the back button of browser, it again goest to the previous visited page although the page is already logged out. The main reason is browser’s cache. Because while user logout the session then the session is abandon in server side. But after click the back button of the browser, the previouse page is not postback, the client side just opens from cache. It only works if the back page refresh/relaod, because in that period the page becomes postback.
The common problem has many solutions but each and every solution has some limitations. Let’s see the existing solutions those we can find easily in searching.

Existing Solution 1: Clear cache/no-cache

// Code disables caching by browser. Hence the back browser button
// grayed out and could not causes the Page_Load event to fire 
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore(); 
Limitations:
  • Server Side code and for that it’s not works without postback.
  • I have to clear my cache in force (I don’t want to clear my cache)

Existing Solution 2: Use meta tag for no-cache

<meta Http-Equiv="Cache-Control" Content="no-cache">
<meta Http-Equiv="Pragma" Content="no-cache">
<meta Http-Equiv="Expires" Content="0"> 

Limitations:
  • This is not possible because Back history is maintained by browser, you will need to close the window
  • I have to clear my cache in force (I don’t want to clear my cache)

Existing Solution 3: Clears browser history and redirects URL

//clears browser history and redirects url
<SCRIPT LANGUAGE="javascript"> 
{  
     var Backlen=history.length;   
     history.go(-Backlen);   
     window.location.href=page url 
}
</SCRIPT> 
Limitations:
  • Same limitation like solution 1: Not working in all browsers, moreover I have to clear my history although I don't want to do this.

Existing Solution 4: Call Javascript from server side to clear cache

Page.ClientScript.RegisterStartupScript(this.GetType(),"cle","windows.history.clear",true); 
Limitations:
  • Server side code so it not works without postback again moreover I have to clear my history although I don't want to do this.

Alternative Solution:

From the above explanation, we can understand that when the user clicks on back button of browser, the client side loads only. Even no postback happens in that period. For that I handle the problem on client side. You can think that if we check the session value in client side with javascript then problem will solve? My answer is: NO. Because when we clear/abandon the session value, its value changed only server side but the value which already taken with javascript variable, it stores on cache also.
The only one solution is if we can check the server session value from client side on loading moment, then we can overcome this issue.

Analysis of Code:

Login Page: Login process is very common like I store a session value while login successful.
protected void btnSave_Click(object sender, EventArgs e)
{
   // User Name and Password Check here
   //Afer sucessfull login store a session value 
   Session["user"] = "user:Desme-BD";
   Response.Redirect("/frmContentHome.aspx", true);
} 
I have stored "user:Desme-BD" in session "user"
Master Page(Server Side): In content page I have checked the session value or Redirect the page to Login page.
// this is simple method only checking the session value while user login
private void CheckLogin()
{
            string domain = Request.Url.Authority.ToString();
            BaseURL = "http://" + domain + "/";
            //Load menu or Do Any database related work
            if (Session["user"] != null)
            {
                lnkLogin.Text = "Logout";
                lnkLogin.PostBackUrl = BaseURL + "frmLogout.aspx";
            }
            else
            {
                Response.Redirect(BaseURL + "frmLogin.aspx", false);
            }
} 
Logout Page: I also clean the session value while logout with those common methods.
Session.Abandon();
Session.Clear();
Session.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("frmLogin.aspx", false);<span style="font-size: 9pt;"> </span>
The Method which checking Server's Session with Client Side:

Master Page(Client Side):

On ASPX page I use the Jquery with JSON and checking the Session value with LogoutCheck() WebMethod.
<script type="text/javascript">
        $(document).ready(function () {
            CheckingSeassion();
        });
        function CheckingSeassion() {
            $.ajax({
                type: "POST",
                url: "frmLogout.aspx/LogoutCheck",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    if (response.d == 0) {
                        window.location = '<%= BaseURL %>' + "frmLogin.aspx";
                    }
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
</script> 
The LogoutCheck() WebMethod is checking the session value from application server on client side loading moment.
I created this method on frmLogout.aspx page like this:
[WebMethod]
public static int LogoutCheck()
{
   if (HttpContext.Current.Session["user"] == null)
   {
       return 0;
   }
   return 1;
}
Now, when user logout the page it redirect to logout page and clears and abandon the session values. Now when user click back button of browser, the client side only loads and in that period the CheckingSeassion()WebMethod fires in JQuery and it checks the session value LogoutCheck() WebMethod. As the session is null the method returns zero and the page redirect again in login page. So, I don't have to clear the cache or clear any history of user's browser.
Download the solution-> browse frmLogin.aspx -> give any password and Login-> now Logout-> click back button on your browser and notice.

Advantage:

  • Works on client side page load. No need to postback because its calling with ajax.
  • No need to remove cache/history
  • No need to disable back button of web browser

Limitations:

This tips has also a limitation that when user click the back button of browser, the back page show for 1 or half second because of execute the WebMethod.

..................
[Reference from codeproject Articles...]

Tuesday, February 12, 2013

Three Layer Architecture in C# .NET

Introduction
Three layer architecture in C# .NET, is a very useful approach for coding due to easy code maintenance.

Overview

First let me give you a small overview about the topic I would like to cover in this article.
  1. Tier vs. Layer
  2. Three Tier/Layer Architecture Design Components
  3. Demo: Three Layer Windows Application in C#.NET

1. Tier vs. Layer

1.1 Tier: Tier indicates a physical separation of components, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers.
As you can see in the above figure, Data Tier have no direction with Presentation Tier, but there is an intermediate Tier called Business Tier which is mainly responsible to pass the data from Data Tier to Presentation Tier and to add defined business logic to Data.
So, if we separate each Tier by its functionality, then we come to know the below conclusion:
1.2 Layer: Layer indicates logical separation of components, such as having distinct namespaces and classes for the Database Access Layer, Business Logic Layer and User Interface Layer.

2. Three Tier/Layer Architecture Design Components

As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier.

  • Data Tier is basically the server which stores all the application’s data. Data tier contents Database Tables, XML Files and other means of storing Application Data.
  • Business Tier is mainly working as the bridge between Data Tier and Presentation Tier. All the Data passes through the Business Tier before passing to the presentation Tier. Business Tier is the sum of Business Logic Layer, Data Access Layer and Value Object and other components used to add business logic.
  • Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.

The above figure is a mixture of Three Tier and Three Layer Architecture. Here, we can clearly see a different between Tier and Layer. Since each component is independent of each other, they are easily maintainable without changing the whole code.
This approach is really very important when several developers are working on the same project and some module needs to be re-used in another project. In a way, we can distribute work among developers and also maintain it in the future without much problems.
Testing is also a very important issue for Architecture when we are considering writing a test case for the project. Since it’s like a modular architecture, it’s very handy testing each module and to trace out bugs without going through the entire code.

3. Demo: 3 Layer Windows Application in C#.NET

Let’s go though from one module to other to have a better understanding of it.

dbConnection

This class is mainly used to do the database activity like Select, Update and Delete query to database. It also checks if the database connection is open or not. If database connection is not open, then it opens the connection and performs the database query. The database results are to be received and being passing in Data Table in this class.
This class takes the database setting from the app.config file so it’s really flexible to manage the database settings.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ThreeLayerDemo.Core
{
    public class dbConnection
    {
        private SqlDataAdapter myAdapter;
        private SqlConnection conn;

        /// <constructor>
        /// Initialise Connection
        /// </constructor>
        public dbConnection()
        {
            myAdapter = new SqlDataAdapter();
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings
     ["dbConnectionString"].ConnectionString);
        }

        /// <method>
        /// Open Database Connection if Closed or Broken
        /// </method>
        private SqlConnection openConnection()
        {
            if (conn.State == ConnectionState.Closed || conn.State == 
      ConnectionState.Broken)
            {
                conn.Open();
            }
            return conn;
        }

        /// <method>
        /// Select Query
        /// </method>
        public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
        {
            SqlCommand myCommand = new SqlCommand();
            DataTable dataTable = new DataTable();
            dataTable = null;
            DataSet ds = new DataSet();
            try
            {
                myCommand.Connection = openConnection();
                myCommand.CommandText = _query;
                myCommand.Parameters.AddRange(sqlParameter);
                myCommand.ExecuteNonQuery();                
                myAdapter.SelectCommand = myCommand;
                myAdapter.Fill(ds);
                dataTable = ds.Tables[0];
            }
            catch (SqlException e)
            {
                Console.Write("Error - Connection.executeSelectQuery - Query: 
   " + _query + " \nException: " + e.StackTrace.ToString());
                return null;
            }
            finally
            {

            }
            return dataTable;
        }

        /// <method>
        /// Insert Query
        /// </method>
        public bool executeInsertQuery(String _query, SqlParameter[] sqlParameter)
        {
            SqlCommand myCommand = new SqlCommand();
            try
            {
                myCommand.Connection = openConnection();
                myCommand.CommandText = _query;
                myCommand.Parameters.AddRange(sqlParameter);
                myAdapter.InsertCommand = myCommand;
                myCommand.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                Console.Write("Error - Connection.executeInsertQuery - Query: 
   " + _query + " \nException: \n" + e.StackTrace.ToString());
                return false;
            }
            finally
            {
            }
            return true;
        }

        /// <method>
        /// Update Query
        /// </method>
        public bool executeUpdateQuery(String _query, SqlParameter[] sqlParameter)
        {
            SqlCommand myCommand = new SqlCommand();
            try
            {
                myCommand.Connection = openConnection();
                myCommand.CommandText = _query;
                myCommand.Parameters.AddRange(sqlParameter);
                myAdapter.UpdateCommand = myCommand;
                myCommand.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                Console.Write("Error - Connection.executeUpdateQuery - Query: 
   " + _query + " \nException: " + e.StackTrace.ToString());
                return false;
            }
            finally
            {
            }
            return true;
        }
    }
}

Database Access Layer

Database Access Layer (DAO) builds the query based on received parameters from the Business Logic Layer and passes it the dbConnection class for execution. And simple return results from the dbConnection class to Business Logic Layer.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ThreeLayerDemo.Core
{
    public class UserDAO
    {
        private dbConnection conn;

        /// <constructor>
        /// Constructor UserDAO
        /// </constructor>
        public UserDAO()
        {
            conn = new dbConnection();
        }

        /// <method>
        /// Get User Email By Firstname or Lastname and return DataTable
        /// </method>
        public DataTable searchByName(string _username)
        {
            string query = string.Format("select * from [t01_user] 
  where t01_firstname like @t01_firstname or t01_lastname 
  like @t01_lastname ");
            SqlParameter[] sqlParameters = new SqlParameter[2];
            sqlParameters[0] = new SqlParameter("@t01_firstname", SqlDbType.VarChar);
            sqlParameters[0].Value = Convert.ToString(_username);
            sqlParameters[1] = new SqlParameter("@t01_lastname", SqlDbType.VarChar);
            sqlParameters[1].Value = Convert.ToString(_username);
            return conn.executeSelectQuery(query, sqlParameters);
        }

        /// <method>
        /// Get User Email By Id and return DataTable
        /// </method>
        public DataTable searchById(string _id)
        {
            string query = "select * from [t01_id] where t01_id = @t01_id";
            SqlParameter[] sqlParameters = new SqlParameter[1];
            sqlParameters[0] = new SqlParameter("@t01_id", SqlDbType.VarChar);
            sqlParameters[0].Value = Convert.ToString(_id);
            return conn.executeSelectQuery(query, sqlParameters);
        }
    }
}

Value Object

Value Object is nothing more but a class with the contents GET and SET methods. It’s mainly used to pass Data from one class to another. It’s directly connected with Business Logic Layer and Presentation Layer. As you can see in the diagram object values are being SET in Business Logic Layer and GET from Presentation Layer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreeLayerDemo.Core
{
    public class UserVO
    {
        private int _idUser;
        private string _firstname;
        private string _lastname;
        private string _email;

        /// <constructor>
        /// Constructor UserVO
        /// </constructor>
        public UserVO()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public int idUser
        {
            get
            { 
                return _idUser;
            }

            set
            {
                _idUser = value;
            }
        }

        public string firstname
        {
            get
            {
                return _firstname;
            }

            set
            {
                _firstname = value;
            }
        }

        public string lastname
        {
            get
            {
                return _lastname;
            }
            set
            {
                _lastname = value;
            }
        }

        public string email
        {
            get
            {
                return _email;
            }

            set
            {
                _email = value;
            }
        }
    }
}

Business Logic Layer

Business Logic Layer (BUS) works as a bridge between Presentation Layer and DAO. All the user values received from the presentation layer are being passed to BUS. The results received from the DAO are in row data in Data Table format but in BUS it’s converting into Value Objects (VO). Business Logic Layer (BUS) is the most important class in the whole architecture because it mainly contains all the business logic of the program. Whenever a user wants to update the business logic of the program only need to update this class.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ThreeLayerDemo.Core
{
    /// <summary>
    /// Summary description for UserBUS
    /// </summary>
    public class UserBUS
    {
        private UserDAO _userDAO;

        /// <constructor>
        /// Constructor UserBUS
        /// </constructor>
        public UserBUS()
        {
            _userDAO  = new UserDAO();
        }

        /// <method>
        /// Get User Email By Firstname or Lastname and return VO
        /// </method>
        public UserVO getUserEmailByName(string name)
        {
            UserVO userVO = new UserVO();
            DataTable dataTable = new DataTable();

            dataTable = _userDAO.searchByName(name);

            foreach (DataRow dr in dataTable.Rows)
            {
                userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
                userVO.firstname = dr["t01_firstname"].ToString();
                userVO.lastname = dr["t01_lastname"].ToString();
                userVO.email = dr["t01_email"].ToString();
            }
            return userVO;
        }

        /// <method>
        /// Get User Email By Id and return DataTable
        /// </method>
        public UserVO getUserById(string _id)
        {
            UserVO userVO = new UserVO();
            DataTable dataTable = new DataTable();
            dataTable = _userDAO.searchById(_id);

            foreach (DataRow dr in dataTable.Rows)
            {
                userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
                userVO.firstname = dr["t01_firstname"].ToString();
                userVO.lastname = dr["t01_lastname"].ToString();
                userVO.email = dr["t01_email"].ToString();
            }
            return userVO;
        }
    }
}

Presentation Layer

Presentation Layer is the only layer which is directly connected with the user. So in this matter, it’s also a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThreeLayerDemo.Core;

namespace ThreeLayerDemo
{
    public partial class frmLogin : Form
    {
        private UserBUS _userBUS;

        public frmLogin()
        {
            InitializeComponent();
             _userBUS = new UserBUS();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            UserVO _userVO = new UserVO();
            _userVO = _userBUS.getUserEmailByName(txtUsername.Text);
            if (_userVO.email == null)
                MessageBox.Show("No Match Found!", "Not Found", 
   MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else
                MessageBox.Show(_userVO.email ,"Result",
   MessageBoxButtons.OK,MessageBoxIcon.Information);       
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}



[Reference : Article from CodeProject]

Monday, December 3, 2012

Differences of Desktop Applications and Metro Applications in Windows 8


Modern UI was introduced tend to Tablet users, but this assumption is only from SOT. That’s why Windows 8 is provided in two versions, which are Pro and also RT. Its application is also available in two versions, desktop and also Metro. Do you know the difference between both? If you haven’t found out, SOT now will discuss about the difference between desktop and metro applications in Windows 8.

#1 Metro UI Application Design Display

In the beginning, we have discussed about Windows 8 display renewal with its Modern UI. What do you think about this Modern UI from Windows 8, do you like or hate it? In the first time Windows 8 appeared, actually this Modern UI design named Metro UI, since it is focused on image typography which appeared in Traffic sign. The average of Metro UI applications run in full screen display and hide Option display which made us focused on the application.

#2 Application is always in Windows Store

If you want Windows 8 with Metro UI or Modern UI applications, you can get it in Windows Store. By visiting Windows Store, then searching for applications you wanted and install it, then you have already enjoy this Metro UI design application. It surely different with desktop application you commonly download and install easily. But it is more profitable for user, since by this way, malware and viruses would be filtered first by Microsoft.

#3 Sandboxed

In Windows with desktop application, we know what we called as User Account Control, it means that application can be run as Administrator. So, this application would be able to access files or system they needed. Does it endanger your privacy? But it is different with Metro UI application. This Metro UI application is similar like Android, you can read what the application needed to be installed. So, if you feel disturbed because this application accessing your privacy too much, you don’t need to install it. This feature is called as Sandboxed.

#4 Always active and cannot be terminated

This metro application is similar like mobile application, so you cannot close the application when you come out from the application. The application will be run in background and doesn’t consume too much memory. If you think you can use Task Manager to close the Metro application, that’s definitely wrong. Microsoft makes an unclear reason so that user wouldn’t be able to close Metro application. That’s why you wouldn’t be able to see close button on upper right of Metro application exists.

#5 Applications cannot run at the same time

Not similar as desktop application which is able to run many application at once, whether application which seemed with various window or run in background, Metro UI application is only able to run by using two applications, the first application run on ¾ of screen, while the second apps run on ¼ screen. This feature is called as Snap. It surely different with Windows 7 which has Aero display with 50/50 snap when we do apps multitasking from the screen.

#6 Metro UI Application programming

In Metro application, developers are able to create it using C/C++ or .NET, JavaScript and HTML5 language programming. Here, Microsoft expects that there would be so many developers would be interested in creating Windows 8 apps according to language programming they understood. Metro UI application also support x86 and ARM devices, makes it possible to run in Windows 8 Pro and Windows 8 RT.


Reference from spyontech

Friday, November 30, 2012

Delegates in C#.Net


Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration:

public delegate type_of_delegate delegate_name()

Example:
public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.
The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.
Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)
Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:
delObj(v1,v2);
Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.


Example 2:


1. Defining the delegate
  public delegate int Calculate (int value1, int value2);

 2. Creating methods which will be assigned to delegate object
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegatepublic int add(int value1, int value2)
{
    return value1 + value2;            
}
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegatepublic int sub( int value1, int value2)
{
    return value1 - value2;            
}
 3. Creating the delegate object and assigning methods to those delegate objects
 
//creating the class which contains the methods 
//that will be assigned to delegate objectsMyClass mc = new MyClass();

//creating delegate objects and assigning appropriate methods
//having the EXACT signature of the delegateCalculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);
 4. Calling the methods via delegate objects
 
//using the delegate objects to call the assigned methods Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));



Thanks...

--Reference from codeproject,...

Saturday, September 8, 2012

Defining Ping Response


"ping XXX.XXX.XXX.XXX"  in run command

Pinging www.some-domain.com [XXX.XXX.XXX.XXX] with 32 bytes of


Reply from XXX.XXX.XXX.XXX: bytes=32 time=564ms TTL=237
Reply from XXX.XXX.XXX.XXX: bytes=32 time=555ms TTL=237
Reply from XXX.XXX.XXX.XXX: bytes=32 time=554ms TTL=237
Reply from XXX.XXX.XXX.XXX: bytes=32 time=548ms TTL=237


Ping statistics for XXX.XXX.XXX.XXX:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)
Approximate round trip times in milli-seconds:
Minimum = 548ms, Maximum = 564ms, Average = 555ms

TTL?

Every IP packet that gets sent out has a TTL field which is set to a relatively high number (in the case of ping a TTL of 255). As the packet traverses the network, the TTL field gets decreased by one by each router it goes through; when the TTL drops to 0, the packet is discarded by the router. The IP spec says that the TTL should be set to 60 (though it's 255 for ping packets). The main purpose of this is so that a packet doesn't live forever on the network and will eventually die when it is deemed "lost." But for ping purposes, it provides additional information. The TTL can be used to determine approximately how many router hops the packet has gone through. If the TTL field varies in successive pings, it could indicate that the successive reply packets are going via different routes, which isn't a great thing.




'ping time'?
"Ping time" refers to the amount of time it takes for a small "packet" of data to travel over the internet from one computer to another computer and back to the first computer. It is usually reported in milliseconds (ms).


(Referred in blogs)