It's a project parted from the Web Application itself and an asmx WebService
Download the whole project along with its Database and its log file in .mdf format here
The MasterPage
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
namespace NewCertification
{
public partial class pageBase1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
//If user's session have expired or a user tries to bypass the login page, redirect to loginAgain.aspx
if (Session["userPk"] == null || Session["name"] == null || Session["surname"] == null || Session["rolePks"] == null || Session["roleDescrs"] == null)
{
Response.Redirect("loginAgain.aspx",false);
}
else
{
lblUsernameSurname.Text = Session["surname"].ToString() + " " + Session["name"].ToString();
//By dynamically creating the menu and storing the menu items, submenu items in the database
//when I want to add a WebForm to my project, I only have to implement it an proceed to database implementation
//to bind the new WebForm to a role. Thus, I dont have to change the master page, as I would if I have an HTML menu, plus
//due to the pivot table between the roles and the menu items, a menu item may be visible to more than one role
NewCertification.ServiceReference1.Service1SoapClient srv = new NewCertification.ServiceReference1.Service1SoapClient();
DataSet menuItems = new DataSet();
//Fetch master menu items from the database
if (Session["roleDescrs"] != null)
{
menuItems = srv.getVisibleMenuItems(Session["roleDescrs"].ToString());
}
//Initialize the menu control
Menu m = new Menu();
m.Orientation = Orientation.Horizontal;
//For every master menu item and if the specific menu item corresponds to the role of the user
//initialize a menu item and add it to the menu control.
foreach (DataRow dr in menuItems.Tables[0].Rows)
{
MenuItem mi = new MenuItem(dr["menuItemDescr"].ToString());
DataSet subMenuItems = srv.getSubMenuItems(Convert.ToInt32(dr["menuItemPk"].ToString()));
//For every master menu item, fetch the corresponing submenu items and add the to the menu item
foreach (DataRow dr1 in subMenuItems.Tables[0].Rows)
{
MenuItem mi1 = new MenuItem(dr1["subMenuItemDescr"].ToString(), "", "", dr1["subMenuItemDescr"].ToString().Replace(" ", "") + ".aspx");
mi.ChildItems.Add(mi1);
}
m.Items.Add(mi);
}
//add the menu to the <td> element
container.Controls.Add(m);
}
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
try
{
if (Session["userPk"] != null && Session["name"] != null && Session["surname"] != null && Session["rolePks"] != null && Session["roleDescrs"] != null)
{
//When logging out it is essential to set all the Sessions to null
Session["userPk"] = null;
Session["name"] = null;
Session["surname"] = null;
Session["rolePks"] = null;
Session["roleDescrs"] = null;
}
Response.Redirect("loginUser.aspx", false);
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
}
}
newUser.aspx
using System;
using System.Data;
namespace NewCertification
{
public partial class newUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadRolesList(true);
return;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
NewCertification.ServiceReference1.Service1SoapClient srv = new NewCertification.ServiceReference1.Service1SoapClient();
//If there already is a user with that username alert...
if (srv.checkUsername(txtUsername.Text) != 0)
{
lblUserCreated.Visible = false;
lblUsernameAlreadyExists.Visible = true;
lblFillAllFields.Visible = false;
return;
}
if (txtName.Text != string.Empty && txtSurname.Text != string.Empty && txtEmail.Text != string.Empty && txtPassword.Text != string.Empty && txtUsername.Text != string.Empty)
{
srv.newUser(txtName.Text, txtSurname.Text, txtEmail.Text, txtPassword.Text, txtUsername.Text, chkIsActive.Checked, Convert.ToInt32(ddlRoles.SelectedValue.ToString()));
lblUsernameAlreadyExists.Visible = false;
lblUserCreated.Visible = true;
lblFillAllFields.Visible = false;
txtEmail.Text = string.Empty;
txtName.Text = string.Empty;
txtPassword.Text = string.Empty;
txtSurname.Text = string.Empty;
txtUsername.Text = string.Empty;
}
else
{
lblFillAllFields.Visible = true;
}
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
private void loadRolesList(bool status)
{
try
{
//Load the DropDownList roles with all the available roles whose status is true
NewCertification.ServiceReference1.Service1SoapClient srv = new NewCertification.ServiceReference1.Service1SoapClient();
DataSet ds = srv.getRoles(status);
if (ds.Tables.Count != 0)
{
ddlRoles.DataSource = ds.Tables[0];
ddlRoles.DataTextField = "roleDescr";
ddlRoles.DataValueField = "rolePk";
ddlRoles.DataBind();
}
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
}
}
searchEditUser.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace NewCertification
{
public partial class searchEditUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
//Set the GridView data source
NewCertification.ServiceReference1.Service1SoapClient srv = new NewCertification.ServiceReference1.Service1SoapClient();
DataSet ds = srv.getUsers(txtSurname.Text, txtUsername.Text, chkActive.Checked);
if (ds.Tables.Count != 0)
{
grdUsers.DataSource = ds.Tables[0];
grdUsers.DataBind();
}
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
HyperLink edit = new HyperLink();
edit.Text = "Edit User";
edit.NavigateUrl = "editUser1.aspx?userPk=" + e.Row.Cells[1].Text;
e.Row.Cells[0].Controls.Add(edit);
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
}
}
editUser1.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace NewCertification
{
public partial class editUser1 : System.Web.UI.Page
{
NewCertification.ServiceReference1.Service1SoapClient srv = new NewCertification.ServiceReference1.Service1SoapClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
}
protected void grdRoles_RowEditing(object sender, GridViewEditEventArgs e)
{
grdRoles.EditIndex = e.NewEditIndex;
bindGridView();
}
protected void grdRoles_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdRoles.EditIndex = -1;
bindGridView();
}
private void bindGridView()
{
try
{
DataSet ds = srv.getUserByPk(Convert.ToInt32(Request.QueryString.Get("userPk").ToString()));
if (ds.Tables.Count != 0)
{
txtName.Text = ds.Tables[0].Rows[0]["name"].ToString();
txtSurname.Text = ds.Tables[0].Rows[0]["surname"].ToString();
txtEmail.Text = ds.Tables[0].Rows[0]["email"].ToString();
txtUsername.Text = ds.Tables[0].Rows[0]["username"].ToString();
chkActive.Checked = Convert.ToBoolean(ds.Tables[0].Rows[0]["active"].ToString());
if (ds.Tables.Count == 2)
{
grdRoles.DataSource = ds.Tables[1];
grdRoles.DataBind();
}
}
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
protected void grdRoles_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
srv.updateUserRole(Convert.ToInt32(grdRoles.Rows[e.RowIndex].Cells[1].Text),
((CheckBox)grdRoles.Rows[e.RowIndex].Cells[3].Controls[0]).Checked);
}
catch (Exception ex)
{
string exceptionPk = ExceptionHandler.logException(ex.StackTrace, ex.Message);
Response.Redirect("ExceptionPage.aspx?exPk=" + exceptionPk);
}
}
}
}
The WebService
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
namespace Service
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public DataSet loginUser(string username, string password)
{
DataSet ds = SqlDatabase.getDataSet("loginUser",
SqlDatabase.getSqlParameter("@username", username.ToLower(), SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@password", EncryptionManager.Encrypt(password,
ConfigurationManager.AppSettings.Get("passPhrase"),
ConfigurationManager.AppSettings.Get("saltValue"),
ConfigurationManager.AppSettings.Get("hashAlgorithm"),
Convert.ToInt32(ConfigurationManager.AppSettings.Get("passwordIterations")),
ConfigurationManager.AppSettings.Get("initVector"),
Convert.ToInt32(ConfigurationManager.AppSettings.Get("keySize"))),
SqlDbType.NVarChar));
return ds;
}
[WebMethod]
public DataSet logException(string stackTrace, string message)
{
DataSet ds = SqlDatabase.getDataSet("logException",
SqlDatabase.getSqlParameter("@stackTrace", stackTrace, SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@message", message, SqlDbType.NVarChar));
return ds;
}
[WebMethod]
public string determineRolePk(string roleDescr)
{
DataSet ds = SqlDatabase.getDataSet("determineRolePk",
SqlDatabase.getSqlParameter("@roleDescr", roleDescr, SqlDbType.NVarChar));
return ds.Tables[0].Rows[0]["pk"].ToString();
}
[WebMethod]
public DataSet getVisibleMenuItems(string roleDescr)
{
DataSet ds = SqlDatabase.getDataSet("getVisibleMenuItems",
SqlDatabase.getSqlParameter("@roleDescr", roleDescr, SqlDbType.NVarChar));
return ds;
}
[WebMethod]
public DataSet getSubMenuItems(int masterMenuItemPk)
{
DataSet ds = SqlDatabase.getDataSet("getSubMenuItems",
SqlDatabase.getSqlParameter("@menuItemPk", masterMenuItemPk, SqlDbType.Int));
return ds;
}
[WebMethod]
public int newUser(string name, string surname, string email, string password, string username, bool active, int roleFk)
{
int rowsAffectedInDB = SqlDatabase.execNonQuery("newUser",
SqlDatabase.getSqlParameter("@name", name, SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@surname", surname, SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@email", email, SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@password", EncryptionManager.Encrypt(password,
ConfigurationManager.AppSettings.Get("passPhrase"),
ConfigurationManager.AppSettings.Get("saltValue"),
ConfigurationManager.AppSettings.Get("hashAlgorithm"),
Convert.ToInt32(ConfigurationManager.AppSettings.Get("passwordIterations")),
ConfigurationManager.AppSettings.Get("initVector"),
Convert.ToInt32(ConfigurationManager.AppSettings.Get("keySize"))),
SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@username", username.ToLower(), SqlDbType.NVarChar),
SqlDatabase.getSqlParameter("@active", active, SqlDbType.Bit),
SqlDatabase.getSqlParameter("@roleFk",roleFk,SqlDbType.Int));
return rowsAffectedInDB;
}
[WebMethod]
public int checkUsername(string username)
{
DataSet ds = SqlDatabase.getDataSet("checkUsername",
SqlDatabase.getSqlParameter("@username", username.ToLower(), SqlDbType.NVarChar));
return ds.Tables[0].Rows.Count;
}
[WebMethod]
public DataSet getRoles(bool status)
{
DataSet ds = SqlDatabase.getDataSet("getRoles",
SqlDatabase.getSqlParameter("@status", status, SqlDbType.Bit));
return ds;
}
[WebMethod]
public DataSet getUsers(string surname, string username, bool active)
{
SqlParameter _surname = new SqlParameter();
SqlParameter _username = new SqlParameter();
if (surname == string.Empty)
{
_surname = SqlDatabase.getSqlParameter("@surname", System.DBNull.Value, SqlDbType.NVarChar);
}
else
{
_surname = SqlDatabase.getSqlParameter("@surname", surname, SqlDbType.NVarChar);
}
if (username == string.Empty)
{
_username = SqlDatabase.getSqlParameter("@username", System.DBNull.Value, SqlDbType.NVarChar);
}
else
{
_username = SqlDatabase.getSqlParameter("@username", username, SqlDbType.NVarChar);
}
DataSet ds = SqlDatabase.getDataSet("getUsers",
_surname,
_username,
SqlDatabase.getSqlParameter("@active", active, SqlDbType.Bit));
return ds;
}
[WebMethod]
public DataSet getUserByPk(int pk)
{
DataSet ds = SqlDatabase.getDataSet("getUserByPk",
SqlDatabase.getSqlParameter("@userPk",pk,SqlDbType.Int));
return ds;
}
[WebMethod]
public int updateUserRole(int userRolePk, bool active)
{
int rowsAffected = SqlDatabase.execNonQuery("updateUserRole",
SqlDatabase.getSqlParameter("@userRolePk", userRolePk, SqlDbType.Int),
SqlDatabase.getSqlParameter("@active", active, SqlDbType.Bit));
return rowsAffected;
}
}
}
The SqlDatabase wrapper class
using System;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace Service
{
public class SqlDatabase
{
/// <summary>
/// Default constractor
/// </summary>
public SqlDatabase()
{
}
#region Connection handle
/// <summary>
/// Connect to a Database by providing the connection string
/// </summary>
/// <param name="cnString"></param>
/// <returns></returns>
public static SqlConnection getConnection(string cnString)
{
SqlConnection conne = null;
try
{
if (cnString.Equals(string.Empty))
{
conne = new SqlConnection(ConfigurationManager.ConnectionStrings["cnString"].ToString());
}
else
{
conne = new SqlConnection(ConfigurationManager.ConnectionStrings[cnString].ToString());
}
conne.Open();
}
catch (InvalidOperationException ex)
{
throw ex;
}
catch (SqlException ex)
{
throw ex;
}
catch (NullReferenceException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
return conne;
}
/// <summary>
/// Overload method. Connect to the default Database whose connection string is stored in the Web.Config file
/// </summary>
/// <returns></returns>
public static SqlConnection getConnection()
{
return getConnection("");
}
public static void closeConnection(SqlConnection connection)
{
try
{
if (connection != null && connection.State != ConnectionState.Closed)
{
connection.Close();
connection.Dispose();
}
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region DataSet handle
/// <summary>
/// Get a data set by providing the stored procedure's name and its parameters
/// </summary>
/// <param name="storedProcName"></param>
/// <param name="sqlParameters"></param>
/// <returns></returns>
public static DataSet getDataSet(string storedProcName, params SqlParameter[] sqlParameters)
{
SqlDataAdapter ad = new SqlDataAdapter();
try
{
ad.SelectCommand = new SqlCommand(storedProcName);
ad.SelectCommand.Connection = getConnection();
ad.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
foreach (SqlParameter _param in sqlParameters)
{
ad.SelectCommand.Parameters.Add(_param);
}
ad.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
ad.Dispose();
}
}
#endregion
#region Parameter handle
/// <summary>
/// Get a Sql parameter
/// </summary>
/// <param name="paramName"></param>
/// <param name="sqlDbValue"></param>
/// <param name="sqlDbType"></param>
/// <returns></returns>
public static SqlParameter getSqlParameter(string paramName, object sqlDbValue, SqlDbType sqlDbType)
{
SqlParameter param = new SqlParameter();
try
{
if (paramName.Trim() != string.Empty)
{
param.ParameterName = paramName;
}
else
{
throw new Exception("ParamName cannot be an empty string");
}
if (sqlDbValue != null)
{
param.Value = sqlDbValue;
}
else
{
param.Value = DBNull.Value;
}
param.SqlDbType = sqlDbType;
}
catch (ArgumentException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
return param;
}
#endregion
#region ExecNonQuery handle
/// <summary>
/// Execute insert, update SQL statements
/// </summary>
/// <param name="storedProcName"></param>
/// <param name="sqlParameters"></param>
/// <returns></returns>
public static int execNonQuery(string storedProcName, params SqlParameter[] sqlParameters)
{
SqlConnection cn = getConnection();
SqlTransaction trans = cn.BeginTransaction();
try
{
SqlCommand cmd = new SqlCommand(storedProcName, cn, trans);
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter _param in sqlParameters)
{
cmd.Parameters.Add(_param);
}
int rowsAffected = cmd.ExecuteNonQuery();
trans.Commit();
return rowsAffected;
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
finally
{
if (cn != null)
{
cn.Dispose();
}
if (trans != null)
{
trans.Dispose();
}
}
}
#endregion
}
}