Tag Archives: winforms
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); } |
How to generate QR barcodes in C#
QR barcodes are machine-readable optical labels that contain certain information. Today we will be looking into how to generate QR codes with the use of the ZXing.Net library.
First you will need to download the ZXing.Net library from zxingnet.codeplex.com. Extract the contents of the file you have downloaded and reference the library that fits your needs in your project.
Using the example code below you will now be able to create your own QR codes.
1 2 3 4 5 6 7 8 9 10 | public Bitmap GenerateQR(int width, int height, string text) { var bw = new ZXing.BarcodeWriter(); var encOptions = new ZXing.Common.EncodingOptions() { Width = width, Height = height, Margin = 0 }; bw.Options = encOptions; bw.Format = ZXing.BarcodeFormat.QR_CODE; var result = new Bitmap(bw.Write(text)); return result; } |
Example: Calling the following method will return a Bitmap object which you can save using the Bitmap’s Bitmap.Save() method or simply display it within your application.
1 | GenerateQR(200, 200, "http://www.fluxbytes.com/csharp/generating-qr-barcode-in-c/"); |
Unzip files using Shell32 in C#
The .NET Framework didn’t have an easy way for developers to unzip files resulting to a lot of people having to use third party libraries to achieve that functionality. This was until the .NET Framework 4.5 was released which had a new class called ZipFile that simplified the process of unzipping files..
But since targeting the .NET Framework 4.5 might not be ideal in many cases, mainly because its adaptation rate is still fairly low I will demostrate another way to unzip .zip files with the use of Shell32.
Firstly you will need to reference in your project the COM library called Microsoft Shell Controls And Automation (Interop.Shell32.dll) in order to be able to access the Shell32 namespace.
The method below is a simple example that takes two parameters. The .zip file location and the folder destination where the files will be extracted to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void UnZip(string zipFile, string folderPath) { if (!File.Exists(zipFile)) throw new FileNotFoundException(); if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath); Shell32.Shell objShell = new Shell32.Shell(); Shell32.Folder destinationFolder = objShell.NameSpace(folderPath); Shell32.Folder sourceFile = objShell.NameSpace(zipFile); foreach (var file in sourceFile.Items()) { destinationFolder.CopyHere(file, 4 | 16); } } |
The usage is fairly simple:
1 | UnZip(@"C:\myzipfile.zip", @"C:\my destination folder"); |
Creating and connecting to a Microsoft Access Database programmatically in C#
The following example aims to get you a bit more familiar as to how to create and connect to a Microsoft Access database programmatically while being able to add any type of tables you want as well are inserting and retrieving data from it.
Firstly we will need to reference two libraries in our project. Microsoft ActiveX Data Objects 2.0 Library (Interop.ADODB.dll) which we will use to ensure that the connection to the database is closed after we are done creating it, and Microsoft ADO Ext. 2.8 for DDL and Security (Interop.ADOX.dll) which is needed to be able to access the classes that are required to create our database.
After you have finished adding those two references to your project you can use the code sample below to create the database file programmatically. Feel free to modify the code to suit your needs. Also please note that setting your project to Any CPU build will cause exceptions to be thrown when creating the database.
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 | public static void CreateAccessDatabase() { string connectionString = string.Format("Provider={0}; Data Source={1}; Jet OLEDB:Engine Type={2}", "Microsoft.Jet.OLEDB.4.0", "mydb.mdb", 5); ADOX.CatalogClass catalog = new ADOX.CatalogClass(); catalog.Create(connectionString); ADOX.Table table = new ADOX.Table(); table.Name = "Users"; // Table name // Column 1 (id) ADOX.ColumnClass idCol = new ADOX.ColumnClass(); idCol.Name = "Id"; // The name of the column idCol.ParentCatalog = catalog; idCol.Type = ADOX.DataTypeEnum.adInteger; // Indicates a four byte signed integer. idCol.Properties["AutoIncrement"].Value = true; // Enable the auto increment property for this column. // Column 2 (Name) ADOX.ColumnClass nameCol = new ADOX.ColumnClass(); nameCol.Name = "Name"; // The name of the column nameCol.ParentCatalog = catalog; nameCol.Type = ADOX.DataTypeEnum.adVarWChar; // Indicates a string value type. nameCol.DefinedSize = 60; // 60 characters max. // Column 3 (Surname) ADOX.ColumnClass surnameCol = new ADOX.ColumnClass(); surnameCol.Name = "Surname"; // The name of the column surnameCol.ParentCatalog = catalog; surnameCol.Type = ADOX.DataTypeEnum.adVarWChar; // Indicates a string value type. surnameCol.DefinedSize = 60; // 60 characters max. table.Columns.Append(idCol); // Add the Id column to the table. table.Columns.Append(nameCol); // Add the Name column to the table. table.Columns.Append(surnameCol); // Add the Surname column to the table. catalog.Tables.Append(table); // Add the table to our database. // Close the connection to the database after we are done creating it and adding the table to it. ADODB.Connection con = (ADODB.Connection)catalog.ActiveConnection; if (con != null && con.State != 0) con.Close(); } |