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

Error Provider in Windows Application

Error Provider is a very useful for Application Validation.
Create Simple form.
Drag and Drop two Text Boxes and Buttons.
TextBox Names are txtUsername,txtPassword
Button Names are btn_Ok,btn_Cancel.
Button Text are &Ok,&Cancel.
Copy and Paste the following code in your Coding Section

 private void btn_Cancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Length == 0 && txtPassword.Text.Length == 0)
            {
                DispayErrorProvider(txtUserName);
                DispayErrorProvider(txtPassword);
            }
            else if (txtUserName.Text.Length == 0 )
            {
                DispayErrorProvider(txtUserName);
            }
            else if (txtPassword.Text.Length == 0)
            {
                DispayErrorProvider(txtPassword);
            }
            else
            {
                MessageBox.Show("Validate successfully");
            }
         }
        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            DispayErrorProvider(txtUserName);
        }
        void DispayErrorProvider(TextBox txt)
        {
            if (txt.Text.Length > 0)
            {
                errorProvider1.Clear();
            }
            else
            {
                errorProvider1.SetError(txt, "Input doesn't Empty");
            }
        }
        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            DispayErrorProvider(txtPassword);
        }
        private void txtUserName_Leave(object sender, EventArgs e)
        {
            DispayErrorProvider(txtUserName);
        }
        private void txtPassword_Leave(object sender, EventArgs e)
        {
            DispayErrorProvider(txtPassword);
        }

Run the Application.
Press Alt+O Button .Error Provider will display in the Screen.
Press Alt+C Application will exit.
Type your User name and Password .Error provider will not display in the Screen.
Note Use Only Keyboard.

Pass TextBox values from One Form to another form Datagridview

                Today we will discuss about Pass TextBox value into another form DataGridview using C#.Net Language. Here we used 2 Class Files and Two Form. 2 Class Files are ClsAddintoiTable and ClsBL. Two forms are Form1 and Form2.
Class Name: ClsAddintoiTable
namespace DatagridviewTasks { class ClsAddintoiTable { DataTable dt; public DataTable Addintotable(ClsBL cls) { dt = new DataTable(); dt.Columns.Add("First Name"); dt.Columns.Add("Last Name"); DataRow dr; dr = dt.NewRow(); dr["First Name"] = cls.FirstName; dr["Last Name"] = cls.LastName; dt.Rows.Add(dr.ItemArray); return dt; } } }
Class Name: ClsBL
namespace DatagridviewTasks { class ClsBL { private static string _FirstName; private static string _LastName; public string FirstName { get { return _FirstName; } set { _FirstName = value; } } public string LastName { get { return _LastName; } set { _LastName = value; } } } }
Form 2
private void button1_Click(object sender, EventArgs e) { cls.FirstName = textBox1.Text; cls.LastName = textBox2.Text; clsAdd.Addintotable(cls); this.Close(); } public DataTable CopyValue() { DataTable dt1 = new DataTable(); dt1 = clsAdd.Addintotable(cls).Copy(); return dt1; }
Form 1
DataTable dt; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(); dt = frm.CopyValue(); dataGridView1.DataSource = dt; } private void button2_Click(object sender, EventArgs e) { Form2 frm = new Form2(); frm.ShowDialog(); }

Shortcut key for Button in Windows Application

              Validation is an important portion in the Application Side.Some User wants to use Keyboard .So I give this Code for Shortcut Key for Button in Windows Application.
Step by step Procedure:
Create Form.
Drag and Drop your Button in the Form.
Give a name for button(like btn_Ok)
Give a text for button (like this &ok)
Click the Button.

 private void btn_Ok_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Thank you");
        }



 Run your Application .

Click Alt+O Key
MessageBox will display.

LINQ Hint -2

Difference between First vs FirstOrDefault in LINQ?
First: Gives first record from the collection, if collection doesn't have any object then throws error.
FirstOrDefault: FirstOrDefault extension method is used to retrieve the first element from the collection, if not then gives null.

Difference between Last vs LastOrDefault in LINQ?
Last:Last extension method gives last element from the collection. If there is no element in the collection, it throws error.
LastOrDefault:LastOrDefault extension method gives the last element form the collection, if not gives null.

When will we use ThenBy in LINQ?
ThenBy is used with OrderBy or OrderByDescending. It is used to apply sorting on already sorted collection using OrderBy or OrderByDescending.

Where to Use SequenceEqual ?
SequenceEqual extension method is used to determine if both collections sequence are equal.

what is mean by SkipWhile?
SkipWhile extension method is used to skip the elements that satisfies the given filter criteria till it doens't get any element that doesn't satisfy.

How to use Take Method in LINQ?
Take extension method is used to take specified number of elements from the collection.

What is mean by Lambda expression?
A lambda expression is an function that contain many expressions and statements.
Lambda expression used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to".
The left side of the lambda operator specifies the input parameters.
The right side holds the expression or statement block.

What is ORM?
ORM stands for Object-Relational Mapping. Sometimes it is called O/RM, or O/R mapping. It is a programming technique that contains a set of classes that map relational database entities to objects in a specific programming language.
What is ODBC?
ODBC (Open Database Connectivity) was developed to unify all of the communication protocols for various RDBMSs. ODBC was designed to be independent of programming languages, database systems, and Operating Systems. So with ODBC, an application could communicate with different RDBMSs by using the same code, simply by replacing the underlying ODBC drivers.
What is LINQ To SQL?
LINQ to SQL is a component of the .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objects.
LINQ to SQL fully supports transactions, views, Stored Procedures, and user-defined functions. It also provides an easy way to integrate data validation and business logic rules into your data model, and supports single table inheritance in the object model.
LINQ to SQL, ADO.NET SqlClient adapters are used to communicate with real SQL Server databases.



Difference between LINQ To SQL and LINQ To Object?

    LINQ to SQL needs a Data Context object. The Data Context object is the bridge between LINQ and the database. LINQ to Objects doesn’t need any intermediate LINQ provider or API.
    LINQ to SQL returns data of type IQueryable<T> while LINQ to Objects returns data of type IEnumerable<T>.
    LINQ to SQL is translated to SQL by way of Expression Trees, which allow them to be evaluated as a single unit and translated to the appropriate and optimal SQL statements. LINQ to Objects does not need to be translated.
    LINQ to SQL is translated to SQL calls and executed on the specified database while LINQ to Objects is executed in the local machine memory.




What is mean by Entity Framework?
ADO.NET Entity Framework (EF) was first released with Visual Studio 2008 and .NET Framework 3.5 Service Pack 1. So far, many people view EF as just another ORM product from Microsoft, though by design it is supposed to be much more powerful than just an ORM tool.
The conceptual data model schema is expressed in the Conceptual Schema Definition Language (CSDL), the actual storage model is expressed in the Storage Schema Definition Language (SSDL), and the mapping in between is expressed in the Mapping Schema Language (MSL).


Difference between LINQ To SQL and LINQ To Entities?
 LINQ to Entities applications work against a conceptual data model (EDM). All mappings between the languages and the databases go through the new EntityClient mapping provider. The application no longer connects directly to a database or sees any database-specific construct; the entire application operates in terms of the higher-level EDM model.


Difference between SQL Query and LINQ ?
http://www.codeproject.com/Articles/136028/Learn-SQL-to-LINQ-Visual-Representation


What are all the Operator Type  in LINQ To Object?

Operator Type    Operator Name
Aggregation    Aggregate, Average, Count, LongCount, Max, Min, Sum
Conversion    Cast, OfType, ToArray, ToDictionary, ToList, ToLookup, ToSequence
Element    DefaultIfEmpty, ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault
Equality    EqualAll
Generation    Empty, Range, Repeat
Grouping    GroupBy
Joining    GroupJoin, Join
Ordering    OrderBy, ThenBy, OrderByDescending, ThenByDescending, Reverse
Partitioning    Skip, SkipWhile, Take, TakeWhile
Quantifiers    All, Any, Contains
Restriction    Where
Selection    Select, SelectMany
Set    Concat, Distinct, Except, Intersect, Union


Get DataBase Exists or not using DataContext

               Today, we discussed about "Get DataBase Exists or not using DataContext in C#.net"
DataContext context = new DataContext(GetConnectionString("YourServerName"));
bool dbExists = context.DatabaseExists();
if (dbExists)
{
MessageBox.Show("Database Exists");
}
else
{
MessageBox.Show("Database doesn't Exist");
}
Get Connection string Method
static string GetConnectionString(string serverName)
{
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = serverName; builder["integrated Security"] = true; builder["Initial Catalog"] = "Sample2";
Console.WriteLine(builder.ConnectionString);
Console.ReadKey(true);
return builder.ConnectionString;
}

DataContext

DataContext:
  1.     To communicate with a Database a connection must be made. In LINQ this connection is created by a DataContext.
  2. Create connection to database.
  3. It submits and retrieves object to database.
  4. Converts objects to SQL queries and vice versa.

LINQ To Object --Example -2

Today, we will see how to use Order class in LINQ.

Create a One Class Called : ClsEmployee
Three Properties in the Class.


1)EmpId2)Name3)Salary
public string Name { get; set; } public string EmpID { get; set; } public int Salary { get; set; }
Create a One form
Drag and Drop one Button.
Button name is btn_Result.
Create a Method:
Method name is "InsertintoTable()
List objEmployee = new List { new ClsEmployees { EmpID = "1001" ,Name ="GANTEC", Salary =10000 }, new ClsEmployees { EmpID = "1002" ,Name ="IBM", Salary =15000 }, new ClsEmployees { EmpID = "1003" ,Name ="CTS", Salary =20000 }, new ClsEmployees { EmpID = "1004" ,Name ="WIPRO", Salary =30000 }, new ClsEmployees { EmpID = "1005" ,Name ="SATHYAM", Salary =40000 }, new ClsEmployees { EmpID = "1006" ,Name ="BUTTERFLY", Salary =50000 }, new ClsEmployees { EmpID = "1007" ,Name ="CON", Salary =10000 }, new ClsEmployees { EmpID = "1008" ,Name ="TVS", Salary =75000 }, new ClsEmployees { EmpID = "1010" ,Name ="TATA", Salary =90000 }, new ClsEmployees { EmpID = "1009 " ,Name ="GANTEC COR", Salary =100000 }, };
Call this method in button Click Event and Add below codes,
var OrderBy = (from emp in objEmployee select emp).OrderBy(x => x.Name);

Happy Coding!!!

LINQ To Object -- Example 1

 Count of Rows in the Table using LINQ
1) Create a One Class Called : ClsEmployee
Three Properties in the Class.
1)EmpId2)Name3)Salary
Code :
   public string Name { get; set; }
   public string EmpID { get; set; }
   public int Salary { get; set; }
2)  Create a One form
Drag and Drop one Button.
Button name is btn_Result.
Create a Method:

Method name is "InsertintoTable()
   List<ClsEmployees> objEmployee = new List<ClsEmployees>
            {
                new ClsEmployees { EmpID = "1001" ,Name ="GANTEC", Salary =10000 },
                new ClsEmployees { EmpID = "1002" ,Name ="IBM", Salary =15000 },
                new ClsEmployees { EmpID = "1003" ,Name ="CTS", Salary =20000 },
                new ClsEmployees { EmpID = "1004" ,Name ="WIPRO", Salary =30000 },
                new ClsEmployees { EmpID = "1005" ,Name ="SATHYAM", Salary =40000 },
                new ClsEmployees { EmpID = "1006" ,Name ="BUTTERFLY", Salary =50000 },
                new ClsEmployees { EmpID = "1007" ,Name ="CON", Salary =10000 },
                new ClsEmployees { EmpID = "1008" ,Name ="TVS", Salary =75000 },
                 new ClsEmployees { EmpID = "1010" ,Name ="TATA", Salary =90000 },
                 new ClsEmployees { EmpID = "1009" ,Name ="GANTEC COR", Salary =100000 },
             };
Call this method in button Click Event and Add below codes,
 var CountofRows = (from emp in objEmployee select emp.Salary).Count();
 MessageBox.Show("Total Records in Employee Table :" + CountofRows );
Result: "Total Records in Employee Table: 10" in the Message Box

Date Format Directory

Today, we discussed Date Format Directory in C#.Net

Code:
public static void CreateDirectory(string DesignationPath) { if (!Directory.Exists(DesignationPath)) { Directory.CreateDirectory(DesignationPath); } } public static string currentYear() { string Year = string.Empty; DateTime dt = DateTime.Now; string format = "yyyy"; Year = dt.ToString(format); return Year; } public static string currentMonth() { string Month = string.Empty; DateTime dt = DateTime.Now; string format = "MM"; Month = dt.ToString(format); return Month; } public static string currentDate() { string day = string.Empty; DateTime dt = DateTime.Now; string format = "dd"; day = dt.ToString(format); return day; }

Set Excel File Format in C#.Net

Set Excel File Format in C#.net

  public static string ExcelFileType()
        {
            string excelFileType = string.Empty;
            Microsoft.Office.Interop.Excel.Application OfficeFileType = new Microsoft.Office.Interop.Excel.Application();
            OfficeFileType.Visible = false;
            string oVersionName = OfficeFileType.Version;
            int length = oVersionName.IndexOf('.');
            oVersionName = oVersionName.Substring(0, length);
            int versionNumber = int.Parse(oVersionName, CultureInfo.GetCultureInfo("en-US"));
            if (versionNumber >= 12)
            {
                excelFileType = ".xlsx";
            }
            else
            {
                excelFileType = ".xls";
            }

            return excelFileType;
        }

MS Office Version in C#.Net

"MS Office Version in C#.Net
public static string GetOfficeVer()
{
string sVersion = string.Empty;
Microsoft.Office.Interop.Excel.Application appVersion = new Microsoft.Office.Interop.Excel.Application();
appVersion.Visible = false;
switch (appVersion.Version.ToString())
{
case "7.0":
sVersion = "95";
break;
case "8.0":
sVersion = "97";
break;
case "9.0":
sVersion = "2000";
break;
case "10.0":
sVersion = "2002";
break;
case "11.0":
sVersion = "2003";
break;
case "12.0":
sVersion = "2007";
break;
case "14.0":
sVersion = "2010";
break;
default:
sVersion = "Too Old!";
break;
}
return sVersion;
}

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;
}