Finalize:
1. Finalize() belongs to the Object class. 2. It is automatically called by the Garbage Collection mechanism when the object goes out of the scope(usually at the end of the program 3. It is slower method and not suitable for instant disposing of the objects. 4. It is non-deterministic function i.e., it is uncertain when Garbage Collector will call Finalize() method to reclaim memory. 5. Example: class employee { //This is the destructor of emp class ~employee() { } //This destructor is implicitly compiled to the Finalize method. } Dispose: 1. Dispose() belongs to the IDisposable interface 2. We have to manually write the code to implement it(User Code) ex: if we have emp class we have to inherit it from the IDisposable interface and write code. We may have to suppress the Finalize method using GC.SuppressFinalize() method. 3. Faster method for instant disposal of the objects. 4. It is deterministic function as Dispose() method is explicitly called by the User Code. 5. Example: user interface Controls. Forms, SqlConnection class have built in implementaion of Dispose method. try { string constring = "Server=(local);Database=my; User Id=sa; Password=sa"; SqlConnection sqlcon = new SqlConnection(constring); sqlcon.Open(); // here connection is open // some code here which will be execute } catch { // code will be execute when error occurred in try block } finally { sqlcon.Close(); // close the connection sqlcon.Dispose(); // detsroy the connection object } |
Saturday, 9 January 2016
disposal and finalyuse
Friday, 8 January 2016
Tuesday, 13 October 2015
Sqltransaction
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SqlTransactionClassinAdodotNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn;
SqlCommand comm1, comm2, comm3;
SqlTransaction trans;
SqlDataAdapter adapter1, adapter2;
DataSet ds1, ds2;
string constring = @"Data Source=BHARTIJILEDAR\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=1234";
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(constring);
conn.Open();
comm1 = new SqlCommand("select userid from userdet", conn);
SqlDataReader reader = comm1.ExecuteReader();
while (reader.Read())
{
cmbuserid.Items.Add(reader[0]);
}
reader.Close();
conn.Close();
}
private void btnshowrecord_Click(object sender, EventArgs e)
{
adapter1 = new SqlDataAdapter("select * from userdet", constring);
adapter2 = new SqlDataAdapter("select * from moneytrans1", constring);
ds1 = new System.Data.DataSet();
adapter1.Fill(ds1);
ds2 = new System.Data.DataSet();
adapter2.Fill(ds2);
dgvforuserdet.DataSource = ds1.Tables[0];
dgvformoneytrans1.DataSource = ds2.Tables[0];
}
private void btnok_Click(object sender, EventArgs e)
{
if (txtamount.Text == "" || cmbuserid.Text == "")
{
MessageBox.Show("Plz, Write Amout");
}
else
{
conn = new SqlConnection(constring);
conn.Open();
comm2 = new SqlCommand("insert into moneytrans1 values(" + cmbuserid.SelectedItem.ToString() + "," + txtamount.Text + ")", conn);
comm3 = new SqlCommand("update userdet set amount=amount-'" + txtamount.Text + "' where userid="+ cmbuserid.SelectedItem.ToString()+" ", conn);
trans = conn.BeginTransaction();
comm2.Transaction = trans;
comm3.Transaction = trans;
try
{
comm2.ExecuteNonQuery();
comm3.ExecuteNonQuery();
trans.Commit();
MessageBox.Show("Transaction Complted. ");
}
catch (Exception)
{
trans.Rollback();
MessageBox.Show("Transaction Failed..");
}
}
conn.Close();
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SqlTransactionClassinAdodotNet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection conn;
SqlCommand comm1, comm2, comm3;
SqlTransaction trans;
SqlDataAdapter adapter1, adapter2;
DataSet ds1, ds2;
string constring = @"Data Source=BHARTIJILEDAR\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=1234";
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(constring);
conn.Open();
comm1 = new SqlCommand("select userid from userdet", conn);
SqlDataReader reader = comm1.ExecuteReader();
while (reader.Read())
{
cmbuserid.Items.Add(reader[0]);
}
reader.Close();
conn.Close();
}
private void btnshowrecord_Click(object sender, EventArgs e)
{
adapter1 = new SqlDataAdapter("select * from userdet", constring);
adapter2 = new SqlDataAdapter("select * from moneytrans1", constring);
ds1 = new System.Data.DataSet();
adapter1.Fill(ds1);
ds2 = new System.Data.DataSet();
adapter2.Fill(ds2);
dgvforuserdet.DataSource = ds1.Tables[0];
dgvformoneytrans1.DataSource = ds2.Tables[0];
}
private void btnok_Click(object sender, EventArgs e)
{
if (txtamount.Text == "" || cmbuserid.Text == "")
{
MessageBox.Show("Plz, Write Amout");
}
else
{
conn = new SqlConnection(constring);
conn.Open();
comm2 = new SqlCommand("insert into moneytrans1 values(" + cmbuserid.SelectedItem.ToString() + "," + txtamount.Text + ")", conn);
comm3 = new SqlCommand("update userdet set amount=amount-'" + txtamount.Text + "' where userid="+ cmbuserid.SelectedItem.ToString()+" ", conn);
trans = conn.BeginTransaction();
comm2.Transaction = trans;
comm3.Transaction = trans;
try
{
comm2.ExecuteNonQuery();
comm3.ExecuteNonQuery();
trans.Commit();
MessageBox.Show("Transaction Complted. ");
}
catch (Exception)
{
trans.Rollback();
MessageBox.Show("Transaction Failed..");
}
}
conn.Close();
}
}
}
Sunday, 11 October 2015
Sign In with valid user with execute scaler
private int IsValidUser()
{
int result = 0;
string strQuery = "Select Email From AUser Where Email = @Email And Password = @Password ";
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand Cmd = new SqlCommand(strQuery, con);
//Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
Cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
con.Open();
result = (int)Cmd.ExecuteScalar();
if (result > 0)
{
//Session["SessionEmail"] = txtEmail.Text;
Session[General.S_USEREMAIL] = txtEmail.Text;
Response.Redirect("~/frmMyAccountMyProfile.aspx");
}
else
{
Literal1.Text = "Invalid Email/Password!";
}
}
Saturday, 3 October 2015
datatable concept
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
dt.Columns.Add("SSN", typeof(string));
dt.Columns.Add("NAME", typeof(string));
dt.Columns.Add("ADDR", typeof(string));
dt.Columns.Add("AGE", typeof(int));
DataColumn[] KEY = new DataColumn[1];
KEY[0] = dt.Columns[0];
dt.PrimaryKey = KEY;
dt.Rows.Add("203456843", "BHARTIJILEDAR", "13 Main Ct, Newyork, NY", 27);
dt.Rows.Add("203456877", "SAM", "13 Main Ct, Newyork, NY", 25);
dt.Rows.Add("203456878", "Elan", "14 Main Street, Newyork, NY", 35);
dt.Rows.Add("203456879", "Smith", "12 Main Street, Newyork, NY", 45);
dt.Rows.Add("203456880", "SAM", "345 Main Ave, Dayton, OH", 55);
dt.Rows.Add("203456881", "Sue", "32 Cranbrook Rd, Newyork, NY", 65);
dt.Rows.Add("203456882", "Winston", "1208 Alex St, Newyork, NY", 65);
dt.Rows.Add("203456883", "Mac", "126 Province Ave, Baltimore, NY", 85);
dt.Rows.Add("203456884", "SAM", "126 Province Ave, Baltimore, NY", 95);
//RETREAVING THE DATA HAVING NAME NOT BE SAME
foreach (DataRow o in dt.Select("NAME <> 'SAM'"))
{
//MessageBox.Show("\t" + DR["SSN"] + "\t" + DR["NAME"] + "\t" + DR["ADDR"] + "\t" + DR["AGE"]);
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" CHECKING THE AGE GREATER THEN 60");
foreach (DataRow o in dt.Select("AGE>60").Take(2))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" AGE IN DECENDING ORDER");
foreach (DataRow o in dt.Select( " ", "AGE DESC"))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add("name ascending order");
foreach (DataRow o in dt.Select(" ", "NAME ASC"))
{ listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
// Console.WriteLine(" The average of all the person's age is: " + avgAge);
listBox1.Items.Add(" getting the name of most age person in the list");
DataRow MOSTAGEDPERSON = dt.Select("", "AGE ASC").Last();
{
listBox1.Items.Add("\t" + MOSTAGEDPERSON["SSN"] + "\t" + "\t" + MOSTAGEDPERSON["NAME"] + "\t" + "\t" + MOSTAGEDPERSON["ADDR"] + "\t" + MOSTAGEDPERSON["AGE"]);
}
listBox1.Items.Add(" PERSON HAVING AGE GREATER THEN 60");
foreach (DataRow o in dt.Select().SkipWhile(m => (int)m.ItemArray[3] < 60))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" Displaying the persons until we find a person with name starts with other than 'S'");
foreach (DataRow o in dt.Select().Where(m => m.ItemArray[1].ToString().StartsWith("S")))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + o["NAME"] + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add("\n Checking all the persons have SSN or not ...");
if (dt.Select().All(m => m.ItemArray[0] != null))
{
listBox1.Items.Add("\t No person is found without SSN");
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
listBox1.Items.Add("\n Finding the person whose SSN = 203456876 in the list");
foreach (DataRow o in dt.Select("SSN = '203456876'"))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + o["NAME"] + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
Console.Read();
listBox1.Items.Add("HECKING THE AGE BETWEEN 13 AND 19 WCHICH IS CALLED TEEN AGE");
if (dt.Select("AGE >= 13 AND AGE <= 19").Any())
{
MessageBox.Show("yeS WE HAVE TEEN AGERS IN LIST");
}
else
{
MessageBox.Show("NO, WE nO HAVE TEEN AGERS IN LIST");
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
Console.WriteLine("\n Checking whether a person having name 'SAM' exists or not...");
if (dt.Select().Any(m => m.ItemArray[1].ToString() == "SAM"))
{
MessageBox.Show("Person having the NAme Sam");
}
Console.WriteLine("\n Getting Average of all the person's age...");
double Sumage = dt.Select("").Average(m => (int)m.ItemArray[3]);
// double avgAge = dt.Select("").Average(m => (int)m.ItemArray[3]);
MessageBox.Show("The Sum Of All Person Age Is" + Sumage);
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
dt.Columns.Add("SSN", typeof(string));
dt.Columns.Add("NAME", typeof(string));
dt.Columns.Add("ADDR", typeof(string));
dt.Columns.Add("AGE", typeof(int));
DataColumn[] KEY = new DataColumn[1];
KEY[0] = dt.Columns[0];
dt.PrimaryKey = KEY;
dt.Rows.Add("203456843", "BHARTIJILEDAR", "13 Main Ct, Newyork, NY", 27);
dt.Rows.Add("203456877", "SAM", "13 Main Ct, Newyork, NY", 25);
dt.Rows.Add("203456878", "Elan", "14 Main Street, Newyork, NY", 35);
dt.Rows.Add("203456879", "Smith", "12 Main Street, Newyork, NY", 45);
dt.Rows.Add("203456880", "SAM", "345 Main Ave, Dayton, OH", 55);
dt.Rows.Add("203456881", "Sue", "32 Cranbrook Rd, Newyork, NY", 65);
dt.Rows.Add("203456882", "Winston", "1208 Alex St, Newyork, NY", 65);
dt.Rows.Add("203456883", "Mac", "126 Province Ave, Baltimore, NY", 85);
dt.Rows.Add("203456884", "SAM", "126 Province Ave, Baltimore, NY", 95);
//RETREAVING THE DATA HAVING NAME NOT BE SAME
foreach (DataRow o in dt.Select("NAME <> 'SAM'"))
{
//MessageBox.Show("\t" + DR["SSN"] + "\t" + DR["NAME"] + "\t" + DR["ADDR"] + "\t" + DR["AGE"]);
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" CHECKING THE AGE GREATER THEN 60");
foreach (DataRow o in dt.Select("AGE>60").Take(2))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" AGE IN DECENDING ORDER");
foreach (DataRow o in dt.Select( " ", "AGE DESC"))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add("name ascending order");
foreach (DataRow o in dt.Select(" ", "NAME ASC"))
{ listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
// Console.WriteLine(" The average of all the person's age is: " + avgAge);
listBox1.Items.Add(" getting the name of most age person in the list");
DataRow MOSTAGEDPERSON = dt.Select("", "AGE ASC").Last();
{
listBox1.Items.Add("\t" + MOSTAGEDPERSON["SSN"] + "\t" + "\t" + MOSTAGEDPERSON["NAME"] + "\t" + "\t" + MOSTAGEDPERSON["ADDR"] + "\t" + MOSTAGEDPERSON["AGE"]);
}
listBox1.Items.Add(" PERSON HAVING AGE GREATER THEN 60");
foreach (DataRow o in dt.Select().SkipWhile(m => (int)m.ItemArray[3] < 60))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + "\t" + o["NAME"] + "\t" + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add(" Displaying the persons until we find a person with name starts with other than 'S'");
foreach (DataRow o in dt.Select().Where(m => m.ItemArray[1].ToString().StartsWith("S")))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + o["NAME"] + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
listBox1.Items.Add("\n Checking all the persons have SSN or not ...");
if (dt.Select().All(m => m.ItemArray[0] != null))
{
listBox1.Items.Add("\t No person is found without SSN");
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
listBox1.Items.Add("\n Finding the person whose SSN = 203456876 in the list");
foreach (DataRow o in dt.Select("SSN = '203456876'"))
{
listBox1.Items.Add("\t" + o["SSN"] + "\t" + o["NAME"] + "\t" + o["ADDR"] + "\t" + o["AGE"]);
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
Console.Read();
listBox1.Items.Add("HECKING THE AGE BETWEEN 13 AND 19 WCHICH IS CALLED TEEN AGE");
if (dt.Select("AGE >= 13 AND AGE <= 19").Any())
{
MessageBox.Show("yeS WE HAVE TEEN AGERS IN LIST");
}
else
{
MessageBox.Show("NO, WE nO HAVE TEEN AGERS IN LIST");
}
Console.WriteLine("\n-----------------------------------------------------------------------------");
Console.WriteLine("\n Checking whether a person having name 'SAM' exists or not...");
if (dt.Select().Any(m => m.ItemArray[1].ToString() == "SAM"))
{
MessageBox.Show("Person having the NAme Sam");
}
Console.WriteLine("\n Getting Average of all the person's age...");
double Sumage = dt.Select("").Average(m => (int)m.ItemArray[3]);
// double avgAge = dt.Select("").Average(m => (int)m.ItemArray[3]);
MessageBox.Show("The Sum Of All Person Age Is" + Sumage);
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Use Sql Parameter in C#
public string GetConnectionString()
{
//we will set up the configuration which will call our
//web.config file to provide the database details because
//in configuration file we have created the <connectionStrings>
//in the process we draged and droped. It creates automatically.
//We normally put the database details in web.config file or
//machine.config file because it is very sensitive information
//usually there IP address of remote database, passwords and
//user names are stored.
return System.Configuration.ConfigurationManager.ConnectionStrings
["onlineapplicationformConnectionString1"].ConnectionString;
//in above line "onlineapplicationformConnectionString1" is
//our configuration name which is inside the web.config file.
}
private void execution(string fname, string lname, string dob, string gender, string fathername, string contact, string address)
{
//In above line we declaring different variables same as backend
SqlConnection conn = new SqlConnection(GetConnectionString());
//In above line we are calling connection
//string function which is defined already on top
string sql = "INSERT INTO regiistrationform (fname, lname, dob, gender, fathername, contact, per_address) VALUES "
+ " (@fname, @lname, @dob, @gender, @fathername, @contact, @per_address)";
//In above lines we are just storing the sql commands which
//will insert value in onlineapplication named table,
//using variable named sql.
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
//In above lines we are opening the connection to work and
//also storing connection name and sql command in cmd variable
//which has 'SqlCommand' type.
SqlParameter[] pram = new SqlParameter[7];
//In above lines we are defining 7 sql parameters will be use
//In below lines we will not disscuss about id column
pram[0] = new SqlParameter("@fname", SqlDbType.VarChar, 10);
pram[1] = new SqlParameter("@lname", SqlDbType.VarChar, 50);
pram[2] = new SqlParameter("@dob", SqlDbType.VarChar, 50);
pram[3] = new SqlParameter("@gender", SqlDbType.Char, 10);
pram[4] = new SqlParameter("@fathername", SqlDbType.VarChar, 50);
pram[5] = new SqlParameter("@contact", SqlDbType.Int, 20);
pram[6] = new SqlParameter("@per_address", SqlDbType.VarChar, 100);
//Now we set-uped all fiels in database in above lines
//Now we will set-up form fields
pram[0].Value = fname;
pram[1].Value = lname;
pram[2].Value = Convert.ToDateTime ( dob);
pram[3].Value = gender;
pram[4].Value = fathername;
pram[5].Value = Convert.ToInt32( contact);
pram[6].Value = address;
//Now create loop to insert
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch(System.Data.SqlClient.SqlException ex_msg)
{
//Here will be catch elements
string msg = "Error occured while inserting";
msg += ex_msg.Message;
throw new Exception(msg);
}
finally
{
//Here will be fially elements
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submit_Click(object sender, EventArgs e)
{
//Here is the command inside the click event of button
if(fname.Text=="")
{
Response.Write("Please complete the form.");
}
else
{
execution(fname.Text,lname.Text,dob.Text,gender.Text,fathername.Text,contact.Text,address.Text);
conform.Visible = true;
fname.Text="";
lname.Text="";
dob.Text="";
gender.Text="";
gender.Text="";
fathername.Text="";
contact.Text="";
address.Text="";
}
}
protected void gender_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
//In above line we are calling connection
//string function which is defined already on top
conn.Open();
string sql = "select * from regiistrationform";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt =new DataTable();
adapter.Fill(dt);
string strName =dt.Rows.Add("fname").ToString();
foreach (DataRow dr in dt.Rows )
{
}
}
}
Call By References
class PassingRefByRef
{
static void Change(ref int[] pArray)
{
// Both of the following changes will affect the original variables:
pArray[0] = 888;
pArray = new int[5] { -3, -1, -2, -3, -4 };
System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
Console.ReadLine();
}
static void Main()
{
int[] array = { 2, 3, 6, 7 };
System.Console.WriteLine("The No Before Calling the ,The first element is{0}", array[0]);
int[] arr = { 1, 4, 5 };
System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);
Change(ref arr);
System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
Console.ReadLine();
}
}
Subscribe to:
Posts (Atom)