Understanding Closures in Swift

Closures are types that hold function references. The code below shows how to declare a function that accepts closures.

The compute function takes three parameters. The first two are operands of type Double. The last parameter is a closure type. The closure type accepts two Doubles as parameter and returns a Double.

To invoke the above function, the following code can be used.

Since Swift can do type inference, the following code works well.

The return keyword is optional. The code below works equally well.

The parameters can be replaced with positional parameters like $0, $1 as follows.

If the closure is the last parameter, the closure can be supplied with a syntax as follows.

For the simple example, operator functions can be used to make the compute call very concise.

Closures in Swift allow developers to write concise and intuitive code.



Launching iOS App without Storyboard

There is no blank project template while creating iOS apps using Xcode. When the iOS app is launched, the settings in the Info.plist file is used to determine the launch screen file name and the Storyboard file name. By emptying the values for the following entries in the Info.plist file, the app can be custom launched.

  1. Launch screen interface file base name
  2. Main storyboard file base name

Custom launch without Storyboard

The AppDelegate object has several methods which manage the state of the application. The didFinishLaunchingWithOptions method of the AppDelegate object is invoked when the application has been launched. Custom code can be written within the AppDelegate method to initialize the window object (UIWindow) as follows:

The window object is created with the default frame. The custom ViewController object is created and is attached to the rootViewController of the window object. Finally, the window object is made visible.

For more information, please visit the iOS App Lifecycle page.

Custom ConfigurationSection for storing email settings.

For sending email, settings like host, port, user name, password should be stored in the configuration file. These settings can be grouped into a emailSettings as shown below.

Custom ConfigurationSection

EmailSettingsConfigurationSection is a custom ConfigurationSection class which is used to retrieved the settings from the configuration file.

The code above is self-explanatory. To ensure that the email settings are read from the configuration file using the EmailSettingsConfigurationSection, the class should be registered within the config file.

Retrieve custom settings

Custom settings can be retrieved using the following code.

Adding Text to Image using Graphics class

Graphics class in System.Drawing assembly has several useful methods to manipulate an image.

Adding Text using Graphics

The following code can be used to add text to an image.

The following methods in the Graphics class are used:

  • FillRectangle – fill an image with a background color.
  • MeasureString – measures the size of a string.
  • DrawString – draws the string to an image.

The result of the method is shown in the image below.



The text is printed in a black background of 100 pixels height. The text is centred within the black background.

Getting the href value using Regular expressions.

Scraping web pages can be done with a few lines of C# code using Regular expressions. Regular expressions is available in the System.Text.RegularExpressions namespace. RegEx is the class representing regular expressions.

Getting href value

The code below is used to retrieve the href value found in web pages. The regular expression used is simplistic (and used as an example).

The regular expression will match the line and retrieve the text within the href attribute.

The parenthesis is a capture group. It is used to capture the text within it. In this example, it is used to capture any text within double quotes.

The regular expression will not match the following valid examples:

The regular expression to match all these cases turns out to be a bit complex.

  • \s = white space.
  • * = 0 or more times.
  • [^””] = not a double quote character.
  • \S = not white space.
  • + = 1 or more times.

Implementing IDisposable interface correctly.

IDisposable interface is used to dispose the resources consumed by the object before the object is garbage collected. The typical resource-intensive object is any resource that has a database connection. The DbContext class of Entity Framework implements an IDisposable interface.

Implementing IDisposable interface

The following code shows how to implement the IDisposable interface correctly.

The class must implement the Dispose method. The Dispose method should dispose the resources consumed by it and finally call the GC.SuppressFinalize method. The SuppressFinalize indicates to the garbage collector that the object is already finalized.

Implementing just the Dispose method is not sufficient. If the class is public and not sealed, then running Code Analysis will show a few warnings. The code analysis tool suggests that disposal of managed resources and native resources should be handled differently.

The private method Dispose(bool) takes a boolean flag that indicates whether managed resources should also be disposed. If the flag is true, then both the native resources and managed resources are disposed of. If the flag is false, then only the native resources are disposed of.

Difference between IComparable and IEqualityComparer.

IComparer and IEqualityComparer<T> are commonly used interfaces in .NET framework. IComparer is a non-generic interface type. IEqualityComparer<T> is a generic interface type. The two interfaces are used for two different purposes. This article explains the difference between the two interfaces using an example class: HouseNumber.

Implementing IComparer interface

The IComparer interface has a single method. The IComparer implementation for the HouseNumber class is shown below.

HouseNumber is first compared by the BlockName property, and if two BlockNames are equal, then it is compared by the Number property.

IComparable interface is used when calling Sort() on a list of HouseNumbers.

Implementing IEqualityComparer<T> interface

IEqualityComparer interface has two methods: Equals() and GetHashCode(). The interface implementation for the HouseNumber class is shown below.

The IEqualityComparer<T> interface is implemented when the class is used as a key in a generic Dictionary. eg.  Dictionary<HouseNumber, Address>

Create zip files using ZipFile class.

ZipFile class introduced in .NET Framework 4.5 is a handy utility class to:

  1. Compress files to a zip file
  2. Extract the contents of a zip file.

ZipFile is available in the System.IO.Compression.FileSystem assembly.

Compression using ZipFile

The code below compresses the source folder into a zip file.

 Extract using ZipFile

The code below extracts the contents of the zip file and stores it in a destination folder.

 Adding new files to the archive

ZipFile class exposes an Open method. The Open method provides a ZipArchive object. With the ZipArchive object, it is possible to enumerate the files within the archive. It is also possible to add new files or remove existing files from the archive. The following code shows how to add a new file to the archive.

The ZipArchive class has the CreateEntryFromFile method which adds a new file to the archive. ZipArchive is available in the System.IO.Compression assembly.

Random selection using Fisher Yates algorithm.

Problem Statement

From a list of N items, pick K items where 0 < K < N.

Fisher Yates algorithm shuffles a collection of N items. The algorithm is simple: For each item in the collection, pick a random item. Swap the item with the random item.

Random Selection

The code for Fisher Yates algorithm is shown below.

If the items to be picked is greater than the size of the collection, then an ArgumentException is thrown.

In the modified version of Fisher Yates algorithm, the last element in the collection is swapped with a random element in the collection. When the last K items are randomly selected, the loop terminates. Finally, the method picks the last K items and returns it as an IEnumerable.

Attribution: The article was published first at VIJAYT.COM.

Execute SQL command or query using ADO.NET

ADO.NET provides a framework for executing SQL command or query against the database. SqlConnection, SqlCommand, SqlDataAdapter, SqlDataReader, and DataSet are useful classes in ADO.NET.

Executing command using ADO.NET

SQL command can be CREATE, UPDATE, or DELETE statements. Commands are used to change the state of the database. The code for executing command is shown below.

The ExecuteNonQuery method of SqlCommand is used to execute commands against the database.

Execute query using ADO.NET

SQL Query is a SELECT statement. Queries are used to retrieved data from the database. The code for executing queries is shown below.

To execute a query, the ExecuteReader method is used. The method returns a move-forward, read-only cursor that can be iterated to retrieve the data. The reader requires a connection to the database.

Alternatively, a DataSet can be used to retrieve data. The DataSet resembles a table with rows and columns of data. DataSet does not require a connection to the database. It is a disconnected collection of data.