#if DEBUG
#define DEBUG_USE_ALT_PATH
#endif
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Diagnostics;
using System.Data;
using System.Net;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace RDPManager
{
static class RdpManager
{
public const String version = "1.755";
private static NotifyIcon _icon = new NotifyIcon();
private static Dictionary<Int32, Machine> machines = null;
private static List<String> configFiles = new List<String>();
private static List<String> monitorFiles = new List<String>();
private static List<FileSystemWatcher> fswWatcherList = new List<FileSystemWatcher>();
public const String VersionXmlLoc = "http://rdpmanager.sourceforge.net/Version.xml";
private static String dataPath = "";
private static String appPath = "";
private static String appFileName = "";
private static String programx86Path = "C:\\Program Files";
private static String credFileName = "Passwords.bin";
private static String recentFileName = "RecentMachs.bin";
private static String MUsFileName = "MUs.bin";
private const String iconName = "RDPManager.Icons.RDPManager.ico";
private const String cmdLineMSTSC = "C:\\Windows\\System32\\MSTSC.EXE";
private static Dictionary<String, Credentials> curCredentials = null;
private static Dictionary<Int32, Machine> recentMachines = null;
private static Dictionary<Int32, Int32> MUs = null;
private static int recentMaxCount = 10;
private static int muMaxCount = 4;
private static dlgManualConnect manualDiag = null;
private static bool deleteOldRDPFiles = true;
private static bool showPasswords = false;
private static bool writeRegEntriesBeforeConnect = false;
private static int regValue = 0xFF;
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
appPath = Path.GetDirectoryName(Application.ExecutablePath);
appFileName = Path.GetFileName(Application.ExecutablePath);
#if DEBUG_USE_ALT_PATH
dataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RdpManager.debug";
#else
dataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RdpManager";
#endif
if (File.Exists(appPath + "\\" + credFileName)) // if there is a credenials file in the application directory
{
dataPath = appPath; // use application directory for data file storage
}
else
{
if (!Directory.Exists(dataPath))
{
if (MessageBox.Show("RdpManager can now store its data files in the users profile, would you like to enable this?", "RdpManager", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Directory.CreateDirectory(dataPath);
if (File.Exists(appPath + "\\RdpManager.xml"))
{
if (MessageBox.Show("There is an RdpManager.xml file in the program directory, would you like to store it in the profile? This will enable easier editing.", "RdpManager", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Move(appPath + "\\RdpManager.xml", dataPath + "\\RdpManager.xml");
}
if (File.Exists(appPath + "\\" + credFileName) && !File.Exists(dataPath + "\\" + credFileName)) File.Move(appPath + "\\" + credFileName, dataPath + "\\" + credFileName);
if (File.Exists(appPath + "\\" + recentFileName) && !File.Exists(dataPath + "\\" + recentFileName)) File.Move(appPath + "\\" + recentFileName, dataPath + "\\" + recentFileName);
}
}
else
{ // profile path declined, set data Path to application path
dataPath = appPath;
}
}
}
credFileName = dataPath + "\\" + credFileName;
recentFileName = dataPath + "\\" + recentFileName;
MUsFileName = dataPath + "\\" + MUsFileName;
machines = new Dictionary<Int32, Machine>();
// create default machine
Machine mach = new Machine();
mach.Clear();
mach.SetDefault();
mach.SetHashCode(0);
mach.MachineName = "Default";
mach.DisplayName = "Default";
mach.ManualCred = new Credentials();
machines[0] = mach;
LoadCreds();
LoadRecent();
LoadMU();
//load the icon
using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(iconName))
{
_icon.Icon = new Icon(s);
}
_icon.ContextMenu = new ContextMenu();
if (args.Length > 0)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i].Contains("--monitor="))
{
String monFileName = args[i].Substring(10);
monitorFiles.Add(monFileName);
String localFilename = dataPath + "\\" + Path.GetFileName(monFileName);
if ( File.Exists(localFilename) ) configFiles.Add(localFilename);
if (!File.Exists(monFileName))
{
MessageBox.Show(monFileName + " not accessible when trying to set up file monitoring, this file will not be monitored...", "RDPManager File Monitor Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (File.Exists(localFilename)) File.Delete(localFilename);
File.Copy(monFileName, localFilename);
AddFileWatcher(monFileName, true);
}
}
else
{
configFiles.Add(args[i]);
}
}
}
else
{
if (!File.Exists(dataPath + "\\" + "RDPManager.xml"))
{
if (MessageBox.Show("Default configuration file RDPManager.xml not found, would you like to locate and load another file?", "Config File Not Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
String fName = findConfigfile();
if (fName != "")
{
configFiles.Add(fName);
}
}
}
else
{
configFiles.Add(dataPath + "\\" + "RDPManager.xml");
}
}
foreach( String file in configFiles )
{
_icon.ContextMenu.MenuItems.Add(new MenuItem("-"));
if (!File.Exists(file))
{
MessageBox.Show("Config file " + file + " not found, exiting...", "RDPManager Config File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
_icon.Visible = false;
_icon.Dispose();
Environment.Exit(0);
}
try
{
LoadFile(file,_icon.ContextMenu.MenuItems,machines);
}
catch( Exception exc)
{
#if DEBUG
MessageBox.Show( String.Format("Err in config file " + file + ", {0}, exiting", exc.Message ), "RDPManager Config File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
Environment.Exit(1);
}
AddFileWatcher(file,false);
}
AddDefaultMenuItems();
_icon.Visible = true;
_icon.Text = "RDPManager";
_icon.MouseClick += new MouseEventHandler(_icon_MouseClick);
VersionCheck();
Application.Run();
}
#region eventhandlers
static void fsWatcher_Changed(object sender, FileSystemEventArgs e)
{
Thread.Sleep(500);
reloadConfig();
}
static void fsMonWatcher_Changed(object sender, FileSystemEventArgs e)
{
String localFilename = dataPath + "\\" + Path.GetFileName(e.FullPath);
File.Delete(localFilename);
File.Copy(e.FullPath, localFilename);
}
static void m_Click(object sender, EventArgs e)
{
Object tagObj = (sender as MenuItem).Tag;
Int32 hashCode = Convert.ToInt32(tagObj.ToString());
if( machines.ContainsKey(hashCode) )
{
Connect(machines[hashCode]);
AddToRecent(machines[hashCode], false);
return;
}
}
static void m_recentClick(object sender, EventArgs e)
{
String hashStr = (sender as MenuItem).Tag as String;
Int32 hash = Convert.ToInt32(hashStr);
if ( recentMachines.ContainsKey(hash) )
{
Connect(recentMachines[hash]);
AddToRecent(recentMachines[hash], false);
reloadConfig();
return;
}
}
static void m_MUsClick(object sender, EventArgs e)
{
String hashStr = (sender as MenuItem).Tag as String;
Int32 hash = Convert.ToInt32(hashStr);
if ( machines.ContainsKey(hash))
{
Connect(machines[hash]);
if (MUs.ContainsKey(hash))
{
MUs[hash]++;
reloadConfig();
}
return;
}
}
static void _icon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ShowManualDialog();
}
}
static void m_MultiClick(object sender, EventArgs e )
{
List<String> machList = (sender as MenuItem).Tag as List<String>;
foreach (String machName in machList)
{
Connect(GetMachine(machName));
}
}
static void manualItem_Click(object sender, EventArgs e)
{
ShowManualDialog();
}
static void addConfig_Click(object sender, EventArgs e)
{
String fName = findConfigfile();
if (fName == "") return;
AddFileWatcher(fName, false);
configFiles.Add(fName);
reloadConfig();
}
static void reloadConfig_Click(object sender, EventArgs e)
{
reloadConfig();
}
static void editConfig_Click(object sender, EventArgs e)
{
String fileName = (sender as MenuItem).Tag as string;
Process Proc = new Process();
Proc = Process.Start("notepad.exe", fileName);
}
static void managePwordItem_Click(object sender, EventArgs e)
{
frmPassManage passManageFrm = new frmPassManage();
passManageFrm.ShowDialog();
SaveCreds();
}
static void aboutItem_Click(object sender, EventArgs e)
{
try
{
frmAbout aboutFrm = new frmAbout();
aboutFrm.Version = version;
aboutFrm.ShowDialog();
}
catch (Exception exc )
{
MessageBox.Show("Error displaying about box.. Error: " + exc.Message, "RDPManager About Display Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
static void exitItem_Click(object sender, EventArgs e)
{
_icon.Visible = false;
_icon.Dispose();
Environment.Exit(0);
}
static void m_MultiGroupClick(object sender, EventArgs e)
{
MenuItem menu = FindSubMenu(_icon.ContextMenu.MenuItems, (sender as MenuItem).Tag as String);
if( menu.Text != "" ) ConnectSubMenu(menu);
}
#endregion
#region properties
public static Dictionary<Int32, Machine> Machines
{
get { return RdpManager.machines; }
set { RdpManager.machines = value; }
}
public static String DataPath
{
get { return RdpManager.dataPath; }
set { RdpManager.dataPath = value; }
}
public static List<String> ConfigFiles
{
get { return RdpManager.configFiles; }
set { RdpManager.configFiles = value; }
}
public static Machine DefMachine
{
get { return machines[0]; }
set { }
}
public static int RecentMaxCount
{
get { return RdpManager.recentMaxCount; }
set { RdpManager.recentMaxCount = value; }
}
public static Dictionary<Int32, Int32> MostedUsedMachines
{
get { return RdpManager.MUs; }
set { RdpManager.MUs = value; }
}
public static Dictionary<Int32, Machine> RecentMachines
{
get { return RdpManager.recentMachines; }
set { RdpManager.recentMachines = value; }
}
public static int MUMaxCount
{
get { return RdpManager.muMaxCount; }
set { RdpManager.muMaxCount = value; }
}
public static bool DeleteOldRDPFiles
{
get { return RdpManager.deleteOldRDPFiles; }
set { RdpManager.deleteOldRDPFiles = value; }
}
public static bool ShowPasswords
{
get { return RdpManager.showPasswords; }
set { RdpManager.showPasswords = value; }
}
public static Credentials DefaultCred
{
get { return curCredentials["Default"]; }
set { curCredentials["Default"] = value; }
}
public static Dictionary<String, Credentials> CurCredentials
{
get { return RdpManager.curCredentials; }
set { RdpManager.curCredentials = value; }
}
#endregion
private static void Connect(Machine mach)
{
if (RdpManager.DefaultCred.Password == "Password")
{
MessageBox.Show("Error, the default password has not been set, or is corrupted. Please set it and try again", "RDPManager Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AddToMU(mach.GetHashCode());
if (mach.CmdLine != "" && mach.CmdLine != null)
{
try
{
if (mach.CmdLine.Contains('%'))
{
mach.CmdLine = Environment.ExpandEnvironmentVariables(mach.CmdLine);
}
if (mach.CmdArgs.Contains('%'))
{
mach.CmdArgs = Environment.ExpandEnvironmentVariables(mach.CmdArgs);
}
if (mach.CmdLine.Contains("%ProgramFiles(x86)%"))
{
mach.CmdLine = mach.CmdLine.Replace("%ProgramFiles(x86)%", programx86Path);
}
if (mach.CmdArgs.Contains("%ProgramFiles(x86)%"))
{
mach.CmdArgs = mach.CmdArgs.Replace("%ProgramFiles(x86)%", programx86Path);
}
Process.Start(mach.CmdLine, mach.CmdArgs);
}
catch (Exception exc)
{
MessageBox.Show("Error, could not connect: " + exc.Message + " - " + mach.CmdLine);
}
return;
}
//create and use an RDP file
FileStream fileStream;
String fileName = String.Format("{0}\\{1}.rdp", dataPath, mach.DisplayName);
try
{
fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
}
catch
{
try
{
fileName = mach.MachineName + ".rdp";
fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
}
catch
{
fileStream = new FileStream("rdpmanager.rdp", FileMode.Create, FileAccess.Write, FileShare.None);
}
}
using (fileStream)
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
// sw.WriteLine("full address:s:{0}", GetIPAddr(mach.MachineName));
sw.WriteLine("full address:s:{0}", mach.MachineName);
sw.WriteLine("screen mode id:i:{0}", mach.ScreenMode == "" ? machines[0].ScreenMode : mach.ScreenMode);
sw.WriteLine("connect to console:i:{0}", mach.ConnectToConsole == "" ? machines[0].ConnectToConsole : mach.ConnectToConsole);
sw.WriteLine("desktopwidth:i:{0}", mach.DesktopWidth == "" ? machines[0].DesktopWidth : mach.DesktopWidth);
sw.WriteLine("desktopheight:i:{0}", mach.DesktopHeight == "" ? machines[0].DesktopHeight : mach.DesktopHeight);
sw.WriteLine("session bpp:i:{0}", mach.SessionBpp == "" ? machines[0].SessionBpp : mach.SessionBpp);
sw.WriteLine("server port:i:{0}", mach.ServerPort == "" ? machines[0].ServerPort : mach.ServerPort);
sw.WriteLine("compression:i:{0}", mach.Compression == "" ? machines[0].Compression : mach.Compression);
sw.WriteLine("keyboardhook:i:{0}", mach.KeyboardHook == "" ? machines[0].KeyboardHook : mach.KeyboardHook);
sw.WriteLine("audiomode:i:{0}", mach.AudioMode == "" ? machines[0].AudioMode : mach.AudioMode);
sw.WriteLine("drivestoredirect:s:{0}", mach.DrivesToRedirect == "" ? machines[0].DrivesToRedirect : mach.DrivesToRedirect);
sw.WriteLine("redirectprinters:i:{0}", mach.RedirectPrinters == "" ? machines[0].RedirectPrinters : mach.RedirectPrinters);
sw.WriteLine("redirectcomports:i:{0}", mach.RedirectComPorts == "" ? machines[0].RedirectComPorts : mach.RedirectComPorts);
sw.WriteLine("redirectsmartcards:i:{0}", mach.RedirectSmartCards == "" ? machines[0].RedirectSmartCards : mach.RedirectSmartCards);
sw.WriteLine("displayconnectionbar:i:{0}", mach.DisplayConnectionBar == "" ? machines[0].DisplayConnectionBar : mach.DisplayConnectionBar);
sw.WriteLine("disable wallpaper:i:{0}", mach.DisableWallpaper == "" ? machines[0].DisableWallpaper : mach.DisableWallpaper);
sw.WriteLine("disable full window drag:i:{0}", mach.DisableWindowDrag == "" ? machines[0].DisableWindowDrag : mach.DisableWindowDrag);
sw.WriteLine("disable menu anims:i:{0}", mach.DisableAnims == "" ? machines[0].DisableAnims : mach.DisableAnims);
sw.WriteLine("disable themes:i:{0}", mach.DisableThemes == "" ? machines[0].DisableThemes : mach.DisableThemes);
sw.WriteLine("disable cursor setting:i:{0}", mach.DisableCursor == "" ? machines[0].DisableCursor : mach.DisableCursor);
sw.WriteLine("bitmapcachepersistenable:i:1");
sw.WriteLine("auto connect:i:1");
if (mach.DisableCredsSPSupport || machines[0].DisableCredsSPSupport)
{
sw.WriteLine("enablecredsspsupport:i:0");
}
sw.WriteLine("autoreconnection enabled:i:1");
sw.WriteLine("authentication level:i:0");
Credentials Cred = null;
if (mach.IsManual && mach.ManualCred.UserName != "")
{
Cred = mach.ManualCred;
}
else if (!curCredentials.TryGetValue(mach.DisplayName, out Cred))
{
Cred = curCredentials["Default"];
}
sw.WriteLine("username:s:{0}", Cred.UserName);
sw.WriteLine("password 51:b:{0}", Cred.Password);
if (Cred.Domain != "") sw.WriteLine("domain:s:{0}", Cred.Domain);
sw.Flush();
}
}
Process proc = null;
if (writeRegEntriesBeforeConnect)
{
AddToReg(mach.MachineName);
}
if (mach.ConnectToConsole == "1")
{
String cmdLine = " /admin \"" + fileName + "\"";
proc = Process.Start(cmdLineMSTSC, cmdLine);
}
else
{
proc = Process.Start(fileName);
}
if (deleteOldRDPFiles)
{
bool procWaitForExit = proc.WaitForExit(10000);
if (!procWaitForExit)
{
File.Delete(fileName);
}
}
}
static void LoadFile(string FileName, Menu.MenuItemCollection menuItems, Dictionary<Int32, Machine> machList)
{
try
{
XmlDocument doc = new XmlDocument();
using (Stream fileIn = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
doc.Load(fileIn);
}
// load defaults
foreach (XmlAttribute attr in doc.DocumentElement.Attributes)
{
switch (attr.Name)
{
case "ScreenMode": machList[0].ScreenMode = attr.Value; break;
case "DesktopWidth": machList[0].DesktopWidth = attr.Value; break;
case "DesktopHeight": machList[0].DesktopHeight = attr.Value; break;
case "SessionBpp": machList[0].SessionBpp = attr.Value; break;
case "Compression": machList[0].Compression = attr.Value; break;
case "KeyboardHook": machList[0].KeyboardHook = attr.Value; break;
case "AudioMode": machList[0].AudioMode = attr.Value; break;
case "DrivesToRedirect": machList[0].DrivesToRedirect = attr.Value; break;
case "RedirectPrinters": machList[0].RedirectPrinters = attr.Value; break;
case "RedirectComPorts": machList[0].RedirectComPorts = attr.Value; break;
case "RedirectSmartCards": machList[0].RedirectSmartCards = attr.Value; break;
case "DisableWallpaper": machList[0].DisableWallpaper = attr.Value; break;
case "DisableWindowDrag": machList[0].DisableWindowDrag = attr.Value; break;
case "DisableAnims": machList[0].DisableAnims = attr.Value; break;
case "DisableThemes": machList[0].DisableThemes = attr.Value; break;
case "DisableCursor": machList[0].DisableCursor = attr.Value; break;
case "ServerPort": machList[0].ServerPort = attr.Value; break;
case "DisplayConnectionBar": machList[0].DisplayConnectionBar = attr.Value; break;
case "ConnectToConsole": machList[0].ConnectToConsole = attr.Value; break;
case "NumRecent": recentMaxCount = Convert.ToInt32(attr.Value); break;
case "NumMUs": muMaxCount = Convert.ToInt32(attr.Value); break;
case "ProgramFiles(x86)Path": programx86Path = attr.Value; break;
case "DeleteOldRDPFiles": if (attr.Value == "1") deleteOldRDPFiles = true; else deleteOldRDPFiles = false; break;
case "WriteRegEntriesBeforeConnect": if (attr.Value == "1") writeRegEntriesBeforeConnect = true; else writeRegEntriesBeforeConnect = false; break;
case "ShowPasswords": if (attr.Value == "1") showPasswords = true; else showPasswords = false; break;
case "DisableCredsSPSupport":
if (attr.Value == "1") machList[0].DisableCredsSPSupport = true;
else machList[0].DisableCredsSPSupport = false;
break;
}
}
ProcessElement(doc.DocumentElement, menuItems, machList);
}
catch (Exception exc)
{
MessageBox.Show(String.Format("XML File error, Error in syntax of file {0}, Exception: {1} ", FileName, exc.Message), "RDPManager XML Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
throw exc;
}
}
private static void ProcessElement(XmlElement xmlElement, Menu.MenuItemCollection menuItems, Dictionary<Int32, Machine> machList)
{
Machine mach;
foreach (XmlNode node in xmlElement)
{
if (node.NodeType == XmlNodeType.Element)
{
XmlElement element = (XmlElement)node;
MenuItem m = new MenuItem();
if (element.Name == "RDPConnection")
{
mach = new Machine();
mach.MachineName = element.GetAttribute("MachineName");
mach.DisplayName = element.GetAttribute("DisplayName");
// handle port w/ machine name
if (mach.MachineName.Contains(":"))
{
int pos = mach.MachineName.IndexOf(':');
mach.ServerPort = mach.MachineName.Substring(pos + 1);
mach.MachineName = mach.MachineName.Substring(0, pos);
}
foreach (XmlAttribute attr in element.Attributes)
{
switch (attr.Name)
{
case "ScreenMode": mach.ScreenMode = attr.Value; break;
case "DesktopWidth": mach.DesktopWidth = attr.Value; break;
case "DesktopHeight": mach.DesktopHeight = attr.Value; break;
case "SessionBpp": mach.SessionBpp = attr.Value; break;
case "Compression": mach.Compression = attr.Value; break;
case "KeyboardHook": mach.KeyboardHook = attr.Value; break;
case "AudioMode": mach.AudioMode = attr.Value; break;
case "DrivesToRedirect": mach.DrivesToRedirect = attr.Value; break;
case "RedirectPrinters": mach.RedirectPrinters = attr.Value; break;
case "RedirectComPorts": mach.RedirectComPorts = attr.Value; break;
case "RedirectSmartCards": mach.RedirectSmartCards = attr.Value; break;
case "DisableWallpaper": mach.DisableWallpaper = attr.Value; break;
case "DisableWindowDrag": mach.DisableWindowDrag = attr.Value; break;
case "DisableAnims": mach.DisableAnims = attr.Value; break;
case "DisableThemes": mach.DisableThemes = attr.Value; break;
case "DisableCursor": mach.DisableCursor = attr.Value; break;
case "ServerPort": mach.ServerPort = attr.Value; break;
case "DisplayConnectionBar": mach.DisplayConnectionBar = attr.Value; break;
case "ConnectToConsole": mach.ConnectToConsole = attr.Value; break;
//case "Domain": curCredentials[mach.DisplayName].Domain = attr.Value; break;
case "CmdLine": mach.CmdLine = attr.Value; mach.CmdLine = mach.CmdLine.Replace('~', '\"'); break;
case "CmdArgs": mach.CmdArgs = attr.Value; mach.CmdArgs = mach.CmdArgs.Replace('~', '\"'); break;
case "DisableCredsSPSupport":
if (attr.Value == "1") mach.DisableCredsSPSupport = true;
else mach.DisableCredsSPSupport = false;
break;
}
}
Int32 hash = mach.GetHashCode();
machList[hash] = mach;
m.Text = mach.DisplayName;
m.Tag = hash;
m.Click += new EventHandler(m_Click);
menuItems.Add(m);
}
else if (element.Name == "RDPMultiConnection")
{
if (element.HasAttribute("MachineNames"))
{
List<String> tmpMachList = new List<String>();
String machStr = element.GetAttribute("MachineNames");
String[] machNames = machStr.Split(';');
foreach (String machName in machNames)
{
tmpMachList.Add(machName);
}
m.Text = element.GetAttribute("DisplayName");
m.Tag = tmpMachList;
m.Click += new EventHandler(m_MultiClick);
menuItems.Add(m);
}
if (element.HasAttribute("GroupName"))
{
String groupName = element.GetAttribute("GroupName");
m.Text = element.GetAttribute("DisplayName");
m.Tag = groupName;
m.Click += new EventHandler(m_MultiGroupClick);
menuItems.Add(m);
}
}
else
{
//is a folder node
m.Text = element.GetAttribute("DisplayName");
menuItems.Add(m);
ProcessElement(element, m.MenuItems, machList);
}
}
}
}
static public void reloadConfig()
{
Dictionary<Int32, Machine> newMachList = new Dictionary<Int32, Machine>();
String errFilename = "";
SaveCreds();
Machine mach = new Machine();
mach.Clear();
mach.MachineName = "Default";
mach.DisplayName = "Default";
mach.SetHashCode(0);
mach.ManualCred = new Credentials();
/*
mach.ManualCred.UserName = DefaultCred.UserName;
mach.ManualCred.Password = DefaultCred.Password;
mach.ManualCred.Domain = DefaultCred.Domain;
*/
newMachList[0] = mach;
ContextMenu menu = new ContextMenu();
try
{
foreach (String configFile in configFiles)
{
errFilename = configFile;
if (!File.Exists(configFile))
{
MessageBox.Show("Can't find config file " + configFile + ", reverting to previous config", "RDPManager Config File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
menu.MenuItems.Add(new MenuItem("-"));
LoadFile(configFile, menu.MenuItems, newMachList);
}
}
catch (Exception) //exc)
{
MessageBox.Show(String.Format("Can't load config file {0}, reverting to previous config", errFilename), "RDPManager Config Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
machines.Clear();
machines = newMachList;
_icon.ContextMenu = menu;
AddDefaultMenuItems();
LoadCreds();
}
private static void AddDefaultMenuItems()
{
#if DEBUG
_icon.ContextMenu.MenuItems.Add(new MenuItem("******************************"));
#else
_icon.ContextMenu.MenuItems.Add(new MenuItem("-"));
#endif
MenuItem item = new MenuItem("Manual Connect");
item.Click += new EventHandler(manualItem_Click);
_icon.ContextMenu.MenuItems.Add(item);
if (recentMachines.Count > 0 || MUs.Count > 0)
{
item = new MenuItem("Recent");
_icon.ContextMenu.MenuItems.Add(item);
if (MUs.Count > 0)
{
try
{
int i = 0;
List<KeyValuePair<Int32, Int32>> revKeys = new List<KeyValuePair<Int32, Int32>>();
// sort topMUs, add # MUs wanted to a list
var revKeysSorted = from MUKey in MUs orderby MUKey.Value descending select new KeyValuePair<Int32, Int32>(MUKey.Key, MUKey.Value);
foreach (KeyValuePair<Int32, Int32> kvp in revKeysSorted)
{
if (i++ >= muMaxCount) break;
revKeys.Add(kvp);
}
// re-sort the List
var MUkeys = from MUKey in revKeys orderby MUKey.Value ascending select new KeyValuePair<Int32, Int32>(MUKey.Key, MUKey.Value);
foreach (KeyValuePair<Int32, Int32> kvp in MUkeys)
{
// if machine in MU is not in the main machine list, delete it from list. This can happen from removing or changing an entry.
if (!machines.ContainsKey(kvp.Key))
{
MUs.Remove(kvp.Key);
SaveMU();
continue;
}
MenuItem m = new MenuItem(machines[kvp.Key].DisplayName);
m.Tag = kvp.Key.ToString();
m.Click += new EventHandler(m_MUsClick);
item.MenuItems.Add(m);
}
item.MenuItems.Add(new MenuItem("-"));
item.MenuItems.Add(new MenuItem("-"));
}
catch (Exception exc)
{
#if DEBUG
MessageBox.Show(String.Format("Err handling MUs, Errmsg: {0}, Source: {1}", exc.Message, exc.Source), "RDPManager Config File Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
}
}
Dictionary<int, Machine> recMachinesCpy = recentMachines;
foreach (KeyValuePair<Int32, Machine> kvp in recMachinesCpy)
{
if (!recMachinesCpy[kvp.Key].IsManual && !recMachinesCpy.ContainsKey(kvp.Key))
{
recentMachines.Remove(kvp.Key);
SaveRecent();
continue;
}
MenuItem m = new MenuItem(recMachinesCpy[kvp.Key].DisplayName);
m.Tag = kvp.Key.ToString();
m.Click += new EventHandler(m_recentClick);
item.MenuItems.Add(m);
}
}
_icon.ContextMenu.MenuItems.Add(new MenuItem("-"));
item = new MenuItem("Manage Passwords");
item.Click += new EventHandler(managePwordItem_Click);
_icon.ContextMenu.MenuItems.Add(item);
item = new MenuItem("Edit XML");
MenuItem subItem = new MenuItem("Add Config File");
subItem.Click += new EventHandler(addConfig_Click);
item.MenuItems.Add(subItem);
MenuItem subItem2 = new MenuItem("Reload Config");
subItem2.Click += new EventHandler(reloadConfig_Click);
item.MenuItems.Add(subItem2);
item.MenuItems.Add(new MenuItem("-"));
foreach (String configFile in configFiles)
{
subItem = new MenuItem(Path.GetFileName(configFile));
subItem.Tag = configFile;
subItem.Click += new EventHandler(editConfig_Click);
item.MenuItems.Add(subItem);
}
_icon.ContextMenu.MenuItems.Add(item);
item = new MenuItem("About/Options");
item.Click += new EventHandler(aboutItem_Click);
_icon.ContextMenu.MenuItems.Add(item);
item = new MenuItem("Exit");
item.Click += new EventHandler(exitItem_Click);
_icon.ContextMenu.MenuItems.Add(item);
}
private static String findConfigfile()
{
OpenFileDialog fileDg = new OpenFileDialog();
fileDg.InitialDirectory = dataPath;
fileDg.AutoUpgradeEnabled = true;
fileDg.CheckFileExists = true;
fileDg.DefaultExt = ".xml";
fileDg.Filter = "XML Files (*.xml)|*.xml";
fileDg.DereferenceLinks = true;
fileDg.RestoreDirectory = true;
fileDg.ValidateNames = true;
fileDg.Multiselect = false;
fileDg.Title = "Locate xml file";
if (fileDg.ShowDialog() != DialogResult.Cancel)
{
return fileDg.FileName;
}
return "";
}
private static void AddFileWatcher(String fName, bool bMonitorFile)
{
FileSystemWatcher fsWatcher = new FileSystemWatcher();
if (Path.GetDirectoryName(fName) != "")
{
fsWatcher.Path = Path.GetDirectoryName(fName);
}
else
{
fsWatcher.Path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
fsWatcher.NotifyFilter = NotifyFilters.LastWrite;
fsWatcher.Filter = Path.GetFileName(fName);
if (bMonitorFile)
{
fsWatcher.Changed += new FileSystemEventHandler(fsMonWatcher_Changed);
}
else
{
fsWatcher.Changed += new FileSystemEventHandler(fsWatcher_Changed);
}
fsWatcher.EnableRaisingEvents = true;
fswWatcherList.Add(fsWatcher);
}
static void ConnectSubMenu(MenuItem menu)
{
foreach (MenuItem item in menu.MenuItems)
{
if (item.IsParent == false)
{
Connect(GetMachine(item.Text.ToString()));
}
else
{
ConnectSubMenu(item);
}
}
}
public static void ShowManualDialog()
{
if (manualDiag == null)
{
manualDiag = new dlgManualConnect();
manualDiag.ShowDialog();
if (manualDiag.DialogResult == DialogResult.OK && manualDiag.CurMachine.MachineName != "")
{
AddToRecent(manualDiag.CurMachine, true);
Connect(manualDiag.CurMachine);
}
manualDiag.Dispose();
manualDiag = null;
}
else
{
manualDiag.Activate();
}
}
static MenuItem FindSubMenu(Menu.MenuItemCollection menu, String menuName)
{
foreach (MenuItem item in menu)
{
if (item.IsParent)
{
if (item.Text == menuName)
{
return item;
}
MenuItem subMenu = FindSubMenu(item.MenuItems, menuName);
if (subMenu.Text == menuName)
return subMenu;
}
}
return new MenuItem();
}
static public Machine GetMachine(String Name)
{
foreach (Int32 key in machines.Keys)
{
if (machines[key].MachineName.ToUpper() == Name.ToUpper()) return machines[key];
if (machines[key].DisplayName.ToUpper() == Name.ToUpper()) return machines[key];
}
return new Machine();
}
private static String GetIPAddr(string addressToResolve)
{
IPHostEntry hostInfo = Dns.GetHostEntry(addressToResolve);
if (hostInfo.AddressList.Length > 0)
{
return hostInfo.AddressList[0].ToString();
}
else
{
return addressToResolve;
}
}
public static string GetEncodedPassword(String passWord)
{
byte[] encoded = DPAPI.Encrypt(DPAPI.KeyType.UserKey, Encoding.Unicode.GetBytes(passWord), null, null);
string temp = BitConverter.ToString(encoded).Replace("-", "");
return temp;
}
private static void VersionCheck()
{
String CurVersion = "";
String DownloadUrl = "";
try
{
XmlDocument doc = new XmlDocument();
doc.Load(VersionXmlLoc);
foreach (XmlElement node in doc.DocumentElement)
{
switch (node.Name)
{
case "CurrentVersion":
CurVersion=node.Attributes[0].Value;
break;
case "DownloadURL":
DownloadUrl = node.Attributes[0].Value;
break;
}
}
if(Convert.ToDouble(CurVersion) > Convert.ToDouble(version) )
{
frmVersionChk frm = new frmVersionChk();
frm.OldVer = version;
frm.NewVer = CurVersion;
frm.DownloadURL = DownloadUrl;
frm.Show();
}
}
catch (Exception exc)
{
#if DEBUG
MessageBox.Show(String.Format("Version XML File error, Error in syntax of file {0}, Exception: {1} ", VersionXmlLoc, exc.Message), "RDPManager XML Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
#endif
return;
}
}
public static void LoadCreds()
{
FileInfo fInfo = new FileInfo(credFileName);
if ( fInfo.Exists )
{
BinaryFormatter binFormat = new BinaryFormatter();
FileStream fStream = File.OpenRead(credFileName);
try
{
curCredentials = (Dictionary<String, Credentials>)binFormat.Deserialize(fStream);
fStream.Close();
if (!curCredentials.ContainsKey("Default"))
{
Credentials Cred = new Credentials();
Cred.UserName = "Administrator";
Cred.Password = "Password";
Cred.Domain = "";
curCredentials["Default"] = Cred;
}
return;
}
#if DEBUG
catch (Exception exc)
{
MessageBox.Show(String.Format("Cred Error, could not load passwords, resetting.. Error: {0}", exc.Message), "RDPManager Password Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
catch (Exception)// exc)
{
#endif
fStream.Close();
File.Delete(credFileName);
}
}
SaveCreds();
}
public static void SaveCreds()
{
FileStream fStream = null;
try
{
FileInfo fInfo = new FileInfo(credFileName);
if (fInfo.Exists)
{
BinaryFormatter binFormat = new BinaryFormatter();
File.Delete(credFileName);
fStream = new FileStream(credFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
// fStream = File.OpenWrite(credFileName);
binFormat.Serialize(fStream, curCredentials);
fStream.Close();
}
else
{
curCredentials = new Dictionary<string, Credentials>();
Credentials Cred = new Credentials();
Cred.UserName = "Administrator";
Cred.Password = "Password";
Cred.Domain = "";
curCredentials["Default"] = Cred;
BinaryFormatter binFormat = new BinaryFormatter();
// File.Create(credFileName);
// fStream = File.OpenWrite(credFileName);
fStream = new FileStream(credFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, curCredentials);
fStream.Close();
MessageBox.Show("Error, could not save passwords, resetting.. You need to set your default password", "RDPManager Password Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception)// exc)
{
MessageBox.Show("Error, could not save passwords..", "RDPManager Password Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (fStream != null) fStream.Close();
//File.Delete(credFileName);
}
}
static void AddToRecent(Machine machineToAdd, bool ifManual)
{
if ( TestMUs(machineToAdd) )
{
return;
}
if (recentMachines.ContainsKey(machineToAdd.GetHashCode()))
{
recentMachines.Remove(machineToAdd.GetHashCode());
}
List<KeyValuePair<Int32, Machine>> recentList = recentMachines.ToList<KeyValuePair<Int32, Machine>>();
recentMachines.Clear();
KeyValuePair<Int32, Machine> kvp = new KeyValuePair<Int32, Machine>(machineToAdd.GetHashCode(), machineToAdd);
recentList.Add(kvp);
//recentMachines.
while (recentList.Count > recentMaxCount)
{
recentList.RemoveAt(0);
}
recentMachines = recentList.ToDictionary(x => x.Key, y => y.Value);
SaveRecent();
reloadConfig();
}
public static void LoadRecent()
{
FileInfo fInfo = new FileInfo(recentFileName);
if (fInfo.Exists)
{
BinaryFormatter binFormat = new BinaryFormatter();
FileStream fStream = null;
try
{
fStream = File.OpenRead(recentFileName);
recentMachines = (Dictionary<Int32, Machine>)binFormat.Deserialize(fStream);
fStream.Close();
while (recentMachines.Count > recentMaxCount)
{
KeyValuePair<Int32, Machine> kvp = recentMachines.First();
recentMachines.Remove(kvp.Key);
}
//while (recentMachines.Count > recentMaxCount) recentMachines.RemoveAt(0);
return;
}
catch (Exception)// exc)
{
MessageBox.Show("Error, could not load recent machines, resetting..", "RDPManager Config Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (fStream != null) fStream.Close();
fInfo.Delete();
}
}
recentMachines = new Dictionary<Int32, Machine>();
}
public static void SaveRecent()
{
Stream fStream = null;
BinaryFormatter binFormat = null;
try
{
binFormat = new BinaryFormatter();
fStream = new FileStream(recentFileName, FileMode.Open, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, recentMachines);
}
catch (Exception)// exc)
{
#if DEBUG
MessageBox.Show("Error, could not save recent machines, resetting..", "RDPManager Config Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
if (recentMachines == null) recentMachines = new Dictionary<Int32, Machine>();
FileInfo fInfo = new FileInfo(recentFileName);
if (fInfo.Exists) { fInfo.Delete(); }
fStream = new FileStream(recentFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, recentMachines);
}
fStream.Close();
}
public static void ResetRecent()
{
recentMachines.Clear();
SaveRecent();
}
private static void AddToMU(int hashCode)
{
Int32 MUCount;
MUs.TryGetValue(hashCode, out MUCount);
if (MUCount != 0)
{
MUs[hashCode]++;
}
else
{
MUs.Add(hashCode, 1);
}
SaveMU();
}
public static void LoadMU()
{
FileInfo fInfo = new FileInfo(MUsFileName);
if (fInfo.Exists)
{
BinaryFormatter binFormat = new BinaryFormatter();
FileStream fStream = null;
try
{
fStream = File.OpenRead(MUsFileName);
MUs = (Dictionary<Int32, Int32>)binFormat.Deserialize(fStream);
fStream.Close();
return;
}
catch (Exception exc)
{
#if DEBUG
MessageBox.Show("Error, could not load MU file, resetting.. " + exc.Message, "RDPManager Config Load Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
if (fStream != null) fStream.Close();
fInfo.Delete();
}
}
MUs = new Dictionary<Int32, Int32>();
}
public static void SaveMU()
{
Stream fStream = null;
BinaryFormatter binFormat = null;
try
{
Dictionary<Int32, Int32> oldMUs = new Dictionary<Int32, Int32>(MUs);
foreach (KeyValuePair<Int32, Int32> kvp in MUs)
{
if (!RdpManager.Machines.ContainsKey(kvp.Key))
{
oldMUs.Remove(kvp.Key);
}
}
MUs.Clear();
MUs = oldMUs;
binFormat = new BinaryFormatter();
fStream = new FileStream(MUsFileName, FileMode.Open, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, MUs);
}
catch (Exception exc)
{
#if DEBUG
MessageBox.Show(String.Format("Error, could not save recent MUs, resetting.. Err: {0}", exc.Message), "RDPManager Config Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
if (MUs == null) MUs = new Dictionary<Int32, Int32>();
FileInfo fInfo = new FileInfo(MUsFileName);
if (fInfo.Exists) { fInfo.Delete(); }
fStream = new FileStream(MUsFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, MUs);
}
fStream.Close();
}
public static void ResetMUs()
{
MUs.Clear();
SaveMU();
}
public static bool TestMUs(Machine machineToTest)
{
int i = 0;
List<KeyValuePair<Int32, Int32>> revKeys = new List<KeyValuePair<Int32, Int32>>();
// sort topMUs, add # MUs wanted to a list
var revKeysSorted = from MUKey in MUs orderby MUKey.Value descending select new KeyValuePair<Int32, Int32>(MUKey.Key, MUKey.Value);
foreach (KeyValuePair<Int32, Int32> kvp in revKeysSorted)
{
if (i++ >= muMaxCount) break;
if (kvp.Key == machineToTest.GetHashCode()) return true;
}
return false;
}
public static bool AddToReg(String MachineName)
{
RegistryKey regKey = Registry.CurrentUser;
RegistryKey regSubKey = null;
try
{
regSubKey = regKey.OpenSubKey("SOFTWARE\\Microsoft\\Terminal Server Client\\LocalDevices", true);
if (regSubKey == null)
{
regSubKey = regKey.CreateSubKey("SOFTWARE\\Microsoft\\Terminal Server Client\\LocalDevices");
if (regSubKey == null)
MessageBox.Show("Error, could not create terminal services client subkey, null", "Error, could not open subkey", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception)
{
MessageBox.Show("Error, could not open or create terminal services client subkey", "Error, could not open subkey", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
if (MachineName == "Default") return true;
try
{
int value = (int)regSubKey.GetValue(MachineName);
if (value != regValue)
{
regSubKey.SetValue(MachineName, regValue, RegistryValueKind.DWord);
}
}
catch (Exception)
{
try
{
//regSubKey.SetValue(MachineName, 0xFFFFFFFF, RegistryValueKind.DWord);
regSubKey.SetValue(MachineName, regValue, RegistryValueKind.DWord);
}
catch (Exception exc)
{
MessageBox.Show(String.Format("Error, could not create reg entry for machine {0}, Error {1} ", MachineName, exc.ToString()), "Error, could not create reg value", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
regSubKey.Close();
return true;
}
}
}
/*
Test cmd line
\\bknsv1\software$\RdpManager\RDPManager.xml C:\Users\jbritton\AppData\Roaming\RdpManager\jeffs.xml
C:\Users\jbritton\AppData\Roaming\RdpManager.debug\jeffs.xml
*/