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

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)

Increment File names If File already exists in C#.Net

private void FileNameIncrement(string SourcePath, string DesignationPath)
        {
            DirectoryInfo dir = new DirectoryInfo(SourcePath);
           
            string fileName = dir.Name;
            string fileNamewithoutExtension = Path.GetFileNameWithoutExtension(DesignationPath + "\\" + fileName);
            string fileExtention = Path.GetExtension(DesignationPath + "\\" + fileName);
            string[] files = Directory.GetFiles(DesignationPath);
            int count = files.Count(file => { return file.Contains(fileName); });
            string newFileName = (count == 0) ? fileName : String.Format("{0} ({1})" + fileExtention, fileName, count +

1);

            if (File.Exists(DesignationPath + "\\" + fileName))
            {
                File.Copy(SourcePath, DesignationPath + "\\" + newFileName);
            }
            else
            {
                File.Copy(SourcePath, DesignationPath + "\\" + fileName);
            }
        }

 string OutputPath = @"C:\Documents and Settings\Naraayanan\My Documents\Downloads";
            FileNameIncrement(textBox1.Text, OutputPath);

Check Input Value 0 To 4 in VB.Net

 Dim chk As Boolean
    Function IsChekcInputValue(ByVal number As Double) As Boolean
        If number = 0 Or number = 1 Or number = 2 Or number = 3 Or number = 4 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For I As Integer = 0 To Trim(TextBox1.Text.Length) 
            chk = IsChekcInputValue(TextBox1.Text.IndexOf(I))
        Next
        If chk = False Then
            MsgBox("Please Enter 0 To 4 Numbers in Input Box")
        Else
            MsgBox("Thank U")
        End If
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Char.IsNumber(e.KeyChar) = False Then
            e.Handled = True
        End If
    End Sub

TextBox Value into ComboBox

 private void MulityTextBoxes(int cnt)
        {
            txt = new TextBox[cnt];
            for (int i = 0; i < cnt; i++)
            {
                txt[i] = new TextBox();
                txt[i].Name = "TextBox" + i.ToString();
                txt[i].Tag = i.ToString();
                txt[i].Size = new Size(50, 20);
                txt[i].Location = new System.Drawing.Point(10, 20 + (i * 28));
                txt[i].Leave += new System.EventHandler(txt_Leave);
                panel1.Controls.Add(txt[i]);        
            }
        }

 private void txt_Leave(object sender, EventArgs e)
        {
            TextBox picbox = (TextBox)sender;
            int PicboxIndex = Convert.ToInt32(picbox.Tag);
            comboBox1.Items.Remove("");
            comboBox1.Items.Add(txt[PicboxIndex].Text); 
        }

Windows Control Starts with “B”

Background Worker:

You can use it to long Processing like Conversion, File Management. If both UI and the long Processing are ran within the same thread the UI appears to hang, making the average PC. So let's do it the decent way and use Background Worker.
Button:

Button accepts Clicks. It is interact with User and UI .This Control accepts Input. It is an interactive component that enables users to communicate with an application. A Button can be clicked by using the mouse, ENTER key or SPACE BAR if the button has focus.

List of Windows Controls


        Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client side Windows applications.

B

·         BackgroundWorker
·         Button

C

·         Checkbox
·         CheckedListBox
·         ComboBox
·         ContextMenuStrip
·         ColorDialog
·         Chart

D

·         DropDownItems
·         DateTimePicker
·         DialogResult
·         DataGridView
·         DomainUpDown
E
·         ErrorProvider
·         EventLog
F
·         FlowLayoutPanel
·         FolderBrowserDialog
·         FontDialog
·         FileSystemWatcher

 G

·         GroupBox

          H
·         HelpProvider
     I
·         ImageList

          L

·         ListBox
·         Label
·         LinkLabel
·         ListView

          M
·         MaskedTextBox
·         MenuStrip
·         MonthCalendar
          N
·         NotifyIcon
·         NumericUpDown
      O
·         OpenFileDialog
  P
·         ProgressBar
·         PictureBox
·         Panel
·         Pointer
·         PropertyGrid
       R
·         RichTextBox
·         RadioButton
          S
·         StatusStrip
·         SaveFileDialog
·         SplitContainer
          T
·         TextBox
·         ToolStripContainer
·         TableLayoutPanel
·         TabControl
·         ToolTip
·         TrackBar
·         TreeView
 W
·         WebBrowser


New-Features-of-Visual-Studio-2008

History of DotNet

.Net was originally known as the NGWS (Next Generation Windows Services) which was said to be an Internet based platform of Next Generation Windows Services. Before the official announcement of .Net.
DOTNET FRAMEWORK
1)  1.0 (2002)
      MDE – Visual Studio
×          ASP.NET 1.0
×          CLR 1.0
×          C# 1.0
×          VB.NET 7
×          NetFx 1.0
2) 1.1 (2003)
      MDE – Visual Studio 2003
      New Features
×          Side by Side Execution
×          .NET Compact Framework
×          IP6 Support
×          API Changes
      Components
×          ASP.NET 1.1
×          CLR 1.1
×          C#1.1
×          VB.NET 7.1
×          NetFx 1.1
3) 2.0 (2005)
MDE – Visual Studio 2005
     New Features
     Components
×          ASP.NET 2.0
×          CLR 2.0
×          C#2.0
×          VB.NET 8.0
×          NetFx 2.0
×          ADO.NET 2.0

4) 3.0 (2006)
×          NetFx 3.0
×          WPF
×          WCF
×          WF
×          Windows Cardspace
5) 3.5  (2007)
      MDE – Visual Studio 2008
×          ASP.NET 3.5
×          CLR 2.0
×          C# 3.0
×          VB.NET 9
×          NetFx 3.5
6) 4.0 (2010)
×          Visual Studio 2010
×          ASP.NET 4.0
×          CLR 4.0

CLR
×          1.0
×          1.1
×          2.0
×          4.0
 ASP.NET
×          1.0
×          1.1
×          2.0
×          3.5
×          4.0
CSHARP (C#)
×          1.0
×          1.1
×          2.0
1.   Generics
2.   Iterators
3.   Partial Classes
4.   Nullable Types
5.   Anonymous Methods
6.   Namespace alias qualifier
7.   Static Classes
8.   External Assembly Alias
1.   Property Accessor Accessibility
2.   Covariance and Contra variance in Delegates
3.   Friend Assemblies
4.   Inline warning control
5.   Volatile
×          3.0
1.   LINQ
2.   Object initializers
3.   Collection initializers
4.   Anonymous types
5.   Local variable type inference
6.   Lambda expressions
7.   Expression trees
8.   Automatic properties
1.   Extension methods
2.   Partial methods
×          4.0
VB.NET
×          7.0
×          7.1
×          8.0
×          9.0