Web Application Projects
Simple Discussion Forum
Class Creation:
1.User.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///
Summary description for User
/// </summary>
public class User
{
private string id,name,address,contact,
email,username,password,occupation;
public User()
{
//
// TODO: Add constructor
logic here
//
}
public
User(string id,string
name,string address,string
contact, string email, string
username, string password, string occupation)
{
this.id
= id;
this.name
= name;
this.address
= address;
this.contact
= contact;
this.email
= email;
this.username
= username;
this.password
= password;
this.occupation=occupation;
}
public string Id
{
get
{
return
id;
}
set
{
id = value;
}
}
public string Name
{
get
{
return
name;
}
set
{
name = value;
}
}
public string Address
{
get
{
return
address;
}
set
{
address = value;
}
}
public string Contact
{
get
{
return
contact;
}
set
{
contact = value;
}
}
public string Email
{
get
{
return
email;
}
set
{
email = value;
}
}
public string UserName
{
get
{
return
username;
}
set
{
username = value;
}
}
public string Password
{
get
{
return
password;
}
set
{
password = value;
}
}
public string Occupation
{
get
{
return
occupation;
}
set
{
occupation = value;
}
}
}
2.UserDAL.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using
System.Configuration;
using
System.Data.SqlClient;
using System.Data;
/// <summary>
///
Summary description for UserDAL
/// </summary>
public class UserDAL
{
public static string s = ConfigurationManager.ConnectionStrings["myconstr"].ToString();
public UserDAL()
{
//
// TODO: Add constructor
logic here
//
}
public static bool Register(string name, string
address, string contact, string email, string
username, string password, string occupation)
{
SqlConnection
con = new SqlConnection(s);
try
{
con.Open();
//Checking
UserName
string
st = "select * from Users where
UserName=@username";
SqlCommand
cmd = new SqlCommand(st,
con);
cmd.Parameters.Add("@username", SqlDbType.VarChar,
50).Value = username;
SqlDataReader
dr = cmd.ExecuteReader();
if
(dr.Read())
{
return
false;
}
dr.Close();
cmd = new
SqlCommand("Register",
con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@name", SqlDbType.VarChar,
50).Value = name;
cmd.Parameters.Add("@address", SqlDbType.VarChar,
50).Value = address;
cmd.Parameters.Add("@contact", SqlDbType.VarChar,
50).Value = contact;
cmd.Parameters.Add("@email", SqlDbType.VarChar,
50).Value = email;
cmd.Parameters.Add("@username", SqlDbType.VarChar,
50).Value = username;
cmd.Parameters.Add("@password", SqlDbType.VarChar,
50).Value = password;
cmd.Parameters.Add("@occupation", SqlDbType.VarChar,
50).Value = occupation;
cmd.ExecuteNonQuery();
return
true;
}
catch (Exception ex)
{
return
false;
}
finally
{
if
(con.State == ConnectionState.Open)
con.Close();
}
}
}
Design Mode:
1.Registration.aspx
<table class="style1">
<tr>
<td class="style2" colspan="3">
<asp:Label ID="lblmessage" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
<tr>
<td class="style4">
Name:</td>
<td class="style3">
<asp:TextBox ID="txtname" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtname"
ErrorMessage="Enter
Your Name" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style4">
Address:</td>
<td class="style3">
<asp:TextBox ID="txtaddress" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtaddress"
ErrorMessage="Enter
Your Address"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style4">
Contact:</td>
<td class="style3">
<asp:TextBox ID="txtcontact" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="txtcontact"
ErrorMessage="Enter
Your Contact"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style4">
Email:</td>
<td class="style3">
<asp:TextBox ID="txtemail" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtemail"
ErrorMessage="Enter
Email Address" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtemail"
ErrorMessage="Enter
Valid Email Address"
ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style4">
UserName:</td>
<td class="style3">
<asp:TextBox ID="txtusername" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ControlToValidate="txtusername"
ErrorMessage="Username
Required"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style4">
Password:</td>
<td class="style3">
<asp:TextBox ID="txtpassword" runat="server" TextMode="Password" Width="212px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ControlToValidate="txtpassword"
ErrorMessage="Password
Required"
ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style4">
Occupation:</td>
<td class="style3">
<asp:TextBox ID="txtoccupation" runat="server" Width="212px"></asp:TextBox>
</td>
<td>
</td>
</tr>
<tr>
<td class="style4">
<asp:Button ID="btnregister" runat="server" Height="26px" Text="Register"
Width="89px" onclick="btnregister_Click"
/>
</td>
<td class="style3">
</td>
<td>
</td>
</tr>
</table>
Registration.aspx.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void btnregister_Click(object
sender, EventArgs e)
{
bool
done;
done = UserDAL.Register(txtname.Text,
txtaddress.Text, txtcontact.Text, txtemail.Text, txtusername.Text,
txtpassword.Text, txtoccupation.Text);
if
(done)
lblmessage.Text = "Registration Successfull. Please Login by clicking
<a href=Login.aspx>here</a>";
else
lblmessage.Text = "Sorrry!Registration
Failed. UserName Already Exists";
}
}
StoredProcedures
1.Register
create proc
Register
(
@name varchar(50),
@address varchar(50),
@contact varchar(50),
@email varchar(50),
@username varchar(50),
@password varchar(50),
@occupation varchar(50)
)
as
begin
declare @uid int
/* Get Next User Id */
select @uid=isnull(max(uid),0)+1
from users;
/* Insert Into User */
insert into
users values(@uid,@name, @address,@contact,@email,@username,@password,@occupation,getdate());
end
Tables
1.Users
CREATE TABLE
[Users](
[uid] [int] NOT
NULL,
[Name] [varchar](50) NULL,
[Address] [varchar](50) NULL,
[Contact] [varchar](50) NULL,
[Email] [varchar](50) NOT NULL,
[UserName] [varchar](50) NOT NULL,
[Password] [varchar](50) NULL,
[Occupation] [varchar](50) NULL,
[JoinedDate] [datetime] NULL,
Login Control
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="60" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<appSettings>
<add key="UploadPath" value="~/UploadFile/" />
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = this.Login1.UserName.Trim();
string password = this.Login1.Password.Trim();
Customer customer = UserManager.ValidateUser(userName, password);
if (customer != null)
{
Enums.UserRole userRole;
if (customer.UserRole.RoleName.Equals("Administrator"))
userRole = Enums.UserRole.Administrator;
else
userRole = Enums.UserRole.Customer;
SessionManager.__doInitializeSession(customer.CustomerId, customer.CName, customer.CEmail, userRole);
e.Authenticated = true;
}
else
{
lblMessage.Text = "Invalid Username and Password!!!";
return;
}
}
protected void Login1_LoggedIn(object sender, EventArgs e)
{
switch (SessionManager.UserRole)
{
case Enums.UserRole.Administrator:
HttpContext.Current.Response.Redirect("~/Admin/default.aspx");
break;
case Enums.UserRole.Customer:
//HttpContext.Current.Response.Redirect("~/client/HF/default.aspx");
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
break;
default:
break;
}
}
public static Customer ValidateUser(string UserName, string Password)
{
dataEntities HFE = new dataEntities ();
Customer user = new Customer();
user = HFE.Customers.Where(x => x.CEmail == UserName && x.CPassword == Password).FirstOrDefault();
return user;
}
public static int CustomerId
{
get
{
if (HttpContext.Current.Session["CustomerId"] == null)
return -1;
return int.Parse(HttpContext.Current.Session["CustomerId"].ToString());
}
set
{
HttpContext.Current.Session["CustomerId"] = value;
}
}
//public static long CompanyId
//{
// get
// {
// if (HttpContext.Current.Session["CompanyId"] == null)
// return -1;
// return long.Parse(HttpContext.Current.Session["CompanyId"].ToString());
// }
// set
// {
// HttpContext.Current.Session["CompanyId"] = value;
// }
//}
public static String CustomerName
{
get
{
return HttpContext.Current.Session["CName"].ToString();
}
set
{
HttpContext.Current.Session["CName"] = value;
}
}
public static String UserName
{
get
{
return HttpContext.Current.Session["CEmail"].ToString();
}
set
{
HttpContext.Current.Session["CEmail"] = value;
}
}
public static Enums.UserRole UserRole
{
get
{
return (Enums.UserRole)HttpContext.Current.Session["UserRole"];
}
set
{
HttpContext.Current.Session["UserRole"] = value;
}
}
public SessionManager(string cName, string userName, Enums.UserRole userRole)
{
//CustomerFirstName = customerFirstName;
//CustomerLastName = customerLastName;
//UserName = userName;
//UserRole = userRole;
}
public static void __doInitializeSession(int pCustomerId, string cName, string userName, Enums.UserRole userRole)
{
CustomerId = pCustomerId;
//CompanyId = companyId;
CustomerName = cName;
//CustomerLastName = customerLastName;
UserName = userName;
UserRole = userRole;
}
public enum UserRole
{
Administrator = 1,
Customer
}
public enum EmailSentStatus
{
Fail,
Success
}
public enum FormMode
{
Save,
Update
}
public enum HostelType
{
Boys = 1,
Girls
}
protected void OnLoggedOut_Click(object sender, EventArgs e)
{
this.Session.Abandon();
HttpContext.Current.Response.Redirect("~/client/HF/home-page.aspx");
}
protected void MainLoginSatatus_LoggedOut(object sender, EventArgs e)
{
this.Session.Abandon();
HttpContext.Current.Response.Redirect("~/client/HF/home-page.aspx");
}
For Image Upload
protected void btnUpload_Click(object sender, EventArgs e)
{
String UploadPath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
String FilePath = string.Empty;
String fileName = string.Empty;
String fileExtension = string.Empty;
int counter = 0;
if (FileUpload1.HasFile)
try
{
Boolean fileExist = true;
FilePath = Server.MapPath(UploadPath) + FileUpload1.FileName;
fileName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf('.'));
fileExtension = FileUpload1.FileName.Substring(FileUpload1.FileName.IndexOf('.'));
//string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileExtension != ".jpg" & fileExtension != ".png" & fileExtension != ".gif" & fileExtension != ".jpeg")
{
//lblMessage.Text = "Please choose only .jpg, .png and .gif image types!";
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Please Choose Only .jpg, .png and .gif Image Types!')", true);
this.imgDispaly.ImageUrl = string.Empty;
return;
}
while (fileExist)
{
if (fileSize < 2100000)
{
if (System.IO.File.Exists(FilePath))
{
fileName += counter.ToString();
FilePath = Server.MapPath(UploadPath) + fileName + fileExtension;
}
else
{
fileExist = false;
}
}
else
{
lblMessageDisplay.Visible = true;
this.imgDispaly.ImageUrl = string.Empty;
//lblMessageDisplay.Text = "Your file was not uploaded because it exceeds the 2 MB size limit.";
return;
}
counter++;
}
FileUpload1.SaveAs(FilePath);
ImageUrl = UploadPath + fileName + fileExtension;
imgDispaly.Visible = true;
imgDispaly.ImageUrl = ImageUrl;
ImageUrl = imgDispaly.ImageUrl;
}
catch (Exception ex)
{
//Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
//Label1.Text = "You have not specified a file.";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.Page.Validate();
if (!Page.IsValid)
return;
string hostelName = txtHName.Text.Trim();
string hDescription = txtDescription.Value;
//string hostelDescription = txtDescription.Text.Trim();
//string Address = txtAddress.Text.Trim();
string Contact = txtContact.Text.Trim();
string Email = txtEmail.Text.Trim();
string HWebAddress = txtHWebAddress.Text.Trim();
decimal price = decimal.Parse(txtHPrice.Text.Trim());
string facilities = txtHFacilities.Value;
//string policies = txtHPolicies.Text.Trim();
decimal lat = decimal.Parse(txtHLat.Text.Trim());
decimal longi = decimal.Parse(txtHLong.Text.Trim());
string room = txtRoom.Value;
string hLocation = txtHLocation.Text.Trim();
string hCity = txtHCity.Text.Trim();
bool IsActive = chkIsActive.Checked;
Hostel hostel = new Hostel();
hostel.HName = hostelName;
//hostel.HDescription = hostelDescription;
//hostel.HAddress = Address;
hostel.HContact = Contact;
hostel.HEmail = Email;
hostel.HWebLink = HWebAddress;
hostel.IsActive = IsActive;
hostel.RatingId = int.Parse(ddlRating.SelectedValue);
hostel.HostelPrice = price;
hostel.HFacilities = facilities;
//hostel.Hostelpolicies = policies;
hostel.HLattitude = lat;
hostel.Hlongitude = longi;
hostel.HosDescription = hDescription;
hostel.HRoom = room;
hostel.HLocation = hLocation;
hostel.HCity = hCity;
if (ImageUrl != null)
{
hostel.HImageUrl = ImageUrl.Replace("~/UploadFile/", "");
}
else
{
ImageUrl = "~/UploadFile/bg_latest.jpg";
hostel.HImageUrl = ImageUrl.Replace("~/UploadFile/", "");
}
switch (CurrentFormMode)
{
case Enums.FormMode.Save:
if (HostelManager.InsetHostel(hostel))
{
lblMessage.Text = "Hostel Added Successfully.";
LoadHostels();
ResetControls();
}
else
{
lblMessage.Text = "Data Saved Failed.";
}
break;
case Enums.FormMode.Update:
hostel.HostelId = HostelId;
if (HostelManager.UpdateHostel(hostel))
{
lblMessage.Text = "Hostel Updated Successfully.";
LoadHostels();
CurrentFormMode = Enums.FormMode.Save;
//ResetControls();
btnSave.Text = "Save";
ResetControls();
}
else
{
lblMessage.Text = "Data Update Failed.";
}
break;
default: break;
}
}
public static bool UpdateHostel(Hostel h)
{
HostelFinderEntities HFE = new HostelFinderEntities();
try
{
Hostel Hos = HFE.Hostels.Where(x => x.HostelId == h.HostelId).FirstOrDefault();
Hos.HName = h.HName;
Hos.HosDescription = h.HosDescription;
Hos.HostelId = h.HostelId;
Hos.HCity = h.HCity;
Hos.HLocation = h.HLocation;
Hos.HContact = h.HContact;
Hos.HWebLink = h.HWebLink;
Hos.HEmail = h.HEmail;
Hos.HostelPrice = h.HostelPrice;
Hos.HLattitude = h.HLattitude;
Hos.Hlongitude = h.Hlongitude;
Hos.RatingId = h.RatingId;
Hos.HRoom = h.HRoom;
Hos.HFacilities = h.HFacilities;
Hos.HImageUrl = h.HImageUrl;
Hos.IsActive = h.IsActive;
HFE.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public static Boolean CheckRatingAlreadyInserted(HostelRating hr)
{
HostelFinderEntities HFE = new HostelFinderEntities();
HostelRating hra= HFE.HostelRatings.Where(x => x.CustomerId == hr.CustomerId && x.HostelId==hr.HostelId).FirstOrDefault();
if(hra==null)
{return false;
}
else
{return true;
}
}
protected void LoadRating()
{
List<Rating> AllEmp = HostelManager.GetAllRating();
ddlRating.DataSource = AllEmp;
ddlRating.DataTextField = "RatingValue";
ddlRating.DataValueField = "RatingId";
ddlRating.DataBind();
ListItem item = new ListItem();
item.Text = "-- Select Rating --";
item.Value = "-1";
ddlRating.Items.Insert(0, item);
ddlRating.SelectedIndex = 0;
}
Login Control
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="60" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<appSettings>
<add key="UploadPath" value="~/UploadFile/" />
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = this.Login1.UserName.Trim();
string password = this.Login1.Password.Trim();
Customer customer = UserManager.ValidateUser(userName, password);
if (customer != null)
{
Enums.UserRole userRole;
if (customer.UserRole.RoleName.Equals("Administrator"))
userRole = Enums.UserRole.Administrator;
else
userRole = Enums.UserRole.Customer;
SessionManager.__doInitializeSession(customer.CustomerId, customer.CName, customer.CEmail, userRole);
e.Authenticated = true;
}
else
{
lblMessage.Text = "Invalid Username and Password!!!";
return;
}
}
protected void Login1_LoggedIn(object sender, EventArgs e)
{
switch (SessionManager.UserRole)
{
case Enums.UserRole.Administrator:
HttpContext.Current.Response.Redirect("~/Admin/default.aspx");
break;
case Enums.UserRole.Customer:
//HttpContext.Current.Response.Redirect("~/client/HF/default.aspx");
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
break;
default:
break;
}
}
public static Customer ValidateUser(string UserName, string Password)
{
dataEntities HFE = new dataEntities ();
Customer user = new Customer();
user = HFE.Customers.Where(x => x.CEmail == UserName && x.CPassword == Password).FirstOrDefault();
return user;
}
public static int CustomerId
{
get
{
if (HttpContext.Current.Session["CustomerId"] == null)
return -1;
return int.Parse(HttpContext.Current.Session["CustomerId"].ToString());
}
set
{
HttpContext.Current.Session["CustomerId"] = value;
}
}
//public static long CompanyId
//{
// get
// {
// if (HttpContext.Current.Session["CompanyId"] == null)
// return -1;
// return long.Parse(HttpContext.Current.Session["CompanyId"].ToString());
// }
// set
// {
// HttpContext.Current.Session["CompanyId"] = value;
// }
//}
public static String CustomerName
{
get
{
return HttpContext.Current.Session["CName"].ToString();
}
set
{
HttpContext.Current.Session["CName"] = value;
}
}
public static String UserName
{
get
{
return HttpContext.Current.Session["CEmail"].ToString();
}
set
{
HttpContext.Current.Session["CEmail"] = value;
}
}
public static Enums.UserRole UserRole
{
get
{
return (Enums.UserRole)HttpContext.Current.Session["UserRole"];
}
set
{
HttpContext.Current.Session["UserRole"] = value;
}
}
public SessionManager(string cName, string userName, Enums.UserRole userRole)
{
//CustomerFirstName = customerFirstName;
//CustomerLastName = customerLastName;
//UserName = userName;
//UserRole = userRole;
}
public static void __doInitializeSession(int pCustomerId, string cName, string userName, Enums.UserRole userRole)
{
CustomerId = pCustomerId;
//CompanyId = companyId;
CustomerName = cName;
//CustomerLastName = customerLastName;
UserName = userName;
UserRole = userRole;
}
public enum UserRole
{
Administrator = 1,
Customer
}
public enum EmailSentStatus
{
Fail,
Success
}
public enum FormMode
{
Save,
Update
}
public enum HostelType
{
Boys = 1,
Girls
}
protected void OnLoggedOut_Click(object sender, EventArgs e)
{
this.Session.Abandon();
HttpContext.Current.Response.Redirect("~/client/HF/home-page.aspx");
}
protected void MainLoginSatatus_LoggedOut(object sender, EventArgs e)
{
this.Session.Abandon();
HttpContext.Current.Response.Redirect("~/client/HF/home-page.aspx");
}
For Image Upload
protected void btnUpload_Click(object sender, EventArgs e)
{
String UploadPath = System.Configuration.ConfigurationManager.AppSettings["UploadPath"];
String FilePath = string.Empty;
String fileName = string.Empty;
String fileExtension = string.Empty;
int counter = 0;
if (FileUpload1.HasFile)
try
{
Boolean fileExist = true;
FilePath = Server.MapPath(UploadPath) + FileUpload1.FileName;
fileName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf('.'));
fileExtension = FileUpload1.FileName.Substring(FileUpload1.FileName.IndexOf('.'));
//string ext = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName);
int fileSize = FileUpload1.PostedFile.ContentLength;
if (fileExtension != ".jpg" & fileExtension != ".png" & fileExtension != ".gif" & fileExtension != ".jpeg")
{
//lblMessage.Text = "Please choose only .jpg, .png and .gif image types!";
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Please Choose Only .jpg, .png and .gif Image Types!')", true);
this.imgDispaly.ImageUrl = string.Empty;
return;
}
while (fileExist)
{
if (fileSize < 2100000)
{
if (System.IO.File.Exists(FilePath))
{
fileName += counter.ToString();
FilePath = Server.MapPath(UploadPath) + fileName + fileExtension;
}
else
{
fileExist = false;
}
}
else
{
lblMessageDisplay.Visible = true;
this.imgDispaly.ImageUrl = string.Empty;
//lblMessageDisplay.Text = "Your file was not uploaded because it exceeds the 2 MB size limit.";
return;
}
counter++;
}
FileUpload1.SaveAs(FilePath);
ImageUrl = UploadPath + fileName + fileExtension;
imgDispaly.Visible = true;
imgDispaly.ImageUrl = ImageUrl;
ImageUrl = imgDispaly.ImageUrl;
}
catch (Exception ex)
{
//Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
//Label1.Text = "You have not specified a file.";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
this.Page.Validate();
if (!Page.IsValid)
return;
string hostelName = txtHName.Text.Trim();
string hDescription = txtDescription.Value;
//string hostelDescription = txtDescription.Text.Trim();
//string Address = txtAddress.Text.Trim();
string Contact = txtContact.Text.Trim();
string Email = txtEmail.Text.Trim();
string HWebAddress = txtHWebAddress.Text.Trim();
decimal price = decimal.Parse(txtHPrice.Text.Trim());
string facilities = txtHFacilities.Value;
//string policies = txtHPolicies.Text.Trim();
decimal lat = decimal.Parse(txtHLat.Text.Trim());
decimal longi = decimal.Parse(txtHLong.Text.Trim());
string room = txtRoom.Value;
string hLocation = txtHLocation.Text.Trim();
string hCity = txtHCity.Text.Trim();
bool IsActive = chkIsActive.Checked;
Hostel hostel = new Hostel();
hostel.HName = hostelName;
//hostel.HDescription = hostelDescription;
//hostel.HAddress = Address;
hostel.HContact = Contact;
hostel.HEmail = Email;
hostel.HWebLink = HWebAddress;
hostel.IsActive = IsActive;
hostel.RatingId = int.Parse(ddlRating.SelectedValue);
hostel.HostelPrice = price;
hostel.HFacilities = facilities;
//hostel.Hostelpolicies = policies;
hostel.HLattitude = lat;
hostel.Hlongitude = longi;
hostel.HosDescription = hDescription;
hostel.HRoom = room;
hostel.HLocation = hLocation;
hostel.HCity = hCity;
if (ImageUrl != null)
{
hostel.HImageUrl = ImageUrl.Replace("~/UploadFile/", "");
}
else
{
ImageUrl = "~/UploadFile/bg_latest.jpg";
hostel.HImageUrl = ImageUrl.Replace("~/UploadFile/", "");
}
switch (CurrentFormMode)
{
case Enums.FormMode.Save:
if (HostelManager.InsetHostel(hostel))
{
lblMessage.Text = "Hostel Added Successfully.";
LoadHostels();
ResetControls();
}
else
{
lblMessage.Text = "Data Saved Failed.";
}
break;
case Enums.FormMode.Update:
hostel.HostelId = HostelId;
if (HostelManager.UpdateHostel(hostel))
{
lblMessage.Text = "Hostel Updated Successfully.";
LoadHostels();
CurrentFormMode = Enums.FormMode.Save;
//ResetControls();
btnSave.Text = "Save";
ResetControls();
}
else
{
lblMessage.Text = "Data Update Failed.";
}
break;
default: break;
}
}
public static bool UpdateHostel(Hostel h)
{
HostelFinderEntities HFE = new HostelFinderEntities();
try
{
Hostel Hos = HFE.Hostels.Where(x => x.HostelId == h.HostelId).FirstOrDefault();
Hos.HName = h.HName;
Hos.HosDescription = h.HosDescription;
Hos.HostelId = h.HostelId;
Hos.HCity = h.HCity;
Hos.HLocation = h.HLocation;
Hos.HContact = h.HContact;
Hos.HWebLink = h.HWebLink;
Hos.HEmail = h.HEmail;
Hos.HostelPrice = h.HostelPrice;
Hos.HLattitude = h.HLattitude;
Hos.Hlongitude = h.Hlongitude;
Hos.RatingId = h.RatingId;
Hos.HRoom = h.HRoom;
Hos.HFacilities = h.HFacilities;
Hos.HImageUrl = h.HImageUrl;
Hos.IsActive = h.IsActive;
HFE.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
public static Boolean CheckRatingAlreadyInserted(HostelRating hr)
{
HostelFinderEntities HFE = new HostelFinderEntities();
HostelRating hra= HFE.HostelRatings.Where(x => x.CustomerId == hr.CustomerId && x.HostelId==hr.HostelId).FirstOrDefault();
if(hra==null)
{return false;
}
else
{return true;
}
}
protected void LoadRating()
{
List<Rating> AllEmp = HostelManager.GetAllRating();
ddlRating.DataSource = AllEmp;
ddlRating.DataTextField = "RatingValue";
ddlRating.DataValueField = "RatingId";
ddlRating.DataBind();
ListItem item = new ListItem();
item.Text = "-- Select Rating --";
item.Value = "-1";
ddlRating.Items.Insert(0, item);
ddlRating.SelectedIndex = 0;
}
Random Password
public static string Password { get; set; }
public void RandomPassword()
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, 10)
.Select(s => s[random.Next(s.Length)])
.ToArray());
Password = result.ToString();
Boolean isDuplicate = true;
while (isDuplicate)
{
isDuplicate = UserManager.IsPasswordExist(Password);
if (isDuplicate)
Password = new string(Enumerable.Repeat(chars, 10).Select(s => s[random.Next(s.Length)]).ToArray()).ToString();
}
}
public static Boolean CheckIfUserNameAlreadyExist(Customer dbuser)
{
EndtCommerceEntities ECE = new EndtCommerceEntities();
Customer dbusers = ECE.Customers.Where(x => x.UserName.ToLower().Equals(dbuser.UserName.ToLower()) && (x.CustomerId != dbuser.CustomerId)).FirstOrDefault<Customer>();
if (dbusers == null) return false;
else return true;
}
public static bool IsPasswordExist(string Password)
{
EndtCommerceEntities ECE = new EndtCommerceEntities();
Customer user = ECE.Customers.Where(x => x.Password == Password).FirstOrDefault();
if (user == null)
return false;
return true;
}
public bool AppendShippingAddressToList(CompanyShippingAddress companyShippingAddress)
{
companyShippingAddresses.Add(companyShippingAddress);
return true;
}
foreach (CompanyShippingAddress csa in companyShippingAddresses)
{
csa.IsPrimary = false;
}
foreach (GridViewRow row in gvShippingAddress.Rows)
{
RadioButton rb = (RadioButton)row.FindControl("rdoIsPrimary");
Label lblShippingAddress = (Label)row.FindControl("lblShippingAddress");
CompanyShippingAddress tempShippingAddress = companyShippingAddresses.Where(x => x.ShippingAddressLocation.ToLower() == lblShippingAddress.Text.ToLower()).FirstOrDefault();
if (rb.Checked)
{
tempShippingAddress.IsPrimary = true;
}
}
public static bool InserNewCustomer(ParentCompany pCompany, Company company, Customer customer, List<CompanyShippingAddress> companyShippingAddresses)
{
EndtCommerceEntities ECE = new EndtCommerceEntities();
try
{
company.ParentCompanyId = pCompany.ParentCompanyId;
ECE.AddToCompanies(company);
ECE.SaveChanges();
customer.CompanyId = company.CompanyId;
ECE.AddToCustomers(customer);
ECE.SaveChanges();
foreach (CompanyShippingAddress companyShippingAddress in companyShippingAddresses)
{
companyShippingAddress.CompanyId = company.CompanyId;
ECE.AddToCompanyShippingAddresses(companyShippingAddress);
ECE.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public enum BookingStatus
{
New = 1,
Pending,
Success,
Cancelled
}
GridView
<asp:TemplateField HeaderText="S. No">
<HeaderStyle HorizontalAlign="left" />
<ItemStyle HorizontalAlign="left" />
<ItemTemplate>
<asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Booking Status">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblapplicationstate" Text='<%# Enum.Parse(typeof(hospitalTicketBooking_BAL.BusinessObject.Enums.BookingStatus), Eval("bookingstatusid").ToString())==null?"-":Enum.Parse(typeof(hospitalTicketBooking_BAL.BusinessObject.Enums.BookingStatus), Eval("bookingstatusid").ToString()) %>'
runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Booking Verified Date">
<HeaderStyle HorizontalAlign="left" />
<ItemStyle HorizontalAlign="left" />
<ItemTemplate>
<asp:Label ID="lblBDate" runat="server" Text='<%# Eval("bookingverifieddate")==null?"-":DateTime.Parse(Eval("bookingverifieddate").ToString()).ToShortDateString() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblapplicationstate" Text='<%# Enum.Parse(typeof(hospitalTicketBooking_BAL.BusinessObject.Enums.BookingStatus), Eval("bookingstatusid").ToString())==null?"-":Enum.Parse(typeof(hospitalTicketBooking_BAL.BusinessObject.Enums.BookingStatus), Eval("bookingstatusid").ToString()) %>'
runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Booking Verified Date">
<HeaderStyle HorizontalAlign="left" />
<ItemStyle HorizontalAlign="left" />
<ItemTemplate>
<asp:Label ID="lblBDate" runat="server" Text='<%# Eval("bookingverifieddate")==null?"-":DateTime.Parse(Eval("bookingverifieddate").ToString()).ToShortDateString() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
OnPageIndexChanging="gvBookingDetails_PageIndexChanging"
protected void gvBookingDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvBookingDetails.PageIndex = e.NewPageIndex;
}
Table
Employee( EmpId,EmpName,Email,Salary) Department(DeptId,EmpId,DeptName)
Design View
<div>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<table>
<tr>
<td>Emp Name:</td>
<td>
<asp:TextBox ID="txtEmpname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Emp Email:</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Emp Salary:</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox></td>
</tr>
</table>
<table>
<tr>
<td>Department Name</td>
<td> <asp:TextBox ID="txtDeptName" runat="server"></asp:TextBox></td>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add Department" OnClick="btnAdd_Click" /></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvDepartment" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
<Columns>
<asp:TemplateField HeaderText="S. No"><HeaderStyle HorizontalAlign="left" /><ItemStyle HorizontalAlign="left" /><ItemTemplate><asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Department"><HeaderStyle HorizontalAlign="left" /><ItemStyle HorizontalAlign="left" /><ItemTemplate><asp:Label ID="lblpatname" runat="server" Text='<%#Eval("deptname") %>'></asp:Label></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="gvEmp" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
Coding
public static List<department> deptList1 = new List<department>();
//public static department deptmnt = new department();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// LoadDepartment();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string deptname = txtDeptName.Text.Trim();
department d = new department();
d.deptname = deptname;
if (AppendDepartmentToList(d))
{
LoadDepartment();
}
}
public bool AppendDepartmentToList(department dep)
{
deptList1.Add(dep);
return true;
}
private void LoadDepartment()
{
gvDepartment.DataSource = deptList1;
gvDepartment.DataBind();
}
//private bool AppendDepartmentToLost(department d)
//{
// foreach (department dep in deptList)
// {
// }
//}
protected void btnSave_Click(object sender, EventArgs e)
{
string empName = txtEmpname.Text.Trim();
string email = txtEmail.Text.Trim();
decimal salary =decimal.Parse( txtSalary.Text.Trim());
Employee emp = new Employee();
emp.Email = email;
emp.Name = empName;
emp.Salary = salary;
if (EmployeeManager.InsertEmployee(emp,deptList1))
{
lblMessage.Text = "Data Saved.";
}
else
{
lblMessage.Text = "Data Save Failed.";
}
}
Class
public static bool InsertEmployee(Employee e,List<department>depts)
{
vwEntities vew = new vwEntities();
try
{
vew.AddToEmployees(e);
vew.SaveChanges();
foreach (department d in depts)
{
d.empId = e.EmpId;
vew.AddTodepartments(d);
vew.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
Table
Employee( EmpId,EmpName,Email,Salary) Department(DeptId,EmpId,DeptName)
Design View
<div>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<table>
<tr>
<td>Emp Name:</td>
<td>
<asp:TextBox ID="txtEmpname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Emp Email:</td>
<td>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Emp Salary:</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox></td>
</tr>
</table>
<table>
<tr>
<td>Department Name</td>
<td> <asp:TextBox ID="txtDeptName" runat="server"></asp:TextBox></td>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add Department" OnClick="btnAdd_Click" /></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" /></td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvDepartment" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
<Columns>
<asp:TemplateField HeaderText="S. No"><HeaderStyle HorizontalAlign="left" /><ItemStyle HorizontalAlign="left" /><ItemTemplate><asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Department"><HeaderStyle HorizontalAlign="left" /><ItemStyle HorizontalAlign="left" /><ItemTemplate><asp:Label ID="lblpatname" runat="server" Text='<%#Eval("deptname") %>'></asp:Label></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
<asp:GridView ID="gvEmp" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
Coding
public static List<department> deptList1 = new List<department>();
//public static department deptmnt = new department();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// LoadDepartment();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string deptname = txtDeptName.Text.Trim();
department d = new department();
d.deptname = deptname;
if (AppendDepartmentToList(d))
{
LoadDepartment();
}
}
public bool AppendDepartmentToList(department dep)
{
deptList1.Add(dep);
return true;
}
private void LoadDepartment()
{
gvDepartment.DataSource = deptList1;
gvDepartment.DataBind();
}
//private bool AppendDepartmentToLost(department d)
//{
// foreach (department dep in deptList)
// {
// }
//}
protected void btnSave_Click(object sender, EventArgs e)
{
string empName = txtEmpname.Text.Trim();
string email = txtEmail.Text.Trim();
decimal salary =decimal.Parse( txtSalary.Text.Trim());
Employee emp = new Employee();
emp.Email = email;
emp.Name = empName;
emp.Salary = salary;
if (EmployeeManager.InsertEmployee(emp,deptList1))
{
lblMessage.Text = "Data Saved.";
}
else
{
lblMessage.Text = "Data Save Failed.";
}
}
Class
public static bool InsertEmployee(Employee e,List<department>depts)
{
vwEntities vew = new vwEntities();
try
{
vew.AddToEmployees(e);
vew.SaveChanges();
foreach (department d in depts)
{
d.empId = e.EmpId;
vew.AddTodepartments(d);
vew.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
0 comments:
Post a Comment