Showing posts with label software. Show all posts
Showing posts with label software. Show all posts

Microsoft Visual Studio / Tips 1

These will make your life easier :)
 
Line Numbers
Go to Tools - Options - Text Editor. Select your language.















Immediate Window
Debug - Windows - Immediate Window
You can execute commands, define variables, classes and call your methods. You dont need to run your application. Detail Information - MSDN
















Todo List
Start your comments with "Todo:"  These comments will be showed at Task List window. The comments with start these special words in all over your solution are showed. There is also Hack and Undone markers.
To open Task List window go to View - Task List. Choose "Comments" from dropdown menu. If you choose "User Tasks", you can create tasks, assign priority and mark them as completed.
Detail information - MSDN













Refactor
Go to Refactor menu or right click and choose Refactor.
For example you can easily create properties from fields.

Custom Keyboard Shortcuts
Tools - Options  - Environment - Keyboard - Assign your favorite keys















Customize Your Toolbars and Menu Items
Tools - Customize
Here you can arrange toolbars and menu items.



















Code Snippets
You can easily insert pre-defined code blocks. You can design your own code snippets
Detail information - MSDN
Snippet Designer
Code Project - Create Your Own Snippets

Right click and choose Insert Snippet
Edit - IntelliSense  - Insert Snippet
Right shortcut of snippet and ENTER
 
















Open Complete Word Window ShortCut
ALT GR + Left Arrow or CTRL + Space

Complete Word Window Transparent

Press CTRL or ALT GR and hold for a while.
Its very annoying when you cant see the code behind it.

 













To be continued...

Happy coding

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.

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