Skip to content

Instantly share code, notes, and snippets.

@incoplex
Forked from namman/lightswitchPortFindingHack.cs
Created September 14, 2019 03:50
Show Gist options
  • Select an option

  • Save incoplex/b35389da3b83c3505278af312800353b to your computer and use it in GitHub Desktop.

Select an option

Save incoplex/b35389da3b83c3505278af312800353b to your computer and use it in GitHub Desktop.
Lightswitch port finding hack
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management;
using System.Linq;
using System.Text.RegularExpressions;
namespace YourApp
{
internal static class LightswitchServicePort
{
public static int GetPort()
{
const string lightswitchApplicationName = "YourAppName";
var vslProcesses = Process.GetProcessesByName("vslshost");
if (vslProcesses.Length > 1)
{
throw new LightswitchPortFindingHackException("Multiple vslshost processes; shut down one: " +
String.Join("\n", vslProcesses.ToString()));
}
if (vslProcesses.Length != 1)
{
throw new LightswitchPortFindingHackException("Cannot find running vslshost process");
}
var process = vslProcesses[0];
// from: http://stackoverflow.com/questions/504208/how-to-read-command-line-arguments-of-another-process-in-c
string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='vslshost.exe'",
process.ProcessName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();
string commandLine = null;
foreach (var retObject in retObjectCollection)
{
commandLine = (string)retObject["CommandLine"];
}
if (commandLine == null)
{
throw new LightswitchPortFindingHackException(
String.Format("Could not find CommandLine property on process {0}", process));
}
else
{
var applicationName = Regex.Match(commandLine, @"\s/n:(.+)\s");
if (!applicationName.Success)
{
throw new LightswitchPortFindingHackException("Could not find name in command line, could be wrong process.");
}
var name = applicationName.Groups[0];
if (name != applicationName)
{
throw new LightswitchPortFindingHackException("Process for wrong application");
}
var portNumberString = Regex.Match(commandLine, @"\s/p:([0-9]+)\s");
if (!portNumberString.Success)
{
throw new LightswitchPortFindingHackException("Could not find port number in command line");
}
var portNumber = Convert.ToInt32(portNumberString.Groups[1].Value);
return portNumber;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment