Sunday, 23 August 2015

INSERT-3 TIER

INSERT
DAL:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;


public class insertdal
{
      SqlCommand cmd;

      connectiondal conobj = new connectiondal();

      public void insertdetails(string name, int age, System.DateTime dob)
      {
            cmd = new SqlCommand("stp_insert", conobj.Connection);
            cmd.CommandType = CommandType.StoredProcedure;

            try {

                  cmd.Parameters.AddWithValue("@name", name);
                  cmd.Parameters.AddWithValue("@age", age);
                  cmd.Parameters.AddWithValue("@dob", dob);
                  cmd.ExecuteNonQuery();


            } catch (Exception ex) {
                  throw ex;
            }


      }

}
BAL:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class insertbal
{
      insertdal obj = new insertdal();
      public void insertdetails(string name, int age, System.DateTime dob)
      {
            obj.insertdetails(name, age, dob);
      }
}
PL:


using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
public class Form1
{
      insertbal OBJ = new insertbal();

      private void Button1_Click(System.Object sender, System.EventArgs e)
      {
            OBJ.insertdetails(TextBox1.Text, TextBox2.Text, DateTimePicker1.Value);

      }
}


Wednesday, 19 August 2015

Fastest method to trim all whitespace from Strings in .NET

 Method 1

        static Regex whitespace = new Regex(@"\s+");

        private void btnOK_Click(object sender, EventArgs e)
          
        {
            string str = txt1.Text;
            txt2.Text = whitespace.Replace(str, "");
        }


Method 2


 private void btnOK_Click(object sender, EventArgs e)
                 
 {
            string str = txt1.Text;
            txt2.Text = string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
       
}


Occurance Of A string

<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
   
    </div>
    </form>
</body>


    protected void Button1_Click(object sender, EventArgs e)
        {
            int occuranceCount = 0;

            //Checking Occurance
            occuranceCount = Regex.Matches(TextBox1.Text.ToLower().Trim(), TextBox2.Text.ToLower().Trim()).Count;
            if (occuranceCount > 0)
                Label1.Text = "The given string pattern <i>" + TextBox2.Text + "</i> Contains " + occuranceCount + " times in  <i>"
                    + TextBox1.Text + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
            else
                Label1.Text = "The given string pattern <i>" + TextBox2.Text + "</i> Is not occured  in  <i>"
                    + TextBox1.Text + "</i><br/><br/> Thank you for visiting. Please Visit Again!!!";
            //End

        }

Tuesday, 11 August 2015

Upload image to a pictureBox in Windows Forms

// open file dialog 
 OpenFileDialog open = new OpenFileDialog(); 
 // image filters
 open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; 
 if (open.ShowDialog() == DialogResult.OK)
{
   // display image in picture box
   pictureBox1.Image = new Bitmap(open.FileName);

  } 

Monday, 10 August 2015

Insert To DB

cmd = new SqlCommand("stp_insert", conobj.Connection);
cmd.CommandType = CommandType.StoredProcedure;

try {

cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@age", age);
cmd.Parameters.AddWithValue("@dob", dob);
cmd.ExecuteNonQuery();


} catch (Exception ex) {
throw ex;
}

Connection Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.SqlClient;

namespace stockexpert1.Datalayer
{
    public class connection
    {
        SqlConnection con = new SqlConnection("Data Source=AABASOFT-02;Initial Catalog=stockexpert;Integrated Security=True");
        public SqlConnection serverConnection()
        {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
            con.Open();
            return con;


        }
    }

}

Tuesday, 28 July 2015

Checking future date in DateTimePicker

 private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            DateTime check;

            bool valid = DateTime.TryParse(dateTimePicker1.Text, out check);
            if (valid && (check > DateTime.Now))
            {
                lblMesage.Text = "Future Date is not Allowed";
            }
        }

EntityFrameWork -Insert,Fetch,Update,Delete

Start a New Project

Start a new "ASP.NET Web Application" as shown below:

Create Database

Here, we are going to use a very simple database with name LearnEF with only one table. The table Employeewill have a list of employees with basic information about each employee. You may use the following script to create the table and a stored procedure used in this application.
CREATE TABLE Employee
(
    EmpId        int NOT NULL IDENTITY(1,1) PRIMARY KEY,
    HREmpId        nvarchar(10),
    FirstName    nvarchar(30),
    LastName    nvarchar(30),
    Address        nvarchar(30),
    City        nvarchar(30)
)
GO
 
--SearchEmployee '', ''
CREATE PROCEDURE SearchEmployee
(
    @FirstName        varchar(30),
    @City            varchar(30)
)
AS
BEGIN
    DECLARE @query    nvarchar(1000)
 
    SET @query = 'SELECT * FROM Employee e'
    SET @query = @query + ' WHERE 1=1'
 
    IF @FirstName != ''
        SET @query = @query + ' AND FirstName LIKE ''' + @FirstName + '%'''
 
    IF @City != ''
        SET @query = @query + ' AND City LIKE ''' + @City + '%'''
 
 
    EXEC (@query)
END
GO
NOTE: Some of my friends will be quick to note that above SP is susceptible to SQL Injection attacks and I agree with this. This is because I have tried to keep the code simple and easy to understand, moreover this article is about entity framework. Please ignore this issue and if you really care about this, please refer to an advanced tutorial related to SQL injection.

Create Entity Data Model

Now, let's create the entity data model. Here are the step-by-step details:
  1. Right-click on the project name, select Add -> New Item.
  2. Select the Data tab from left pane, then select ADO.NET Entity Data Model.
  3. Name it as LearnEF.edmx. Click Add.
  4. Select Generate from database in the Entity Data Model Wizard.
  5. In the next window, set the connection properties for your database and click Next.
  6. The next window will show you the objects in your database. Select the table Employee and the stored procedure SearchEmployee.
  7. Click Finish. If you have completed the above steps successfully, you will see your EDM in design mode as shown below:
Note: The name of database used in this article is LearnEF and hence the system will generate anObjectContext class with name LearnEFEntities. Similarly, the system will create a class of typeEntityObject with name Employee based upon the table name. As shown in the above snapshot, there is a stored procedure with name SearchEmployee, so the class LearnEFEntities will expose a corresponding method with name SearchEmployee.
If the name of your database/table/stored procedure is different, then remember to modify the code accordingly.

Insert a New Record

To insert a new record:
  1. Create an object of the object context, i.e., LearnEFEntities:
    LearnEFEntities db = new LearnEFEntities();
  2. Create an object of Employee class, e.g.:
    Employee objEmp = new Employee();  
  3. Set the values of all the columns which are exposed in form of properties like:
    objEmp.FirstName = txtFirstName.Text; 
  4. Add object to the Employees collection in ObjecContext and call SaveChanges to actually insert the record into the table:
    db.Employees.AddObject(objEmp); 
    db.SaveChanges();  
Here is a complete code snippet:
LearnEFEntities db = new LearnEFEntities();

Employee objEmp = new Employee();
objEmp.HREmpId = txtHREmpId.Text;
objEmp.FirstName = txtFirstName.Text;
objEmp.LastName = txtLastName.Text;
objEmp.Address = txtAddress.Text;
objEmp.City = txtCity.Text;
 
db.Employees.AddObject(objEmp);
db.SaveChanges();

Read from Employee table and populate GridView

To read data from the Employee table, we will use a LINQ query that will fetch data from the Employeescollection. It will return a generic List of objects of type Employee, i.e. List<Employee>. The complete code to read data from the Employee table and then bind a drop-down list and GridView is given below:
LearnEFEntities db = new LearnEFEntities();
 
var empQuery = from emp in db.Employees
                select emp;
List<Employee> empList = empQuery.ToList();
 
ddlEmployee.DataSource = empList;
ddlEmployee.DataValueField = "EmpId";
ddlEmployee.DataTextField = "FirstName";
ddlEmployee.DataBind();
 
ddlEmployee.Items.Insert(0, new ListItem("--Add New--", "0"));
 
//bind grid
GridView1.DataSource = empList;
GridView1.DataBind();

Update an Employee Record

To update a record in the database, we will perform the following three steps:
  1. Read a record from the database. The process is similar as explained in the above section.
  2. Set the new values of the properties (columns) that we want to modify.
  3. Save the changes into the database using SaveChages method.
 //Read the record from the database.
 LearnEFEntities db = new LearnEFEntities();
 
 //following query will fetch a record based upon the EmpID passed through local variable empId
 var empQuery = from emp in db.Employees
                 where emp.EmpId == empId
                 select emp;
 Employee objEmp = empQuery.Single();
 
 //set the new values of the columns (properties), based upon the values entered using the text boxes
 objEmp.HREmpId = txtHREmpId.Text;
 objEmp.FirstName = txtFirstName.Text;
 objEmp.LastName = txtLastName.Text;
 objEmp.Address = txtAddress.Text;
 objEmp.City = txtCity.Text;
 
 //save your changes into the database
 db.SaveChanges(); 

How to Delete a Record

There are multiple ways to delete a record using entity framework. The steps involved in the approach that we follow are:
  1. Create a new instance of the entity object that you want to delete and set the value of the property that will be used to filter the records to be deleted. In this case, we are going to create a new Employee and set the value of its EmpID property.
  2. Attach the object to the corresponding collection or entity set in object context.
  3. Mark the object for deletion using the DeleteObject() method.
  4. Delete the record from the database using the SaveChanges() method.
The following code will clarify the above mentioned steps to delete a record:
LearnEFEntities db = new LearnEFEntities();
 
//create a new object using the value of EmpId
Employee objEmp = new Employee() { EmpId = empId };
 
//attach object in the entity set
db.Employees.Attach(objEmp);

//mark the object for deletion
db.Employees.DeleteObject(objEmp);
 
//save changes
db.SaveChanges(); 

Saturday, 25 July 2015

PlaceHolder For LinkButton

protected void Page_Load(object sender, EventArgs e) { LinkButton btnLink = new LinkButton(); btnLink.ID = "btnLink_" + "1"; btnLink.Text = "1"; btnLink.CommandArgument = "1"; btnLink.Click += new EventHandler(btnLink_Click); phPaging.Controls.Add(btnLink); } protected void btnLink_Click(object sender, EventArgs e) { throw new NotImplementedException(); }