Tag Archives: snippet
Wake-on-Lan (WoL) in C#
Wake on LAN is a computer networking standard that allows devices to be powered on when they receive a specific network message, if your device supports this feature.
In this example we will demonstrate how to craft this “magic” packet in C#. The concept of the packet is fairly simple. The packet must contain anywhere in the payload six (6) 255 bytes in a row (FF in hexadecimal) followed by the MAC address of the device repeated sixteen times.
As an example, if your device MAC address is 01-00-00-00-00-02 the payload will look like this:
1 | FFFFFFFFFFFF010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002010000000002 |
You can find the implementation of WoL in C# below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | var macAddress = "01-00-00-00-00-02"; // Our device MAC address macAddress = Regex.Replace(macAddress, "[-|:]", ""); // Remove any semicolons or minus characters present in our MAC address var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { EnableBroadcast = true }; int payloadIndex = 0; /* The magic packet is a broadcast frame containing anywhere within its payload 6 bytes of all 255 (FF FF FF FF FF FF in hexadecimal), followed by sixteen repetitions of the target computer's 48-bit MAC address, for a total of 102 bytes. */ byte[] payload = new byte[1024]; // Our packet that we will be broadcasting // Add 6 bytes with value 255 (FF) in our payload for (int i = 0; i < 6; i++) { payload[payloadIndex] = 255; payloadIndex++; } // Repeat the device MAC address sixteen times for (int j = 0; j < 16; j++) { for (int k = 0; k < macAddress.Length; k += 2) { var s = macAddress.Substring(k, 2); payload[payloadIndex] = byte.Parse(s, NumberStyles.HexNumber); payloadIndex++; } } sock.SendTo(payload, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 0)); // Broadcast our packet sock.Close(10000); |
Feel free to leave your questions or feedback in the comment section below.
Create a MySQL table dynamically in C#
Sometimes you might need to create database tables dynamically, based on new users, products etc. The snippet below allows you to do exactly that, create a new table in your database dynamically, straight from your code.
This example is heavily based on How to connect to a MySQL database and retrieve data in C# as the same concept of connecting to the database is required.
The first thing you need to do, as mentioned in the article linked above, is that you will need to add a reference to MySQL.Data in your project. After you have done that, you can modify the snippet below to create the table with the columns you want based on your requirements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | string createTableQuery = string.Format(@"CREATE TABLE `{0}` ( `sid` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(120) NOT NULL DEFAULT '', `title` varchar(120) NOT NULL DEFAULT '', `description` text NOT NULL, `optionscode` text NOT NULL, `value` text NOT NULL, `disporder` smallint(5) unsigned NOT NULL DEFAULT '0', `gid` smallint(5) unsigned NOT NULL DEFAULT '0', `isdefault` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`sid`), KEY `gid` (`gid`)) ENGINE = MyISAM AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;", "YourTableName"); string serverIp = "<Server IP or Hostname>"; string username = "<DB username>"; string password = "<DB password>"; string databaseName = "<DB name>"; string dbConnectionString = string.Format("server={0};uid={1};pwd={2};database={3};", serverIp, username, password, databaseName); var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString); conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(createTableQuery, conn); cmd.ExecuteNonQuery(); |
If you are unsure as to which database engine to use, please take a look at https://dev.mysql.com/doc/refman/5.0/en/storage-engines.html as every database engine has different type of limitations, so it is better to choose the one that better suits your needs.
How to connect to a MySQL database and retrieve data in C#
Connecting to a MySQL database is fairly simple and straight forward. The first thing you will need to do is to add a reference to MySQL.Data in your project.
This can be done in a few ways:
- Right click on references in your project -> click Manage NuGet packages -> Search and install MySQL.Data from Oracle
- Open Package Manager Console from Tools -> NuGet Package Manager -> Paste in the console the following line:
Install-Package MySql.Data
- If you have installed the .NET Connector from MySQL you can navigate to where you have installed the connector and add a reference to the MySQL.Data.dll file
After you have added a reference to MySQL.Data you can tailor the snippet below to suit your requirements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | string serverIp = "<Server IP or Hostname>"; string username = "<DB username>"; string password = "<DB password>"; string databaseName = "<DB name>"; string dbConnectionString = string.Format("server={0};uid={1};pwd={2};database={3};", serverIp, username, password, databaseName); string query = "SELECT * FROM YourTable"; var conn = new MySql.Data.MySqlClient.MySqlConnection(dbConnectionString); conn.Open(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(query, conn); var reader = cmd.ExecuteReader(); while (reader.Read()) { var someValue = reader["SomeColumnName"]; // Do something with someValue } |
If you are interested in other type of databases you can check my Microsoft Access Database and SQLite database tutorials.
Convert DateTime to Unix time in C#
I’ve been asked recently by a few people how to convert Unix time to DateTime format (and the other way around) so I decided to make a post about it explaining how Unix time works and provide a snippet to help people that want to convert DateTime to Unix time or vise versa.
Unix time is basically the number of seconds that have passed since 1/1/1970 00:00:00 (UTC). In order to convert a specific date and time to a Unix time value we will need to subtract the date above from the date we want to convert to Unix time.
Example:
1 2 3 4 5 6 7 8 9 10 11 | /// <summary> /// Convert a date time object to Unix time representation. /// </summary> /// <param name="datetime">The datetime object to convert to Unix time stamp.</param> /// <returns>Returns a numerical representation (Unix time) of the DateTime object.</returns> public static long ConvertToUnixTime(DateTime datetime) { DateTime sTime = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc); return (long)(datetime - sTime).TotalSeconds; } |
Now if we want to convert a Unix time value to a DateTime object the the principle is the same. We take the 1/1/1970 00:00:00 (UTC) date and add the value of the Unix time as seconds to that date. The result would be the actual DateTime of the Unix time stamp.
Example:
1 2 3 4 5 6 7 8 9 10 | /// <summary> /// Convert Unix time value to a DateTime object. /// </summary> /// <param name="unixtime">The Unix time stamp you want to convert to DateTime.</param> /// <returns>Returns a DateTime object that represents value of the Unix time.</returns> public static DateTime UnixTimeToDateTime(long unixtime) { DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return sTime.AddSeconds(unixtime); } |
Tracert implementation in C#
While I was looking for a tracert method that I could use for an application of mine I noticed that the .NET framework doesn’t provide one out of the box, so I decided to create one that matched my requirements.
The method below works in the exact same fashion the tracert method works. Providing
the method with the IP address, the max number of hops you would like to receive and a timeout value for the hops will allow you to track down the route your data will travel in order to get to their destination, as well as the time (in milliseconds) it will take for each hop.
Main method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | /// <summary> /// Traces the route which data have to travel through in order to reach an IP address. /// </summary> /// <param name="ipAddress">The IP address of the destination.</param> /// <param name="maxHops">Max hops to be returned.</param> public IEnumerable<TracertEntry> Tracert(string ipAddress, int maxHops, int timeout) { IPAddress address; // Ensure that the argument address is valid. if (!IPAddress.TryParse(ipAddress, out address)) throw new ArgumentException(string.Format("{0} is not a valid IP address.", ipAddress)); // Max hops should be at least one or else there won't be any data to return. if (maxHops < 1) throw new ArgumentException("Max hops can't be lower than 1."); // Ensure that the timeout is not set to 0 or a negative number. if (timeout < 1) throw new ArgumentException("Timeout value must be higher than 0."); Ping ping = new Ping(); PingOptions pingOptions = new PingOptions(1, true); Stopwatch pingReplyTime = new Stopwatch(); PingReply reply; do { pingReplyTime.Start(); reply = ping.Send(address, timeout, new byte[] { 0 }, pingOptions); pingReplyTime.Stop(); string hostname = string.Empty; if (reply.Address != null) { try { hostname = Dns.GetHostByAddress(reply.Address).HostName; // Retrieve the hostname for the replied address. } catch (SocketException) { /* No host available for that address. */ } } // Return out TracertEntry object with all the information about the hop. yield return new TracertEntry() { HopID = pingOptions.Ttl, Address = reply.Address == null ? "N/A" : reply.Address.ToString(), Hostname = hostname, ReplyTime = pingReplyTime.ElapsedMilliseconds, ReplyStatus = reply.Status }; pingOptions.Ttl++; pingReplyTime.Reset(); } while (reply.Status != IPStatus.Success && pingOptions.Ttl <= maxHops); } |