User Details Aspx page(UserDetail.aspx) <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserDetails.aspx.cs" Inherits="Assessment_User.UserDetails" %></td> <td colspan="2"> <asp:TextBox ID="txtFirstName" runat="server"> </asp:TextBox> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtFirstName" ValidationExpression="[a-zA-Z]*$" ErrorMessage="Accepts alphabets only"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Last Name" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtLastName" runat="server" /> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtLastName" ValidationExpression="[a-zA-Z]*$" ErrorMessage="Accepts alphabets only"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Email ID" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtEmailID" TextMode="Email" runat="server"> </asp:TextBox> </td> <td colspan="2"> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVEmail" runat="server" ControlToValidate="txtEmailID" ErrorMessage="Email is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label Text="Contact Number" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtContactNumber" TextMode="Phone" runat="server"> </asp:TextBox> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtContactNumber" ValidationExpression="[0-9]{10}" ErrorMessage="accepts numbers only"></asp:RegularExpressionValidator> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVContactno" runat="server" ControlToValidate="txtContactNumber" ErrorMessage="Contact No is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label Text="Gender" runat="server" /> </td> <td colspan="2"> <asp:DropDownList ID="ddlGender" runat="server"> <asp:ListItem> Male</asp:ListItem> <asp:ListItem>Female</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> <asp:Label Text="Address" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtAddress" TextMode="MultiLine" runat="server"> </asp:TextBox> </td> </tr> <hr /> <tr> <td> <asp:Label Text="User Name" runat="server" /> </td> <td> <asp:TextBox ID="txtUserName" runat="server"> </asp:TextBox> </td> <%--<td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVUserName" runat="server" ControlToValidate="txtUserName" ErrorMessage="UserName is required"></asp:RequiredFieldValidator> </td>--%> <td> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtUserName" ValidationExpression="[A-Za-z0-9]{6,15}" ErrorMessage="accepts both alphabets and numbers"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Password" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtPassword" TextMode="Password" runat="server"> </asp:TextBox> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVPassword" runat="server" ControlToValidate="txtPassword" ErrorMessage="password is required"></asp:RequiredFieldValidator> </td> <asp:RegularExpressionValidator ID="Password" ForeColor="Red" runat="server" ControlToValidate="txtPassword" ValidationExpression="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$" ErrorMessage="Minimum 8 to 10 chars including all alphanumeric"></asp:RegularExpressionValidator> </tr> <tr> <td> <asp:Label Text="Confirm Password" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtConfirmPassword" TextMode="Password" require="true" runat="server"> </asp:TextBox> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVconfirmpassword" ControlToValidate="txtConfirmPassword" runat="server" ErrorMessage="Email is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td></td> <td> <asp:Button Text="Submit" ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" /> </td> </tr> <tr> <td></td> <td> <asp:Label ID="lblSuccessMessage" ForeColor="Green" runat="server"></asp:Label> </td> </tr> <tr> <td></td> <td> <asp:Label ID="lblErrorMessage" ForeColor="Red" runat="server"></asp:Label> </td> </tr> </table> </div> </form>
User Details Aspx.cs page using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Assessment_User { public partial class UserDetails : System.Web.UI.Page {// string conn = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { var conn = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; if (txtPassword.Text != txtConfirmPassword.Text) lblErrorMessage.Text = "Password must be the same"; else using (SqlConnection cons = new SqlConnection(conn)) { using (SqlCommand cmd = new SqlCommand("userdata")) // using(SqlCommand cmds= new SqlCommand("select count(*)from UseTable where EmailID=@EmailID",cons)) { cmd.Connection = cons; //cons.Open(); // cmds.Parameters.AddWithValue("@EmailID", txtEmailID.Text.Trim()); //int count = Convert.ToInt32(cmds.ExecuteScalar()); //if (count == 1) //{ // lblErrorMessage.Text = "This Email Id is already exists"; //} //else //{ // SqlCommand cmd = new SqlCommand("userdata", cons); cons.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", Convert.ToInt32(hfUserID.Value == "" ? "0" : hfUserID.Value)); cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim()); cmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim()); cmd.Parameters.AddWithValue("@EmailID", txtEmailID.Text.Trim()); cmd.Parameters.AddWithValue("@ContactNumber", txtContactNumber.Text.Trim()); cmd.Parameters.AddWithValue("@Gender", ddlGender.SelectedValue); cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim()); cmd.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()); bool success = Convert.ToBoolean(cmd.ExecuteScalar()); if (success) { // lblErrorMessage.Text = ""; lblSuccessMessage.Text = "Successfully submitted"; // lblErrorMessage.Attributes.Add("style", "display:none"); } else { lblErrorMessage.Text = "User Name already exists"; // lblSuccessMessage.Text = ""; //Response.Write("User exists"); //Clear(); } //Clear(); cons.Close(); //Clear(); // cmd.ExecuteNonQuery(); // lblSuccessMessage.Text = "Submitted Successfully"; } } } }
} Sql stored procedure UseTable UserData ALTER proc [dbo].[userdata] @UserID int, @FirstName varchar(50), @LastName varchar(50), @EmailID varchar(50), @ContactNumber varchar(50), @Gender varchar(10), @Address varchar(250), @UserName varchar(50), @Password varchar(50) as begin set nocount on; if exists(select * from UseTable where UserName=@UserName) begin select 'false' end else begin insert into UseTable (FirstName,LastName,EmailID,ContactNumber,Gender,Address,UserName,Password) values (@FirstName,@LastName,@EmailID,@ContactNumber,@Gender,@Address,@UserName,@Password) SELECT 'TRUE' End end GridView <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridview.aspx.cs" Inherits="Assessment_User.gridview" %><asp:GridView ID="GridView1" runat="server" DataKeyNames="UserID" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
</div> </form>
gridview.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Assessment_User { public partial class gridview : System.Web.UI.Page {string strConnString = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT UserID, FirstName, LastName, EmailID, ContactNumber,Gender,Address,UserName,Password FROM UseTable")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void OnRowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGrid(); } protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string FirstName = (row.Cells[2].Controls[0] as TextBox).Text; string LastName = (row.Cells[3].Controls[0] as TextBox).Text; string EmailID = (row.Cells[4].Controls[0] as TextBox).Text; string ContactNumber = (row.Cells[5].Controls[0] as TextBox).Text; string Gender = (row.Cells[6].Controls[0] as TextBox).Text; string Address = (row.Cells[7].Controls[0] as TextBox).Text; string UserName = (row.Cells[8].Controls[0] as TextBox).Text; string Password = (row.Cells[9].Controls[0] as TextBox).Text; string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("UPDATE UseTable SET FirstName = @FirstName, LastName = @LastName, EmailID = @EmailID,ContactNumber = @ContactNumber,Gender = @Gender, Address = @Address, UserName=@UserName,Password = @Password WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Parameters.AddWithValue("@FirstName", FirstName); cmd.Parameters.AddWithValue("@LastName", LastName); cmd.Parameters.AddWithValue("@EmailID", EmailID); cmd.Parameters.AddWithValue("@ContactNumber", ContactNumber); cmd.Parameters.AddWithValue("@Gender", Gender); cmd.Parameters.AddWithValue("@Address", Address); cmd.Parameters.AddWithValue("@UserName", UserName); cmd.Parameters.AddWithValue("@Password", Password); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowCancelingEdit(object sender, EventArgs e) { GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("DELETE FROM UseTable WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex) { (e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; } } }
}
Registration form& gridview in asp.net
<pre> User Details Aspx page(UserDetail.aspx) —————————– <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”UserDetails.aspx.cs” Inherits=”Assessment_User.UserDetails” %>
Male Female | ||||||
————————————————————
User Details Aspx.cs page
————————————————–
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Assessment_User
{
public partial class UserDetails : System.Web.UI.Page
{
// string conn = ConfigurationManager.ConnectionStrings[“Usercon”].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var conn = ConfigurationManager.ConnectionStrings[“Usercon”].ConnectionString;
if (txtPassword.Text != txtConfirmPassword.Text)
lblErrorMessage.Text = “Password must be the same”;
else
using (SqlConnection cons = new SqlConnection(conn))
{
using (SqlCommand cmd = new SqlCommand(“userdata”))
// using(SqlCommand cmds= new SqlCommand(“select count(*)from UseTable where EmailID=@EmailID”,cons))
{
cmd.Connection = cons;
//cons.Open();
// cmds.Parameters.AddWithValue(“@EmailID”, txtEmailID.Text.Trim());
//int count = Convert.ToInt32(cmds.ExecuteScalar());
//if (count == 1)
//{
// lblErrorMessage.Text = “This Email Id is already exists”;
//}
//else
//{
// SqlCommand cmd = new SqlCommand(“userdata”, cons);
cons.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@UserID”, Convert.ToInt32(hfUserID.Value == “” ? “0” : hfUserID.Value));
cmd.Parameters.AddWithValue(“@FirstName”, txtFirstName.Text.Trim());
cmd.Parameters.AddWithValue(“@LastName”, txtLastName.Text.Trim());
cmd.Parameters.AddWithValue(“@EmailID”, txtEmailID.Text.Trim());
cmd.Parameters.AddWithValue(“@ContactNumber”, txtContactNumber.Text.Trim());
cmd.Parameters.AddWithValue(“@Gender”, ddlGender.SelectedValue);
cmd.Parameters.AddWithValue(“@Address”, txtAddress.Text.Trim());
cmd.Parameters.AddWithValue(“@UserName”, txtUserName.Text.Trim());
cmd.Parameters.AddWithValue(“@Password”, txtPassword.Text.Trim());
bool success = Convert.ToBoolean(cmd.ExecuteScalar());
if (success)
{
// lblErrorMessage.Text = “”;
lblSuccessMessage.Text = “Successfully submitted”;
// lblErrorMessage.Attributes.Add(“style”, “display:none”);
}
else
{
lblErrorMessage.Text = “User Name already exists”;
// lblSuccessMessage.Text = “”;
//Response.Write(“User exists”);
//Clear();
}
//Clear();
cons.Close();
//Clear();
// cmd.ExecuteNonQuery();
// lblSuccessMessage.Text = “Submitted Successfully”;
}
}
}
}
}
————————————————————————
Sql stored procedure
UseTable
UserData
————————————————————
ALTER proc [dbo].[userdata]
@UserID int,
@FirstName varchar(50),
@LastName varchar(50),
@EmailID varchar(50),
@ContactNumber varchar(50),
@Gender varchar(10),
@Address varchar(250),
@UserName varchar(50),
@Password varchar(50)
as
begin
set nocount on;
if exists(select * from UseTable where UserName=@UserName)
begin
select ‘false’
end
else
begin
insert into UseTable (FirstName,LastName,EmailID,ContactNumber,Gender,Address,UserName,Password)
values (@FirstName,@LastName,@EmailID,@ContactNumber,@Gender,@Address,@UserName,@Password)
SELECT ‘TRUE’
End
end
—————————————————————
GridView
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”gridview.aspx.cs” Inherits=”Assessment_User.gridview” %>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="UserID" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
</div> </form>
gridview.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Assessment_User
{
public partial class gridview : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT UserID, FirstName, LastName, EmailID, ContactNumber,Gender,Address,UserName,Password FROM UseTable")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void OnRowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGrid(); } protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string FirstName = (row.Cells[2].Controls[0] as TextBox).Text; string LastName = (row.Cells[3].Controls[0] as TextBox).Text; string EmailID = (row.Cells[4].Controls[0] as TextBox).Text; string ContactNumber = (row.Cells[5].Controls[0] as TextBox).Text; string Gender = (row.Cells[6].Controls[0] as TextBox).Text; string Address = (row.Cells[7].Controls[0] as TextBox).Text; string UserName = (row.Cells[8].Controls[0] as TextBox).Text; string Password = (row.Cells[9].Controls[0] as TextBox).Text; string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("UPDATE UseTable SET FirstName = @FirstName, LastName = @LastName, EmailID = @EmailID,ContactNumber = @ContactNumber,Gender = @Gender, Address = @Address, UserName=@UserName,Password = @Password WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Parameters.AddWithValue("@FirstName", FirstName); cmd.Parameters.AddWithValue("@LastName", LastName); cmd.Parameters.AddWithValue("@EmailID", EmailID); cmd.Parameters.AddWithValue("@ContactNumber", ContactNumber); cmd.Parameters.AddWithValue("@Gender", Gender); cmd.Parameters.AddWithValue("@Address", Address); cmd.Parameters.AddWithValue("@UserName", UserName); cmd.Parameters.AddWithValue("@Password", Password); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowCancelingEdit(object sender, EventArgs e) { GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("DELETE FROM UseTable WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex) { (e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; } } }
}
</pre>
Registration & GridView in asp.net
User Details Aspx page(UserDetail.aspx)
<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”UserDetails.aspx.cs” Inherits=”Assessment_User.UserDetails” %>
</td> <td colspan="2"> <asp:TextBox ID="txtFirstName" runat="server"> </asp:TextBox> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtFirstName" ValidationExpression="[a-zA-Z]*$" ErrorMessage="Accepts alphabets only"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Last Name" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtLastName" runat="server" /> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtLastName" ValidationExpression="[a-zA-Z]*$" ErrorMessage="Accepts alphabets only"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Email ID" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtEmailID" TextMode="Email" runat="server"> </asp:TextBox> </td> <td colspan="2"> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVEmail" runat="server" ControlToValidate="txtEmailID" ErrorMessage="Email is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label Text="Contact Number" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtContactNumber" TextMode="Phone" runat="server"> </asp:TextBox> </td> <td colspan="3"> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtContactNumber" ValidationExpression="[0-9]{10}" ErrorMessage="accepts numbers only"></asp:RegularExpressionValidator> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVContactno" runat="server" ControlToValidate="txtContactNumber" ErrorMessage="Contact No is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label Text="Gender" runat="server" /> </td> <td colspan="2"> <asp:DropDownList ID="ddlGender" runat="server"> <asp:ListItem> Male</asp:ListItem> <asp:ListItem>Female</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td> <asp:Label Text="Address" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtAddress" TextMode="MultiLine" runat="server"> </asp:TextBox> </td> </tr> <hr /> <tr> <td> <asp:Label Text="User Name" runat="server" /> </td> <td> <asp:TextBox ID="txtUserName" runat="server"> </asp:TextBox> </td> <%--<td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVUserName" runat="server" ControlToValidate="txtUserName" ErrorMessage="UserName is required"></asp:RequiredFieldValidator> </td>--%> <td> <asp:RegularExpressionValidator ForeColor="Red" ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtUserName" ValidationExpression="[A-Za-z0-9]{6,15}" ErrorMessage="accepts both alphabets and numbers"></asp:RegularExpressionValidator> </td> </tr> <tr> <td> <asp:Label Text="Password" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtPassword" TextMode="Password" runat="server"> </asp:TextBox> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVPassword" runat="server" ControlToValidate="txtPassword" ErrorMessage="password is required"></asp:RequiredFieldValidator> </td> <asp:RegularExpressionValidator ID="Password" ForeColor="Red" runat="server" ControlToValidate="txtPassword" ValidationExpression="^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$" ErrorMessage="Minimum 8 to 10 chars including all alphanumeric"></asp:RegularExpressionValidator> </tr> <tr> <td> <asp:Label Text="Confirm Password" runat="server" /> </td> <td colspan="2"> <asp:TextBox ID="txtConfirmPassword" TextMode="Password" require="true" runat="server"> </asp:TextBox> </td> <td> <asp:RequiredFieldValidator ForeColor="Red" ID="RFVconfirmpassword" ControlToValidate="txtConfirmPassword" runat="server" ErrorMessage="Email is required"></asp:RequiredFieldValidator> </td> </tr> <tr> <td></td> <td> <asp:Button Text="Submit" ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" /> </td> </tr> <tr> <td></td> <td> <asp:Label ID="lblSuccessMessage" ForeColor="Green" runat="server"></asp:Label> </td> </tr> <tr> <td></td> <td> <asp:Label ID="lblErrorMessage" ForeColor="Red" runat="server"></asp:Label> </td> </tr> </table> </div> </form> User Details Aspx.cs page using System;using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Assessment_User { public partial class UserDetails : System.Web.UI.Page { // string conn = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { var conn = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; if (txtPassword.Text != txtConfirmPassword.Text) lblErrorMessage.Text = "Password must be the same"; else using (SqlConnection cons = new SqlConnection(conn)) { using (SqlCommand cmd = new SqlCommand("userdata")) // using(SqlCommand cmds= new SqlCommand("select count(*)from UseTable where EmailID=@EmailID",cons)) { cmd.Connection = cons; //cons.Open(); // cmds.Parameters.AddWithValue("@EmailID", txtEmailID.Text.Trim()); //int count = Convert.ToInt32(cmds.ExecuteScalar()); //if (count == 1) //{ // lblErrorMessage.Text = "This Email Id is already exists"; //} //else //{ // SqlCommand cmd = new SqlCommand("userdata", cons); cons.Open(); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", Convert.ToInt32(hfUserID.Value == "" ? "0" : hfUserID.Value)); cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim()); cmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim()); cmd.Parameters.AddWithValue("@EmailID", txtEmailID.Text.Trim()); cmd.Parameters.AddWithValue("@ContactNumber", txtContactNumber.Text.Trim()); cmd.Parameters.AddWithValue("@Gender", ddlGender.SelectedValue); cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim()); cmd.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()); bool success = Convert.ToBoolean(cmd.ExecuteScalar()); if (success) { // lblErrorMessage.Text = ""; lblSuccessMessage.Text = "Successfully submitted"; // lblErrorMessage.Attributes.Add("style", "display:none"); } else { lblErrorMessage.Text = "User Name already exists"; // lblSuccessMessage.Text = ""; //Response.Write("User exists"); //Clear(); } //Clear(); cons.Close(); //Clear(); // cmd.ExecuteNonQuery(); // lblSuccessMessage.Text = "Submitted Successfully"; } } } } } Sql stored procedureUseTable UserData ALTER proc [dbo].[userdata] @UserID int, @FirstName varchar(50), @LastName varchar(50), @EmailID varchar(50), @ContactNumber varchar(50), @Gender varchar(10), @Address varchar(250), @UserName varchar(50), @Password varchar(50) as begin set nocount on; if exists(select * from UseTable where UserName=@UserName) begin select ‘false’ end else begin insert into UseTable (FirstName,LastName,EmailID,ContactNumber,Gender,Address,UserName,Password) values (@FirstName,@LastName,@EmailID,@ContactNumber,@Gender,@Address,@UserName,@Password) SELECT ‘TRUE’ End end ———————————————————————————————– GridView <%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”gridview.aspx.cs” Inherits=”Assessment_User.gridview” %> <asp:GridView ID="GridView1" runat="server" DataKeyNames="UserID" OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit" OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added." AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"> </div> </form> gridview.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Assessment_User { public partial class gridview : System.Web.UI.Page { string strConnString = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT UserID, FirstName, LastName, EmailID, ContactNumber,Gender,Address,UserName,Password FROM UseTable")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } } protected void OnRowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; this.BindGrid(); } protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string FirstName = (row.Cells[2].Controls[0] as TextBox).Text; string LastName = (row.Cells[3].Controls[0] as TextBox).Text; string EmailID = (row.Cells[4].Controls[0] as TextBox).Text; string ContactNumber = (row.Cells[5].Controls[0] as TextBox).Text; string Gender = (row.Cells[6].Controls[0] as TextBox).Text; string Address = (row.Cells[7].Controls[0] as TextBox).Text; string UserName = (row.Cells[8].Controls[0] as TextBox).Text; string Password = (row.Cells[9].Controls[0] as TextBox).Text; string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("UPDATE UseTable SET FirstName = @FirstName, LastName = @LastName, EmailID = @EmailID,ContactNumber = @ContactNumber,Gender = @Gender, Address = @Address, UserName=@UserName,Password = @Password WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Parameters.AddWithValue("@FirstName", FirstName); cmd.Parameters.AddWithValue("@LastName", LastName); cmd.Parameters.AddWithValue("@EmailID", EmailID); cmd.Parameters.AddWithValue("@ContactNumber", ContactNumber); cmd.Parameters.AddWithValue("@Gender", Gender); cmd.Parameters.AddWithValue("@Address", Address); cmd.Parameters.AddWithValue("@UserName", UserName); cmd.Parameters.AddWithValue("@Password", Password); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowCancelingEdit(object sender, EventArgs e) { GridView1.EditIndex = -1; this.BindGrid(); } protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e) { int UserID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); string constr = ConfigurationManager.ConnectionStrings["Usercon"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("DELETE FROM UseTable WHERE UserID = @UserID")) { cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); } protected void OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex) { (e.Row.Cells[0].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; } } } } —————————————————— |
Protected: Web Design
New_Year_Wishes_From_TK
Dear friends, on this joyous occasion of New Year, cherish our memories and feel the warmth of my wishes. Happy New Year!.
In soft glistening night of stars,
hope all your aspirations come true.
May every star present in the sky,
Bring love and mirth to you.
Happy New Year 2018!
Wishes from T K NANOINFOTECH.
Happy Ganesha Chaturthi
HAPPY GANESHA CHATURTHI
Srinivasa T K
Wishing You Happy Ganesh Chaturthi!!
May this Ganesh Chaturthi brings you
Bakthi, Shakthi, Siddhi and Laskhmi.
Happy Ganesh Chaturthi!!
– Nano Infotech
ವಕ್ರತುಂಡ ಮಹಾಕಾಯ ಕೋಟಿಸೂರ್ಯ ಸಮಪ್ರಭ
ನಿರ್ವಿಘ್ನಂ ಕುರು ಮೇ ದೇವ ಸರ್ವಕಾರ್ಯೇಷು ಸರ್ವದಾ ||
ವಿಘ್ನಗಳೆಲ್ಲ ನಿವಾರಣೆಯಾಗಿ ಸಕಲ ಕಾರ್ಯಗಳು ನಿರ್ವಿಘ್ನವಾಗಿ ನೆರವೇರಿ ಯಶಸ್ಸು,ಸಾಧನೆ,ಕೀರ್ತಿ,ಸಂಪತ್ತು,ಆರೋಗ್ಯ ಸರ್ವರಿಗೂ ಲಭಿಸಲಿ.
ಸರ್ವರಿಗೂ
ಗಣೇಶ ಹಬ್ಬದ ಹಾರ್ದಿಕ ಶುಭಾಶಯಗಳು.
Computer graphics.
Graphics (from Greek γραφικός ‘graphikos’, ‘something written’ e.g. autograph) are visual images or designs on some surface, such as a wall, canvas, screen, paper, or stone to inform, illustrate, or entertain. In contemporary usage it includes: pictorial representation of data, as in computer-aided design and manufacture, in typesetting and the graphic arts, and in educational and recreational software. Images that are generated by a computer are called computer graphics.
Examples are photographs, drawings, Line art, graphs, diagrams, typography, numbers, symbols, geometric designs, maps, engineering drawings, or other images. Graphics often combine text, illustration, and color. Graphic design may consist of the deliberate selection, creation, or arrangement of typography alone, as in a brochure, flyer, poster, web site, or book without any other element. Clarity or effective communication may be the objective, association with other cultural elements may be sought, or merely, the creation of a distinctive style.
Graphics can be functional or artistic. The latter can be a recorded version, such as a photograph, or an interpretation by a scientist to highlight essential features, or an artist, in which case the distinction with imaginary graphics may become blurred.
Some of mini projects of computer graphics as mentioned below.
you can download.
1.Robot-3d
2.Clipping
Download full code of CLIPPING
3.SWEET HOME-3D
Download full code of GECR BUS
5.Line draw
6.Newtons Law
7.Rain water
8.Selection sort
Computer Graphics Miniprojects
Download Opengl Mini Projects Source Codes, Opengl Mini Projects Scripts – OpenGL OO Windowing Environment by Gloworm, Jot-pad by Anonymous and more…
|
Home | Submit Code | Top Code Search | Last Code Search | Privacy Policy | Link to Us | Contact |
© Copyright 2000-2015 Source Code Online. Free Source Code and Scripts Downloads.
All files and free downloads are copyright of their respective owners. We do not provide any hacked, cracked, illegal, pirated version of scripts, codes, components downloads. All files are downloaded from the publishers website, our file servers or download mirrors. Always Virus check files downloaded from the web specially zip, rar, exe, trial, full versions etc. Download links from rapidshare, depositfiles, megaupload etc not published.
Happy Independence day!
“HAPPY INDEPENDENCE DAY TO ALL MY INDIANS”
“Celebrate this day with silent prayers of thanks to
our heroes who made it possible for us to live in a free nation.
Happy Independence Day!”
Today we have gathered here to celebrate this great national event. As we all know that Independence day is an auspicious occasion for all of us. India’s Independence Day is the most important day to all the Indian citizens and has been mentioned forever in the history. It is the day when we got freedom from the British rule after many years of hard struggle by the great freedom fighters of India. We celebrate independence day every year on 15th of August to remember the first day of freedom of India as well as remember all the sacrifices of the great leaders who have sacrificed their lives in getting freedom for India.
India got independence on 15th of August in 1947 from the British rule. After independence we got our all the fundamental rights in our own Nation, our Motherland. We all should feel proud to be an Indian and admire our fortune that we took birth on the land of an Independent India. History of slave India reveals everything that how our ancestors and forefathers had worked hard and suffered all the brutal behavior of Britishers. We cannot imagine by sitting here that how hard the independence was for India from the British rule. It took sacrifices of lives of many freedom fighters and several decades of struggle from 1857 to 1947. An Indian soldier (Mangal Pandey) in the British force had first raised his voice against Britishers for the independence of India.
Later several great freedom fighters had struggled and spent their whole life only for getting freedom. We can never forget the sacrifices of the Bhagat Singh, Khudi Ram Bose and Chandra Sekhar Azad who had lost their lives in their early age just for fighting for their country. How can we ignore all the struggles of Netaji and Gandhiji. Gandhiji was a great Indian personalities who taught Indians a big lesson of non-violence. He was the one and only who lead India to get freedom with the help of non-violence. Finally the result of long years of struggle came in front on 15th of August 1947 when India got freedom.
We are so lucky that our forefathers have given us a land of peace and happy where we can sleep whole night without fear and enjoy whole day in our school or home. Our country is developing very fast in the field of technology, education, sports, finance and various other fields which were almost impossible before freedom. India is one of the countries rich in nuclear power. We are going ahead by actively participating in the sports like Olympics, Commonwealth games and Asian games. We have full rights to chose our government and enjoy largest democracy in the world. Yes, we are free and have complete freedom however we should not understand ourselves free of responsibilities towards our country. As being responsible citizens of the country, we should be always ready to handle any emergency condition in our country.
Jai Hind, Jai Bharat.
Powered by RiiiT
wishes by : SRINIVASA T K
UNIX SYSTEMS PROGRAMMING & COMPILER DESIGN LAB
INTRODUCTION TO UNIX
What is UNIX?
UNIX is an operating system which was first developed in the 1960s, and has been under constant development ever since. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which provides an easy to use environment. However, knowledge of UNIX is required for operations which aren’t covered by a graphical program, or for when there is no windows interface available, for example, in a telnet session.
Types of UNIX
There are many different versions of UNIX, although they share common similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.
The UNIX operating system
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile). The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems).
1.Write a C/C++ POSIX compliant program to check the following limits:
(i) No. of clock ticks (ii) Max. no. of child processes (iii) Max. path length
(iv) Max. no. of characters in a file name (v) Max. no. of open files/ process
/*pgm1.cpp*/
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE 199309L
#include<stdio.h>
#include<iostream>
#include<unistd.h>
using namespace std;
int main()
{
int res;
if((res=sysconf(_SC_CLK_TCK))==-1)
perror(“sysconf”);
else cout<<“clock ticks:”<<res<<endl;
if((res=sysconf(_SC_CHILD_MAX))==-1)
perror(“sysconf”);
else cout<<“NO OF CHILD PROCESSES:”<<res<<endl;
if((res=pathconf(“/”,_PC_PATH_MAX))==-1)
perror(“pathconf”);
else cout<<“max pathname:”<<(res+1)<<endl;
if((res=pathconf(“/”,_PC_NAME_MAX))==-1)
perror(“pathconf”);
else cout<<“max file name:”<<(res)<<endl;
if((res=sysconf(_SC_OPEN_MAX))==-1)
perror(“sysconf”);
else cout<<“NO OF FILES:”<<res<<endl;
return 0;
}
OUTPUT
[gec@localhost ~]$ c++ pg1.cpp
[gec@localhost ~]$ ./a.out
clock ticks:100
NO OF CHILD PROCESSES:1024
max pathname:4097
max file name:255
NO OF FILES:1024
OF FILES:1024
2.Write a C/C++ POSIX compliant program that prints the POSIX defined configuration options supported on any given system using feature test macros.
/*pgm2.c*/
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE 199309L
#include<stdio.h>
#include<unistd.h>
int main()
{
#ifdef _POSIX_JOB_CONTROL
printf(“the system supports job control\n”);
#endif
#ifdef _POSIX_SAVED_IDS
printf(“the system supports saved ID\n”);
#else
printf(“saved IDs not supported\n”);
#endif
#ifdef _POSIX_CHOWN_RESTRICTED
printf(“system supports _POSIX_CHOWN_RESTRICTED”);
#else
printf(“no supports of chown restricted\n”);
#endif
#ifdef _POSIX_NO_TRUNC
printf(“system wide pathname supported\n”);
#else
printf(“wide pathname not supported\n”);
#endif
#ifdef _POSIX_VDISABLE
printf(“disabling character is supported\n”);
#else
printf(“no disabling character\n”);
#endif
return 0;
}
OUTPUT
[gec@localhost ~]$ cc pg2.cpp
[gec@localhost ~]$ ./a.out
the system supports job control
the system supports saved ID
system supports _POSIX_CHOWN_RESTRICTEDsystem wide pathname supported
disabling character is supported
3.Consider the last 100 bytes as a region. Write a C/C++ program to check whether the region is locked or not. If the region is locked, print pid of the process which has locked. If the region is not locked, lock the region with an exclusive lock, read the last 50 bytes and unlock the region.
/*pgm3.cpp*/
#include<iostream>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
using namespace std;
int main(int argc,char *argv[])
{
struct flock fvar;
int fdesc,i;
unsigned char buf[50];
while(–argc>0)
{
cout<<“number of arguments entered=”<<argc<<endl;
if((fdesc=open(*++argv,O_RDWR))==-1)
{
perror(“open”);
continue;
}
lseek(fdesc,-100,SEEK_END);
cout<<“file opened is:”<<*argv<<endl;
fvar.l_type=F_WRLCK;
fvar.l_whence=SEEK_CUR;
fvar.l_start=-100;
fvar.l_len=100;
if(fcntl(fdesc,F_SETLK,&fvar)==-1)
{
cout<<“trying to set the lock\n”;
if(fcntl(fdesc,F_GETLK,&fvar)!=-1 && fvar.l_type!=F_UNLCK)
{
cout<<“lock is acquired by the following process\n”;
cout<<*argv<<“\t locked by”<<fvar.l_pid<<“\t from”<<fvar.l_start<<“\t for”<<fvar.l_len<<“\t byte for\t”<<(fvar.l_type==F_WRLCK? “write”:”read”)<<endl;
return 0;
}
}
fvar.l_start+=fvar.l_len;
fvar.l_len=0;
lseek(fdesc,-50,SEEK_END);
read(fdesc,&buf,50);
buf[50]=’\0′;
getchar();
cout<<“LAST 50 BYTES OF THE FILE ARE….\n”;
cout<<buf;
fvar.l_type=F_UNLCK;
fvar.l_whence=SEEK_END;
fvar.l_start=-100;
fvar.l_len=100;
if(fcntl(fdesc,F_SETLKW,&fvar)==-1)
perror(“fcntl”);
}
return 0;
}
OUTPUT
1st terminal
gec@localhost ~]$ cat>lmn
hwwwwwwfr jrrrrrhkh jrghhhhhhhhjk jdddddddddddddddddddd shhfj urrrrrrrrrrrrrrrt jssssssssssssssehhh jeeeeeeeeeeeeeeeeee jsddfhjfh jddddddddddddddd jdfffffffffffff jffffffffffffffffh jdfffffffffffffffffffffffs hbffffffffffffffffhbbb
[gec@localhost ~]$ ./a.out lmn
number of arguments entered=1
file opened is:lmn
Press <ENTER>
LAST 50 BYTES OF THE FILE ARE
defghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
2nd Terminal
[gec@localhost ~]$ c++ pg3.cpp
[gec@localhost ~]$ ./a.out lmn
number of arguments entered=1
file opened is:lmn
trying to set the lock
lock is acquired by the following process
lmn locked by4485 from32 for100 byte for write
4.Write a C/C++ program which demonstrates interprocess communication between a reader process and a writer process. Use mkfifo, open, read, write and close APIs in your program.
/*pgm4read.c*/
#include<fcntl.h> //reader
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#define MAX_BUF 1024
int main()
{
int fd;
char *myfifo=”/tmp/myfifo”;
char buf[MAX_BUF];
fd=open(myfifo,O_RDONLY);
read(fd,buf,MAX_BUF);
printf(“received:%s\n”,buf);
close(fd);
return 0;
}
/*pgm4write.c*/
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int fd;
char *myfifo=”/tmp/myfifo”;
mkfifo(myfifo,0666);
printf(“run reader to read the FIFO file\n”);
fd=open(myfifo,O_WRONLY);
write(fd,”hi”,sizeof(“hi”));
close(fd);
unlink(myfifo);
return 0;
}
OUTPUT
1st terminal
/*Write Terminal*/
[gec@localhost ~]$ cc writer1.c
[gec@localhost ~]$ ./a.out
run reader to read the FIFO file
<Ctrl> + c
2nd Terminal
/*Read Terminal*/
output: terminal 2
[gec@localhost ~]$ cc reader1.c
[gec@localhost ~]$ ./a.out
received:hi
5.a) Write a C/C++ program that outputs the contents of its Environment list.
/*pgm5a.c*/
#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[], char *envp[])
{
int i;
for(i=0;envp[i];i++)
printf(“%s\n”,envp[i]);
}
OUTPUT
[gec@localhost CSE]$vi pgm5a.c
[gec@localhost CSE]$ cc pgm5a.c
[gec@localhost CSE]$ ./a.out
NCTUNSHOME=/USR/LOCAL/NCTUNS
ORBIT_SOCKETDIR=/tmp/orbit-NIT
HOSTNAME=localhost.localdomain
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
XDG_SESSION_COOKIE=588ea643320f0612413442364ec39d1a-1359072729.324813-396874535
GTK_RC_FILES=/etc/gtk/gtkrc:/home/NIT/.gtkrc-1.2-gnome2
WINDOWID=60817471
QTDIR=/usr/lib/qt-3.3
NCTUNS_TOOLS=/USR/LOCAL/NCTUNS/TOOLS
QTINC=/usr/lib/qt-3.3/include
NCTUNS_BIN=/USR/LOCAL/NCTUNS/BIN
USER=NIT
………..
5.b) Write a C / C++ program to emulate the unix ln command.
/*pgm5b.c*/
#include<iostream>
#include<unistd.h>
int main(int argc, char*argv[])
{
using namespace std;
if(argc!=3)
{
cout<<“Usage ./a.out sourcefile destinationfile\n”;
return 0;
}
if(link(argv[1],argv[2])==-1)
{
cout<<“Can’t Link\n”;
return 1;
}
else
{
cout<<“Files have been linked\n”;
}
return 0;
}
OUTPUT
[gec@localhost ~]$ c++ program5b.cpp
[gec@localhost ~]$ ./a.out
Usage ./a.out sourcefile destinationfile
[gec@localhost ~]$ ./a.out program5b.cpp abcde
Files have been linked
[gec@localhost ~]$ cat>xyz
hi hello srinivas
[gec@localhost ~]$ ls -il program5b.cpp abcde
183646 -rw-rw-r– 8 gec gec 293 2008-01-01 01:33 abcde
183646 -rw-rw-r– 8 gec gec 293 2008-01-01 01:33 program5b.cpp
[gec@localhost ~]$ ln -s program5b.cpp pqr
[gec@localhost ~]$ ls -il program5b.cpp pqr
184006 lrwxrwxrwx 1 sln sln 13 2008-01-01 00:29 pqr -> program5b.cpp
183646 -rw-rw-r– 8 sln sln 293 2008-01-01 01:33 program5b.cpp
[gec@localhost ~]$ ./a.out program5b.cpp xyz
Can’t Link
6.Write a C/C++ program to illustrate the race condition.
/*pgm6.c*/
#include “apue.h”
#include “error.c”
static void charatatime(char *);
int main(void)
{
pid_t pid;
if((pid=fork())<0)
{
err_sys(“fork error”);
}
else if(pid==0)
{
charatatime(“output from child\n”);
}
else
{
charatatime(“output from parent\n”);
}
exit(0);
}
static void charatatime(char *str)
{
char *ptr;
int c;
setbuf(stdout,NULL);
for(ptr=str;(c=*ptr++)!=0;)
putc(c,stdout);
}
OUTPUT
[gec@localhost ~]$ vi pg6.c
[gec@localhost ~]$ cc pg6.c
[gec@localhost ~]$ ./a.out
output from child
output from parent
[gec@localhost ~]$ vi pg6.c
[gec@localhost ~]$ cc pg6.c
[gec@localhost ~]$ ./a.out
output from parent
[gec@localhost ~]$ output from child
7.Write a C/C++ program that creates a zombie and then calls system to execute the ps command to verify that the process is zombie.
/*pgm7.c*/
#include “apue.h”
#ifdef SOLARIS
#define PSCMD “ps -a -o pid,ppid,s,tty,comm”
#else
#define PSCMD “ps -o pid,ppid,state,tty,command”
#endif
int main(void)
{
pid_t pid;
if ((pid = fork()) < 0)
perror(“fork error”);
else if (pid == 0) /* child */
exit(0);
/* parent */
sleep(4);
system(PSCMD);
exit(0);
}
OUTPUT
Run 1
[gec@localhost CSE]$vi pgm7.c
[gec@localhost CSE]$ cc pgm7.c
[gec@localhost CSE]$ ./a.out
PID PPID S TT COMMAND
2913 2908 S pts/0 bash
3823 2913 S pts/0 ./a.out
3824 3823 Z pts/0 [a.out] <defunct>
3826 3823 R pts/0 ps -o pid,ppid,state,tty,command
Run 2
[gec@localhost CSE]$ ./a.out
PID PPID S TT COMMAND
2913 2908 S pts/0 bash
3835 2913 S pts/0 ./a.out
3836 3835 Z pts/0 [a.out] <defunct>
35 R pts/0 ps -o pid,ppid,state,tty,command
8.Write a C/C++ program to avoid zombie process by forking twice.
/*pgm8.c*/
#include “apue.h”
#include “error.c”
#include<sys/wait.h>
int main(void)
{
pid_t pid;
if((pid=fork())<0)
{
err_sys(“fork error”);
}
else if(pid==0)
{
if((pid=fork())<0)
exit(0);
sleep(2);
printf(“second child, parent pid=%d\n”,getppid());
exit(0);
}
if(waitpid(pid,NULL,0)!=pid)
err_sys(“waitpid error”);
exit(0);
}
OUTPUT
Run 1
[gec@localhost CSE]$vi pgm8.c
[gec@localhost CSE]$ cc pgm8.c
[gec@localhost CSE]$ ./a.out
second child, parent pid=3876
second child, parent pid=3875
Run 2
[gec@localhost CSE]$ ./a.out
second child, parent pid=3888
second child, parent pid=3887
Run 3
[gec@localhost CSE]$ ./a.out
second child, parent pid=3280
second child, parent pid=1
9.Write a C/C++ program to implement the system function.
/*pgm9.c*/
#include<stdio.h>
#include<sys/wait.h>
#include<errno.h>
#include<unistd.h>
main()
{
char cmd[10];
printf(“enter the command:\n”);
scanf(“%s”,cmd);
system(cmd);
}
int
system(const char *cmdstring) /* version without signal handling */
{
pid_t pid;
int status;
if (cmdstring == NULL)
return(1); /* always a command processor with UNIX */
if ((pid = fork()) < 0) {
status = -1; /* probably out of processes */
} else if (pid == 0) { /* child */
execl(“/bin/sh”, “sh”, “-c”, cmdstring, (char *)0);
_exit(127); /* execl error */
} else { /* parent */
while (waitpid(pid, &status, 0) < 0) {
if (errno != EINTR) {
status = -1; /* error other than EINTR from waitpid() */
break;
}
}
}
return(status);
}
OUTPUT
Run 1
[gec@localhost CSE]$vi pgm9.c
[gec@localhost CSE]$ cc pgm9.c
[gec@localhost CSE]$ ./a.out
enter the command: date
Fri april 20 06:23:34 IST 2017
Run 2
[gec@localhost CSE]$ ./a.out
enter the command: cal
TUE APRIL 2017
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
0 31
10.Write a C/C++ program to set up a real-time clock interval timer using the alarm API.
/*pgm10.c*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<errno.h>
#define INTERVAL 10
void wakeup()
{
alarm(INTERVAL);
printf(“hello\n”);
printf(“————\n”);
}
int main()
{
int i;
struct sigaction action;
action.sa_handler=wakeup;
action.sa_flags=SA_RESTART;
sigemptyset(&action.sa_mask);
if(sigaction(SIGALRM,&action,0)==-1)
{
perror(“sigaction”);
}
alarm(10);
for(i=0;i<5;i++)
{
printf(“wainting for alarm\n”);
sleep(10);
}
return 0;
}
OUTPUT
[gec@localhost ~]$ cc p10.c
[gec@localhost ~]$ ./a.out
wainting for alarm
hello
————
wainting for alarm
hello
————
wainting for alarm
hello
————
wainting for alarm
hello
————
wainting for alarm
hello
————
Write a C program to implement the syntax-directed definition of “if E then S1”
and “if E then S1 else S2”.
#include<ctype.h>
#include<string.h>
char input[60],stmt[3][60];
int len,cur,i,j;
void gen()
{
int l1=101,l2=102,l3=103;
printf(“if %s goto %d\n”,stmt[0],l1);
printf(“goto %d\n”,l2);
printf(“%d:%s\n”,l1,stmt[1]);
if(cur<3)
printf(“%d:STOP\n”,l2);
else
{
printf(“goto %d\n”,l3);
printf(“%d %s\n”,l2,stmt[2]);
printf(“%d:STOP\n”,l3);
}
}
int main()
{
printf(“format of if stmt\n example\n”);
printf(“if(a<b)then(s=a);\n”);
printf(“if(a<b)then(s=a)else(s=b);\n”);
printf(“enter stmt:”);
gets(input);
len=strlen(input);
int index=0;
for(i=0;i<len && input[i]!=’;’;i++)
if(input[i]=='(‘)
{
index=0;
for(j=i;input[j-1]!=’)’;j++)
stmt[cur][index++]=input[j];
cur++;
i=j;
}
gen();
return 0;
}
output:
[gec@localhost ~]$ cc pgm11.c
/tmp/ccGqFjJI.o: In function `main’:
pgm11.c:(.text+0x113): warning: the `gets’ function is dangerous and should not be used.
[gec@localhost ~]$ ./a.out
format of if stmt
example
if(a<b)then(s=a);
if(a<b)then(s=a)else(s=b);
enter stmt:if(a<b)then(s=a);
if (a<b) goto 101
goto 102
101:(s=a)
102:STOP
[sln@localhost ~]$ ./a.out
format of if stmt
example
if(a<b)then(s=a);
if(a<b)then(s=a)else(s=b);
enter stmt:if(a<b)then(s=a)else(s=b);
if (a<b) goto 101
goto 102
101:(s=a)
goto 103
102 (s=b)
103:STOP
Write a yacc program that accepts a regular expression as input and produce its
parse tree as output.
%{
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
int getREindex(const char*);
signed char productions[MAX][MAX];
int count=0,i,j;
char temp[MAX+MAX],temp2[MAX+MAX];
%}
%token ALPHABET
%left’|’
%left’.’
%nonassoc’*”+’
%%
S:re’\n'{
printf(“this is the rightmost derivation–\n”);
for(i=count-1;i>=0;–i){
if(i==count-1){
printf(“\n re=>”);
strcpy(temp,productions[i]);
printf(“%s”,productions[i]);
}
else{
printf(“\n=>”);
j=getREindex(temp);
temp[j]=’\0′;
sprintf(temp2,”%s%s%s”,temp,productions[i],(temp+j+2));
printf(“%s”,temp2);
strcpy(temp,temp2);
}
}
printf(“\n”);
exit(0);
}
re:ALPHABET{
temp[0]=yylval;temp[1]=’\0′;
strcpy(productions[count++],temp);
}
|'(‘re’)’
{
strcpy(productions[count++],”(re)”);}
|re’*’
{strcpy(productions[count++],”re*”);}
|re’+’
{strcpy(productions[count++],”re+”);}
|re’|’re
{strcpy(productions[count++],”re|re”);}
|re’.’re
{strcpy(productions[count++],”re.re”);};
%%
int main(int argc,char **argv)
{
yyparse();
return 0;
}
yylex()
{
signed char ch=getchar();
yylval=ch;
if(isalpha(ch))
return ALPHABET;
return ch;
}
yyerror()
{
fprintf(stderr,”invalid regular expression!!\n”);
exit(1);
}
int getREindex(const char*str)
{
int i=strlen(str)-1;
for(;i>=0;–i){
if(str[i]==’e’&&str[i-1]==’r’)
return i-1;
}
}
output:
[gec@localhost ~]$ yacc -d pm12.y
[gec@localhost ~]$ cc y.tab.c
[gec@localhost ~]$ ./a.out
a+|b*|(b.c*)
this is the rightmost derivation–
re=>re|re
=>re|(re)
=>re|(re.re)
=>re|(re.re*)
=>re|(re.c*)
=>re|(b.c*)
=>re|re|(b.c*)
=>re|re*|(b.c*)
=>re|b*|(b.c*)
=>re+|b*|(b.c*)
=>a+|b*|(b.c*)
Click on below link to download USP LAB manual.
https://seenubabueducom.files.wordpress.com/2017/05/usplabmanual.docx