Showing posts with label dotnet. Show all posts
Showing posts with label dotnet. Show all posts

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# Console - Press Any Key to Exit

If your console program is closing immediately before you see anything then add this code to your program. It doesn't consume any system resources. When you enter something, program will exit.

  1. string s = Console.ReadLine();

When a specific key  (ex: ESC (ESCAPE)) is pressed, the program below exit.
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             ConsoleKeyInfo k;
  10.  
  11.             Console.WriteLine("Press ESC to exit...");
  12.             while (true)
  13.             {
  14.                 k = Console.ReadKey(true);
  15.                 if (k.Key == ConsoleKey.Escape)
  16.                     break;
  17.  
  18.                 Console.WriteLine("{0} --- ", k.Key);
  19.             }
  20.         }
  21.     }
  22. }

ReadKey and ReadLine functions block input. If you want to do anything until key pressed, you should use KeyAvailable property.
  1. Console.KeyAvailable

Example
  1. using System;
  2.  
  3. namespace Test
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             ConsoleKeyInfo k;
  10.             bool bln = true;
  11.  
  12.             Console.WriteLine("Press ESC to exit...");
  13.             while (true)
  14.             {                
  15.                 while(!Console.KeyAvailable)
  16.                 {
  17.                     if(!bln)
  18.                         Console.WriteLine("{0:s}", "x");
  19.                     bln = true;
  20.                 }
  21.                 bln = false;
  22.  
  23.                 k = Console.ReadKey(true);
  24.                 if (k.Key == ConsoleKey.Escape)
  25.                     break;
  26.  
  27.                 Console.Write("{0} --- ", k.Key);
  28.             }
  29.         }
  30.     }
  31. }

C# Object Initializers

Members of an object can be assigned without calling a constructor at creation time.
  1. MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};

Example
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.  
  6.         //Object initializer
  7.         MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};
  8.  
  9.         int id =myObject.GetMyID();
  10.         string name = myObject.GetMyName();
  11.  
  12.         Console.WriteLine("{0,-3:0}{1:s}",id,name);
  13.     }
  14. }
  15.  
  16. public class MyClass
  17. {
  18.     private int _myID;
  19.     private string _myName;
  20.  
  21.     public int MyID { get; set; }
  22.     public string MyName { get; set; }
  23.  
  24.     public MyClass() { }
  25.  
  26.     public int GetMyID()
  27.     {
  28.         return MyID;
  29.     }
  30.  
  31.     public string GetMyName()
  32.     {
  33.         return MyName;
  34.     }
  35. }

C# Named Parameters

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Test
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //calling method
  13.             DoSomething(1, "john", false);
  14.             DoSomething(1, "john");
  15.             DoSomething(id: 1, name: "john", status: false);
  16.             DoSomething(name: "john", id: 1);
  17.             DoSomething(name: "john", status: false, id: 1);
  18.         }
  19.  
  20.         public static void DoSomething(int id, string name, bool status = true)
  21.         {
  22.            //Do something
  23.         }          
  24.     }
  25. }


C# Optional Parameters

Optional parameters were introduced with .NET 4.0. You just only give default value these parameters.

  1. public void DoSomething(int x, string s = "test")
  2. {
  3.    //Do something
  4. }

  1. //Calling methods
  2. DoSomething(1);
  3. DoSomething(2, "abc");


There are other some ways to use optional parameters.
Method overloading

  1. public void DoSomething(int x, string s)
  2. {
  3.    //Do something
  4. }
  5.                
  6. public void DoSomething(int x)
  7. {
  8.    DoSomething(x, "test");
  9. }


params keyword

  1. public void DoSomething(params object[] obj)
  2. {
  3.    //Do something
  4. }


Optional attribute

  1. using System.Runtime.InteropServices;
  2.  
  3. public void DoSomething(int x, [Optional, DefaultParameterValue("test")] string s)
  4. {
  5.    //Do something
  6. }


Nullable types

  1. public void DoSomething(int? x)
  2. {
  3.    //Check if parameter has value
  4.    if (x.HasValue)
  5.    {
  6.        //Use Value property of nullable type
  7.        int y = x.Value;
  8.  
  9.        //Do something
  10.    }
  11.    else
  12.    {
  13.        //Do something
  14.    }
  15. }


User NameValueCollection or Dictionary type parameter

  1. Dictionary<string, object> dict = new Dictionary<string, object>();
  2. dict.Add("x",1);
  3. //dict.Add("s","test");
  4. DoSomething(dict);

  1. public void DoSomething(Dictionary<string, object>)
  2. {
  3.    //Do something
  4. }

m ant / Mechanical Ant