There is very nice SSH library for .NET called SSH.NET. You can find it here:
https://github.com/sshnet/SSH.NET, also available as a nuget package, so you can install it in a couple of clicks. Here is a brief client example:
using Renci.SshNet;
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter IP:");
var ip = Console.ReadLine();
Console.WriteLine("Enter username:");
var username = Console.ReadLine();
Console.WriteLine("Enter password:");
var password = Console.ReadLine();
using (var client = new SshClient(ip, username, password))
{
client.Connect();
while (true)
{
var input = Console.ReadLine();
if (input.Contains("exit my console app"))
break;
Console.WriteLine(client.RunCommand(input).Result);
}
}
}
}
}
Thursday, October 26, 2017
OpenVPN Jumpstart
Yesterday I badly needed to establish VPN connection between two computers, nothing extraordinary, one server and one client. In order to accomplish this quite trivial task I created a key:
openvpn --genkey --secret whatever.key
and two configuration files for the server(192.168.1.1):
and surprisingly it worked :)
dev tun
ifconfig 10.0.0.1 10.0.02
secret whatever.key
and the client(192.168.1.2) respectively:
remote 192.168.1.1
dev tun
ifconfig 10.0.0.2 10.0.01
secret whatever.key
Then I just ran:
openvpn --config server.conf
openvpn --config client.conf
By the way, if you have some kinda firewall or something you might need to consider opening port 1194.
Expression Bodied Functions and Properties in C#
Since C# 6 you can take advantage of using much more laconic expression bodied functions. Oh, expression bodied basically means lambdish or just bodiless :)
using System;
namespace ConsoleApp
{
class Program
{
static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);
static void Main(string[] args)
{
ExpressionBodiedMethod("Hello!");
}
}
}
That shortened syntax can also be used to create a getter-only property:
using System;
namespace ConsoleApp
{
class Program
{
static string ExpressionBodiedReadOnlyPrpoperty => "Hello!";
/*static string ExpressionBodiedReadOnlyPrpoperty { get; } = "Hello!";*/
static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);
static void Main(string[] args)
{
ExpressionBodiedMethod(ExpressionBodiedReadOnlyPrpoperty);
}
}
}
using System;
namespace ConsoleApp
{
class Program
{
static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);
static void Main(string[] args)
{
ExpressionBodiedMethod("Hello!");
}
}
}
That shortened syntax can also be used to create a getter-only property:
using System;
namespace ConsoleApp
{
class Program
{
static string ExpressionBodiedReadOnlyPrpoperty => "Hello!";
/*static string ExpressionBodiedReadOnlyPrpoperty { get; } = "Hello!";*/
static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);
static void Main(string[] args)
{
ExpressionBodiedMethod(ExpressionBodiedReadOnlyPrpoperty);
}
}
}
Thursday, October 19, 2017
Async and Await in C#
It's possible to do asynchronous programming in C#. In order to ease your life a little bit they came up with the idea to add a couple of extra keywords: async and await.
using System;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int result = DoSomeJobAsync().Result;
Console.WriteLine("Result: " + result);
}
async static Task<int> DoSomeJobAsync() {
return await Task.Run(() => { return 777; });
}
}
}
So, to tell compiler you want your method to be "asynchronous" you have to prepend it with async keyword which enables you to use await keyword inside it in order to create so-called suspension point which is basically the asynchronous equivalent of blocking. The whole concept is meant to manage asynchronous and synchronous calls separately, but I'll tell you what, it's impossible and if you disagree, take a look at what happens in Main. As we cannot use await in synchronous method we are forced to block until we get the result from asynchronous chain of methods.
using System;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
int result = DoSomeJobAsync().Result;
Console.WriteLine("Result: " + result);
}
async static Task<int> DoSomeJobAsync() {
return await Task.Run(() => { return 777; });
}
}
}
So, to tell compiler you want your method to be "asynchronous" you have to prepend it with async keyword which enables you to use await keyword inside it in order to create so-called suspension point which is basically the asynchronous equivalent of blocking. The whole concept is meant to manage asynchronous and synchronous calls separately, but I'll tell you what, it's impossible and if you disagree, take a look at what happens in Main. As we cannot use await in synchronous method we are forced to block until we get the result from asynchronous chain of methods.
Tuesday, October 17, 2017
Simple data binding in WPF
Data binding in WPF is how you pass data between your code and user interface. The simplest way to bind some data is to use DataContext property. Each element has its own DataContext property, which if not set, inherits its value from parent element. In the example below all elements are gonna inherit DataContext from MainWindow.
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Location();
}
}
public class Location
{
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public Location()
{
Country = "Russian Federation";
State = "Sverdlovsk";
City = "Yekaterinburg";
}
}
}
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="Country:"
HorizontalAlignment="Left"
Margin="29,21,0,0"
VerticalAlignment="Top"/>
<Label Content="State:"
HorizontalAlignment="Left"
Margin="29,70,0,0"
VerticalAlignment="Top"/>
<Label Content="City:"
HorizontalAlignment="Left"
Margin="29,125,0,0"
VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,49,0,0"
TextWrapping="Wrap"
Text="{Binding Country, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,99,0,0"
TextWrapping="Wrap"
Text="{Binding State, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,154,0,0"
TextWrapping="Wrap"
Text="{Binding City, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
</Grid>
</Window>
Ok, now all texboxes have text field set to corresponding Location property's value. But what if we also wanna set whatever user enters in textbox to corresponding Location property's value? We can easily do this by simply changing binding mode from OneWay to TwoWay.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="Country:"
HorizontalAlignment="Left"
Margin="29,21,0,0"
VerticalAlignment="Top"/>
<Label Content="State:"
HorizontalAlignment="Left"
Margin="29,70,0,0"
VerticalAlignment="Top"/>
<Label Content="City:"
HorizontalAlignment="Left"
Margin="29,125,0,0"
VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,49,0,0"
TextWrapping="Wrap"
Text="{Binding Country, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,99,0,0"
TextWrapping="Wrap"
Text="{Binding State, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,154,0,0"
TextWrapping="Wrap"
Text="{Binding City, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
</Grid>
</Window>
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Location();
}
}
public class Location
{
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public Location()
{
Country = "Russian Federation";
State = "Sverdlovsk";
City = "Yekaterinburg";
}
}
}
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="Country:"
HorizontalAlignment="Left"
Margin="29,21,0,0"
VerticalAlignment="Top"/>
<Label Content="State:"
HorizontalAlignment="Left"
Margin="29,70,0,0"
VerticalAlignment="Top"/>
<Label Content="City:"
HorizontalAlignment="Left"
Margin="29,125,0,0"
VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,49,0,0"
TextWrapping="Wrap"
Text="{Binding Country, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,99,0,0"
TextWrapping="Wrap"
Text="{Binding State, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,154,0,0"
TextWrapping="Wrap"
Text="{Binding City, Mode=OneWay}"
VerticalAlignment="Top"
Width="120"/>
</Grid>
</Window>
Ok, now all texboxes have text field set to corresponding Location property's value. But what if we also wanna set whatever user enters in textbox to corresponding Location property's value? We can easily do this by simply changing binding mode from OneWay to TwoWay.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="Country:"
HorizontalAlignment="Left"
Margin="29,21,0,0"
VerticalAlignment="Top"/>
<Label Content="State:"
HorizontalAlignment="Left"
Margin="29,70,0,0"
VerticalAlignment="Top"/>
<Label Content="City:"
HorizontalAlignment="Left"
Margin="29,125,0,0"
VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,49,0,0"
TextWrapping="Wrap"
Text="{Binding Country, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,99,0,0"
TextWrapping="Wrap"
Text="{Binding State, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
<TextBox HorizontalAlignment="Left"
Height="23"
Margin="29,154,0,0"
TextWrapping="Wrap"
Text="{Binding City, Mode=TwoWay}"
VerticalAlignment="Top"
Width="120"/>
</Grid>
</Window>
Monday, October 16, 2017
finally block and using statement in C#
In addition to try and catch C# got so-called finally block whose purpose is to free resources allocated within try block.
using System.IO;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter("myFile.txt");
sw.WriteLine("Hello");
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
}
}
using System.IO;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter("myFile.txt");
sw.WriteLine("Hello");
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
}
}
finally block will get executed even if something in your try block throws an exception. There is much more convenient way to create try-finally block around your code though, its called using statement:
using System.IO;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using(StreamWriter sw = new StreamWriter("myFile.txt"))
{
sw.WriteLine("Hello");
}
}
}
}
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using(StreamWriter sw = new StreamWriter("myFile.txt"))
{
sw.WriteLine("Hello");
}
}
}
}
If you need to be able to handle exception you're gonna have to use the previous syntax plus catch block as using statement can't help you with that:
using System.IO;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter("myFile.txt");
sw.WriteLine("Hello");
}
catch(IOException e)
{
// Handle exception before resource gets freed in finally block.
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
}
}
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter("myFile.txt");
sw.WriteLine("Hello");
}
catch(IOException e)
{
// Handle exception before resource gets freed in finally block.
}
finally
{
if (sw != null)
{
sw.Dispose();
}
}
}
}
}
Extension methods in C#
C# got very interesting feature allowing you to add a method to existing class. Here is what it looks like:
namespace ConsoleApp
{
class A
{
public double value { get; set; }
public A()
{
value = 7.0;
}
}
static class ExtensionMethods
{
public static double ComputeReciprocal(this A a)
{
return 1.0 / a.value;
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
var value = a.value;
var reciprocal = a.ComputeReciprocal();
}
}
}
C# successfully recognized ComputeReciprocal as A class extension method and let us call it like if it belonged to the class. Please pay attention to extension method parameter list, the first parameter always has to be: this ClassName parameterName, after the first parameter you can add as many additional parameters as you want:
namespace ConsoleApp
{
class Person
{
public string FirstName { get; set; }
public Person()
{
FirstName = "Alex";
}
}
static class ExtensionMethods
{
public static string GetFullName(this Person person, string lastName)
{
return person.FirstName + " " + lastName;
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person();
var fullName = person.GetFullName("Peters");
}
}
}
By the way, it doesn't matter what you call static class which contains your extension methods.
namespace ConsoleApp
{
class A
{
public double value { get; set; }
public A()
{
value = 7.0;
}
}
static class ExtensionMethods
{
public static double ComputeReciprocal(this A a)
{
return 1.0 / a.value;
}
}
class Program
{
static void Main(string[] args)
{
var a = new A();
var value = a.value;
var reciprocal = a.ComputeReciprocal();
}
}
}
C# successfully recognized ComputeReciprocal as A class extension method and let us call it like if it belonged to the class. Please pay attention to extension method parameter list, the first parameter always has to be: this ClassName parameterName, after the first parameter you can add as many additional parameters as you want:
namespace ConsoleApp
{
class Person
{
public string FirstName { get; set; }
public Person()
{
FirstName = "Alex";
}
}
static class ExtensionMethods
{
public static string GetFullName(this Person person, string lastName)
{
return person.FirstName + " " + lastName;
}
}
class Program
{
static void Main(string[] args)
{
var person = new Person();
var fullName = person.GetFullName("Peters");
}
}
}
By the way, it doesn't matter what you call static class which contains your extension methods.
Increment and Decrement operator overloading in C++
In C++ you can overload both prefix and postfix increment and decrement operators like that:
class Dummy
{
public:
Dummy() :value(0) {}
Dummy(int pmValue) : value(pmValue) {}
Dummy(const Dummy& dummy) : value(dummy.getValue()) {}
int getValue() const
{
return value;
}
//---------------------------------------- Prefix
Dummy& operator++()
{
++value;
return *this;
};
Dummy& operator--()
{
--value;
return *this;
};
//---------------------------------------- Postfix
Dummy operator++(int)
{
Dummy lvDummy(*this);
++value;
return lvDummy;
};
Dummy operator--(int)
{
Dummy lvDummy(*this);
--value;
return lvDummy;
};
private:
int value;
};
If you had a problem with postfix ones, you just needed to add a parameter. Keep in mind that according to C++ standard (page 327, 13.5.7), the parameter must be int. Oh, you can also overload all of them globally following the same principle:
class Dummy
{
public:
Dummy() :value(0) {}
Dummy(const Dummy& dummy) : value(dummy.value) {}
Dummy(int pmValue) : value(pmValue) {}
int value;
};
Dummy& operator ++ (Dummy& dummy) {
++dummy.value;
return dummy;
}
Dummy& operator -- (Dummy& dummy) {
--dummy.value;
return dummy;
}
Dummy operator ++ (Dummy& dummy, int) {
Dummy lvDummy(dummy);
++dummy.value;
return lvDummy;
}
Dummy operator -- (Dummy& dummy, int) {
Dummy lvDummy(dummy);
--dummy.value;
return lvDummy;
}
class Dummy
{
public:
Dummy() :value(0) {}
Dummy(int pmValue) : value(pmValue) {}
Dummy(const Dummy& dummy) : value(dummy.getValue()) {}
int getValue() const
{
return value;
}
//---------------------------------------- Prefix
Dummy& operator++()
{
++value;
return *this;
};
Dummy& operator--()
{
--value;
return *this;
};
//---------------------------------------- Postfix
Dummy operator++(int)
{
Dummy lvDummy(*this);
++value;
return lvDummy;
};
Dummy operator--(int)
{
Dummy lvDummy(*this);
--value;
return lvDummy;
};
private:
int value;
};
If you had a problem with postfix ones, you just needed to add a parameter. Keep in mind that according to C++ standard (page 327, 13.5.7), the parameter must be int. Oh, you can also overload all of them globally following the same principle:
class Dummy
{
public:
Dummy() :value(0) {}
Dummy(const Dummy& dummy) : value(dummy.value) {}
Dummy(int pmValue) : value(pmValue) {}
int value;
};
Dummy& operator ++ (Dummy& dummy) {
++dummy.value;
return dummy;
}
Dummy& operator -- (Dummy& dummy) {
--dummy.value;
return dummy;
}
Dummy operator ++ (Dummy& dummy, int) {
Dummy lvDummy(dummy);
++dummy.value;
return lvDummy;
}
Dummy operator -- (Dummy& dummy, int) {
Dummy lvDummy(dummy);
--dummy.value;
return lvDummy;
}
Sunday, October 15, 2017
Move constructor and assignment operator in C++
In addition to copy constructor and assignment operator C++ got so-called move constructor and assignment operator. First I am gonna show you what copy constructor and assignment operators are:
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Copy constructor
A(const A& a)
{
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
~A()
{
delete[] some_data;
}
// Assignment operator
A& operator = (const A& a)
{
if (this != &a)
{
delete[] some_data;
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
return *this;
}
};
int main()
{
A a1;
A a2(a1); // Copy constructor call
A a3;
a3 = a1; // Assignment operator call
return 0;
}
As you can see both copy constructor and assignment operator do exactly the same thing, they create a copy of other instance of the same class. In the example above, copying maybe slightly optimized using move constructor and move assignment operator:
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Move constructor
A(A&& a)
{
some_data = a.some_data;
a.some_data = nullptr;
}
~A()
{
delete[] some_data;
}
// Move assignment operator
A& operator = (A&& a)
{
if (this != &a)
{
delete[] some_data;
some_data = a.some_data;
a.some_data = nullptr;
}
return *this;
}
};
int main()
{
A a1;
A a2(std::move(a1)); // Move constructor call
A a3;
a3 = std::move(a1); // Move assignment operator call
return 0;
}
In other words, move constructor and move assignment operator are merely optimized versions of regular copy constructor and assignment operator.
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Copy constructor
A(const A& a)
{
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
~A()
{
delete[] some_data;
}
// Assignment operator
A& operator = (const A& a)
{
if (this != &a)
{
delete[] some_data;
some_data = new int[128];
memcpy(some_data, a.some_data, 128);
}
return *this;
}
};
int main()
{
A a1;
A a2(a1); // Copy constructor call
A a3;
a3 = a1; // Assignment operator call
return 0;
}
As you can see both copy constructor and assignment operator do exactly the same thing, they create a copy of other instance of the same class. In the example above, copying maybe slightly optimized using move constructor and move assignment operator:
class A
{
public:
int* some_data;
A()
{
some_data = new int[128];
}
// Move constructor
A(A&& a)
{
some_data = a.some_data;
a.some_data = nullptr;
}
~A()
{
delete[] some_data;
}
// Move assignment operator
A& operator = (A&& a)
{
if (this != &a)
{
delete[] some_data;
some_data = a.some_data;
a.some_data = nullptr;
}
return *this;
}
};
int main()
{
A a1;
A a2(std::move(a1)); // Move constructor call
A a3;
a3 = std::move(a1); // Move assignment operator call
return 0;
}
In other words, move constructor and move assignment operator are merely optimized versions of regular copy constructor and assignment operator.
C++ inheritance flavors
C++ has 4 types of inheritance. Let's start with public inheritance:
class A {
public:
void one() {}
protected:
void two() {}
private:
void three() {}
};
class B : public A {};
Public inheritance implies that class B inherits all public and protected methods from class A as is. This is what signature of class B looks like now:
class B : public A
{
public:
void one() {}
protected:
void two() {}
};
Let's move on and take a look at protected inheritance as well:
class B : protected A
{
protected:
void one() {}
void two() {}
};
As you can see the difference between the two is that all public methods of class A become protected in class B. Now, guess what happens when you use private inheritance? This is what happens:
class B : private A
{
private:
void one() {}
void two() {}
};
All public and protected methods inherited from A become private. Ok, I said there are 4, the fourth one is so-called virtual inheritance which allows you to literally share your base class when, for instance to fight famous diamond problem. Let's create some kinda diamond for clarity:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Despite the fact that there will be two Top classes in our hierarchy, this will compile and run like it's no problem. Please run it and you'll see that Top constructor gets called twice. If such a behavior bothers you, you can get rid of the second Top class using virtual inheritance:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public virtual Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public virtual Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Now, run it again to make sure we have only one Top.
class A {
public:
void one() {}
protected:
void two() {}
private:
void three() {}
};
class B : public A {};
Public inheritance implies that class B inherits all public and protected methods from class A as is. This is what signature of class B looks like now:
class B : public A
{
public:
void one() {}
protected:
void two() {}
};
Let's move on and take a look at protected inheritance as well:
class B : protected A
{
protected:
void one() {}
void two() {}
};
As you can see the difference between the two is that all public methods of class A become protected in class B. Now, guess what happens when you use private inheritance? This is what happens:
class B : private A
{
private:
void one() {}
void two() {}
};
All public and protected methods inherited from A become private. Ok, I said there are 4, the fourth one is so-called virtual inheritance which allows you to literally share your base class when, for instance to fight famous diamond problem. Let's create some kinda diamond for clarity:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Despite the fact that there will be two Top classes in our hierarchy, this will compile and run like it's no problem. Please run it and you'll see that Top constructor gets called twice. If such a behavior bothers you, you can get rid of the second Top class using virtual inheritance:
class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}
void topMethod() {}
};
class Left : public virtual Top
{
public:
void leftMethod()
{
topMethod();
}
};
class Right : public virtual Top
{
public:
void rightMethod()
{
topMethod();
}
};
class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};
Now, run it again to make sure we have only one Top.
Multithreading in C++
Since C++ 11 multithreading in C++ became a lot easier. You no longer need to wrap system specific stuff like threads and synchronization primitives yourself as they all are already there. Ok, let's get to it. In modern C++ you can spawn a new thread as easy as that:
As you can see std::unique_lock is much more flexible when it comes to a lock management. Talking about flexibility, there is one more synchronization primitive I'd like to show you, which is a condition variable. Let's slightly modify our example to use this primitive:
Ok, now let me try to explain to you what's going on in here. First of, as you can see, we still use locks to protect our resource. Well, actually we protect both our resource and std::condition_variable whose purpose is to unblock all threads waiting on it and then reacquire locks upon notification from other thread, which, in our example, happens to be main thread. Yes, I know, my example is way too trivial to be practical, but it wasn't the goal here, I merely wanted to explain the idea.
#include <thread>
void threadFunction() {}
int main()
{
std::thread thread(threadFunction);
thread.join();
return 0;
}
Now, let's talk about synchronization, starting with Mutex. Mutex is a quite simple synchronization primitive meant for protecting a resource from accessing by multiple threads at the same time. Here is what it looks like:
#include <thread>
#include <mutex>
std::mutex mutex;
int resource = 2;
void threadFunction()
{
std::lock_guard<std::mutex> lock(mutex);
resource *= 2;
}
int main()
{
std::thread thread1(threadFunction);
std::thread thread2(threadFunction);
thread1.join();
thread2.join();
return 0;
}
As you can see from the example above we successfully protected our resource variable from accessing by multiple threads using mutex. You probably noticed that we used std::lock_guard template class to lock our mutex, well std::lock_guard is that exact lock wrapper we used to make ourselves before C++11 arrival. If you forgot how it works, its very simple. It locks mutex upon construction and then releases it upon destruction when we leave function body scope. You may be wondering why cant you lock and unlock mutex whenever you need using std::lock_guard, well, thats because std::lock_guard follows so-called scope ownership which prevents you from managing your lock in any way. If you need to manage your lock you kinda have to use a different kinda lock which is std::unique_lock.
#include <thread>
#include <mutex>
std::mutex mutex;
int resource = 2;
void threadFunction()
{
std::unique_lock<std::mutex> lock(mutex);
resource *= 2;
lock.unlock();
lock.unlock();
}
int main()
{
std::thread thread1(threadFunction);
std::thread thread2(threadFunction);
thread1.join();
thread2.join();
return 0;
}
As you can see std::unique_lock is much more flexible when it comes to a lock management. Talking about flexibility, there is one more synchronization primitive I'd like to show you, which is a condition variable. Let's slightly modify our example to use this primitive:
#include <thread>
#include <mutex>
#include <condition_variable>
#include <condition_variable>
std::mutex mutex;
std::condition_variable condition_variable;
std::condition_variable condition_variable;
int resource = 2;
void threadFunction()
{
// Lock or if we can't block as usual
// Lock or if we can't block as usual
std::unique_lock<std::mutex> lock(mutex);
// Successfully acquired lock, now we can access our std::condition_variable.
// Calling wait method, which blocks this thread and releases lock.
condition_variable.wait(lock);
// Successfully acquired lock, now we can access our std::condition_variable.
// Calling wait method, which blocks this thread and releases lock.
condition_variable.wait(lock);
// If we got here it means main thread called condition_variable.notify_all(),
// which resulted in unblocking current thread and reacquiring lock.
// We can thread-safely mess with out beloved resource.
// which resulted in unblocking current thread and reacquiring lock.
// We can thread-safely mess with out beloved resource.
resource *= 2;
}
int main()
{
std::thread thread1(threadFunction);
std::thread thread2(threadFunction);
std::unique_lock<std::mutex> lock(mutex);
condition_variable.notify_all();
std::unique_lock<std::mutex> lock(mutex);
condition_variable.notify_all();
thread1.join();
thread2.join();
return 0;
}
Ok, now let me try to explain to you what's going on in here. First of, as you can see, we still use locks to protect our resource. Well, actually we protect both our resource and std::condition_variable whose purpose is to unblock all threads waiting on it and then reacquire locks upon notification from other thread, which, in our example, happens to be main thread. Yes, I know, my example is way too trivial to be practical, but it wasn't the goal here, I merely wanted to explain the idea.
Saturday, October 14, 2017
SOLID
SOLID is an acronym for 5 design principles:
S - Single Responsibility Principle
O - Open Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
S - Single Responsibility Principle
O - Open Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
Friday, October 13, 2017
Lambdas in C++
So you wanna use lambdas in C++ huh? It's as simple as that:
auto lambda = []() = {
printf("Hello, I am a simplest lambda.");
};
Now, if you wanna invoke it only once you can omit assigning value and either add parentheses at the end or use std::invoke():
[]() = {
printf("Hello, I am a simplest lambda.");
}();
std::invoke([]() {
printf("Hello, I am a simplest lambda.");
});
Or if you got a value you can just call it like any other function:
lambda();
What about parameters, return value? Just put them where they belong:
auto lambda = [](int a, int b) {
return a + b;
};
int result = lambda(1, 2);
Guess we are done here, let's move on and talk about captures. Ok, see those square brackets over there? That's called Capture List, a place where you put your captures. A capture is an identifier of a variable defined outside your lambda and a method to copy(capture) it.
[] - empty brackets mean there is nothing to capture.
[count] - identifier means capturing a variable by value.
int count = 9;
auto lambda = [count]() {
std::cout << count << std::endl;
};
[&count] - identifier with ampersand means capturing a variable by reference.
auto lambda = [&count]() {
std::cout << count << std::endl;
};
[=] - means capturing all local variables used inside lambda by value.
void function()
{
int count = 9;
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
[&] - means capturing all local variables used inside lambda by reference.
void function()
{
int count = 9;
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
[this] - means capturing this pointer.
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [this]() {
std::cout << count << std::endl;
};
lambda();
}
};
Actually [=] and [&] capture this pointer too, if it exists:
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
};
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
};
auto lambda = []() = {
printf("Hello, I am a simplest lambda.");
};
Now, if you wanna invoke it only once you can omit assigning value and either add parentheses at the end or use std::invoke():
[]() = {
printf("Hello, I am a simplest lambda.");
}();
std::invoke([]() {
printf("Hello, I am a simplest lambda.");
});
Or if you got a value you can just call it like any other function:
lambda();
What about parameters, return value? Just put them where they belong:
auto lambda = [](int a, int b) {
return a + b;
};
int result = lambda(1, 2);
Guess we are done here, let's move on and talk about captures. Ok, see those square brackets over there? That's called Capture List, a place where you put your captures. A capture is an identifier of a variable defined outside your lambda and a method to copy(capture) it.
[] - empty brackets mean there is nothing to capture.
[count] - identifier means capturing a variable by value.
int count = 9;
auto lambda = [count]() {
std::cout << count << std::endl;
};
[&count] - identifier with ampersand means capturing a variable by reference.
auto lambda = [&count]() {
std::cout << count << std::endl;
};
[=] - means capturing all local variables used inside lambda by value.
void function()
{
int count = 9;
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
[&] - means capturing all local variables used inside lambda by reference.
void function()
{
int count = 9;
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
[this] - means capturing this pointer.
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [this]() {
std::cout << count << std::endl;
};
lambda();
}
};
Actually [=] and [&] capture this pointer too, if it exists:
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [=]() {
std::cout << count << std::endl;
};
lambda();
}
};
class ClassWithLambda
{
private:
int count;
public:
ClassWithLambda():count(9) {}
void methodWithLambda()
{
auto lambda = [&]() {
std::cout << count << std::endl;
};
lambda();
}
};
Thursday, October 12, 2017
Arrays and Collections in C#
Arrays
C# supports single-dimensional as well as multidimensional arrays. Here is what array declaration looks like:
int[] array1 = new int[4];
This is how you normally access its elements using subscript operator:
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
Now I'mma show you exactly the same array, but with initialization upon declaration:
int[] array1 = new int[4] {0,1,2,3};
Convenient, isn't it? Ok, before we go any further, I wanna show you a couple of ways to iterate through an array:
for (int i = 0; i < array1.Length; ++i)
Console.WriteLine(array1[i]);
foreach (int element in array1)
Console.WriteLine(element);
I think it's time to get familiar with multidimensional arrays.
int[,] array2 = new int[4,4];
int[,] array2 = new int[4,4];
{
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 }
};
Array.Length property returns total length of the array including all dimensions. If you wanna know how many elements are in concrete dimension, use Array.GetLength(dimension). If you wanna know how many dimensions are in your array, use Array.Rank property.
foreach doesnt care about dimensionality of your array, it will iterate from the beginning to the end, dimension by dimension:
foreach (int element in array2)
Console.WriteLine(element);
for (int k = 0; k < array2.GetLength(1); ++k)
Console.WriteLine(array2[i,k]);
Collections
C# also got plenty of different collections, let's take a brief look at some of them, starting with dictionary. Ok this is what dictionary looks like:
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
Basically it's just an associative array storing key-value pairs. The first generic type parameter is a type of key, the second one is a type of value respectively. Let me show you how this thing works.
You add key-value pairs this way:
dictionary.Add("One", 1);
dictionary.Add("Two", 2);
And that's how you access its values:
int one = dictionary["One"];
int two = dictionary["Two"];
Ok, now I wanna show you some lists. Let's start with regular List which looks like this:
List<string> list = new List<string>();
And works like this:
list.Add("One");
list.Add("Two");
list.Add("Three");
string One = list[0];
string Two = list[1];
string Three = list[2];
As you can see List behaves just like array, but its more advanced and flexible. Ok, the last one is gonna be LinkedList. This is what it looks like:
LinkedList<string> linkedList =
new LinkedList<string>();
You can add nodes at any end:
linkedList.AddFirst("first");
linkedList.AddLast("last");
And access them in the following manner:
string first = linkedList.First.Value;
string last = linkedList.First.Next.Value;
foreach (var element in linkedList){}
Lambdas in C#
C# supports lambdas. Here is what simplest lambda looks like:
Action l = () => Console.WriteLine(
"Hello, I am a simplest lambda.");
l();
As its the simplest, it got no parameters and doesn't return anything. Ok, now I'mma show you lambda with one parameter:
Action<string> l = (s) => Console.WriteLine(s);
l("Hello, I am a lambda 1 parameter.");
You probably noticed that I omitted parameter type, it's not necessary as type was already specified by the delegate. Well, if you really want it, you can safely put the same type in argument list.
Action<string> l = (string s) => Console.WriteLine(s);
l("Hello, I am a lambda with 1 parameter.");
Now, what about lambdas with multiple parameters?
Action<string, string> l = (s1, s2) => Console.WriteLine(s1 + s2);
l("Hello,", "I am a lambda with 2 parameters.");
Almost forgot, lambdas can have bodies too:
Action<string, string> l = (s1, s2) =>
{
Console.WriteLine(s1 + s2);
};
l("Hello,", "I am a lambda with 2 parameters.");
If you need lambdas returning some kinda value you need different delegate:
Action l = () => Console.WriteLine(
"Hello, I am a simplest lambda.");
l();
As its the simplest, it got no parameters and doesn't return anything. Ok, now I'mma show you lambda with one parameter:
Action<string> l = (s) => Console.WriteLine(s);
l("Hello, I am a lambda 1 parameter.");
You probably noticed that I omitted parameter type, it's not necessary as type was already specified by the delegate. Well, if you really want it, you can safely put the same type in argument list.
Action<string> l = (string s) => Console.WriteLine(s);
l("Hello, I am a lambda with 1 parameter.");
Now, what about lambdas with multiple parameters?
Action<string, string> l = (s1, s2) => Console.WriteLine(s1 + s2);
l("Hello,", "I am a lambda with 2 parameters.");
Almost forgot, lambdas can have bodies too:
Action<string, string> l = (s1, s2) =>
{
Console.WriteLine(s1 + s2);
};
l("Hello,", "I am a lambda with 2 parameters.");
If you need lambdas returning some kinda value you need different delegate:
Func<int> l = () => { return 7; };
Func delegate may have parameters too, just like Action:
Func<int, int> l = (i) => { return i; };
Func<int, int> l = i => i;
Equality in C#
Ok, let's start with so-called reference equality (as in two pointers with same or different addresses).
In order to demonstrate reference comparison I'mma create some class and then instantiate it 2 times, so we cover both true and false cases:
class A{}
var a1 = new A();
var a2 = new A();
What's really interesting about this comparison is that its kinda default, meaning all method calls including equality operator will return true for a1 == a1:
var result1 = Object.Equals(a1,a1); // true
var result2 = Object.ReferenceEquals(a1, a1); // true
var result3 = a1.equals(a1); // true
var result4 = a1 == a2; // true
Correspondingly, all of them will return false for a1 == a2:
var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // false
var result4 = a1 == a2; // false
Unlike Java C# actually has operator overloading, so why don't we overload all equality related methods of class A? Here is how we do this:
class A
{
public static bool operator == (A a1, A a2)
{
return true;
}
// Irrelevant, but C# requires that we overload this one too
public static bool operator != (A a1, A a2)
{
return false;
}
public bool Equals(A a)
{
return true;
}
}
Let's compare a1 to a2 again:
var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // true
var result4 = a1 == a2; // true
Now that we overloaded A's equality operators we can no longer rely on them to do reference equality comparison unless we know for sure they behave exactly like the default ones. In other words if we want reference equality our best option is definitely Object.ReferenceEquals method.
In order to demonstrate reference comparison I'mma create some class and then instantiate it 2 times, so we cover both true and false cases:
class A{}
var a1 = new A();
var a2 = new A();
What's really interesting about this comparison is that its kinda default, meaning all method calls including equality operator will return true for a1 == a1:
var result1 = Object.Equals(a1,a1); // true
var result2 = Object.ReferenceEquals(a1, a1); // true
var result3 = a1.equals(a1); // true
var result4 = a1 == a2; // true
Correspondingly, all of them will return false for a1 == a2:
var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // false
var result4 = a1 == a2; // false
Unlike Java C# actually has operator overloading, so why don't we overload all equality related methods of class A? Here is how we do this:
class A
{
public static bool operator == (A a1, A a2)
{
return true;
}
// Irrelevant, but C# requires that we overload this one too
public static bool operator != (A a1, A a2)
{
return false;
}
public bool Equals(A a)
{
return true;
}
}
Let's compare a1 to a2 again:
var result1 = Object.Equals(a1,a2); // false
var result2 = Object.ReferenceEquals(a1, a2); // false
var result3 = a1.equals(a2); // true
var result4 = a1 == a2; // true
Now that we overloaded A's equality operators we can no longer rely on them to do reference equality comparison unless we know for sure they behave exactly like the default ones. In other words if we want reference equality our best option is definitely Object.ReferenceEquals method.
Looks like I completely omitted Value Equality. Well, if you need it, just implement your own equality/inequality operators and Equals method.
Factory pattern in C#
Ok, so the idea is to create a class able to mass-produce instances of a different class or classess.
First, let's create something to be produced by our Factory class as in product:
abstract class Product
{
public abstract ProductType GetProductType();
}
class Car : Product
{
public override ProductType GetProductType()
{
return ProductType.Car;
}
}
class Motorcycle : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
class Airplane : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).
Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:
abstract class Factory
{
public abstract Product createProduct();
}
class CarFactory : Factory
{
public override Product createProduct()
{
return new Car();
}
}
class MotorcycleFactory : Factory
{
public override Product createProduct()
{
return new Motorcycle();
}
}
class AirplaneFactory : Factory
{
public override Product createProduct()
{
return new Airplane();
}
}
Well, I guess, that's about it.
First, let's create something to be produced by our Factory class as in product:
abstract class Product
{
public abstract ProductType GetProductType();
}
class Car : Product
{
public override ProductType GetProductType()
{
return ProductType.Car;
}
}
class Motorcycle : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
class Airplane : Product
{
public override ProductType GetProductType()
{
return ProductType.Motorcycle;
}
}
You don't have to do it exactly this way, I mean, you can use interfaces if you want or even concrete unrelated classes (which you can return from Factory as Object).
Now we need to make some Factories. I create one for each type of product, but again, this one is up to you, you can implement this functionality as you please:
abstract class Factory
{
public abstract Product createProduct();
}
class CarFactory : Factory
{
public override Product createProduct()
{
return new Car();
}
}
class MotorcycleFactory : Factory
{
public override Product createProduct()
{
return new Motorcycle();
}
}
class AirplaneFactory : Factory
{
public override Product createProduct()
{
return new Airplane();
}
}
Well, I guess, that's about it.
Singleton pattern in C#
Frankly I am a big fan of globals and there is no way you can convince me that Singleton is better in any way. Here is the quite popular (from what I heard) not thread-safe implementation:
class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
If your extra cautious, you can also make this class uninheritable using keyword sealed like this:
sealed class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
I mean it's crystal clear that this is not thread-safe, but the real question is, why do people keep mentioning thread-safety which isn't directly related to this design pattern in particular?. Singleton's goal is to merely restrict class instantiation, which has nothing to do with multithreading.
Ok, here is a thread-safe implementation. As you can see the primary difference between the two is a presence of a lock, which is beyond intuitive, I mean anyone would do it exactly this way:
{
private static object dummy = new Object();
private static volatile Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (dummy)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
In case you forgot, volatile keyword tells the compiler that a variable is volatile, meaning its value may rapidly change, for example, if multiple threads change it. In other words, using volatile keyword we ask the compiler not to optimize anything about this variable in particular.
Subscribe to:
Comments (Atom)