Posts

Showing posts from October, 2016

How to await asynchronous tasks in the constructor in C#

Image
For original inspiration see this excellent link by Stephen Cleary: http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html Step 1: Create a new WPF application Step 2: Define your example service In this example, a service to count the number of bytes in a web page: MyStaticService.cs [code language="csharp"] using System; using System.Net.Http; using System.Threading.Tasks; namespace AsyncWpf { public static class MyStaticService { public static async Task<int> CountBytesInUrlAsync(string url) { // Artificial delay to show responsiveness. await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false); // Download the actual data and count it. using (var client = new HttpClient()) { var data = await client.GetByteArrayAsync(url).ConfigureAwait(false); return data.Length; } } } } [/code] Step 3:...

Using HttpClient to download files from the internet

Image
A simple console application to demonstrate the downloading of files form the internet. It is pretty much the same as the example at the dot net pearls website , with some screenshots for further clarification. Step 1: Create a new console application: Step 2: Add the System.Net.Http reference Make sure this reference has been added to your project. Right-click on References and select Add reference. Add the System.Net.Http reference: Step 3: Full code listing This uses the HttpClient class and GetAsynch method plus the await keyword to do the actual download: [code language="csharp"] using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientDownload { internal class Program { private static void Main() { var t = new Task(DownloadPageAsync); t.Start(); Console.WriteLine("Downloading page..."); Console.ReadLine(); } public ...

Running a WPF Progress bar as a background worker thread

Image
How to run a WPF progress bar as a background worker thread. This code uses ICommand to respond to the user's request to both and pause start the progress bar background process. Step 1: Create a new WPF application Step 2: Create the MainWindow.xaml user interface components [code language="csharp"] <Window x:Class="ProgressThread.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:ProgressThread" mc:Ignorable="d" Title="MainWindow" Height="250" Width="525"> <Window.DataContext> <local:MainWindowViewModel/> </Window.D...

Binding the visibility of WPF elements to a property

Image
How to set the visibility of your WPF user interface item so that it may be hidden/collapsed or shown as desired Step 1: Create a new WPF Application Step 2: Modify the MainWindow.xaml to create a User control Let's keep it simple - a button: [code language="xml"] <Window x:Class="VisbilityBinding.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:VisbilityBinding" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Width="100" Height="30" Content="OK!" /> ...

Inserting button controls into a WPF ListView and handling their click events

Image
Some instructions on how to : 1. Create a WPF ListView control containing a button in each row 2. Handle the event when the button in the ListView is clicked Step 1: Create the Visual Studio WPF project Step 2: Add event-handling and event-raising infrastructure Just add the following classes to your project: EventArgs.cs [code language="csharp"] using System; namespace ListViewButtonEvents { public class EventArgs<T> : EventArgs { public EventArgs(T value) { Value = value; } public T Value { get; private set; } } } [/code] EventRaiser.cs [code language="csharp"] using System; namespace ListViewButtonEvents { public static class EventRaiser { public static void Raise(this EventHandler handler, object sender) { handler?.Invoke(sender, EventArgs.Empty); } public static void Raise<T>(this EventHandler<EventArgs<T>> handler, object sender, ...

Displaying a WPF application icon in the notification area

Image
A short set of instructions on how to get your WPF application to display its application icon in the notification area of your Windows screen (the area in the bottom right of your screen). Step 1: create a new WPF application Step 2: Ensure the necessary references are added In particular: [code language="csharp"] using System.Drawing; using System.Windows; using System.Windows.Forms; [/code] Also make sure System.Drawing and System.Windows have been added via Add Reference. Right click your References and select Add Reference: Step 3: Modify MainWindow.xaml.cs code Full code listing as follows. In particular pay attention to how we create the NotifyIcon object and its other properties such as file location, visibility and text: [code language="csharp"] using System; using System.Drawing; using System.Windows; using System.Windows.Forms; namespace NotificationIcon { public partial class MainWindow : Window { NotifyIcon ...

Setting the application icon in WPF XAML

Image
Some instructions on how to set the application icon in a WPF / XAML application to something other than the default icon. Step 1: Create a new WPF application: Step 2: Right click your project folder and set properties: Select the Application tab: We are interested in configuring the 'Icon and manifest' section. Click the button next the Icon drop-down menu and select your *.ico file. Example *.ico file downloadable from here: https://www.technical-recipes.com/Downloads/icon.ico Step 3: Set the Main Window properties We want to be able to display the application even in Debug (F5) mode as well. To do this just set the Icon property in the MainWindow.xaml: I added the icon file to my project folder, so there is no need for me to set any relative or absolute path, but this can be easily done if necessary: [code language="xml"] <Window x:Class="SetIcon.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xa...

Recursively searching directories to find text within files in C#

Image
A straightforward utility to recursively search for text contained within files and directories. I created a C# console application. The actual recursive routine to search the directories and subdirectories recursively is quite straightforward: [code language="csharp"] foreach (var directory in Directory.GetDirectories(sDir)) { foreach (var filename in Directory.GetFiles(directory)) { using (var streamReader = new StreamReader(filename)) { var contents = streamReader.ReadToEnd().ToLower(); if (contents.Contains(SearchText)) { FilesFound.Add(filename); } } } DirSearch(directory); } [/code] Each directory is recursively searches as well as all the files contained within it. Full code listing [code language="csharp"] using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RecursiveSearch { internal class Progr...