Unix domain socket support in Windows

UNIX domain sockets enable efficient inter process communication between the processes running on the same machine.,UNIX domain socket uses file pathname to identify the server instead of  an IP address and port. Support for UNIX domain sockets has existed on many flavors UNIX & LINUX for the longest time but this facility was no available on Windows. On Windows  if you want to do  Local IPC  then you had to use named pipes . Named pipe had different API’s then sockets., This difference made porting UNIX domain sockets based application to Windows difficult.

Windows 10 Version 1803  brings native support of UNIX domain sockets to Windows. You can program in “C”  with Windows SDK version 1803 (10.0.17134 or greater ) and program in C# using .NET core 2.1 ,

Here is how to check support for UNIX domain sockets on Windows.

sc query afunix” from a Windows admin command prompt

image

Here is the C#  demo sample


using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace UnixSocketsDemo
{
class UnixSocketsOnWindows
{
public static void Demo()
{
string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var task = Task.Run(() =>
{
StartServer(path);
});
// wait for server to start
Thread.Sleep(2000);
StartClient(path);
Console.ReadLine();
}
private static void StartClient(String path)
{
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
client.Connect(endPoint);
Console.WriteLine($"[Client] Connected to … ..{path}");
String str = String.Empty;
var bytes = new byte[100];
while (!str.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("[Client]Enter something: ");
var line = Console.ReadLine();
client.Send(Encoding.UTF8.GetBytes(line));
Console.Write("[Client]From Server: ");
int byteRecv = client.Receive(bytes);
str = Encoding.UTF8.GetString(bytes, 0, byteRecv);
Console.WriteLine(str);
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
private static void StartServer(String path)
{
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
Console.WriteLine($"[Server] Listening … ..{path}");
server.Listen(1);
using (Socket accepted = server.Accept())
{
Console.WriteLine("[Server]Connection Accepted …" + accepted.RemoteEndPoint.ToString());
var bytes = new byte[100];
while (true)
{
int byteRecv = accepted.Receive(bytes);
String str = Encoding.UTF8.GetString(bytes, 0, byteRecv);
Console.WriteLine("[Server]Received " + str);
accepted.Send(Encoding.UTF8.GetBytes(str.ToUpper()));
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

 

Resource

Monitor process startup/shutdown using WMI & PowerShell

Recently I was working on a project, where I needed to monitor process for startup/shutdown events,  after searching internet  found that it can be easily done using WMI and PowerShell .

WMI (Windows Management Instrumentation) is a technology built in to Windows since Windows 2000, that provides standard interface to manage windows systems. For example it can used to find software products installed in single or multiple machines in network or to verify necessary OS service pack is installed on all machines in the network.

PowerShell provides easy way of accessing WMI functionality using simple scripting language.

Here is how you can monitor for process startup using PowerShell & WMI events

1. Launch PowerShell and enter following command. This command will register for process started event and prints statement in console whenever notepad.exe is executed.

Register-WMIEvent -query “SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName=’notepad.exe'” -SourceIdentifier “testevent” -action { $e = $Event.SourceEventArgs.NewEvent

Write-Host $e.ProcessName,” started ” }

2. Now launch notepad and observer that console has message confirming the same.

3. Once you are done, unregister the event by entering following command

Unregister-Event testevent

4. You can also see list of event subscribers with “Get-EventSubscriber” command.

Some more examples of using WMI & PowerShell

1.Monitor process stop events

Register-WMIEvent -query “SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName=’notepad.exe'” -SourceIdentifier “testevent” -action { $e = $Event.SourceEventArgs.NewEvent

Write-Host $e.ProcessName,” stopped ” }

2. Monitor Windows Service stop/start status. Replace “TargetInstance.Name” value with your service name

Register-WMIEvent -query “Select * From __InstanceOperationEvent within 1 Where TargetInstance ISA ‘Win32_Service’ and TargetInstance.Name=’Fax'” -sourceIdentifier “MyServMonitor” -action { Write-host “Service Name :”,$EventArgs.NewEvent.TargetInstance.Name ,” Service State :”, $EventArgs.NewEvent.TargetInstance.State }

image

You can also do the same event monitoring using WMI & C#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace WmiEventTest
{
    class ServiceStatusMonitor
    {
        static void Main(string[] args)
        {

            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ServiceStatusMonitor  ");
                Environment.Exit(0);
            }
            string WMI_EVENT_QUERY = @"SELECT * FROM __InstanceModificationEvent
                WITHIN 1 WHERE TargetInstance ISA 'Win32_Service'";

            string WMI_EVENT_QUERY_WITH_SERVICE_NAME = WMI_EVENT_QUERY
                    + " and TargetInstance.Name = '{0}'";
            WqlEventQuery serviceModificationEvent =
                    new WqlEventQuery(string.Format(WMI_EVENT_QUERY_WITH_SERVICE_NAME, args[0]));
            ManagementEventWatcher eventWatcher =
                    new ManagementEventWatcher(serviceModificationEvent);
            eventWatcher.EventArrived +=
                    new EventArrivedEventHandler(Watcher_EventArrived);
            Console.WriteLine("Waiting for service status change events ...");
            eventWatcher.Start();
            Console.ReadLine();
        }

        static void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            string eventType = e.NewEvent.ClassPath.ClassName;

            switch (eventType)
            {
                case "__InstanceCreationEvent":

                    Console.BackgroundColor = ConsoleColor.Blue;
                    Console.WriteLine("'{0}' Service created ....",
                            Environment.GetCommandLineArgs()[1]);
                    Console.ResetColor();
                    break;
                case "__InstanceDeletionEvent":

                    Console.BackgroundColor = ConsoleColor.Green;
                    Console.WriteLine("'{0}' Service deleted ....",
                        Environment.GetCommandLineArgs()[1]);
                    Console.ResetColor();
                    break;

                case "__InstanceModificationEvent":

                    Console.BackgroundColor = ConsoleColor.Blue;
                    ManagementBaseObject obj = (ManagementBaseObject)e.NewEvent["TargetInstance"];
                    Console.WriteLine("'{0}' Service Modified ( {1} )",
                        Environment.GetCommandLineArgs()[1], obj["State"]);
                    Console.ResetColor();
                    break;
            }

        }
    }
}

Resources

1. Introduction to WMI

2. Receiving WMI Events

3. PowerShell for event monitoring.

Microsoft All-In-One Code Framework

Often you will looking for code samples to solve certain programing tasks.
Code samples will help in  understanding available operating system API’s and it usage.

All-In-One Code Framework  is code samples library provided by Microsoft. More than 3500 quality code samples covering various technical topic ranging from System programming,Device Driver programming, Windows Azure,ASP.NET ,Office SharePoint etc. Samples will be available both for Native ( C++,MFC ) and .NET developers.

Microsoft All-In-One Code Framework  has “Sample browser” application , that helps you to find the code samples written by the Microsoft team.
These sample are based on request from developer communities, customers and typical  programming scenarios.

image[3]-20[1]

 

To find the code samples
Visit http://1code.codeplex.com/ and download the application. This application is based on click once technology.

Once it is downloaded , you can launch the application and search for samples by entering the query in the search box.
You can also apply search filter based on programming language ( C++,C#,VB.NET ) and technology.
Following picture shows the search results for “Mutex” with C++ filter.

 

allinone

 

More information can be found from

1. Codeplex website

2. Channel9 Resource

3. How to use video on developer channel

Speedy resolution of customer issues using Problem step recorder

Recently I saw a tool ( PSR) in windows 7 which allows customer to report issue/problem using screen capture technology.
This tool by default present in Windows 7 systems. Just type “PSR.exe” from the command prompt to launch this tool.

Using this tool is simple, run this tool and start using the system/application to reproduce the issue.
This tool records all user interaction with the system as screenshots along with the system information.
At the end , tool generates zip file containing all the necessary information.
User can submit zip file to developer for analysis. This allows developer to exactly see what operations user was doing when problem happens.

As this tool captures the screen shots it can be useful for anybody who wants to understand the customer interaction with the
system and to see exactly what customer was doing when problem happens.

Next time somebody tells you that your application is not working, ask them to run this tool and send the information to you.
More information can be found at
PSR