h1.post-title { color:orange; font-family:verdana,Arial; font-weight:bold; padding-bottom:5px; text-shadow:#64665b 0px 1px 1px; font-size:32px; } -->

Pages

LINQ Hints

LINQ :
  LINQ -- Language INtegrate Query.
  It supporst all .Net Language.
LINQ -- Data Provider:

  1.    LINQ To Object
  2.   LINQ To ADO.NET
  3.   LINQ To XML


     LINQ To ADO.NET:

  •              LINQ To SQL.
  •              LINQ To Entity Framework.
  •              LINQ To Dataset.

Query Basics:
         Query Expression consists of set of Clauses written in a declarative Syntax similar to SQL /XQuery.
  Query must:

  •      Begin with from Clause.
  •      End with select/Group clause.
  •      Between one or more of following clauses using
  •              Where,Join,from orderby,let,into.

Aggragate Clause:
    Select ,Distinct,Order bymTake,Takewhile,skip,skipwhile,wheremjoinmgroupbymlet,into

Two ways to write LINQ Query:

  1.    Query syntax -- Use Query
  2.    Method Syntax -- Uses Lambda Expression.

Lambda Expression:
    => Goes into Separate Parameters from method body.

LINQ To Object:

  • Object supports either IEnumerable or Ienumerable<t>
  • Array,ArrayList,Collection,Generic Collection.
  • Using System.LINQ namespace.

LINQ To SQL:
  •     Using System.Data.LINQ namespace.
  •     Requires Entity  classes which you can build using the ORD.
  •     ORD-- Object Relational Designer.
  •     E-R data models will use for Other Database.

LINQ To Dataset:

  •       Collections of data from ADO.NET and Put into Dataset or DataTable.

Destroying Threads

Thread.Abort();

Select All string in TextBox using C#.Net

Copy and Paste this Code in your TextBox Keydown Event

if ((e.Control == true) && (e.KeyCode == Keys.A))
{
textBox1.SelectAll();
}

Cannot set a value on node type 'Element'

         Today , we discussed "Cannot set a value on node type 'Element' "
Suppose user are using below code in the below Structure:

TamilNadu private void ChangeValueofXMLNodeValue(string XMLPath,string SelectedSingleTag)
{
XmlDocument doc = new XmlDocument();
doc.Load(XMLPath);
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode(SelectedSingleTag);
myNode.Value = textBox1.Text ;
doc.Save(XMLPath);
}
you will get "Cannot set a value on node type 'Element'." Solution: myNode.Value = textBox1.Text ; change myNode.InnerText = textBox1.Text ;

Set Value for SingleXMLNode usng C#.Net

            Today, we will discuss about "Set Value for SingleXMLNode usng C#.Net"
 Copy and Paste the Following Code

private void ChangeValueofXMLNodeValue(string XMLPath,string SelectedSingleTag) { XmlDocument doc = new XmlDocument(); doc.Load(XMLPath); XmlNode root = doc.DocumentElement; XmlNode myNode = root.SelectSingleNode(SelectedSingleTag); myNode.InnerText = textBox1.Text ; doc.Save(XMLPath); }

Add or Remove Datagridview in C#.Net

    Today, we discussed "Add or Remove Datagridview in C#.Net"

public void AddorRemoveRows(DataGridView DGV, CheckedListBox chk, string Mode)
{
try
{
switch (Mode)
{
case "Add":
if (chk.SelectedItem.ToString() != null)
{
string SelectedItem = chk.SelectedItem.ToString();
DGV.RowCount = DGV.RowCount + 1;
DGV.Rows[DGV.RowCount - 1].Cells[0].Value = SelectedItem;
chk.SelectedIndex = -1;
}
break;
case "Remove":
string UnSelectedItem = chk.SelectedItem.ToString();
int SelectedIndex = RowId(UnSelectedItem, DGV);
DGV.Rows.RemoveAt(SelectedIndex);
break;
}
}
catch (Exception ex)
{
Program.WriteLog(ex.Message, ex.StackTrace);
}
}
RowId Method
int rowId;
private int RowId(string unSelectedItem, DataGridView dgv)
{
for (int rowidx = 0; rowidx < dgv.Rows.Count; rowidx++)
{
if (unSelectedItem == Convert.ToString(dgv.Rows[rowidx].Cells[0].Value))
{
rowId = rowidx;
break;
}
}
return rowId;
}

Three Tier Architecture -- Windows Application

Three Tier Architecture -- Windows Application

  Introduction:
                   This Article describes How to build C Sharp Application using 3-Architecture.
Three Tier Architecture:
      Application /Presentation Layer >>Business Logic Layer >> Data Access Layer.
First, we start with Data Access Layer.
Data Access Layer:
                    The following information used in the Data Access Layer:
Queries.
Connection String.
Class Name: DLLoginMaster.
Table Name: tbl_LoginMaster
Table Description:  This table contains login Master Data.
Table Fields,Description and Field Type:            
   Id – This is a Primary Key of this Table.Login Id Stores here.It is Auto Increment.[int]
  Username – Login User name stores here.[Varchar(50)]
  Password – Password of Username.Password stores here.[Varchar(50)].
  FirstName—First Name of the User. First Name stores here. .[Varchar(50)]
  LastName – Last Name of the User. Last Name stores here. .[Varchar(50)]
  Active – user may alive or not .[bit].

Now, we go to Coding Section .
Create One Class file under DataLayer Folder.before, we create three folders in the your Project.
1)ApplicationLayer.2)BusinessLayer.3)DataLayer.
Step by Step:
Call SQLClient namespace in the Code page.
TextBox1 : txtUserNamet TextBox2 : txtPasswordt TextBox3 : txtFirstNamet TextBox4 : txtLastName Check Box: ChkActive Button1:Add Button2:Update Button3:Delete DataGridView:DGVFillData
using System.Data.SqlClient; private SqlConnection Con; // Set your Server Name,DatabaseName,User Name and Password. private string ConStr = "Server=;Database=;User Id=;Password="; Copy the Code and Paste in your Class File public DLLoginMaster () { } public bool InsertintoTable(BLLoginMaster BLUserMas) { string query = "insert into tbl_LoginMaster(Username,Password,FirstName,LastName,Active) values('"+ BLUserMas.UserName +"','"+ BLUserMas.Password+"','"+ BLUserMas.FirstName +"','"+ BLUserMas.LastName+"','"+BLUserMas.Active +"')"; Con = new SqlConnection(ConStr); Con.Open(); SqlCommand cmd = new SqlCommand(query, Con); try { cmd.ExecuteNonQuery(); Con.Close(); result = true; } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); result = false; } finally { cmd.Dispose(); Con.Close(); Con.Dispose(); } return result; } public bool UpdateintoTable(BLLoginMaster BLUserMas) { string query = "update tbl_LoginMaster set Username='" + BLUserMas.UserName + "',Password='" + BLUserMas.Password + "',FirstName ='" + BLUserMas.FirstName + "',LastName='" + BLUserMas.LastName + "',Active='" + BLUserMas.Active + "' where id='" + BLUserMas.UserId + "' "; Con = new SqlConnection(ConStr); Con.Open(); SqlCommand cmd = new SqlCommand(query, Con); try { cmd.ExecuteNonQuery(); Con.Close(); result = true; } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); result = false; } finally { cmd.Dispose(); Con.Close(); Con.Dispose(); } return result; } public bool DeletefromTable(BLLoginMaster BLUserMas) { string query = "delete from tbl_LoginMaster where id='" + BLUserMas.UserId + "' "; Con = new SqlConnection(ConStr); Con.Open(); SqlCommand cmd = new SqlCommand(query, Con); try { cmd.ExecuteNonQuery(); Con.Close(); result = true; } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); result = false; } finally { cmd.Dispose(); Con.Close(); Con.Dispose(); } return result; } public DataSet FillData() { DataSet ds = null; try { string query = "Select distinct Username as [User Name],Password,FirstName as [First Name],LastName as [Last Name],Active from tbl_LoginMaster"; Con = new SqlConnection(ConStr); Con.Open(); SqlDataAdapter da = new SqlDataAdapter(query, Con); ds = new DataSet(); da.Fill(ds); Con.Close(); } catch (Exception e) { Program.WriteLog(e.Message, e.StackTrace); } return ds; } public string GetUserId(string str) { string query = "Select distinct id from tbl_LoginMaster where Password='" + str + "' "; Con = new SqlConnection(ConStr); Con.Open(); SqlCommand cmd = new SqlCommand(query, Con); try { SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adapter.Fill(dt); if (dt.Rows.Count > 0) { DataColumn col = dt.Columns["id"]; foreach (DataRow row in dt.Rows) { id = row[col].ToString(); } } Con.Close(); return id; } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); return id; } finally { cmd.Dispose(); Con.Close(); Con.Dispose(); } } bool returnvalue; public bool CheckPassowrd(string Passwrd) { string query = "Select distinct password from userMaster where password='" + Passwrd + "'"; Con = new SqlConnection(ConStr); Con.Open(); SqlCommand cmd = new SqlCommand(query, Con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adapter.Fill(dt); if (dt.Rows.Count > 0) { returnvalue = true; } Con.Close(); return returnvalue; }
Here , We declare BLLoginMaster.Why we Declare BLLoginMaster?.Passing Data from BLLoginMaster to DLLoginMaster. Business Layer : The following information used in the Business Layer: Create Methods/Functions Create Properties. Class Name: BLLoginMaster
using System.Data; using System.Windows.Forms; private static int _UserId; private static string _UserName; private static string _Password; private static string _Firstname; private static string _LastName; private static bool _Active; private DLLoginMaster DLUser; /// Property User Name /// public int UserId { get { return _UserId; } set { _UserId = value; } } /// /// Property User Name /// public string UserName { get { return _UserName; } set { _UserName = value; } } /// /// Property Password /// public string Password { get { return _Password; } set { _Password = value; } } /// /// Property FirstName /// public string FirstName { get { return _Firstname; } set { _Firstname = value; } } /// /// Property LastName /// public string LastName { get { return _LastName; } set { _LastName = value; } } /// /// Property Active /// public bool Active { get { return _Active; } set { _Active = value; } } public bool SaveRecord() { bool Output; DLUser = new DLLoginMaster (); Output = DLUser.InsertintoTable(this); return Output; } public bool UpdateRecord() { bool Output; DLUser = new DLLoginMaster (); Output = DLUser.UpdateintoTable(this); return Output; } public bool DeleteRecord() { bool Output; DLUser = new DLLoginMaster (); Output = DLUser.DeletefromTable(this); return Output; } public DataSet FillData() { DataSet ds = null; DLUser = new DLLoginMaster (); ds = DLUser.FillData(); return ds; } public string GetUserId(string str) { string Rid; DLUser = new DLLoginMaster (); Rid = DLUser.GetUserId(str); return Rid; } public bool CheckPassword(TextBox txt) { bool Output; DLUser = new DLLoginMaster (); Output = DLUser.CheckPassowrd(txt.Text); if (Output) { Output = true; } else { Output = false; } return Output; } Application Layer: Drag and Drop Items: No of TextBoxes = 4 No of Check Box =1 No Of Button =3 No of DataGridview =1
using .BusinessLayer; private BLLoginMaster BLUserMas; bool SaveStatus; private void FillData() { BLUserMas = new BLLoginMaster (); DGFillData.DataSource = BLUserMas.FillData().Tables[0]; } private void btn_Add_Click(object sender, EventArgs e) { InsertIntoTable(); } private void btn_Update_Click(object sender, EventArgs e) { UpdateIntoTable(); } private void btn_Delete_Click(object sender, EventArgs e) { DeleteFromTable(); } private void InsertIntoTable() { try { BLUserMas = new BLLoginMaster (); BLUserMas.UserName = txtUsername.Text.ToString(); BLUserMas.Password = txtPassword.Text.ToString(); BLUserMas.FirstName = txtFirstname.Text.ToString(); BLUserMas.LastName = txtLastname.Text.ToString(); if (chkActive.Checked) { BLUserMas.Active = true; } else { BLUserMas.Active = false; } if (txtPassword.Text != "") { BLUserMas = new BLLoginMaster (); bool Result = BLUserMas.CheckPassword(txtPassword); if (Result) { MessageBox.Show("Password Already Exists"); } else { SaveStatus = BLUserMas.SaveRecord(); } } if (SaveStatus) { MessageBox.Show("Saved Successfully"); FillData(); } } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); } } private void UpdateIntoTable() { try { BLUserMas = new BLLoginMaster (); BLUserMas.UserName = txtUsername.Text.ToString(); BLUserMas.Password = txtPassword.Text.ToString(); BLUserMas.FirstName = txtFirstname.Text.ToString(); BLUserMas.LastName = txtLastname.Text.ToString(); if (chkActive.Checked) { BLUserMas.Active = true; } else { BLUserMas.Active = false; } int Index = DGFillData.CurrentRow.Index; string userId = BLUserMas.GetUserId(Convert.ToString(DGFillData.Rows[Index].Cells[1].Value)); BLUserMas.UserId = Convert.ToInt32(userId); if (chkActive.Checked) { BLUserMas.Active = true; } else { BLUserMas.Active = false; } bool Status = BLUserMas.UpdateRecord(); if (Status) { MessageBox.Show("Updated Successfully", "Gantec"); FillData(); } } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); } } private void DeleteFromTable() { try { BLUserMas = new BLLoginMaster (); int Index = DGFillData.CurrentRow.Index; BLUserMas.UserId = Convert.ToInt32(DGFillData.Rows[Index].Cells[0].Value); bool Status = BLUserMas.DeleteRecord(); if (Status) { MessageBox.Show("Deleted Successfully"); FillData(); } } catch (Exception ex) { Program.WriteLog(ex.Message, ex.StackTrace); } }
Conclusion: Thanks for Reading this Article.

TextBox Validation Control for Windows Application

               Today , we will discuss about step by step creation of User control and How to handle in the Windows Application? Validation is an important part of Development as well as Application side. No Validation Control for windows Application.
Purpose of this Article:
         Text Box Validation[Int,Double and String].
         Using Enumeraion in the User control.
         Call the User control in the another Project.
Create User Control in C#.Net:
         Name of the User Control: ValidateTextBox
         File Extension : .dll.
In Project Section:
Open your VS 2008/2005.
      Select “Class Library” in the VS Template. 
         Type “Class Library” name in the Name Input Box Eg: ValidateTextBox
         Click “Ok” Button.
         Right Click on the “Project Name”.
         Select Add >>“New Item”
         Select “Windows Forms” on the Left side of the Window.
         Select “user Control” on the Right side of the Window.
         Type “User Control “ Name in the Inpyt Box Eg: ValidateTextBox
         Click “Add” button.
         Now User control added in the Project.
         Drag “Text Box” from Tool Box and Drop into User control.
         Now , Copy and paste in the Code View Code.
         public enum ValidationType
        {
            None,
            Int,
            Double
        }
        private ValidationType m_align;
        public ValidationType ValidationTypes
        {
            get { return m_align; }
            set { m_align = value; }
        }
        public void ValidateTextNumber(KeyPressEventArgs e)
        {
            if (e.KeyChar >= 65 && e.KeyChar <= 122 || e.KeyChar == 32)
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }
        public bool IsValidNumber(string number)
        {
            int position = number.IndexOf(".");
            if (position != -1)
            {
                int decdigits = number.Substring(position + 1, number.Length - number.IndexOf('.') - 1).Length;
                if (decdigits == 2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (ValidationTypes == ValidationType.Double)
            {
                ValidateTextNumber(e);
            }
            else if (ValidationTypes == ValidationType.Int)
            {
                ValidateTextNumber(e);
            }
        }
        public void ValidateTextDouble(TextBox t)
        {
            bool val = IsValidNumber(t.Text);
            if (!val)
            {
                MessageBox.Show("Invalid number");
                t.Focus();
            }
        }
      public void ValidateTextInt(TextBox t)
      {
          bool val = IsValidNumber(t.Text);
          if (val)
          {
              MessageBox.Show("Invalid number");
              t.Focus();
          }
      }
        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (ValidationTypes == ValidationType.Double)
            {
                ValidateTextDouble(textBox1);
            }
            else if (ValidationTypes == ValidationType.Int)
            {
                ValidateTextInt(textBox1);
            }
        }
Rebuild a Project.
Go To Project Folder (Bin>>Debug)
File Name:“ValidateTextBox.dll”
Now , You add this DLL in your Project .
How to add?
Go to Add Reference
Click “Browse” button
Select your Path of the DLL .
How to Test it?
Drag “ValidateTextBox” from Toolbar
Drop “ValidateTextBox“ into Form.
Drag “Button” from Toolbar
Drop “Button“ into Form.
Change the Value of “ValidationType” Property in the ValidateTextBox.
If you select “Int” – Only Interger value will type(10).
   you select “Double” – Only Double value will type (like 10.10).
   you select “None” – string value will type (like GOOD0205).
Conclusion:    
    Thank you for reading this Article .and I hope , You enjoy it.

Invalid attempt to call Read when reader is closed

Why?:Invalid attempt to call Read when reader is closed
if (reader.HasRows) { while (reader.Read()) { Id = reader["Id"].ToString(); Con.Close(); } }
Solution:
if (reader.HasRows) { while (reader.Read()) { Id = reader["Id"].ToString(); } Con.Close(); }

Increment File names If File already exists in Designation Path

Private Sub FileNameIncrement(SourcePath As String, DesignationPath As String)
    Dim dir As New DirectoryInfo(SourcePath)
    Dim fileName As String = dir.Name
    Dim fileNamewithoutExtension As String = Path.GetFileNameWithoutExtension(DesignationPath & "\" &
fileName)
    Dim fileExtention As String = Path.GetExtension(DesignationPath & "\" & fileName)
    Dim files As String() = Directory.GetFiles(DesignationPath)
    Dim count As Integer = files.Count(Function(file__1)
    Return file__1.Contains(fileName)
End Function)
    Dim newFileName As String = If((count = 0), fileName, [String].Format("{0} ({1})" & fileExtention, fileName,
count + 1))
    If File.Exists(DesignationPath & "\" & fileName) Then
        File.Copy(SourcePath, DesignationPath & "\" & newFileName)
    Else
        File.Copy(SourcePath, DesignationPath & "\" & fileName)
    End If
End Sub

Dim OutputPath As String = "C:\Documents and Settings\Naraayanan\My Documents\Downloads"
FileNameIncrement(textBox1.Text, OutputPath)