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
Showing posts with label software. Show all posts
Showing posts with label software. 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
Happy Coding
After you installed it, you are ready to go. Its that simple and easy.
Here is an example
Add Mysql.Data assembly reference

- using System.Data;
- using MySql.Data.MySqlClient;
- public DataTable GetDataFromMySql()
- {
- MySqlDataAdapter da;
- MySqlConnection con = new MySqlConnection("Server=your_server;Database=your_db;Uid=your_username;Password=your_password");
- try
- {
- con.Open();
- da.Fill(ds);
- }
- catch
- {
- throw;
- }
- finally
- {
- if (con.State == ConnectionState.Open)
- con.Close();
- }
- return ds.Tables[0];
- }
Happy Coding
C# Call Constructor From Constructor
- public class A
- {
- public A() { }
- public A(int i) : this() { }
- public A(int i, string s) : this(i) { }
- }
- public class B : A
- {
- public B() { }
- public B(int i) : base() { }
- public B(int i, string s) : base(i, s) { }
- }
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
- public static string GeneratePassword(int minLen, int maxLen, bool isUpperCase = true, bool isLowerCase = true, bool isNumber = true, bool isSymbol = true)
- {
- string allowedChars = string.Empty;
- if (isUpperCase)
- allowedChars += "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
- if (isLowerCase)
- allowedChars += "abcdefghiklmnopqrstuvwxyz";
- if (isNumber)
- allowedChars += "1234567890";
- if(isSymbol)
- allowedChars += "!'^#+$%&/{([)]=}*?\\_-@~,;:<>";
- int len = rd.Next(minLen, maxLen);
- int randomIndex;
- char randomChar;
- for (int i = 0; i <= len; i++)
- {
- randomIndex = rd.Next(allowedChars.Length);
- randomChar = allowedChars[randomIndex];
- sb.Append(randomChar);
- }
- return sb.ToString();
- }
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-
~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.
- 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.
- using System;
- //Declare GLOBALS class in global namespace or wherever you want
- public static class GLOBALS
- {
- public const int KEY = 5000;
- public static string STATUS = "NULL";
- }
- namespace Test
- {
- class Program
- {
- public static void MyMethod()
- {
- //Do something
- GLOBALS.STATUS = "MYMETHOD";
- }
- static void Main(string[] args)
- {
- Console.WriteLine("KEY:{0,10:d}", GLOBALS.KEY);
- Console.WriteLine("STATUS: {0}", GLOBALS.STATUS);
- Console.WriteLine();
- MyMethod();
- Console.WriteLine("KEY:{0,10:d}", GLOBALS.KEY);
- Console.WriteLine("STATUS: {0}", GLOBALS.STATUS);
- }
- }
- }
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.
Second way use ref, out keywords.
You can create your custom classes or structs and return them. These classes will include return variables.
4th way. Use List or Array
Join return variables string or serialization values with a separator.
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.
First way Tuple, our new class comes with .net 4.0.
- using System;
- namespace Test
- {
- class Program
- {
- public static Tuple<int, string> ReturnTuple()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- //There is two way to create a tuple object
- return Tuple.Create(i, str);
- //return new Tuple<int, string>(i, str);
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- Tuple<int, string> myTuple = ReturnTuple();
- myInt = myTuple.Item1;
- myString = myTuple.Item2;
- Console.WriteLine("{0:d}-{1}", myInt, myString);
- }
- }
- }
Second way use ref, out keywords.
- using System;
- namespace Test
- {
- class Program
- {
- public static int UseOut(out string str)
- {
- int i = 0;
- str = string.Empty;
- //Do something
- return i;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- myInt = UseOut(out myString);
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
You can create your custom classes or structs and return them. These classes will include return variables.
- using System;
- namespace Test
- {
- class Program
- {
- public static ReturnValues ReturnCustomStruct()
- {
- ReturnValues rv;
- int i = 0;
- string str = string.Empty;
- //Do something
- rv.ValueInt = i;
- rv.ValueString = str;
- return rv;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- ReturnValues rv = ReturnCustomStruct();
- myInt = rv.ValueInt;
- myString = rv.ValueString;
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- struct ReturnValues
- {
- public int ValueInt;
- public string ValueString;
- }
- }
4th way. Use List or Array
- using System;
- using System.Collections.Generic;
- namespace Test
- {
- class Program
- {
- public static List<object> ReturnList()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- List<object> list = ReturnList();
- myInt = Convert.ToInt32(list[0]);
- myString = list[1].ToString();
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
Join return variables string or serialization values with a separator.
- using System;
- namespace Test
- {
- class Program
- {
- public static string JoinReturnValues()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- //separator |
- string returnValue = string.Join("|", i, str);
- return returnValue;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- string s = JoinReturnValues();
- myInt = Convert.ToInt32(sArray[0]);
- myString = sArray[1].ToString();
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
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.
When a specific key (ex: ESC (ESCAPE)) is pressed, the program below exit.
ReadKey and ReadLine functions block input. If you want to do anything until key pressed, you should use KeyAvailable property.
Example
- string s = Console.ReadLine();
When a specific key (ex: ESC (ESCAPE)) is pressed, the program below exit.
- using System;
- namespace Test
- {
- class Program
- {
- static void Main(string[] args)
- {
- ConsoleKeyInfo k;
- Console.WriteLine("Press ESC to exit...");
- while (true)
- {
- k = Console.ReadKey(true);
- if (k.Key == ConsoleKey.Escape)
- break;
- Console.WriteLine("{0} --- ", k.Key);
- }
- }
- }
- }
ReadKey and ReadLine functions block input. If you want to do anything until key pressed, you should use KeyAvailable property.
- Console.KeyAvailable
Example
- using System;
- namespace Test
- {
- class Program
- {
- static void Main(string[] args)
- {
- ConsoleKeyInfo k;
- bool bln = true;
- Console.WriteLine("Press ESC to exit...");
- while (true)
- {
- while(!Console.KeyAvailable)
- {
- if(!bln)
- Console.WriteLine("{0:s}", "x");
- bln = true;
- }
- bln = false;
- k = Console.ReadKey(true);
- if (k.Key == ConsoleKey.Escape)
- break;
- Console.Write("{0} --- ", k.Key);
- }
- }
- }
- }
C# Object Initializers
Members of an object can be assigned without calling a constructor at creation time.
Example
- MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};
Example
- class Program
- {
- static void Main(string[] args)
- {
- //Object initializer
- MyClass myObject = new MyClass() {MyID = 1, MyName = "John Doe"};
- int id =myObject.GetMyID();
- string name = myObject.GetMyName();
- Console.WriteLine("{0,-3:0}{1:s}",id,name);
- }
- }
- public class MyClass
- {
- private int _myID;
- private string _myName;
- public int MyID { get; set; }
- public string MyName { get; set; }
- public MyClass() { }
- public int GetMyID()
- {
- return MyID;
- }
- public string GetMyName()
- {
- return MyName;
- }
- }
C# Named Parameters
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Test
- {
- class Program
- {
- static void Main(string[] args)
- {
- //calling method
- DoSomething(1, "john", false);
- DoSomething(1, "john");
- DoSomething(id: 1, name: "john", status: false);
- DoSomething(name: "john", id: 1);
- DoSomething(name: "john", status: false, id: 1);
- }
- public static void DoSomething(int id, string name, bool status = true)
- {
- //Do something
- }
- }
- }
C# Optional Parameters
Optional parameters were introduced with .NET 4.0.
You just only give default value these parameters.
There are other some ways to use optional parameters.
Method overloading
params keyword
Optional attribute
Nullable types
User NameValueCollection or Dictionary type parameter
- public void DoSomething(int x, string s = "test")
- {
- //Do something
- }
- //Calling methods
- DoSomething(1);
- DoSomething(2, "abc");
There are other some ways to use optional parameters.
Method overloading
- public void DoSomething(int x, string s)
- {
- //Do something
- }
- public void DoSomething(int x)
- {
- DoSomething(x, "test");
- }
params keyword
- public void DoSomething(params object[] obj)
- {
- //Do something
- }
Optional attribute
- using System.Runtime.InteropServices;
- public void DoSomething(int x, [Optional, DefaultParameterValue("test")] string s)
- {
- //Do something
- }
Nullable types
- public void DoSomething(int? x)
- {
- //Check if parameter has value
- if (x.HasValue)
- {
- //Use Value property of nullable type
- int y = x.Value;
- //Do something
- }
- else
- {
- //Do something
- }
- }
User NameValueCollection or Dictionary type parameter
- dict.Add("x",1);
- //dict.Add("s","test");
- DoSomething(dict);
- public void DoSomething(Dictionary<string, object>)
- {
- //Do something
- }
Subscribe to:
Posts (Atom)