示例#1
0
        private void AntViewer_Load(object sender, System.EventArgs e)
        {
            Text = string.Format("Spiceminer's Ant Viewer - v{0}", FileVersionInfo.GetVersionInfo(typeof(AntViewer).Assembly.Location).FileVersion);

            ThemeResolutionService.ApplicationThemeName = "Windows8";

            WindowState = FormWindowState.Maximized;

            _settings = SettingsService.GetSettings();

            #region Data Dispatch Timer

            _dataDispatchTimer.Enabled   = false;
            _dataDispatchTimer.AutoReset = true;
            _dataDispatchTimer.Elapsed  += _dataDispatchTimer_Elapsed;

            #endregion

            #region BTC Timer

            _btcTimer.Enabled   = true;
            _btcTimer.AutoReset = true;
            _btcTimer.Elapsed  += _btcTimer_Elapsed;
            _btcTimer.Start();

            #endregion

            #region Notify Icon

            _notifyIcon.Icon            = Icon;
            _notifyIcon.BalloonTipTitle = "SAntViewer Minimized to tray";
            _notifyIcon.BalloonTipText  = "SAntViewer has been minimized to tray, click to open.";
            _notifyIcon.DoubleClick    += _notifyIcon_DoubleClick;
            _notifyIcon.Click          += _notifyIcon_DoubleClick;

            #endregion

            #region Antminers Grid

            #region Context Menu

            var contextMenu = new ContextMenu();

            var details = new MenuItem("View Details");
            details.Click += details_Click;
            contextMenu.MenuItems.Add(details);

            var restart = new MenuItem("Restart");
            restart.Click += restart_Click;
            contextMenu.MenuItems.Add(restart);

            var openInBrowser = new MenuItem("Open in browser");
            openInBrowser.Click += openInBrowser_Click;
            contextMenu.MenuItems.Add(openInBrowser);

            #endregion

            grdAntminers.AutoGenerateColumns  = false;
            grdAntminers.AutoSizeColumnsMode  = GridViewAutoSizeColumnsMode.Fill;
            grdAntminers.AllowAddNewRow       = false;
            grdAntminers.EnableGrouping       = true;
            grdAntminers.AllowCellContextMenu = false;
            grdAntminers.AllowAutoSizeColumns = true;
            grdAntminers.ContextMenu          = contextMenu;

            grdAntminers.Columns.Add("Id", "Id", "Id");
            grdAntminers.Columns.Add("Number", "#", "Number");
            grdAntminers.Columns.Add("LastUpdated", "Last Updated", "LastUpdated");
            grdAntminers.Columns.Add("IpAddress", "Ip Address", "IpAddress");
            grdAntminers.Columns.Add("Name", "Name", "Name");
            grdAntminers.Columns.Add("Status", "Status", "Status");
            grdAntminers.Columns.Add("Ghs5s", "GH/S (5s)", "Ghs5s");
            grdAntminers.Columns.Add("GhsAv", "GH/S Av", "GhsAv");
            grdAntminers.Columns.Add("Block", "Blocks", "Blocks");
            grdAntminers.Columns.Add("HardwareErrorPercentage", "Hardware Error %", "HardwareErrorPercentage");
            grdAntminers.Columns.Add("RejectPercentage", "Reject %", "RejectPercentage");
            grdAntminers.Columns.Add("StalePercentage", "Stale %", "StalePercentage");
            grdAntminers.Columns.Add("BestShare", "Best Share", "BestShare");
            grdAntminers.Columns.Add("Fans", "Fans", "Fans");
            grdAntminers.Columns.Add("Temps", "Temps", "Temps");
            grdAntminers.Columns.Add("Freq", "Freq", "Freq");
            grdAntminers.Columns.Add("AsicStatus", "ASIC Status", "Asic Status");

            grdAntminers.Columns[0].IsVisible = false;
            grdAntminers.Columns[1].Width     = 25;
            grdAntminers.Columns[2].Width     = 100;
            grdAntminers.Columns[3].Width     = 100;
            grdAntminers.Columns[4].Width     = 100;
            grdAntminers.Columns[5].Width     = 50;
            grdAntminers.Columns[6].Width     = 50;
            grdAntminers.Columns[7].Width     = 50;
            grdAntminers.Columns[8].Width     = 50;
            grdAntminers.Columns[9].Width     = 100;
            grdAntminers.Columns[10].Width    = 100;
            grdAntminers.Columns[11].Width    = 100;
            grdAntminers.Columns[12].Width    = 75;
            grdAntminers.Columns[13].Width    = 60;
            grdAntminers.Columns[14].Width    = 60;
            grdAntminers.Columns[15].Width    = 60;
            grdAntminers.Columns[16].Width    = 350;

            #endregion

            _antminers = AntminerService.GetAntminers();

            if (grdAntminers.Rows.Count == 0)
            {
                PopulateGrid(_antminers);
                BeginMonitoring();
            }
            else
            {
                BeginMonitoring();
            }
        }
示例#2
0
        public MainWindowVM(MainWindow mainWindow, MainSettings settings)
        {
            ConverterRegistration.Register();
            MainWindow               = mainWindow;
            Settings                 = settings;
            Installer                = new Lazy <InstallerVM>(() => new InstallerVM(this));
            Compiler                 = new Lazy <CompilerVM>(() => new CompilerVM(this));
            SettingsPane             = new Lazy <SettingsVM>(() => new SettingsVM(this));
            Gallery                  = new Lazy <ModListGalleryVM>(() => new ModListGalleryVM(this));
            ModeSelectionVM          = new ModeSelectionVM(this);
            UserInterventionHandlers = new UserInterventionHandlers(this);

            // Set up logging
            Utils.LogMessages
            .ObserveOn(RxApp.TaskpoolScheduler)
            .ToObservableChangeSet()
            .Buffer(TimeSpan.FromMilliseconds(250), RxApp.TaskpoolScheduler)
            .Where(l => l.Count > 0)
            .FlattenBufferResult()
            .ObserveOnGuiThread()
            .Bind(Log)
            .Subscribe()
            .DisposeWith(CompositeDisposable);

            Utils.LogMessages
            .OfType <IUserIntervention>()
            .ObserveOnGuiThread()
            .SelectTask(async msg =>
            {
                try
                {
                    await UserInterventionHandlers.Handle(msg);
                }
                catch (Exception ex)
                    when(ex.GetType() != typeof(TaskCanceledException))
                    {
                        Utils.Error(ex, $"Error while handling user intervention of type {msg?.GetType()}");
                        try
                        {
                            if (!msg.Handled)
                            {
                                msg.Cancel();
                            }
                        }
                        catch (Exception cancelEx)
                        {
                            Utils.Error(cancelEx, $"Error while cancelling user intervention of type {msg?.GetType()}");
                        }
                    }
            })
            .Subscribe()
            .DisposeWith(CompositeDisposable);

            if (IsStartingFromModlist(out var path))
            {
                Installer.Value.ModListLocation.TargetPath = path;
                NavigateTo(Installer.Value);
            }
            else
            {
                // Start on mode selection
                NavigateTo(ModeSelectionVM);
            }

            try
            {
                var assembly = Assembly.GetExecutingAssembly();
                var fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                Consts.CurrentWabbajackVersion = Version.Parse(fvi.FileVersion);
                VersionDisplay = $"v{fvi.FileVersion}";
                Utils.Log($"Wabbajack Version: {fvi.FileVersion}");

                Task.Run(() => Metrics.Send("started_wabbajack", fvi.FileVersion)).FireAndForget();
            }
            catch (Exception ex)
            {
                Utils.Error(ex);
                VersionDisplay = "ERROR";
            }
            CopyVersionCommand = ReactiveCommand.Create(() =>
            {
                Clipboard.SetText($"Wabbajack {VersionDisplay}\n{ThisAssembly.Git.Sha}");
            });
            OpenSettingsCommand = ReactiveCommand.Create(
                canExecute: this.WhenAny(x => x.ActivePane)
                .Select(active => !SettingsPane.IsValueCreated || !object.ReferenceEquals(active, SettingsPane.Value)),
                execute: () => NavigateTo(SettingsPane.Value));
        }
示例#3
0
        private void AnalyzePackage(XtbPlugin plugin)
        {
            var files = plugin.Files;

            bool install = false, update = false, otherFilesFound = false;

            if (string.IsNullOrEmpty(plugin.MinimalXrmToolBoxVersion))
            {
                plugin.Compatibilty = CompatibleState.Other;
            }
            else
            {
                plugin.Compatibilty = IsPluginDependencyCompatible(new Version(plugin.MinimalXrmToolBoxVersion));
            }

            var currentVersion      = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);
            var currentVersionFound = false;

            foreach (var file in files)
            {
                var directoryName = Path.GetDirectoryName(file);
                if (directoryName == null)
                {
                    continue;
                }

                if (directoryName.ToLower().EndsWith("plugins"))
                {
                    // Only check version of files in the Plugins folder
                    var existingPluginFile =
                        plugins.FirstOrDefault(p => file.ToLower().EndsWith(p.Name.ToLower()));
                    if (existingPluginFile == null)
                    {
                        install = true;
                    }
                    else
                    {
                        // If a file is found, we check version only if the file
                        // contains classes that implement IXrmToolBoxPlugin
                        if (!existingPluginFile.ImplementsXrmToolBoxPlugin())
                        {
                            otherFilesFound = true;
                            continue;
                        }

                        var fileVersionInfo = FileVersionInfo.GetVersionInfo(existingPluginFile.FullName);
                        var fileVersion     = new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart, fileVersionInfo.FilePrivatePart);

                        var existingFileVersion = fileVersion;
                        if (existingFileVersion < currentVersion)
                        {
                            currentVersion      = existingFileVersion;
                            currentVersionFound = true;
                        }
                        if (existingFileVersion < new Version(plugin.Version))
                        {
                            update = true;
                        }
                    }
                }
            }

            if (currentVersionFound)
            {
                plugin.CurrentVersion = currentVersion;
            }

            if (otherFilesFound || update)
            {
                plugin.RequiresXtbRestart = true;
            }

            if (plugin.Compatibilty != CompatibleState.Compatible)
            {
                plugin.Action = PackageInstallAction.Unavailable;
            }
            else if (update)
            {
                plugin.Action = PackageInstallAction.Update;
            }
            else if (install)
            {
                plugin.Action = PackageInstallAction.Install;
            }
            else
            {
                plugin.Action = PackageInstallAction.None;
            }
        }
示例#4
0
        public List <FileEntity> Search(string where, string what, string machine)
        {
            List <FileEntity> result = new List <FileEntity>();

            var connection = new OleDbConnection(@"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows""");

            var query = string.Format(BaseQuery,
                                      (Recursive) ? "scope" : "directory",
                                      where,
                                      what);

            try
            {
                connection.Open();

                using (var command = new OleDbCommand(query, connection))
                {
                    using (var r = command.ExecuteReader())
                    {
                        while (r.Read())
                        {
                            try
                            {
                                FileEntity fn = new FileEntity();

                                if (File.Exists(r[1].ToString() + "\\" + r[0].ToString()))
                                {
                                    fn.Name            = r[0].ToString();
                                    fn.Path            = r[1].ToString();
                                    fn.Size            = r[4].ToString();
                                    fn.DateModified    = (DateTime)r[7];
                                    fn.DateAccessed    = (DateTime)r[8];
                                    fn.DateCreated     = (DateTime)r[9];
                                    fn.FileDescription = r[14].ToString();
                                    fn.FileExtension   = r[15].ToString();
                                    fn.ItemType        = r[16].ToString();
                                    fn.SoftwareUsed    = r[18].ToString();
                                    fn.Version         = FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).ProductVersion;
                                    fn.ApplicationName = r[10].ToString() ?? FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).ProductName;
                                    fn.Author          = r[11].ToString() ?? FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).LegalTrademarks;
                                    fn.Company         = r[12].ToString() ?? FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).CompanyName;
                                    fn.Copyright       = r[13].ToString() ?? FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).LegalCopyright;
                                    fn.Language        = r[17].ToString() ?? FileVersionInfo.GetVersionInfo(r[1].ToString() + "\\" + r[0].ToString()).Language;


                                    result.Add(fn);
                                }
                            }
                            catch (FileNotFoundException e)
                            {
                                Console.WriteLine(e.Message);
                                Console.WriteLine(e.StackTrace);
                            }
                        }
                    }
                }

                foreach (var x in result)
                {
                    var crc32 = new Crc32();
                    var hash  = string.Empty;

                    try
                    {
                        using (var fs = File.Open(x.Path + "\\" + x.Name, FileMode.Open, FileAccess.Read))
                            foreach (byte b in crc32.ComputeHash(fs))
                            {
                                hash += b.ToString("x2").ToLower();
                            }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.StackTrace);
                    }

                    x.Crc32 = hash;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                connection.Close();
            }

            return(result);
        }
        void handleVersion(string xmlData)
        {
            try
            {
                Assembly        assembly       = Assembly.GetExecutingAssembly();
                FileVersionInfo fvi            = FileVersionInfo.GetVersionInfo(assembly.Location);
                string          currentVersion = fvi.FileVersion;

                XDocument doc = XDocument.Parse(xmlData);

                IEnumerable <XElement> parent = doc.Descendants("cli");

                string latestVersion = parent.Descendants()
                                       .Where(x => (string)x.Attribute("name") == "version_number")
                                       .FirstOrDefault()
                                       .Value;

                string release_date = parent.Descendants()
                                      .Where(x => (string)x.Attribute("name") == "release_date")
                                      .FirstOrDefault()
                                      .Value;

                string release_url = parent.Descendants()
                                     .Where(x => (string)x.Attribute("name") == "release_url")
                                     .FirstOrDefault()
                                     .Value;

                string download_url = parent.Descendants()
                                      .Where(x => (string)x.Attribute("name") == "download_url")
                                      .FirstOrDefault()
                                      .Value;

                string changelog = parent.Descendants()
                                   .Where(x => (string)x.Attribute("name") == "changelog")
                                   .FirstOrDefault()
                                   .Value;

                Version cVersion = new Version(currentVersion);
                Version lVersion = new Version(latestVersion);

#if !DEBUG
                if (lVersion > cVersion)
#endif
                {
                    UpdateDialog ud = new UpdateDialog();
                    ud.ShowInTaskbar = isHidden;
                    ud.SetNewVersion(lVersion);
                    ud.changelogRtf.Rtf = changelog;
                    ud.infoLabel.Text   = string.Format(strings.updateInfoFormat, latestVersion, release_date);
                    DialogResult res = ud.ShowDialog();

                    if (res == DialogResult.OK)
                    {
                        DownloadDialog dd = new DownloadDialog();
                        dd.DownloadURL = download_url;
                        dd.ShowDialog();
                    }
                    else if (res == DialogResult.Ignore) // Download manually
                    {
                        Process.Start(release_url + "&ov=" + currentVersion);
                    }
                }
            }
            catch (Exception)
            {
            }

            checkForUpdatesButton.Text    = strings.checkForUpdates;
            checkForUpdatesButton.Enabled = true;
        }
示例#6
0
        /// <summary>
        /// Constructs an instance of PathManager object.
        /// </summary>
        /// <param name="pathManagerParams">Parameters to configure the new
        /// instance of PathManager. See PathManagerParams for details of each
        /// field.</param>
        ///
        internal PathManager(PathManagerParams pathManagerParams)
        {
            var corePath     = pathManagerParams.CorePath;
            var pathResolver = pathManagerParams.PathResolver;

            if (string.IsNullOrEmpty(corePath) || !Directory.Exists(corePath))
            {
                // If the caller does not provide an alternative core path,
                // use the default folder in which DynamoCore.dll resides.
                var dynamoCorePath = Assembly.GetExecutingAssembly().Location;
                corePath = Path.GetDirectoryName(dynamoCorePath);
            }

            dynamoCoreDir = corePath;
            var assemblyPath = Path.Combine(dynamoCoreDir, "DynamoCore.dll");

            if (!PathHelper.IsValidPath(assemblyPath))
            {
                throw new Exception("Dynamo's core path could not be found. " +
                                    "If you are running Dynamo from a test, try specifying the " +
                                    "Dynamo core location in the DynamoBasePath variable in " +
                                    "TestServices.dll.config.");
            }

            hostApplicationDirectory  = pathManagerParams.HostPath;
            extensionsDirectories     = new HashSet <string>();
            viewExtensionsDirectories = new HashSet <string>();

            extensionsDirectories.Add(Path.Combine(dynamoCoreDir, ExtensionsDirectoryName));
            viewExtensionsDirectories.Add(Path.Combine(dynamoCoreDir, ViewExtensionsDirectoryName));

            if (!string.IsNullOrEmpty(hostApplicationDirectory))
            {
                extensionsDirectories.Add(Path.Combine(hostApplicationDirectory, ExtensionsDirectoryName));
                viewExtensionsDirectories.Add(Path.Combine(hostApplicationDirectory, ViewExtensionsDirectoryName));
            }

            // If both major/minor versions are zero, get from assembly.
            majorFileVersion = pathManagerParams.MajorFileVersion;
            minorFileVersion = pathManagerParams.MinorFileVersion;
            if (majorFileVersion == 0 && (minorFileVersion == 0))
            {
                var v = FileVersionInfo.GetVersionInfo(assemblyPath);
                majorFileVersion = v.FileMajorPart;
                minorFileVersion = v.FileMinorPart;
            }

            // Current user specific directories.
            userDataDir = GetUserDataFolder(pathResolver);

            // When running as a headless process, put the logs directory in a consistent
            // location that doesn't change every time the version number changes.
            var userDataDirNoVersion = Directory.GetParent(userDataDir).FullName;

            logDirectory = Path.Combine(Dynamo.Models.DynamoModel.IsHeadless ? userDataDirNoVersion : userDataDir,
                                        LogsDirectoryName);

            preferenceFilePath = Path.Combine(userDataDir, PreferenceSettingsFileName);
            backupDirectory    = Path.Combine(userDataDirNoVersion, BackupDirectoryName);

            // Common directories.
            commonDataDir = GetCommonDataFolder(pathResolver);

            commonDefinitions = Path.Combine(commonDataDir, DefinitionsDirectoryName);
            samplesDirectory  = GetSamplesFolder(commonDataDir);
            var galleryDirectory = GetGalleryDirectory(commonDataDir);

            galleryFilePath = Path.Combine(galleryDirectory, GalleryContentsFileName);

            rootDirectories = new List <string> {
                userDataDir
            };

            nodeDirectories = new HashSet <string>
            {
                Path.Combine(dynamoCoreDir, NodesDirectoryName)
            };

            preloadedLibraries        = new HashSet <string>();
            additionalResolutionPaths = new HashSet <string>();
            LoadPathsFromResolver(pathResolver);
        }
 public static string GetCopyrightInfo()
 {
     System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
     FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
     return fvi.LegalCopyright;
 }
示例#8
0
        protected override void SaveToStream(Stream stream, DataStructures.MapObjects.Map map, DataStructures.GameData.GameData gameData, TextureCollection textureCollection)
        {
            var groups = new List <Group>();
            var solids = new List <Solid>();
            var ents   = new List <Entity>();

            FlattenTree(map.WorldSpawn, solids, ents, groups);

            var fvi         = FileVersionInfo.GetVersionInfo(typeof(VmfProvider).Assembly.Location);
            var versioninfo = new GenericStructure("versioninfo");

            versioninfo.AddProperty("editorname", "CBRE");
            versioninfo.AddProperty("editorversion", fvi.ProductMajorPart.ToString() + "." + fvi.ProductMinorPart.ToString());
            versioninfo.AddProperty("editorbuild", fvi.ProductBuildPart.ToString());
            versioninfo.AddProperty("mapversion", map.Version.ToString());
            versioninfo.AddProperty("formatversion", "100");
            versioninfo.AddProperty("prefab", "0");

            var visgroups = new GenericStructure("visgroups");

            foreach (var visgroup in map.Visgroups.OrderBy(x => x.ID).Where(x => !x.IsAutomatic))
            {
                visgroups.Children.Add(WriteVisgroup(visgroup));
            }

            var viewsettings = new GenericStructure("viewsettings");

            viewsettings.AddProperty("bSnapToGrid", map.SnapToGrid ? "1" : "0");
            viewsettings.AddProperty("bShowGrid", map.Show2DGrid ? "1" : "0");
            viewsettings.AddProperty("bShow3DGrid", map.Show3DGrid ? "1" : "0");
            viewsettings.AddProperty("nGridSpacing", map.GridSpacing.ToString());
            viewsettings.AddProperty("bIgnoreGrouping", map.IgnoreGrouping ? "1" : "0");
            viewsettings.AddProperty("bHideFaceMask", map.HideFaceMask ? "1" : "0");
            viewsettings.AddProperty("bHideNullTextures", map.HideNullTextures ? "1" : "0");
            viewsettings.AddProperty("bTextureLock", map.TextureLock ? "1" : "0");
            viewsettings.AddProperty("bTextureScalingLock", map.TextureScalingLock ? "1" : "0");

            var world = WriteWorld(map, solids, groups);

            var entities = ents.OrderBy(x => x.ID).Select(WriteEntity).ToList();

            var cameras = new GenericStructure("cameras");

            cameras.AddProperty("activecamera", map.Cameras.IndexOf(map.ActiveCamera).ToString());
            foreach (var cam in map.Cameras)
            {
                var camera = new GenericStructure("camera");
                camera.AddProperty("position", "[" + FormatCoordinate(cam.EyePosition) + "]");
                camera.AddProperty("look", "[" + FormatCoordinate(cam.LookPosition) + "]");
                cameras.Children.Add(camera);
            }

            var cordon = new GenericStructure("cordon");

            cordon.AddProperty("mins", map.CordonBounds.Start.ToString());
            cordon.AddProperty("maxs", map.CordonBounds.End.ToString());
            cordon.AddProperty("active", map.Cordon ? "1" : "0");

            using (var sw = new StreamWriter(stream)) {
                versioninfo.PrintToStream(sw);
                visgroups.PrintToStream(sw);
                viewsettings.PrintToStream(sw);
                world.PrintToStream(sw);
                entities.ForEach(e => e.PrintToStream(sw));
                cameras.PrintToStream(sw);
                cordon.PrintToStream(sw);
            }
        }
示例#9
0
        static void Main(string[] args)
        {
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

#if !DEBUG
            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);
                }
            };
#endif
            //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];
            }

            XsollaLink = Helpers.RegHelper.GetRegValue("XsollaLink");
            XsollaApiId = Helpers.RegHelper.GetRegValue("XsollaApiId");
            XsollaApiKey = Helpers.RegHelper.GetRegValue("XsollaApiKey");
            try { xsollaProjId = int.Parse(Helpers.RegHelper.GetRegValue("XsollaProjId")); } catch { xsollaProjId = 0; }
            xsollaClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{XsollaApiId}:{XsollaApiKey}")));

            //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();
            }

#if BETA
            BetaUnlocked = File.Exists(Path.Combine(Bot.RootDirectory, ".betaunlocked"));
#endif

            //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;

            //now pause the main thread to let everything else run
            Thread.Sleep(-1);
        }
示例#10
0
        private const int MaxLogLineSize     = 0xA00000;     //10mb

        static WooCommerceLogger()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            _versionInfo = FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion;
        }
        public void Start()
        {
            _versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);

            // TODO: Use some sort of build tool or something to populate the DependencyInformation
            DependencyInformation = new IProductInfo[]
            {
                new ProductInfo
                {
                    ProductName = "Fody",
                    LicenceUrl  = "https://raw.githubusercontent.com/Fody/Fody/master/License.txt",
                    SourceUrl   = "https://github.com/Fody/Fody",
                },
                new ProductInfo
                {
                    ProductName = "Lustd",
                    LicenceUrl  = "https://raw.githubusercontent.com/Fody/Fody/master/License.txt",
                    SourceUrl   = "https://raw.githubusercontent.com/gpriaulx/Lustd/master/LICENSE",
                },
                new ProductInfo
                {
                    ProductName = "NETStandard.Library",
                    ProjectUrl  = "https://dotnet.microsoft.com/",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/standard/master/LICENSE.TXT",
                    SourceUrl   = "https://github.com/dotnet/standard",
                },
                new ProductInfo
                {
                    ProductName = "ReactiveUI",
                    ProjectUrl  = "https://reactiveui.net/",
                    LicenceUrl  = "https://raw.githubusercontent.com/reactiveui/ReactiveUI/master/LICENSE",
                    SourceUrl   = "https://github.com/reactiveui/reactiveui",
                },
                new ProductInfo
                {
                    ProductName = "ReactiveUI.Fody",
                    ProjectUrl  = "https://reactiveui.net/",
                    LicenceUrl  = "https://raw.githubusercontent.com/reactiveui/ReactiveUI/master/LICENSE",
                    SourceUrl   = "https://github.com/reactiveui/reactiveui",
                },
                new ProductInfo
                {
                    ProductName = "ReactiveUI.WPF",
                    ProjectUrl  = "https://reactiveui.net/",
                    LicenceUrl  = "https://raw.githubusercontent.com/reactiveui/ReactiveUI/master/LICENSE",
                    SourceUrl   = "https://github.com/reactiveui/reactiveui",
                },
                new ProductInfo
                {
                    ProductName = "System.Collections.Immutable",
                    ProjectUrl  = "https://dotnet.microsoft.com/",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/corefx/master/LICENSE.TXT",
                    SourceUrl   = "https://github.com/dotnet/corefx",
                },
                new ProductInfo
                {
                    ProductName = "System.Drawing.Common",
                    ProjectUrl  = "https://dotnet.microsoft.com/",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/corefx/master/LICENSE.TXT",
                    SourceUrl   = "https://github.com/dotnet/corefx",
                },
                new ProductInfo
                {
                    ProductName = "System.Reactive",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/reactive/master/LICENSE",
                    SourceUrl   = "https://github.com/dotnet/reactive",
                },
                new ProductInfo
                {
                    ProductName = "System.Runtime.CompilerServices.Unsafe",
                    ProjectUrl  = "https://dotnet.microsoft.com/",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/corefx/master/LICENSE.TXT",
                    SourceUrl   = "https://github.com/dotnet/corefx",
                },
                new ProductInfo
                {
                    ProductName = "System.ValueTuple",
                    ProjectUrl  = "https://dotnet.microsoft.com/",
                    LicenceUrl  = "https://raw.githubusercontent.com/dotnet/corefx/master/LICENSE.TXT",
                    SourceUrl   = "https://github.com/dotnet/corefx",
                },
                new ProductInfo
                {
                    ProductName = "UniForm.Core",
                    LicenceUrl  = "https://raw.githubusercontent.com/gpriaulx/UniForm/master/LICENSE",
                    SourceUrl   = "https://github.com/gpriaulx/UniForm",
                },
                new ProductInfo
                {
                    ProductName = "UniForm.Engine",
                    LicenceUrl  = "https://raw.githubusercontent.com/gpriaulx/UniForm/master/LICENSE",
                    SourceUrl   = "https://github.com/gpriaulx/UniForm",
                },
                new ProductInfo
                {
                    ProductName = "UniForm.Wpf",
                    LicenceUrl  = "https://raw.githubusercontent.com/gpriaulx/UniForm/master/LICENSE",
                    SourceUrl   = "https://github.com/gpriaulx/UniForm",
                },
            };
        }
示例#12
0
        public string GetVersion(string prg)
        {
            var fvi = FileVersionInfo.GetVersionInfo(prg);

            return(fvi.FileVersion);
        }
        /// <summary>
        /// Gets the file version as a string.
        /// </summary>
        /// <returns></returns>
        public static string GetFileVersion()
        {
            Assembly assembly = typeof(TwitterUtils).Assembly;

            return(FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion);
        }
示例#14
0
        /// <summary>
        /// Gets the File Version Information that is stored as a resource in the PE file.  (This is what the
        /// version tab a file's property page is populated with).  
        /// </summary>
        public FileVersionInfo GetFileVersionInfo()
        {
            var resources = GetResources();
            var versionNode = ResourceNode.GetChild(ResourceNode.GetChild(resources, "Version"), "1");
            if (versionNode == null)
                return null;
            if (!versionNode.IsLeaf && versionNode.Children.Count == 1)
                versionNode = versionNode.Children[0];


            var buff = AllocBuff();
            byte* bytes = versionNode.FetchData(0, versionNode.DataLength, buff);
            var ret = new FileVersionInfo(bytes, versionNode.DataLength);

            FreeBuff(buff);
            return ret;
        }
示例#15
0
        public static void Main(string[] args)
        {
            Console.Title = "Wow RDP Patcher";
            ColorPrint(@"  _      __             ___  ___  ___    ___       __      __          ", ConsoleColor.White);
            ColorPrint(@" | | /| / /__ _    __  / _ \/ _ \/ _ \  / _ \___ _/ /_____/ /  ___ ____", ConsoleColor.White);
            ColorPrint(@" | |/ |/ / _ \ |/|/ / / , _/ // / ___/ / ___/ _ `/ __/ __/ _ \/ -_) __/", ConsoleColor.White);
            ColorPrint(@" |__/|__/\___/__,__/ /_/|_/____/_/    /_/   \_,_/\__/\__/_//_/\__/_/   ", ConsoleColor.White);
            ColorPrint($"                                      Version: ", $"{Assembly.GetEntryAssembly().GetName().Version}\n", ConsoleColor.Yellow);

            if (args.Length < 1)
            {
                ColorPrint(">> Drop an *.exe on me...");
            }
            else
            {
                string file = args[0];

                if (string.IsNullOrEmpty(file))
                {
                    ColorPrint(">> Invalid filepath...");
                }
                else
                {
                    if (File.Exists(file))
                    {
                        byte[] exeBytes = File.ReadAllBytes(file);

                        if (exeBytes[0] != 'M' || exeBytes[1] != 'Z')
                        {
                            ColorPrint($">> {Path.GetFileName(file)} is not a valid PE file...", ConsoleColor.Red);
                        }
                        else
                        {
                            FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(file);
                            ColorPrint($">> File version:\t\t", versionInfo.FileVersion, ConsoleColor.Yellow);

                            if (FindByteSequence(exeBytes, rdpStringBytes, out int stringOffset))
                            {
                                if (FindByteSequence(exeBytes, peHeader, out int peHeaderOffset))
                                {
                                    if (FindByteSequence(exeBytes, rdataHeader, out int rdataOffset))
                                    {
                                        // for wow this should be 0x400000
                                        int imageBase = BitConverter.ToInt32(exeBytes, peHeaderOffset + 0x34);
                                        ColorPrint($">> PE ImageBase:\t\t", $"0x{imageBase:X}", ConsoleColor.Cyan);

                                        rdataOffset += imageBase;
                                        ColorPrint($">> .rdata section at:\t\t", $"0x{rdataOffset:X}", ConsoleColor.Cyan);

                                        // the string is stored in the .rdata section
                                        int virtualAddress   = BitConverter.ToInt32(exeBytes, rdataOffset - imageBase + 12);
                                        int pointerToRawData = BitConverter.ToInt32(exeBytes, rdataOffset - imageBase + 20);

                                        ColorPrint($">> VirtualAddress:\t\t", $"0x{virtualAddress:X}", ConsoleColor.Cyan);
                                        ColorPrint($">> PointerToRawData:\t\t", $"0x{pointerToRawData:X}", ConsoleColor.Cyan);

                                        // virtual memory offset to find the usage of our string
                                        int vaOffset = virtualAddress - pointerToRawData;
                                        ColorPrint($">> Virtual Address Offset:\t", $"0x{vaOffset:X}", ConsoleColor.Cyan);

                                        // add base offset
                                        stringOffset += imageBase + vaOffset;
                                        ColorPrint(">> Found RDP string at:\t\t", $"0x{stringOffset:X}", ConsoleColor.Cyan);

                                        // we will look for the place, where the string gets loaded
                                        // 0x68 = PUSH
                                        byte[] stringOffsetBytes = BitConverter.GetBytes(stringOffset);
                                        byte[] bytesRdpCheck     = new byte[] { 0x68, 0x00, 0x00, 0x00, 0x00 };

                                        // copy the string offset behind the push instruction
                                        Array.Copy(stringOffsetBytes, 0, bytesRdpCheck, 1, 4);

                                        StringBuilder sbRdpCheck = new StringBuilder();

                                        for (int i = 0; i < 5; ++i)
                                        {
                                            sbRdpCheck.Append($"0x{bytesRdpCheck[i]:X} ");
                                        }

                                        ColorPrint($">> Searching RDP string PUSH:\t", sbRdpCheck.ToString(), ConsoleColor.Cyan);

                                        if (FindByteSequence(exeBytes, bytesRdpCheck, out int offset))
                                        {
                                            ColorPrint(">> Found RDP check function at: ", $"0x{offset:X}", ConsoleColor.Cyan);

                                            if (exeBytes[offset] == 0x90)
                                            {
                                                ColorPrint($">> Wow is already patched");
                                            }
                                            else
                                            {
                                                string backupFilename = $"{file}.backup";

                                                File.WriteAllBytes(backupFilename, exeBytes);
                                                ColorPrint($">> Backup exe:\t\t\t", Path.GetFileName(backupFilename), ConsoleColor.Green);

                                                StringBuilder sbRdpFunc = new StringBuilder();

                                                // fill the next 15 bytes with NOP's to prevent wow from exiting
                                                for (int i = 0; i < 15; ++i)
                                                {
                                                    sbRdpFunc.Append($"0x{exeBytes[offset + i]:X} ");
                                                    exeBytes[offset + i] = 0x90; // NOP
                                                }

                                                ColorPrint($">> Replaced bytes with NOP:\t", sbRdpFunc.ToString(), ConsoleColor.Cyan);
                                                File.WriteAllBytes(file, exeBytes);

                                                ColorPrint(">> Patching: ", "successful", ConsoleColor.Green);
                                            }
                                        }
                                        else
                                        {
                                            ColorPrint(">> Unable to locate rdp check function...", ConsoleColor.Red);
                                            ColorPrint(">> Executeable is already patched or incompatible...");
                                        }
                                    }
                                    else
                                    {
                                        ColorPrint(">> Unable to locate .rdata section header...", ConsoleColor.Red);
                                    }
                                }
                                else
                                {
                                    ColorPrint(">> Unable to locate PE header...", ConsoleColor.Red);
                                }
                            }
                            else
                            {
                                ColorPrint(">> Unable to locate RDP string", ConsoleColor.Red);
                            }
                        }
                    }
                    else
                    {
                        ColorPrint(">> File not found...", ConsoleColor.Red);
                    }
                }
            }

            ColorPrint(">> Press a key to exit...");
            Console.ReadKey();
        }
        /// <summary>
        /// Main running method for the application.
        /// </summary>
        /// <param name="args">Commandline arguments to the application.</param>
        /// <returns>Returns the application error code.</returns>
        private int Run(string[] args)
        {
            int beginTickCount = Environment.TickCount;

            try
            {
                this.tempFileCollection = new TempFileCollection();

                Environment.SetEnvironmentVariable("WixUnitTempDir", this.tempFileCollection.BasePath, EnvironmentVariableTarget.Process);
                this.ParseCommandline(args);

                // get the assemblies
                Assembly        wixUnitAssembly = this.GetType().Assembly;
                FileVersionInfo fv = FileVersionInfo.GetVersionInfo(wixUnitAssembly.Location);

                if (this.showHelp)
                {
                    Console.WriteLine("WixUnit version {0}", fv.FileVersion);
                    Console.WriteLine("Copyright (C) .NET Foundation and contributors. All rights reserved.");
                    Console.WriteLine();
                    Console.WriteLine(" usage: WixUnit [-?] tests.xml");
                    Console.WriteLine();
                    Console.WriteLine("   -env:<var>=<value>  Sets an environment variable to the value for the current process");
                    Console.WriteLine("   -notidy             Do not delete temporary files (for checking results)");
                    Console.WriteLine("   -rf                 Re-run the failed test from the last run");
                    Console.WriteLine("   -st                 Run the tests on a single thread");
                    Console.WriteLine("   -test:<Test_name>   Run only the specified test (may use wildcards)");
                    Console.WriteLine("   -update             Prompt user to auto-update a test if expected and actual output files do not match");
                    Console.WriteLine("   -v                  Verbose output");
                    Console.WriteLine("   -val                Run MSI validation for light unit tests");

                    return(0);
                }

                // set the environment variables for the process only
                foreach (KeyValuePair <string, string> environmentVariable in this.environmentVariables)
                {
                    Environment.SetEnvironmentVariable(environmentVariable.Key, environmentVariable.Value, EnvironmentVariableTarget.Process);
                }

                // load the schema
                XmlReader           schemaReader = null;
                XmlSchemaCollection schemas      = null;
                try
                {
                    schemas = new XmlSchemaCollection();

                    schemaReader = new XmlTextReader(wixUnitAssembly.GetManifestResourceStream("WixToolset.Unit.unitTests.xsd"));
                    XmlSchema schema = XmlSchema.Read(schemaReader, null);
                    schemas.Add(schema);
                }
                finally
                {
                    if (schemaReader != null)
                    {
                        schemaReader.Close();
                    }
                }

                // load the unit tests
                XmlTextReader reader = null;
                XmlDocument   doc    = new XmlDocument();
                try
                {
                    reader = new XmlTextReader(this.unitTestsFile);
                    XmlValidatingReader validatingReader = new XmlValidatingReader(reader);
                    validatingReader.Schemas.Add(schemas);

                    // load the xml into a DOM
                    doc.Load(validatingReader);
                }
                catch (XmlException e)
                {
                    SourceLineNumber           sourceLineNumber  = new SourceLineNumber(this.unitTestsFile, e.LineNumber);
                    SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber });

                    throw new WixException(WixErrors.InvalidXml(sourceLineNumbers, "unitTests", e.Message));
                }
                catch (XmlSchemaException e)
                {
                    SourceLineNumber           sourceLineNumber  = new SourceLineNumber(this.unitTestsFile, e.LineNumber);
                    SourceLineNumberCollection sourceLineNumbers = new SourceLineNumberCollection(new SourceLineNumber[] { sourceLineNumber });

                    throw new WixException(WixErrors.SchemaValidationFailed(sourceLineNumbers, e.Message, e.LineNumber, e.LinePosition));
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }

                // check the document element
                if ("UnitTests" != doc.DocumentElement.LocalName || XmlNamespace != doc.DocumentElement.NamespaceURI)
                {
                    throw new InvalidOperationException("Unrecognized document element.");
                }

                // create a regular expression of the selected tests
                Regex selectedUnitTests = new Regex(String.Concat("^", String.Join("$|^", (string[])this.unitTests.ToArray(typeof(string))), "$"), RegexOptions.IgnoreCase | RegexOptions.Singleline);

                // find the unit tests
                foreach (XmlNode node in doc.DocumentElement)
                {
                    if (XmlNodeType.Element == node.NodeType)
                    {
                        switch (node.LocalName)
                        {
                        case "UnitTest":
                            XmlElement unitTestElement = (XmlElement)node;
                            string     unitTestName    = unitTestElement.GetAttribute("Name");

                            if (selectedUnitTests.IsMatch(unitTestName))
                            {
                                unitTestElement.SetAttribute("TempDirectory", this.tempFileCollection.BasePath);
                                this.unitTestElements.Enqueue(node);
                            }
                            break;
                        }
                    }
                }

                if (this.unitTests.Count > 0)
                {
                    this.totalUnitTests = this.unitTestElements.Count;
                    int numThreads;

                    if (this.updateTests || this.singleThreaded)
                    {
                        // If the tests are running with the -update switch, they must run on one thread
                        // so that all execution is paused when the user is prompted to update a test.
                        numThreads = 1;
                    }
                    else
                    {
                        // create a thread for each processor
                        numThreads = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"), CultureInfo.InvariantCulture);
                    }

                    Thread[] threads = new Thread[numThreads];

                    for (int i = 0; i < threads.Length; i++)
                    {
                        threads[i] = new Thread(new ThreadStart(this.RunUnitTests));
                        threads[i].Start();
                    }

                    // wait for all threads to finish
                    foreach (Thread thread in threads)
                    {
                        thread.Join();
                    }

                    // report the results
                    Console.WriteLine();
                    int elapsedTime = (Environment.TickCount - beginTickCount) / 1000;
                    if (0 < this.failedUnitTests.Count)
                    {
                        Console.WriteLine("Summary of failed tests:");
                        Console.WriteLine();

                        // Put the failed tests into an ArrayList, which will get serialized
                        ArrayList serializedFailedTests = new ArrayList();
                        foreach (string failedTest in this.failedUnitTests.Keys)
                        {
                            serializedFailedTests.Add(failedTest);
                            Console.WriteLine("{0}. {1}", this.failedUnitTests[failedTest], failedTest);
                        }

                        Console.WriteLine();
                        Console.WriteLine("Re-run the failed tests with the -rf option");
                        Console.WriteLine();
                        Console.Error.WriteLine("Failed {0} out of {1} unit test{2} ({3} seconds).", this.failedUnitTests.Count, this.totalUnitTests, (1 != this.completedUnitTests ? "s" : ""), elapsedTime);

                        using (XmlWriter writer = XmlWriter.Create(this.failedTestsFile))
                        {
                            XmlSerializer serializer = new XmlSerializer(serializedFailedTests.GetType());
                            serializer.Serialize(writer, serializedFailedTests);
                            writer.Close();
                        }
                    }
                    else
                    {
                        Console.WriteLine("Successful unit tests: {0} ({1} seconds).", this.completedUnitTests, elapsedTime);
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("No unit tests were selected.");
                }
            }
            catch (WixException we)
            {
                this.messageHandler.Display(this, we.Error);
            }
            catch (Exception e)
            {
                this.messageHandler.Display(this, WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace));
                if (e is NullReferenceException)
                {
                    throw;
                }
            }
            finally
            {
                if (this.noTidy)
                {
                    Console.WriteLine();
                    Console.WriteLine("The notidy option was specified, temporary files can be found at:");
                    Console.WriteLine(this.tempFileCollection.BasePath);
                }
                else
                {
                    // try three times and give up with a warning if the temp files aren't gone by then
                    const int RetryLimit = 3;

                    for (int i = 0; i < RetryLimit; i++)
                    {
                        try
                        {
                            Directory.Delete(this.tempFileCollection.BasePath, true); // toast the whole temp directory
                            break;                                                    // no exception means we got success the first time
                        }
                        catch (UnauthorizedAccessException)
                        {
                            if (0 == i)                                                                                    // should only need to unmark readonly once - there's no point in doing it again and again
                            {
                                RecursiveFileAttributes(this.tempFileCollection.BasePath, FileAttributes.ReadOnly, false); // toasting will fail if any files are read-only. Try changing them to not be.
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (DirectoryNotFoundException)
                        {
                            // if the path doesn't exist, then there is nothing for us to worry about
                            break;
                        }
                        catch (IOException)            // directory in use
                        {
                            if (i == (RetryLimit - 1)) // last try failed still, give up
                            {
                                break;
                            }
                            Thread.Sleep(300);  // sleep a bit before trying again
                        }
                    }
                }
            }

            return(this.failedUnitTests.Count);
        }
示例#17
0
        private static Settings Init()
        {
            var settings = new Settings();

            settings.EnableSSL = GetBool("EnableSSL");

            string value = GetString("BaseURL");

            if (!String.IsNullOrEmpty(value))
            {
                if (value.EndsWith("/"))
                {
                    value = value.Substring(0, value.Length - 1);
                }

                if (settings.EnableSSL && value.StartsWith("http:"))
                {
                    value = value.ReplaceFirst("http:", "https:");
                }
                else if (!settings.EnableSSL && value.StartsWith("https:"))
                {
                    value = value.ReplaceFirst("https:", "http:");
                }

                settings.BaseURL = value;
            }

            settings.InternalProjectId           = GetString("InternalProjectId");
            settings.WebsiteMode                 = GetEnum <WebsiteMode>("WebsiteMode", WebsiteMode.Dev);
            settings.TestEmailAddress            = GetString("TestEmailAddress");
            settings.AllowedOutboundAddresses    = GetStringList("AllowedOutboundAddresses", "exceptionless.io").Select(v => v.ToLowerInvariant()).ToList();
            settings.GeoIPDatabasePath           = GetString("GeoIPDatabasePath");
            settings.RunJobsInProcess            = GetBool("RunJobsInProcess", true);
            settings.LogJobLocks                 = GetBool("LogJobLocks");
            settings.LogJobEvents                = GetBool("LogJobEvents");
            settings.LogJobCompleted             = GetBool("LogJobCompleted");
            settings.LogStackingInfo             = GetBool("LogStackingInfo");
            settings.AppendMachineNameToDatabase = GetBool("AppendMachineNameToDatabase");
            settings.SaveIncomingErrorsToDisk    = GetBool("SaveIncomingErrorsToDisk");
            settings.IncomingErrorPath           = GetString("IncomingErrorPath");
            settings.EnableLogErrorReporting     = GetBool("EnableLogErrorReporting");
            settings.EnableSignalR               = GetBool("EnableSignalR", true);
            settings.BotThrottleLimit            = GetInt("BotThrottleLimit", 25);
            settings.ApiThrottleLimit            = GetInt("ApiThrottleLimit", Int32.MaxValue);
            settings.MaximumEventPostSize        = GetInt("MaximumEventPostSize", Int32.MaxValue);
            settings.EnableDailySummary          = GetBool("EnableDailySummary");
            settings.ShouldAutoUpgradeDatabase   = GetBool("ShouldAutoUpgradeDatabase", true);
            settings.MetricsServerName           = GetString("MetricsServerName") ?? "127.0.0.1";
            settings.MetricsServerPort           = GetInt("MetricsServerPort", 12000);
            settings.EnableMetricsReporting      = GetBool("EnableMetricsReporting");
            settings.IntercomAppSecret           = GetString("IntercomAppSecret");
            settings.EnableAccountCreation       = GetBool("EnableAccountCreation", true);
            settings.GoogleAppId                 = GetString("GoogleAppId");
            settings.GoogleAppSecret             = GetString("GoogleAppSecret");
            settings.MicrosoftAppId              = GetString("MicrosoftAppId");
            settings.MicrosoftAppSecret          = GetString("MicrosoftAppSecret");
            settings.FacebookAppId               = GetString("FacebookAppId");
            settings.FacebookAppSecret           = GetString("FacebookAppSecret");
            settings.GitHubAppId                 = GetString("GitHubAppId");
            settings.GitHubAppSecret             = GetString("GitHubAppSecret");
            settings.StripeApiKey                = GetString("StripeApiKey");
            settings.StorageFolder               = GetString("StorageFolder");
            settings.BulkBatchSize               = GetInt("BulkBatchSize", 1000);

            string connectionString = GetConnectionString("RedisConnectionString");

            if (!String.IsNullOrEmpty(connectionString))
            {
                settings.RedisConnectionString = connectionString;
                settings.EnableRedis           = GetBool("EnableRedis", !String.IsNullOrEmpty(settings.RedisConnectionString));
            }

            connectionString = GetConnectionString("AzureStorageConnectionString");
            if (!String.IsNullOrEmpty(connectionString))
            {
                settings.AzureStorageConnectionString = connectionString;
                settings.EnableAzureStorage           = GetBool("EnableAzureStorage", !String.IsNullOrEmpty(settings.AzureStorageConnectionString));
            }

            connectionString = GetConnectionString("MongoConnectionString");
            if (!String.IsNullOrEmpty(connectionString))
            {
                settings.MongoConnectionString = connectionString;
            }

            connectionString = GetConnectionString("ElasticSearchConnectionString");
            if (!String.IsNullOrEmpty(connectionString))
            {
                settings.ElasticSearchConnectionString = connectionString;
            }

            settings.Version = FileVersionInfo.GetVersionInfo(typeof(Settings).Assembly.Location).ProductVersion;

            return(settings);
        }
示例#18
0
        private PEInfo(string filename)
        {
            _filename = filename;
            try {
                IsPEBinary      = true;
                _executableInfo = new Lazy <ExecutableInfo>(() => {
                    var result = IsManaged ? ExecutableInfo.managed : ExecutableInfo.native;
                    if (IsAny)
                    {
                        result |= ExecutableInfo.any;
                    }
                    else
                    {
                        switch (CoffHeader.Machine)
                        {
                        case 0x01c0:
                            result |= ExecutableInfo.arm;
                            break;

                        case 0x014c:
                            result |= ExecutableInfo.x86;
                            break;

                        case 0x0200:
                            result |= ExecutableInfo.ia64;
                            break;

                        case 0x8664:
                            result |= ExecutableInfo.x64;
                            break;

                        default:
                            throw new ClrPlusException("Unrecognized Executable Machine Type.");
                        }
                    }

                    return(result);
                });

                _fileVersionInfo   = new Lazy <FileVersionInfo>(() => FileVersionInfo.GetVersionInfo(_filename));
                _fileVersionString =
                    new Lazy <string>(
                        () =>
                        string.Format("{0}.{1}.{2}.{3}", _fileVersionInfo.Value.FileMajorPart, _fileVersionInfo.Value.FileMinorPart,
                                      _fileVersionInfo.Value.FileBuildPart, _fileVersionInfo.Value.FilePrivatePart));
                _fileVersionLong =
                    new Lazy <ulong>(
                        () =>
                        (((ulong)_fileVersionInfo.Value.FileMajorPart) << 48) + (((ulong)_fileVersionInfo.Value.FileMinorPart) << 32) +
                        (((ulong)_fileVersionInfo.Value.FileBuildPart) << 16) + (ulong)_fileVersionInfo.Value.FilePrivatePart);

#if TODO
                DependencyInformation = new CacheEnumerable <DependencyInformation>(DependencyInformationImpl);
#endif
                using (var reader = new BinaryReader(File.OpenRead(_filename))) {
                    // Skip DOS Header and seek to PE signature
                    if (reader.ReadUInt16() != 0x5A4D)
                    {
                        // Logger.Warning("File '{0}' does not have a valid PE Header", _filename);
                        throw new ClrPlusException("Invalid DOS header.", true);
                    }

                    reader.ReadBytes(58);
                    reader.BaseStream.Position = reader.ReadUInt32();

                    // Read "PE\0\0" signature
                    if (reader.ReadUInt32() != 0x00004550)
                    {
                        throw new ClrPlusException("File is not a portable executable.");
                    }

                    // Read COFF header
                    CoffHeader = new ImageCoffHeader {
                        Machine            = reader.ReadUInt16(),
                        NumberOfSections   = reader.ReadUInt16(),
                        TimeDateStamp      = reader.ReadUInt32(),
                        SymbolTablePointer = reader.ReadUInt32(),
                        NumberOfSymbols    = reader.ReadUInt32(),
                        OptionalHeaderSize = reader.ReadUInt16(),
                        Characteristics    = reader.ReadUInt16()
                    };

                    // Compute data sections offset
                    var dataSectionsOffset = reader.BaseStream.Position + CoffHeader.OptionalHeaderSize;

                    // Read NT-specific fields
                    NtHeader = new ImageOptionalHeaderNt();

                    NtHeader.Magic = reader.ReadUInt16();
                    NtHeader.MajorLinkerVersion      = reader.ReadByte();
                    NtHeader.MinorLinkerVersion      = reader.ReadByte();
                    NtHeader.SizeOfCode              = reader.ReadUInt32();
                    NtHeader.SizeOfInitializedData   = reader.ReadUInt32();
                    NtHeader.SizeOfUninitializedData = reader.ReadUInt32();
                    NtHeader.AddressOfEntryPoint     = reader.ReadUInt32();
                    NtHeader.BaseOfCode              = reader.ReadUInt32();

                    if (Is32BitPE)
                    {
                        NtHeader.BaseOfData_32bit = reader.ReadUInt32();
                        NtHeader.ImageBase_32bit  = reader.ReadUInt32();
                    }

                    if (Is64BitPE)
                    {
                        NtHeader.ImageBase_64bit = reader.ReadUInt64();
                    }

                    NtHeader.SectionAlignment = reader.ReadUInt32();
                    NtHeader.FileAlignment    = reader.ReadUInt32();
                    NtHeader.OsMajor          = reader.ReadUInt16();
                    NtHeader.OsMinor          = reader.ReadUInt16();
                    NtHeader.UserMajor        = reader.ReadUInt16();
                    NtHeader.UserMinor        = reader.ReadUInt16();
                    NtHeader.SubSysMajor      = reader.ReadUInt16();
                    NtHeader.SubSysMinor      = reader.ReadUInt16();
                    NtHeader.Reserved         = reader.ReadUInt32();
                    NtHeader.ImageSize        = reader.ReadUInt32();
                    NtHeader.HeaderSize       = reader.ReadUInt32();
                    NtHeader.FileChecksum     = reader.ReadUInt32();
                    NtHeader.SubSystem        = reader.ReadUInt16();
                    NtHeader.DllFlags         = reader.ReadUInt16();

                    if (Is32BitPE)
                    {
                        NtHeader.StackReserveSize_32bit = reader.ReadUInt32();
                        NtHeader.StackCommitSize_32bit  = reader.ReadUInt32();
                        NtHeader.HeapReserveSize_32bit  = reader.ReadUInt32();
                        NtHeader.HeapCommitSize_32bit   = reader.ReadUInt32();
                    }
                    if (Is64BitPE)
                    {
                        NtHeader.StackReserveSize_64bit = reader.ReadUInt64();
                        NtHeader.StackCommitSize_64bit  = reader.ReadUInt64();
                        NtHeader.HeapReserveSize_64bit  = reader.ReadUInt64();
                        NtHeader.HeapCommitSize_64bit   = reader.ReadUInt64();
                    }
                    NtHeader.LoaderFlags             = reader.ReadUInt32();
                    NtHeader.NumberOfDataDirectories = reader.ReadUInt32();
                    if (NtHeader.NumberOfDataDirectories < 16)
                    {
                        return;
                    }

                    // Read data directories
                    _exportTable         = ReadDataDirectory(reader);
                    _importTable         = ReadDataDirectory(reader);
                    _resourceTable       = ReadDataDirectory(reader);
                    _exceptionTable      = ReadDataDirectory(reader);
                    _certificateTable    = ReadDataDirectory(reader);
                    _baseRelocationTable = ReadDataDirectory(reader);
                    _debug                 = ReadDataDirectory(reader);
                    _copyright             = ReadDataDirectory(reader);
                    _globalPtr             = ReadDataDirectory(reader);
                    _tlsTable              = ReadDataDirectory(reader);
                    _loadConfigTable       = ReadDataDirectory(reader);
                    _boundImport           = ReadDataDirectory(reader);
                    _iat                   = ReadDataDirectory(reader);
                    _delayImportDescriptor = ReadDataDirectory(reader);
                    _runtimeHeader         = ReadDataDirectory(reader);
                    _reserved              = ReadDataDirectory(reader);

                    if (_runtimeHeader.Size == 0)
                    {
                        return;
                    }

                    // Read data sections
                    reader.BaseStream.Position = dataSectionsOffset;
                    SectionHeaders             = new ImageSectionHeader[CoffHeader.NumberOfSections];
                    for (var i = 0; i < SectionHeaders.Length; i++)
                    {
                        reader.ReadBytes(12);
                        SectionHeaders[i].VirtualAddress   = reader.ReadUInt32();
                        SectionHeaders[i].SizeOfRawData    = reader.ReadUInt32();
                        SectionHeaders[i].PointerToRawData = reader.ReadUInt32();
                        reader.ReadBytes(16);
                    }

                    // Read COR20 Header
                    reader.BaseStream.Position = RvaToVa(_runtimeHeader.Rva);
                    CorHeader = new ImageCor20Header {
                        Size = reader.ReadUInt32(),
                        MajorRuntimeVersion = reader.ReadUInt16(),
                        MinorRuntimeVersion = reader.ReadUInt16(),
                        MetaData            = ReadDataDirectory(reader),
                        Flags                   = reader.ReadUInt32(),
                        EntryPointToken         = reader.ReadUInt32(),
                        Resources               = ReadDataDirectory(reader),
                        StrongNameSignature     = ReadDataDirectory(reader),
                        CodeManagerTable        = ReadDataDirectory(reader),
                        VTableFixups            = ReadDataDirectory(reader),
                        ExportAddressTableJumps = ReadDataDirectory(reader)
                    };
                }
            } catch {
                IsPEBinary = false;
            }
        }
示例#19
0
        public NewMainWindow()
        {
            try
            {
                Log("<-- Запуск DSList -->");
                InitializeComponent();


                Bindings    = new BindingVariables();
                DataContext = Bindings; // Выполняется привязка контекста MainWindows к BindingVariables для корректной работы привязки элементов, прописанных в Xaml

                #region Поиск сотрудников в TS и формирование списка AD


                Bindings.VisibilitySetting = Visibility.Collapsed;
                progressBarWorker          = new BackgroundWorker();

                listPcIPAndPcName = new ObservableCollection <IPAndName>();

                listADUsers      = new ObservableCollection <ADUser>();
                searchListADUser = new ObservableCollection <ADUser>();

                listTSUser       = new ObservableCollection <TSUser>();
                searchListTSUser = new ObservableCollection <TSUser>();

                dataGridTS.ItemsSource   = listTSUser;
                dataGridAD.ItemsSource   = listADUsers;
                dataGridIPPC.ItemsSource = listPcIPAndPcName;
                dataGridIPPC.HorizontalContentAlignment = HorizontalAlignment.Stretch;


                searchListBoxAD.ItemsSource = searchListADUser;
                searchListBoxTS.ItemsSource = searchListTSUser;

                #endregion

                this.version                         = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                Bindings.title                       = "DSList " + this.version;
                IsWindows10                          = FileVersionInfo.GetVersionInfo(System.IO.Path.Combine(Environment.SystemDirectory, "Kernel32.dll")).ProductMajorPart >= 10;
                Bindings.IsTSConnecting              = Environment.UserDomainName.ToLower().Contains("dengisrazy") ? true : false;
                NewMainWindow.settings.OnSaveOrLoad += settings_OnSaveOrLoad;
                Title = Bindings.title;

                //siteTable = new TableFromSite();

                //TabCtrl.SelectionChanged += TabCtrl_SelectionChanged;
                Tabs.SelectionChanged += Tabs_SelectionChanged;

                //searchListBox.DisplayMemberPath = "ToStringDisplay";    // Представление отображения в списке найденных Customer

                cvzNotifyIcon.Icon    = Properties.Resources.vsnetwebservicedynamicdiscovery_8215;
                cvzNotifyIcon.Text    = "DSList";
                cvzNotifyIcon.Visible = true;
                cvzNotifyIcon.Click  += new EventHandler(this.ni_Click);
                if (DSList.Properties.Settings.Default.Maximized)
                {
                    base.WindowState = WindowState.Maximized;
                }

                this.SearchTimer.Tick += new EventHandler(this.SearchTimer_Tick);

                this.SearchADTimer.Tick += new EventHandler(this.SearchADTimer_Tick);

                //this.UpdateTimer.Tick += new EventHandler(this.UpdateTimer_Tick);

                this.UpdateTimer.Interval = new TimeSpan(0, 0, 15, 0, 0);
                this.UpdateTimer.Start();

                LoadHotkeys();
                LoadUserCredentials();
                SelectedLoginCreate();
                CreateNewCredentials();    // Формируется список логинов и паролей, прописанных в методе CreateCredentials()
                LoadCredentialsFromSQLServer();


                NewMainWindow.MRU = new ObservableCollection <MRUTT>();
                LoadMRU();
                ListViewMRU.ItemsSource = MRU;
                //ListViewMRU.MouseDoubleClick += (object sender, MouseButtonEventArgs args) => { };
                ListViewMRU.MouseDoubleClick += MRUItem_Click;

                //TabCtrl.ItemsSource = OpenedTT;

                //Tabs.ItemsSource = OpenedTT;


                TabContextMenuCreate();

                LoadPopup();

                RefreshCredentials();
                //TabCtrl.ContextMenu = tabContextMenu;
                #region PinnedWatchTimer
                this.PinnedWatchTimer.Tick    += new EventHandler(this.PinnedWatchTimer_Tick);
                this.PinnedWatchTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
                this.PinnedWatchTimer.Start();
                #endregion

                //ListViewIP.DataContext = SelectedTT;

                TextBoxSearch.Focus();
            }
            catch (Exception ex)
            {
                Log("Ошибка загрузки основного окна MainWindow. " + ex.Message, true, false, ex.StackTrace);
            }
        }
示例#20
0
        public MainForm()
        {
            Assembly        assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string          version  = fvi.FileVersion;

            // Initialize component
            InitializeComponent();

            Opacity       = 0;
            ShowInTaskbar = false;

            // Load "resources.resx" into a ResourceManager to access its resources
            resources = new ResourceManager("CapsLockIndicatorV3.resources", Assembly.GetExecutingAssembly());

            // Load the icons into variables
            ReloadIcons();

            // Set the values
            numState    = KeyHelper.isNumlockActive;
            capsState   = KeyHelper.isCapslockActive;
            scrollState = KeyHelper.isScrolllockActive;

            // Load settings
            enableNumIcon.Checked    = SettingsManager.Get <bool>("numIco");
            enableCapsIcon.Checked   = SettingsManager.Get <bool>("capsIco");
            enableScrollIcon.Checked = SettingsManager.Get <bool>("scrollIco");

            enableNumInd.Checked    = SettingsManager.Get <bool>("numInd");
            enableCapsInd.Checked   = SettingsManager.Get <bool>("capsInd");
            enableScrollInd.Checked = SettingsManager.Get <bool>("scrollInd");

            showNoIcons.Checked        = SettingsManager.Get <bool>("noIco");
            showNoNotification.Checked = SettingsManager.Get <bool>("noInd");

            iconsGroup.Enabled     = !showNoIcons.Checked;
            indicatorGroup.Enabled = !showNoNotification.Checked;

            generalIcon.ContextMenu                =
                numLockIcon.ContextMenu            =
                    capsLockIcon.ContextMenu       =
                        scrollLockIcon.ContextMenu =
                            contextMenu1;

            HandleCreated += (sender, e) =>
            {
                DarkModeChanged += MainForm_DarkModeChanged;
                DarkModeProvider.RegisterForm(this);
            };

            // Check if application is in startup
            startonlogonCheckBox.Checked = Registry.GetValue(@"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run", "CapsLock Indicator", null) != null;

            // Hides the window on startup if enabled
            if (SettingsManager.Get <bool>("hideOnStartup"))
            {
                hideOnStartupCheckBox.Checked = true;
                hideWindowTimer.Start();
            }
            else
            {
                Opacity       = 1;
                ShowInTaskbar = true;
            }

            checkForUpdatedCheckBox.Checked = SettingsManager.Get <bool>("checkForUpdates");

            AddCultures();

            ApplyLocales();

            SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
        }
示例#21
0
        /// <summary>
        /// Constructor for the ModuleInfo object. Takes (string)modules filepath (IntPtr)module handle (Process)Process from which the module is loaded
        /// </summary>
        /// <param name="module">Filepath of the module</param>
        /// <param name="ptr">Handle to the module</param>
        /// <param name="process">Process where the module is loaded</param>
        /// <param name="core">An ErcCore object</param>
        internal unsafe ModuleInfo(string module, IntPtr ptr, Process process, ErcCore core)
        {
            try
            {
                ModuleCore    = core;
                ModuleProcess = process;
                ModuleName    = FileVersionInfo.GetVersionInfo(module).InternalName;
                ModulePath    = FileVersionInfo.GetVersionInfo(module).FileName;
                ModuleBase    = ptr;

                FileInfo   fileInfo = new FileInfo(ModulePath);
                FileStream file     = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                PopulateHeaderStructs(file);

                if (!string.IsNullOrEmpty(FileVersionInfo.GetVersionInfo(module).FileVersion))
                {
                    ModuleVersion = FileVersionInfo.GetVersionInfo(module).FileVersion.Split(' ')[0];
                }
                else
                {
                    ModuleVersion = "";
                }

                ModuleProduct = FileVersionInfo.GetVersionInfo(module).ProductName;

                if (ModuleMachineType == MachineType.I386)
                {
                    ModuleEntry     = (IntPtr)ImageOptionalHeader32.AddressOfEntryPoint;
                    ModuleSize      = (int)ImageOptionalHeader32.SizeOfImage;
                    ModuleImageBase = (IntPtr)ImageOptionalHeader32.ImageBase;
                    byte[]   dllByte = BitConverter.GetBytes(ImageOptionalHeader32.DllCharacteristics);
                    BitArray bits    = new BitArray(dllByte);
                    for (int i = 0; i < bits.Count; i++)
                    {
                        if (bits[i] == true && i == 6)
                        {
                            ModuleASLR = true;
                        }
                        else
                        {
                            ModuleASLR = false;
                        }

                        if (bits[i] == true && i == 8)
                        {
                            ModuleNXCompat = true;
                        }
                        else
                        {
                            ModuleNXCompat = false;
                        }
                    }

                    if (ModuleMachineType == MachineType.I386)
                    {
                        PopulateConfigStruct();

                        if (ImageConfigDir32.SEHandlerCount == 0 && ImageConfigDir32.SEHandlerTable == 0)
                        {
                            ModuleSafeSEH = false;
                        }
                        else
                        {
                            ModuleSafeSEH = true;
                        }
                    }
                    else
                    {
                        ModuleSafeSEH = true;
                    }
                }
                else if (ModuleMachineType == MachineType.x64)
                {
                    ModuleEntry     = (IntPtr)ImageOptionalHeader64.AddressOfEntryPoint;
                    ModuleSize      = (int)ImageOptionalHeader64.SizeOfImage;
                    ModuleImageBase = (IntPtr)ImageOptionalHeader64.ImageBase;
                    byte[]   dllByte = BitConverter.GetBytes(ImageOptionalHeader64.DllCharacteristics);
                    BitArray bits    = new BitArray(dllByte);
                    for (int i = 0; i < bits.Count; i++)
                    {
                        if (bits[i] == true && i == 6)
                        {
                            ModuleASLR = true;
                        }
                        else if (bits[i] == false && i == 6)
                        {
                            ModuleASLR = false;
                        }

                        if (bits[i] == true && i == 8)
                        {
                            ModuleNXCompat = true;
                        }
                        else if (bits[i] == false && i == 8)
                        {
                            ModuleNXCompat = false;
                        }
                    }

                    PopulateConfigStruct();

                    if (ImageConfigDir64.SEHandlerCount == 0 && ImageConfigDir64.SEHandlerTable == 0)
                    {
                        ModuleSafeSEH = false;
                    }
                    else
                    {
                        ModuleSafeSEH = true;
                    }
                }
                else
                {
                    ModuleFailed = true;
                    throw new ERCException("Unsupported machine type: " + ModuleMachineType.ToString());
                }

                if (ModuleProduct == "Microsoft® Windows® Operating System")
                {
                    ModuleOsDll = true;
                }
                else
                {
                    ModuleOsDll = false;
                }

                if (ModuleImageBase != ptr)
                {
                    ModuleRebase = true;
                }
                else
                {
                    ModuleRebase = false;
                }

                long MaxAddress = 0x7fffffff;
                long address    = (long)ModuleBase;

                if (!ProcessInfo.Is64Bit(process))
                {
                    List <ERC.Structures.MEMORY_BASIC_INFORMATION32> ProcessMemoryBasicInfo32 = new List <ERC.Structures.MEMORY_BASIC_INFORMATION32>();
                    do
                    {
                        ERC.Structures.MEMORY_BASIC_INFORMATION32 m;
                        int result = ErcCore.VirtualQueryEx32(ModuleProcess.Handle, (IntPtr)address, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION32)));
                        if (address == (long)m.BaseAddress + (long)m.RegionSize)
                        {
                            break;
                        }
                        address          = (long)m.BaseAddress + (long)m.RegionSize;
                        ModuleProtection = m.AllocationProtect;
                    } while (address <= MaxAddress);
                }
                else
                {
                    List <ERC.Structures.MEMORY_BASIC_INFORMATION64> ProcessMemoryBasicInfo64 = new List <ERC.Structures.MEMORY_BASIC_INFORMATION64>();
                    do
                    {
                        ERC.Structures.MEMORY_BASIC_INFORMATION64 m;
                        int result = ErcCore.VirtualQueryEx64(ModuleProcess.Handle, (IntPtr)address, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION64)));
                        if (address == (long)m.BaseAddress + (long)m.RegionSize)
                        {
                            break;
                        }
                        address          = (long)m.BaseAddress + (long)m.RegionSize;
                        ModuleProtection = m.AllocationProtect;
                    } while (address <= MaxAddress);
                }
            }
            catch (Exception e)
            {
                ErcResult <Exception> ExceptionLogger = new ErcResult <Exception>(ModuleCore);
                ExceptionLogger.Error = e;
                ExceptionLogger.LogEvent();
                ModuleFailed = true;
            }
        }
示例#22
0
 public List<FileSimpleInfo> GetLocalFolderFile(string dirPath)
 {
     List<FileSimpleInfo> files = new List<FileSimpleInfo>();
     DirectoryInfo mydir = new DirectoryInfo(dirPath);
     foreach (FileInfo file in mydir.GetFiles())
     {
         FileSimpleInfo fileInfo = new FileSimpleInfo();
         fileInfo.Name = file.Name;
         fileInfo.Length = file.Length;
         fileInfo.ModifyDateTime = file.LastWriteTime;
         fileInfo.Version = FileVersionInfo.GetVersionInfo(file.FullName).FileVersion == null ? "" : FileVersionInfo.GetVersionInfo(file.FullName).FileVersion;
         files.Add(fileInfo);
     }
     return files;
 }
示例#23
0
        public static void Main()
        {
            var productVersion = FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.Location).ProductVersion;

            WriteRuleJson(productVersion);
        }
        protected async Task <Tuple <string, string> > LaunchService(
            string logPath,
            bool waitForDebugger = false)
        {
            string modulePath = Path.GetFullPath(TestUtilities.NormalizePath("../../../../../module"));
            string scriptPath = Path.GetFullPath(Path.Combine(modulePath, "PowerShellEditorServices", "Start-EditorServices.ps1"));

            if (!File.Exists(scriptPath))
            {
                throw new IOException(String.Format("Bad start script path: '{0}'", scriptPath));
            }

            Assembly assembly = this.GetType().GetTypeInfo().Assembly;

            string          assemblyPath    = new Uri(assembly.CodeBase).LocalPath;
            FileVersionInfo fileVersionInfo =
                FileVersionInfo.GetVersionInfo(assemblyPath);

            string sessionPath =
                Path.Combine(
                    Path.GetDirectoryName(assemblyPath), $"session-{++sessionCounter}.json");

            if (File.Exists(sessionPath))
            {
                File.Delete(sessionPath);
            }

            string editorServicesModuleVersion =
                string.Format(
                    "{0}.{1}.{2}",
                    fileVersionInfo.FileMajorPart,
                    fileVersionInfo.FileMinorPart,
                    fileVersionInfo.FileBuildPart);

            string scriptArgs =
                "\"" + scriptPath + "\" " +
                "-HostName \\\"PowerShell Editor Services Test Host\\\" " +
                "-HostProfileId \"Test.PowerShellEditorServices\" " +
                "-HostVersion \"1.0.0\" " +
                "-BundledModulesPath \\\"" + modulePath + "\\\" " +
                "-LogLevel \"Verbose\" " +
                "-LogPath \"" + logPath + "\" " +
                "-SessionDetailsPath \"" + sessionPath + "\" " +
                "-FeatureFlags @() " +
                "-AdditionalModules @() ";

            if (waitForDebugger)
            {
                scriptArgs += "-WaitForDebugger ";
            }

            string[] args =
                new string[]
            {
                "-NoProfile",
                "-NonInteractive",
                "-ExecutionPolicy", "Unrestricted",
                "-Command \"" + scriptArgs + "\""
            };

            this.serviceProcess = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = GetPwshExeName(),
                    Arguments              = string.Join(" ", args),
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    StandardOutputEncoding = Encoding.UTF8
                },
                EnableRaisingEvents = true,
            };

            // Start the process
            this.serviceProcess.Start();

            string sessionDetailsText = string.Empty;

            // Wait up to ~5 seconds for the server to finish initializing
            var maxRetryAttempts = 10;

            while (maxRetryAttempts-- > 0)
            {
                if (this.serviceProcess.HasExited)
                {
                    throw new Exception(String.Format("Server host process quit unexpectedly: '{0}'", this.serviceProcess.StandardError.ReadToEnd()));
                }

                try
                {
                    using (var stream = new FileStream(sessionPath, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (var reader = new StreamReader(stream))
                        {
                            sessionDetailsText = reader.ReadToEnd();
                            break;
                        }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Session details at '{sessionPath}' not available: {ex.Message}");
                }

                Thread.Sleep(500);
            }

            JObject result = JObject.Parse(sessionDetailsText);

            if (result["status"].Value <string>() == "started")
            {
                return(new Tuple <string, string>(
                           result["languageServicePipeName"].Value <string>(),
                           result["debugServicePipeName"].Value <string>()));
            }

            Debug.WriteLine($"Failed to read session details from '{sessionPath}'");

            return(null);
        }
示例#25
0
        static void Main(string[] args)
        {
            // parse command line
            var options = new Options();

            if (args.Length == 0)
            {
                Console.WriteLine(options.GetUsage());
                Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
            }

            var parser = new Parser(settings =>
            {
                settings.MutuallyExclusive = true;
                settings.HelpWriter        = Parser.Default.Settings.HelpWriter;
                settings.CaseSensitive     = false;
            });

            if (!parser.ParseArguments(args, options))
            {
                Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
            }

            System.Collections.Generic.List <Mode> lstmode = options.GetAllOptions(args);

            // perform additional validation
            if (!String.IsNullOrEmpty(options.ClientID))
            {
                if (String.IsNullOrEmpty(options.ClientSecret))
                {
                    Console.WriteLine("If you specify a client id you also need to specify a client secret");
                    Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
                }
            }
            if (!String.IsNullOrEmpty(options.ClientSecret))
            {
                if (String.IsNullOrEmpty(options.ClientID))
                {
                    Console.WriteLine("If you specify a client secret you also need to specify a client id");
                    Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
                }
            }

            if (!String.IsNullOrEmpty(options.User))
            {
                if (String.IsNullOrEmpty(options.Password))
                {
                    Console.WriteLine("If you specify a user you also need to specify a password");
                    Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
                }
            }
            if (!String.IsNullOrEmpty(options.Password))
            {
                if (String.IsNullOrEmpty(options.User))
                {
                    Console.WriteLine("If you specify a password you also need to specify a user");
                    Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
                }
            }

            // Better support for running/testing the tool when SharePoint site certificate is not trusted on the box running the scan
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
            {
                return(true);
            };

            // Instantiate scan job
            AccessAppScanner accessAppScanner = new AccessAppScanner()
            {
                UseThreading    = true,
                Modes           = lstmode,
                MaximumThreads  = options.Threads,
                TenantAdminSite = options.TenantAdminSite,
                OutputFolder    = DateTime.Now.Ticks.ToString(),
                Separator       = options.Separator,
                Tenant          = options.Tenant,
                UseSearchQuery  = !options.DontUseSearchQuery
            };

            // temp debug
            //accessAppScanner.UseThreading = false;

            // set scan creds
            if (options.UsesAppOnly())
            {
                accessAppScanner.UseAppOnlyAuthentication(options.ClientID, options.ClientSecret);
            }
            else if (options.UsesCredentials())
            {
                accessAppScanner.UseOffice365Authentication(options.User, options.Password);
            }

            accessAppScanner.ExcludeOD4B = options.ExcludeOD4B;

            if (!accessAppScanner.UseSearchQuery)
            {
                // set scan urls
                if (!String.IsNullOrEmpty(options.Tenant))
                {
                    accessAppScanner.AddSite(string.Format("https://{0}.sharepoint.com/*", options.Tenant));
                    if (!accessAppScanner.ExcludeOD4B)
                    {
                        accessAppScanner.AddSite(string.Format("https://{0}-my.sharepoint.com/*", options.Tenant));
                    }
                }
                else
                {
                    foreach (var url in options.Urls)
                    {
                        accessAppScanner.AddSite(url);
                    }
                }
            }

            DateTime start = DateTime.Now;

            Console.WriteLine("=====================================================");
            Console.WriteLine("Scanning is starting...{0}", start.ToString());
            Console.WriteLine("=====================================================");
            Console.WriteLine("Building a list of site collections...");

            // Launch the job
            accessAppScanner.Run();

            // Dump scan results
            Console.WriteLine("=====================================================");
            Console.WriteLine("Scanning is done...now dump the results to a CSV file");
            Console.WriteLine("=====================================================");
            System.IO.Directory.CreateDirectory(accessAppScanner.OutputFolder);
            string outputfile = null;

            string[] outputHeaders = null;

            #region Access App report
            if (lstmode.Contains(Mode.Scan))
            {
                // output summary report
                outputfile = string.Format("{0}\\AccessApps.csv", accessAppScanner.OutputFolder);
                Console.WriteLine("Outputting Access App scan to {0}", outputfile);
                outputHeaders = new string[] { "Site Url", "Parent Site Url", "Site Collection Url", "Web Title",
                                               "Web Template", "App Created On", "Access 2013 App Last Accessed On", "Access 2010 App Last Modified By User On", "App Instance Status", "App Instance Id", "Web Id",
                                               "ViewsRecent", "viewsRecentUnique", "viewsLifetime", "viewsLifetimeUnique" };
                System.IO.File.AppendAllText(outputfile, string.Format("{0}\r\n", string.Join(options.Separator, outputHeaders)));

                AccessAppScanData scanData;
                while (accessAppScanner.AccessAppResults.TryPop(out scanData))
                {
                    System.IO.File.AppendAllText(outputfile, string.Format("{0}\r\n", string.Join(options.Separator, ToCsv(scanData.SiteUrl), ToCsv(scanData.ParentSiteUrl), ToCsv(scanData.SiteColUrl), ToCsv(scanData.WebTitle),
                                                                                                  ToCsv(scanData.WebTemplate), scanData.WebCreatedDate, scanData.LastAccessedDate, scanData.LastModifiedByUserDate, scanData.AppInstanceStatus, scanData.AppInstanceId, scanData.WebId,
                                                                                                  scanData.ViewsRecent, scanData.ViewsRecentUnique, scanData.ViewsLifetime, scanData.ViewsLifetimeUnique)));
                }
            }
            #endregion

            #region Error reporting
            if (accessAppScanner.AccessAppScanErrors.Count > 0)
            {
                string errorfile = string.Format("{0}\\errors.csv", accessAppScanner.OutputFolder);
                // Dump scan errors
                Console.WriteLine("Outputting errors to {0}", errorfile);
                outputHeaders = new string[] { "Site Url", "Site Collection Url", "Error" };
                System.IO.File.AppendAllText(errorfile, string.Format("{0}\r\n", string.Join(options.Separator, outputHeaders)));
                AccessAppScanError error;
                while (accessAppScanner.AccessAppScanErrors.TryPop(out error))
                {
                    System.IO.File.AppendAllText(errorfile, string.Format("{0}\r\n", string.Join(options.Separator, ToCsv(error.SiteUrl), ToCsv(error.SiteColUrl), ToCsv(error.Error))));
                }
            }
            #endregion

            #region Scanner data
            if (accessAppScanner.ScannedSites > 0)
            {
                outputfile = string.Format("{0}\\ScannerSummary.csv", accessAppScanner.OutputFolder);
                Console.WriteLine("Outputting information over the done scan to {0}", outputfile);
                outputHeaders = new string[] { "Site collections scanned", "Webs scanned", "Scan duration", "Scanner version" };
                System.IO.File.AppendAllText(outputfile, string.Format("{0}\r\n", string.Join(options.Separator, outputHeaders)));

                Assembly        assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                string          version  = fvi.FileVersion;
                TimeSpan        ts       = DateTime.Now.Subtract(accessAppScanner.StartTime);
                System.IO.File.AppendAllText(outputfile, string.Format("{0}\r\n", string.Join(options.Separator, !accessAppScanner.UseSearchQuery?accessAppScanner.ScannedSites:0, accessAppScanner.ScannedWebs, $"{ts.Days} days, {ts.Hours} hours, {ts.Minutes} minutes and {ts.Seconds} seconds", version)));
            }
            #endregion

            Console.WriteLine("=====================================================");
            Console.WriteLine("All done. Took {0} for {1} sites", (DateTime.Now - start).ToString(), accessAppScanner.ScannedSites);
            Console.WriteLine("=====================================================");
        }
示例#26
0
        /// <summary>
        /// Retrieves the names of all loaded modules in the process, their base
        /// address and size on disk.
        /// </summary>
        ///
        /// <param name="pid">
        /// Id of the process.
        /// </param>
        private void GetModuleDetails(int pid)
        {
            const Win32.SnapshotFlags flags = Win32.SnapshotFlags.TH32CS_SNAPMODULE |
                                              Win32.SnapshotFlags.TH32CS_SNAPMODULE32;

            var hModuleSnap = Win32.CreateToolhelp32Snapshot(flags, pid);

            if (hModuleSnap == INVALID_HANDLE_VALUE)
            {
                return;
            }

            var modEntry = new Win32.MODULEENTRY32()
            {
                dwSize       = (uint)Marshal.SizeOf(typeof(Win32.MODULEENTRY32)),
                th32ModuleID = 0
            };

            if (!Win32.Module32First(hModuleSnap, ref modEntry))
            {
                Win32.CloseHandle(hModuleSnap);
                return;
            }

            do
            {
                try
                {
                    var modPath = modEntry.szExePath;
                    var modInfo = FileVersionInfo.GetVersionInfo(modPath);
                    var modSize = new FileInfo(modPath).Length;
                    var lvi     = new ListViewItem(modEntry.szModule)
                    {
                        Tag         = modInfo.FileName,
                        ToolTipText = modInfo.FileName + "\n" +
                                      modInfo.LegalCopyright + "\n" +
                                      modInfo.FileDescription + "\n" +
                                      modInfo.ProductVersion
                    };
                    lvi.SubItems.Add("0x" + modEntry.modBaseAddr.ToString("X4"));
                    lvi.SubItems.Add(FormatByteSize(modSize));
                    LV_Module.Items.Add(lvi);
                }
                catch
                {
                    break;
                }
            }while (Win32.Module32Next(hModuleSnap, ref modEntry));

            // Close the object
            Win32.CloseHandle(hModuleSnap);

            /* Sort the items and remove the duplicate module name. The
            ** duplication happens because SnapshotFlags searches for both 32-bit
            ** and 64-bit modules. Therefore, it adds the main module from both
            ** TH32CS_SNAPMODULE and TH32CS_SNAPMODULE32.
            */
            LV_Module.Items[0].ForeColor = Color.Red;
            LV_Module.Sorting            = SortOrder.Ascending;
            for (var i = 0; i < LV_Module.Items.Count - 1; i++)
            {
                if (LV_Module.Items[i].Tag.Equals(LV_Module.Items[i + 1].Tag))
                {
                    LV_Module.Items[i].ForeColor = Color.Red;
                    LV_Module.Items[i + 1].Remove();
                    i--;
                }
                moduleCount = i;
            }

            SetModuleCount();
        }
示例#27
0
        private static void Install(PatchContext context)
        {
            try
            {
                bool installFiles = true;
                // first, check currently installed version, if any
                if (File.Exists(Path.Combine(context.ProjectRoot, "winhttp.dll")))
                { // installed, so check version of installed assembly
                    string injectorPath = Path.Combine(context.ManagedPath, "IPA.Injector.dll");
                    if (File.Exists(injectorPath))
                    {
                        var verInfo     = FileVersionInfo.GetVersionInfo(injectorPath);
                        var fileVersion = new Version(verInfo.FileVersion);

                        if (fileVersion > Version)
                        {
                            installFiles = false;
                        }
                    }
                }

                if (installFiles || ArgForce)
                {
                    var backup = new BackupUnit(context);

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Restoring old version... ");
                    if (BackupManager.HasBackup(context))
                    {
                        BackupManager.Restore(context);
                    }

                    var  nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
                    bool isFlat             = Directory.Exists(nativePluginFolder) &&
                                              Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
                    bool force        = !BackupManager.HasBackup(context) || ArgForce;
                    var  architecture = DetectArchitecture(context.Executable);

                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Installing files... ");

                    CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
                            backup,
                            (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
                                                                  architecture));
                    CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
                            backup,
                            null, false);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Not copying files because newer version already installed");
                }

                #region Create Plugin Folder

                if (!Directory.Exists(context.PluginsFolder))
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("Creating plugins folder... ");
                    Directory.CreateDirectory(context.PluginsFolder);
                    Console.ResetColor();
                }

                #endregion
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Fail("Oops! This should not have happened.\n\n" + e);
            }
            Console.ResetColor();
        }
 /// <summary>
 /// Determines the FileVersion of the file passed in
 /// </summary>
 /// <param name="file_path">Relative or full path to a file</param>
 /// <returns>A string representing the FileVersion of the passed in file</returns>
 public string get_file_version_from(string file_path)
 {
     return(FileVersionInfo.GetVersionInfo(get_full_path(file_path)).FileVersion);
 }
示例#29
0
        public Form1()
        {
            form1 = this;
            InitializeComponent();
            Log.logBox = logBox;
            if (File.Exists("Assembly-CSharp.dll") || File.Exists("UnityEngine.dll") || File.Exists("mysummercar.exe") || File.Exists("mainData") || File.Exists("mono.dll") || File.Exists("CSteamworks.dll")) //check if idiot unpacked this to game folder.
            {
                if (MessageBox.Show("Did you read the instructions? (Readme.txt)", "Question for you!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    MessageBox.Show(string.Format("Why are you lying?{0}Or maybe you can't read?{0}If you could read, you would know what you did wrong.", Environment.NewLine), "You are a liar", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(string.Format("Yes I see.{0}Go back to readme and you will know what you did wrong.", Environment.NewLine), "You are a liar", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                Environment.Exit(0);
            }
            if (File.Exists("MSCFolder.txt"))
            {
                mscPath = File.ReadAllText("MSCFolder.txt");
                if (!Directory.Exists(mscPath))
                {
                    Log.Write(string.Format("Saved MSC Folder, doesn't exists: {0}", mscPath));
                    mscPath = "(unknown)";
                    try
                    {
                        File.Delete("MSCFolder.txt");
                    }
                    catch (Exception e)
                    {
                        Log.Write(e.Message);
                    }
                }
                else
                {
                    Log.Write(string.Format("Loaded saved MSC Folder: {0}", mscPath));
                }
            }
            mscPathLabel.Text = mscPath;
            MDlabel.Text      = mdPath;
            if (Directory.Exists(mdPath))
            {
                Log.Write(string.Format("Found mods folder in: {0}", mdPath));
                MDlabel.ForeColor = Color.Green;
                MDradio.Checked   = true;
                modPath           = mdPath;
            }
            ADlabel.Text = adPath;
            if (Directory.Exists(adPath))
            {
                Log.Write(string.Format("Found mods folder in: {0}", adPath));
                ADlabel.ForeColor = Color.Green;
                ADradio.Checked   = true;
                modPath           = adPath;
            }
            try
            {
                mscLoaderVersion = FileVersionInfo.GetVersionInfo("MSCLoader.dll");
                string currentVersion;
                if (mscLoaderVersion.FileBuildPart != 0)
                {
                    currentVersion = string.Format("{0}.{1}.{2}", mscLoaderVersion.FileMajorPart, mscLoaderVersion.FileMinorPart, mscLoaderVersion.FileBuildPart);
                }
                else
                {
                    currentVersion = string.Format("{0}.{1}", mscLoaderVersion.FileMajorPart, mscLoaderVersion.FileMinorPart);
                }

                string version;
                string res;
                using (WebClient client = new WebClient())
                {
                    client.QueryString.Add("core", "stable");
                    res = client.DownloadString("http://my-summer-car.ml/ver.php");
                }
                string[] result = res.Split('|');
                if (result[0] == "error")
                {
                    switch (result[1])
                    {
                    case "0":
                        throw new Exception("Unknown branch");

                    case "1":
                        throw new Exception("Database connection error");

                    default:
                        throw new Exception("Unknown error");
                    }
                }
                else if (result[0] == "ok")
                {
                    if (result[1].Trim().Length > 8)
                    {
                        throw new Exception("Parse Error, please report that problem!");
                    }
                    version = result[1].Trim();
                }
                else
                {
                    throw new Exception("Unknown server response.");
                }
                int i = currentVersion.CompareTo(version.Trim());
                if (i != 0)
                {
                    Log.Write(string.Format("{2}MCSLoader v{0}, New version available: v{1}", currentVersion, version.Trim(), Environment.NewLine));
                    if (MessageBox.Show(string.Format("New version is available: v{0}, wanna check it out?", version.Trim()), "MCSLoader v" + currentVersion, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            if (File.Exists("MSCLoader_Launcher.exe"))
                            {
                                Process.Start("MSCLoader_Launcher.exe");
                            }
                            else
                            {
                                Process.Start("https://github.com/piotrulos/MSCModLoader/releases");
                            }
                            Environment.Exit(0);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(string.Format("Failed to open update info!{1}{1}Error details:{1}{0}", ex.Message, Environment.NewLine), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    statusBarLabel.Text = string.Format("New version available: v{0}", version.Trim());
                }
                else if (i == 0)
                {
                    Log.Write(string.Format("{1}MCSLoader v{0} is up to date, no new version found.", currentVersion, Environment.NewLine));
                    statusBarLabel.Text = "MSCPatcher Ready!";
                }
            }
            catch (Exception e)
            {
                Log.Write(string.Format("Check for new version failed with error: {0}", e.Message));
                statusBarLabel.Text = "MSCPatcher Ready!";
            }

            if (!Directory.Exists("Debug"))
            {
                groupBox5.Visible      = false;
                basicDebugInfo.Visible = true;
            }
            Log.Write("MSCPatcher ready!", true, true);

            if (mscPath != "(unknown)")
            {
                mscPathLabel.Text = mscPath;
                AssemblyFullPath  = Path.Combine(mscPath, AssemblyPath);
                gfPath            = Path.Combine(mscPath, @"Mods");
                GFlabel.Text      = gfPath;
                if (Directory.Exists(gfPath))
                {
                    Log.Write(string.Format("Found mods folder in: {0}", gfPath));
                    GFlabel.ForeColor = Color.Green;
                    GFradio.Checked   = true;
                    modPath           = gfPath;
                }
                Log.Write(string.Format("Game folder set to: {0}{1}", mscPath, Environment.NewLine));

                MainData.LoadMainData(OutputlogLabel, resDialogLabel, resDialogCheck);

                DebugStatusInfo();
                CheckPatchStatus();
            }
        }
示例#30
0
        public static FileVersionInfo GetFileVersionInfo(string path)
        {
            uint unuse = 0;
            uint bufSize = Win32Import.GetFileVersionInfoSize(path, ref unuse);
            if (bufSize != 0)
            {
                byte[] buf = new byte[bufSize];
                if (Win32Import.GetFileVersionInfo(path, 0, bufSize, buf) != 0)
                {
                    FileVersionInfo fileVersionInfo = new FileVersionInfo();

                    IntPtr data = IntPtr.Zero;
                    uint dataSize = 0;
                    if (Win32Import.VerQueryValue(buf, @"\", ref data, ref dataSize) > 0 &&
                        dataSize == Marshal.SizeOf(fileVersionInfo.fixedInfo))
                    {
                        fileVersionInfo.fixedInfo = (Win32Import.VS_FixedFileInfo)Marshal.PtrToStructure(
                            data, typeof(Win32Import.VS_FixedFileInfo));
                    }

                    short[] langCodeList = null;
                    if (Win32Import.VerQueryValue(buf, @"\VarFileInfo\Translation", ref data, ref dataSize) > 0)
                    {
                        langCodeList = new short[dataSize / 2];
                        Marshal.Copy(data, langCodeList, 0, langCodeList.Length);
                    }

                    if (langCodeList != null)
                    {
                        fileVersionInfo.langBasedInfoList = new FileVersionInfo.LanguageBasedFileInfo[langCodeList.Length / 2];
                        for (int i = 0; i < fileVersionInfo.langBasedInfoList.Length; ++i)
                        {
                            FileVersionInfo.LanguageBasedFileInfo langBasedInfo = new FileVersionInfo.LanguageBasedFileInfo();

                            langBasedInfo.language = unchecked((ushort)langCodeList[i * 2]);
                            langBasedInfo.codePage = unchecked((ushort)langCodeList[i * 2 + 1]);

                            Func<string, string> verQueryString = s =>
                            {
                                string fmt =
                                string.Format(
                                "\\StringFileInfo\\{0:x4}{1:x4}\\{2}",
                                langBasedInfo.language, langBasedInfo.codePage, s);

                                if (Win32Import.VerQueryValue(buf, fmt, ref data, ref dataSize) > 0)
                                {
                                    char[] tempBuf = new char[dataSize / 2];
                                    Marshal.Copy(data, tempBuf, 0, tempBuf.Length);
                                    return new string(tempBuf);
                                }
                                return string.Empty;
                            };

                            langBasedInfo.comments = verQueryString("Comments");
                            langBasedInfo.internalName = verQueryString("InternalName"); ;
                            langBasedInfo.productName = verQueryString("ProductName"); ;
                            langBasedInfo.companyName = verQueryString("CompanyName"); ;
                            langBasedInfo.legalCopyright = verQueryString("LegalCopyright"); ;
                            langBasedInfo.productVersion = verQueryString("ProductVersion"); ;
                            langBasedInfo.fileDescription = verQueryString("FileDescription"); ;
                            langBasedInfo.legalTrademarks = verQueryString("LegalTrademarks"); ;
                            langBasedInfo.privateBuild = verQueryString("PrivateBuild"); ;
                            langBasedInfo.fileVersion = verQueryString("FileVersion"); ;
                            langBasedInfo.originalFilename = verQueryString("OriginalFilename"); ;
                            langBasedInfo.specialBuild = verQueryString("SpecialBuild"); ;

                            fileVersionInfo.langBasedInfoList[i] = langBasedInfo;
                        }
                    }

                    return fileVersionInfo;
                }
            }

            return new FileVersionInfo();
        }
示例#31
0
        public override void Initialize()
        {
            EnvironmentVariablePrefix = "Exceptionless_";

            EnableSSL = GetBool("EnableSSL");

            string value = GetString("BaseURL");

            if (!String.IsNullOrEmpty(value))
            {
                if (value.EndsWith("/"))
                {
                    value = value.Substring(0, value.Length - 1);
                }

                if (EnableSSL && value.StartsWith("http:"))
                {
                    value = value.ReplaceFirst("http:", "https:");
                }
                else if (!EnableSSL && value.StartsWith("https:"))
                {
                    value = value.ReplaceFirst("https:", "http:");
                }

                BaseURL = value;
            }

            InternalProjectId        = GetString("InternalProjectId", "54b56e480ef9605a88a13153");
            WebsiteMode              = GetEnum <WebsiteMode>("WebsiteMode", WebsiteMode.Dev);
            AppScope                 = GetString("AppScope", String.Empty);
            TestEmailAddress         = GetString("TestEmailAddress");
            AllowedOutboundAddresses = GetStringList("AllowedOutboundAddresses", "exceptionless.io").Select(v => v.ToLowerInvariant()).ToList();
            RunJobsInProcess         = GetBool("RunJobsInProcess", true);
            BotThrottleLimit         = GetInt("BotThrottleLimit", 25);
            ApiThrottleLimit         = GetInt("ApiThrottleLimit", Int32.MaxValue);
            EventSubmissionDisabled  = GetBool(nameof(EventSubmissionDisabled));
            MaximumEventPostSize     = GetInt("MaximumEventPostSize", Int32.MaxValue);
            EnableDailySummary       = GetBool("EnableDailySummary");
            MetricsServerName        = GetString("MetricsServerName") ?? "127.0.0.1";
            MetricsServerPort        = GetInt("MetricsServerPort", 8125);
            EnableMetricsReporting   = GetBool("EnableMetricsReporting");
            IntercomAppSecret        = GetString("IntercomAppSecret");
            EnableAccountCreation    = GetBool("EnableAccountCreation", true);
            GoogleAppId              = GetString("GoogleAppId");
            GoogleAppSecret          = GetString("GoogleAppSecret");
            MicrosoftAppId           = GetString("MicrosoftAppId");
            MicrosoftAppSecret       = GetString("MicrosoftAppSecret");
            FacebookAppId            = GetString("FacebookAppId");
            FacebookAppSecret        = GetString("FacebookAppSecret");
            GitHubAppId              = GetString("GitHubAppId");
            GitHubAppSecret          = GetString("GitHubAppSecret");
            StripeApiKey             = GetString("StripeApiKey");
            StorageFolder            = GetString("StorageFolder");
            BulkBatchSize            = GetInt("BulkBatchSize", 1000);

            SmtpHost      = GetString("SmtpHost");
            SmtpPort      = GetInt("SmtpPort", 587);
            SmtpEnableSsl = GetBool("SmtpEnableSsl", true);
            SmtpUser      = GetString("SmtpUser");
            SmtpPassword  = GetString("SmtpPassword");

            AzureStorageConnectionString = GetConnectionString("AzureStorageConnectionString");
            EnableAzureStorage           = GetBool("EnableAzureStorage", !String.IsNullOrEmpty(AzureStorageConnectionString));

            ElasticSearchConnectionString = GetConnectionString("ElasticSearchConnectionString");
            EnableElasticsearchTracing    = GetBool("EnableElasticsearchTracing");

            RedisConnectionString = GetConnectionString("RedisConnectionString");
            EnableRedis           = GetBool("EnableRedis", !String.IsNullOrEmpty(RedisConnectionString));

            EnableSignalR = GetBool(nameof(EnableSignalR), true);

            Version         = FileVersionInfo.GetVersionInfo(typeof(Settings).Assembly.Location).ProductVersion;
            MinimumLogLevel = GetEnum <LogLevel>("MinimumLogLevel", LogLevel.Info);
        }
示例#32
0
 public FileVersionInfo GetFileVersionInfo()
 {
     var buff = _file.AllocBuff();
     byte* bytes = FetchData(0, DataLength, buff);
     var ret = new FileVersionInfo(bytes, DataLength);
     _file.FreeBuff(buff);
     return ret;
 }
示例#33
0
 public void FileVersionInfo_FileNotFound()
 {
     Assert.Throws <FileNotFoundException>(() =>
                                           FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName)));
 }