Category Archives: C#

Switching to a different thread with async/await in C#

The code below switches to a different thread when the execution of Main() is resumed at line 11:

internal class Program
{
    static async Task Main(string[] args)
    {
        try
        {
            HttpClient client = new HttpClient();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");
                
            HttpResponseMessage response = await client.GetAsync("https://developernote.com/");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            response.EnsureSuccessStatusCode();

            string responseBody = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine(responseBody);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");

            Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}");

            Console.WriteLine($"Message: {e.Message}");
        }
    }
}
(more…)

How to run WIX bootstrapper application UI with elevated privileges?

WIX bootstrapper application (BA) can easily determine if it runs as admin with the following code:

using System;
using System.Diagnostics;
using System.Security.Principal;

static bool IsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

and if it does not, run a new instance as admin and exit:

static void RunAsAdmin()
{
    ProcessStartInfo proc = new ProcessStartInfo
    {
        UseShellExecute = true,
        WorkingDirectory = Environment.CurrentDirectory,
        FileName = Process.GetCurrentProcess().MainModule.FileName,
        Verb = "runas"
    };

    Process.Start(proc);
}

(more…)

Developing Universal Windows App (UWP) with Xamarin.Forms 2.0 in Visual Studio 2015

Visual Studio 2015 has “Blank App (Xamarin.Forms Portable)” project template that creates three separate C# projects for Android, iOS and Windows.Phone 8.0 platforms that share the same C#/XAML code via so called PCL (Portable Class Library):

Blank App (Xamarin.Forms Portable)

(more…)

Using a WPF control in a MFC application

I’ve been working on some MFC application and to apply my WPF knowledge I added a WPF control written in C# to my MFC CView with the following code:

int CMyView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    if (CView::OnCreate(lpCreateStruct) == -1)
        return -1;

    try
    {
        gcroot<hwndsource ^> hwnd_source = gcnew HwndSource(0, WS_VISIBLE | WS_CHILD, 0, 0, 0, "HwndSource", IntPtr(m_hWnd));

        MyWpfControl ^ control = gcnew MyWpfControl();

        hwnd_source->RootVisual = control;
    }
    catch (Exception ^ ex)
    {
        String ^ msg = ex->Message;
    }

    return 0;
}

All that I needed to do is to follow the steps described in this post: How do I host WPF content in MFC Applications, fix VS2012 bug described here, and got rid of std::mutex and std::lock_guard replacing them with the following classes using typedefs:

(more…)

How to pass a Dictionary<Key, Value> from C# to PHP

I believe that the simplest way to pass complex data from C# to PHP is through WCF service. See my previous post How to implement WCF service in PHP for more details.

Let assume we have a WCF service contract that has the following method with some nested dictionary as a parameter:

[ServiceContract]
public interface IStore
{
    [OperationContract]
    void UpdateRows(Dictionary<int, Dictionary<string, object>> rows);
}

Below I provided the sample implementation of UpdateRows in PHP that iterates through nested dictionaries (first level called ‘rows’ and second level called ‘properties’):

(more…)

How to implement WCF service in PHP

Today I implemented my first PHP Web Service and successfully used it by C# client or, more precisely, I created WCF service contract in C# and implemented it in PHP.  A new option “singlewsdl” in WCF 4.5  helped me a lot. Using this option I generated the service description as a single WSDL-file without additional XSD-files containing the data contracts of the service. Then I uploaded this WSDL-file on my Web Server and written PHP code for all the methods of the service.

(more…)

Integrating C# and PHP using XML-RPC and WCF

While investigating how to make C# and PHP interact with each other I run into an interesting extension of WCF Service Model for working over XML-RPC protocol. I played a bit with this extension and after fixing some bug in its source code I made it work with my little custom XML-RPC server implemented as Joomla XML-RPC plugin.

(more…)

How to make PHP Web Service with NuSoap

While investigating how to create a Web Service in PHP I run into NuSoap library, that can generate WSDL based on some matadata describing Web Service method signatures and the data structures. I downloaded NuSoap library and found some trivial sample that started working after adding the highlighted line of code:

(more…)

How to specify WPF control size in millimeters using XAML

The first thing that we need to do to use millimeters in XAML is to define simple Mm2PixelConverter class that performs the conversion from millimeter to pixels:

[ValueConversion(typeof(double), typeof(double))]
class Mm2PixelConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        double mm = (double)value;

        return WinUtil.Mm2Pixel(mm);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

(more…)

Using ADO.NET Entity Framework with MySQL

In general, getting EF work with MySQL is a fairly simple task, that could be accomplished by downloading and installing ADO.NET driver for MySQL. But what concerns to me, it taken me about four hours to clarify some MySQL-specific details that affect generation of associations in Model Designer. Also after doing an experimentation with the code I realized that ADO.NET driver for MySQL, as well as other third party ADO.NET drivers, do not support “MARS” and, as far as I see, this significant restriction makes EF unusable with MySQL in large real-life projects. Please read below if you interested in more information on this questions.
(more…)