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.
Subscribe to:
Posts (Atom)