Connect MySql Database with C#

First go to MySQL site and download MySQL Connector.
After you installed it, you are ready to go. Its that simple and easy.
Here is an example

Add Mysql.Data assembly reference

  1. using System.Data;
  2. using MySql.Data.MySqlClient;
  3.  
  4. public DataTable GetDataFromMySql()
  5. {          
  6.     DataSet ds = new DataSet();
  7.     MySqlDataAdapter da;
  8.     MySqlConnection con = new MySqlConnection("Server=your_server;Database=your_db;Uid=your_username;Password=your_password");
  9.  
  10.     try
  11.     {
  12.         MySqlCommand cmd = new MySqlCommand("select * from your_table", con);
  13.         con.Open();
  14.         da = new MySqlDataAdapter(cmd);
  15.         da.Fill(ds);                
  16.     }
  17.     catch
  18.     {
  19.         throw;
  20.     }
  21.     finally
  22.     {
  23.         if (con.State == ConnectionState.Open)
  24.             con.Close();
  25.     }
  26.  
  27.     return ds.Tables[0];
  28. }


Happy Coding

C# Call Constructor From Constructor

  1. public class A
  2. {
  3.     public A() { }
  4.  
  5.     public A(int i) : this() { }
  6.  
  7.     public A(int i, string s) : this(i) { }
  8. }
  9.  
  10. public class B : A
  11. {
  12.     public B() { }
  13.  
  14.     public B(int i) : base() { }
  15.  
  16.     public B(int i, string s) : base(i, s) { }
  17. }

Class A constructors call itself constructor by using this keyword. B is derived from A. Constructors of B call base constructors using base keyword.

Happy coding

C# Password Generator

  1. public static string GeneratePassword(int minLen, int maxLen, bool isUpperCase = true, bool isLowerCase = true, bool isNumber = true, bool isSymbol = true)
  2. {
  3.     string allowedChars = string.Empty;
  4.     if (isUpperCase)
  5.         allowedChars += "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
  6.     if (isLowerCase)
  7.         allowedChars += "abcdefghiklmnopqrstuvwxyz";
  8.     if (isNumber)
  9.         allowedChars += "1234567890";
  10.     if(isSymbol)
  11.         allowedChars += "!'^#+$%&/{([)]=}*?\\_-@~,;:<>";
  12.  
  13.     Random rd = new Random();
  14.     StringBuilder sb = new StringBuilder();    
  15.            
  16.     int len = rd.Next(minLen, maxLen);
  17.     int randomIndex;
  18.     char randomChar;
  19.     for (int i = 0; i <= len; i++)
  20.     {
  21.         randomIndex = rd.Next(allowedChars.Length);
  22.         randomChar = allowedChars[randomIndex];
  23.         sb.Append(randomChar);
  24.     }
  25.  
  26.     return sb.ToString();
  27. }

Here is the result for min length = 5 and max length = 15
rsN\&,Juk
~1-?Q'~Mku
wFnElGP:L+8sA
FN#'(i
Q6oid5l
xe$iFlD
ft*kA;
)u-)Kx
o3L2fn>9
o%=2i-


Random object use seed from system clock. If you are going to create passwords consecutive in very small time interval, probably random.next will return same value. In this case define random object as a static field. Also you can pass it as parameter. Even you can seed random object by yourself but you must change seed value everytime you call. You can use a counter.

  1.     Random rd = new Random(seed);

C# GLOBALS

Global values are useful to store constant values of your program or transfer values between different scopes. They can be accessed anywhere. Unfortunately there is not any predefined struct in .NET . Globals is defined using static class.

  1. using System;
  2.  
  3. //Declare GLOBALS class in global namespace or wherever you want
  4. public static class GLOBALS
  5. {
  6.     public const int KEY = 5000;
  7.     public static string STATUS = "NULL";
  8. }
  9.  
  10. namespace Test
  11. {
  12.     class Program
  13.     {
  14.         public static void MyMethod()
  15.         {
  16.            //Do something
  17.  
  18.             GLOBALS.STATUS = "MYMETHOD";
  19.         }
  20.  
  21.         static void Main(string[] args)
  22.         {
  23.             Console.WriteLine("KEY:{0,10:d}", GLOBALS.KEY);
  24.             Console.WriteLine("STATUS:   {0}", GLOBALS.STATUS);
  25.             Console.WriteLine();
  26.  
  27.             MyMethod();
  28.  
  29.             Console.WriteLine("KEY:{0,10:d}", GLOBALS.KEY);
  30.             Console.WriteLine("STATUS:   {0}", GLOBALS.STATUS);
  31.         }        
  32.     }
  33. }

C# Method Return Multiple Values

There are various ways return multiple values from method in .net .
First way Tuple, our new class comes with .net 4.0.

  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         public static Tuple<int, string> ReturnTuple()
  8.         {
  9.             int i = 0;
  10.             string str = string.Empty;
  11.  
  12.             //Do something
  13.  
  14.             //There is two way to create a tuple object
  15.             return Tuple.Create(i, str);
  16.             //return new Tuple<int, string>(i, str);                
  17.         }
  18.  
  19.         static void Main(string[] args)
  20.         {
  21.             int myInt;
  22.             string myString;
  23.  
  24.             Tuple<int, string> myTuple = ReturnTuple();
  25.  
  26.             myInt = myTuple.Item1;
  27.             myString = myTuple.Item2;
  28.  
  29.             Console.WriteLine("{0:d}-{1}", myInt, myString);
  30.         }        
  31.     }
  32. }

Second way use ref, out keywords.
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         public static int UseOut(out string str)
  8.         {
  9.             int i = 0;
  10.             str = string.Empty;
  11.  
  12.             //Do something
  13.  
  14.             return i;        
  15.         }
  16.  
  17.         static void Main(string[] args)
  18.         {
  19.             int myInt;
  20.             string myString;
  21.  
  22.             myInt = UseOut(out myString);
  23.  
  24.             Console.WriteLine("{0:d} - {1}", myInt, myString);
  25.         }        
  26.     }
  27. }

You can create your custom classes or structs and return them. These classes will include return variables.
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         public static ReturnValues ReturnCustomStruct()
  8.         {
  9.             ReturnValues rv;
  10.             int i = 0;
  11.             string str = string.Empty;
  12.  
  13.             //Do something
  14.  
  15.             rv.ValueInt = i;
  16.             rv.ValueString = str;
  17.             return rv;        
  18.         }
  19.  
  20.         static void Main(string[] args)
  21.         {
  22.             int myInt;
  23.             string myString;
  24.  
  25.             ReturnValues rv = ReturnCustomStruct();
  26.  
  27.             myInt = rv.ValueInt;
  28.             myString = rv.ValueString;
  29.             Console.WriteLine("{0:d} - {1}", myInt, myString);
  30.         }        
  31.     }
  32.  
  33.     struct ReturnValues
  34.     {
  35.         public int ValueInt;
  36.         public string ValueString;
  37.     }
  38. }

4th way. Use List or Array
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Test
  5. {
  6.     class Program
  7.     {
  8.         public static List<object> ReturnList()
  9.         {
  10.             int i = 0;
  11.             string str = string.Empty;
  12.  
  13.             //Do something
  14.  
  15.             return new List<object> {i,str};        
  16.         }
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             int myInt;
  21.             string myString;
  22.  
  23.             List<object> list = ReturnList();
  24.  
  25.             myInt = Convert.ToInt32(list[0]);
  26.             myString = list[1].ToString();
  27.             Console.WriteLine("{0:d} - {1}", myInt, myString);
  28.         }        
  29.     }
  30. }

Join return variables string or serialization values with a separator.
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         public static string JoinReturnValues()
  8.         {
  9.             int i = 0;
  10.             string str = string.Empty;
  11.  
  12.             //Do something
  13.  
  14.             //separator |
  15.             string returnValue = string.Join("|", i, str);
  16.             return returnValue;
  17.         }
  18.  
  19.         static void Main(string[] args)
  20.         {
  21.             int myInt;
  22.             string myString;
  23.  
  24.             string s = JoinReturnValues();
  25.  
  26.             string[] sArray = s.Split(new char[] { '|' }, 2);
  27.             myInt = Convert.ToInt32(sArray[0]);
  28.             myString = sArray[1].ToString();
  29.             Console.WriteLine("{0:d} - {1}", myInt, myString);
  30.         }        
  31.     }
  32. }

If you are going to return two values you can use KeyValuePair class. There are some other ways too. We can use GLOBAL variables or XML.
m ant / Mechanical Ant