Пример #1
0
        /// <summary>
        /// Prepare HttpWebRequest with default parameters
        /// </summary>
        /// <param name="url">URL for request. </param>
        /// <param name="method">Method type - GET, PUT, POST. </param>
        /// <returns>Prepared HttpWebRequest.</returns>
        public static HttpWebRequest PrepareHttpWebRequest(string url, string method)
        {
            if (String.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (String.IsNullOrEmpty(method))
            {
                throw new ArgumentNullException("method");
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = method.ToUpper();

            //if (StreamCompressPlugin.IsAvailable)
            //{
            request.Headers["Accept-Encoding"] = "gzip, deflate";
            //}

            request.UserAgent         = PlatformDetection.GetCurrentClientVersion();
            request.Timeout           = SystemConfiguration.ServerConnectionTimeOutShort;
            request.AllowAutoRedirect = false;
            return(request);
        }
Пример #2
0
 static void Main()
 {
     Central.InitializeLogger();
     Central.InitializeSystem(new Manager(), PlatformDetection.Detect());
     Central.Manager.Initalize();
     Central.Manager.Start();
 }
Пример #3
0
        private Process StartSubnautica()
        {
            if (PirateDetection.TriggerOnDirectory(subnauticaPath))
            {
                return(null);
            }

            string           subnauticaExe = Path.Combine(subnauticaPath, "Subnautica.exe");
            ProcessStartInfo startInfo     = new ProcessStartInfo
            {
                WorkingDirectory = subnauticaPath,
                FileName         = subnauticaExe
            };

            if (PlatformDetection.IsEpic(subnauticaPath))
            {
                startInfo.Arguments = "-EpicPortal";
            }
            else if (PlatformDetection.IsSteam(subnauticaPath))
            {
                startInfo.FileName = "steam://run/264710";
            }

            return(Process.Start(startInfo));
        }
Пример #4
0
        internal static Service GetDefaultService(IConfigurationReader configurationReader, IApmLogger loggerArg)
        {
            IApmLogger logger  = loggerArg.Scoped(nameof(Service));
            var        service = new Service
            {
                Name    = configurationReader.ServiceName,
                Version = configurationReader.ServiceVersion,
                Agent   = new AgentC
                {
                    Name    = Consts.AgentName,
                    Version = typeof(Agent).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion
                },
                Environment = configurationReader.Environment,
                Node        = new Node {
                    ConfiguredName = configurationReader.ServiceNodeName
                }
            };

            //see https://github.com/elastic/apm-agent-dotnet/issues/859
            try
            {
                service.Runtime = PlatformDetection.GetServiceRuntime(logger);
            }
            catch (Exception e)
            {
                logger.Warning()?.LogException(e, "Failed detecting runtime - no runtime name and version will be reported");
            }

            return(service);
        }
Пример #5
0
        public void DumpRuntimeInformationToConsole()
        {
            // Not really a test, but useful to dump to the log to
            // sanity check that the test run or CI job
            // was actually run on the OS that it claims to be on
            string dvs = PlatformDetection.GetDistroVersionString();
            string osd = RuntimeInformation.OSDescription.Trim();
            string osv = Environment.OSVersion.ToString();
            string osa = RuntimeInformation.OSArchitecture.ToString();
            string pra = RuntimeInformation.ProcessArchitecture.ToString();
            string frd = RuntimeInformation.FrameworkDescription.Trim();
            string lcr = PlatformDetection.LibcRelease;
            string lcv = PlatformDetection.LibcVersion;

            Console.WriteLine($@"### CONFIGURATION: {dvs} OS={osd} OSVer={osv} OSArch={osa} Arch={pra} Framework={frd} LibcRelease={lcr} LibcVersion={lcv}");

            if (!PlatformDetection.IsNetNative)
            {
                string binariesLocation = Path.GetDirectoryName(typeof(object).Assembly.Location);
                Console.WriteLine("location: " + binariesLocation);
                string binariesLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(binariesLocation).DriveFormat;
                Console.WriteLine($"### BINARIES: {binariesLocation} (drive format {binariesLocationFormat})");
            }

            string tempPathLocation       = Path.GetTempPath();
            string tempPathLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(tempPathLocation).DriveFormat;

            Console.WriteLine($"### TEMP PATH: {tempPathLocation} (drive format {tempPathLocationFormat})");

            Console.WriteLine($"### CURRENT DIRECTORY: {Environment.CurrentDirectory}");
        }
Пример #6
0
        static void Main()
        {
            // add global exception handler
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

            DebugHelper.WriteTraceEntry("-------------------- Start programm --------------------");

            Process[] proc = Process.GetProcesses();
            int       i    = 0;

            foreach (Process process in proc)
            {
                if (process.ProcessName == "VKontakteWM.exe")
                {
                    i++;
                    if (i > 1)
                    {
                        Application.Exit();
                        return;
                    }
                }
            }

            SystemConfiguration.Init("ВКонтакте", "sysconfig.xml");

            if (PlatformDetection.IsSmartphone() || !(Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1)) //5.2 - WM6+, 5.1 - WM5))
            {
                MessageBox.Show(Resources.PlatformSupport, SystemConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);

                return;
            }

            Cache.InitPath(SystemConfiguration.AppInstallPath + "\\Cache");

            ////make sure we have enough memory to run
            CoreHelper.FreeProgramMemoryIfNeeded(4000);
            // make sure device does not go to sleep during startup
            CoreHelper.KeepDeviceAwake();

            MobileDevice.Hibernate += MobileDevice_Hibernate;

            // Инициализация синглтона бизнес-логики
            Globals.Init(new BaseLogic(new DataLogic(), new CommunicationLogic()));

            // init master form
            MasterForm form = new MasterForm();

            form.Closing += form_Closing;
            form.Initialize();

            Application.Run(form);
        }
Пример #7
0
        //public void Init(string audioFilePath)
        //{
        //    Init(CodecFactory.Instance.GetCodec(audioFilePath));
        //}

        public void Init(IWaveSource source)
        {
            _soundSource = source;
            // Use ALSound out if we are running on Mac/Linux
            _soundOut = (PlatformDetection.RunningPlatform() == Platform.Windows) ?
                        (ISoundOut) new WasapiOut() : new ALSoundOut();
            _soundOut.Initialize(_soundSource);
            _soundOut.Stopped += (sender, args) => { if (args.HasError)
                                                     {
                                                         throw new Exception("exception thrown on stoping audio", args.Exception);
                                                     }
            };
        }
Пример #8
0
        private void StartSubnautica(string subnauticaPath)
        {
            string subnauticaExe = Path.Combine(subnauticaPath, "Subnautica.exe");

            if (PlatformDetection.IsEpic(subnauticaPath))
            {
                Process.Start(subnauticaExe, "-EpicPortal");
            }
            else
            {
                Process.Start(subnauticaExe);
            }
        }
Пример #9
0
        internal void StartSubnautica(string subnauticaPath)
        {
            string subnauticaExe = Path.Combine(subnauticaPath, "Subnautica.exe");
            var    startInfo     = new ProcessStartInfo();

            startInfo.WorkingDirectory = subnauticaPath;
            startInfo.FileName         = subnauticaExe;

            if (PlatformDetection.IsEpic(subnauticaPath))
            {
                startInfo.Arguments = "-EpicPortal";
            }
            Process.Start(startInfo);
        }
Пример #10
0
        public void DumpRuntimeInformationToConsole()
        {
            // Not really a test, but useful to dump to the log to
            // sanity check that the test run or CI job
            // was actually run on the OS that it claims to be on
            string dvs = PlatformDetection.GetDistroVersionString();
            string osd = RuntimeInformation.OSDescription.Trim();
            string osv = Environment.OSVersion.ToString();
            string osa = RuntimeInformation.OSArchitecture.ToString();
            string pra = RuntimeInformation.ProcessArchitecture.ToString();
            string frd = RuntimeInformation.FrameworkDescription.Trim();

            Console.WriteLine($@"{dvs} OS={osd} OSVer={osv} OSArch={osa} Arch={pra} Framework={frd}");
        }
Пример #11
0
        internal static Service GetDefaultService(IConfigurationReader configurationReader, IApmLogger loggerArg)
        {
            IApmLogger logger = loggerArg.Scoped(nameof(Service));

            return(new Service
            {
                Name = configurationReader.ServiceName,
                Agent = new AgentC
                {
                    Name = Consts.AgentName,
                    Version = typeof(Agent).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion
                },
                Runtime = PlatformDetection.GetServiceRuntime(logger)
            });
        }
Пример #12
0
        public SettingsViewModel(Settings settings)
        {
            _settings        = settings;
            IsInAppContainer = PlatformDetection.IsInAppContainer();
            if (!IsInAppContainer)
            {
                CheckIsInstalled();
            }

            _lazySaveTimer = new DispatcherTimer {
                Interval = TimeSpan.FromMilliseconds(1000)
            };
            _lazySaveTimer.Tick += (s, e) => SaveSettings();

            PropertyChanged += SettingsViewModel_PropertyChanged;
        }
Пример #13
0
        public override void Load()
        {
            SceneManager.GameWindow.Cursor = MouseCursor.Default;

            // Remap keypad enter to normal enter
            InputSystem.KeyRemappings.Add(Key.KeypadEnter, Key.Enter);

            _gameVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // Choose correct version directive because OSX is dumb
            string version = "#version 130";

            if (PlatformDetection.RunningPlatform() == Platform.MacOSX)
            {
                version = "#version 150";
            }

            // Load shaders
            var vert = new Shader(Path.Combine(SceneManager.Directories["Shaders"].FullName, "simple.vs"), version);
            var frag = new Shader(Path.Combine(SceneManager.Directories["Shaders"].FullName, "simple.fs"), version);

            _shaderProgram = new ShaderProgram();
            _shaderProgram.Load(vert, frag);

            _player                      = new Player();
            _player.Position             = new PolarVector(1.5 * (Math.PI / 3) - _player.Length * 0.5f, _player.Position.Radius);
            _player.ShaderProgram        = _shaderProgram;
            _centerPolygon               = new PolarPolygon(Enumerable.Repeat(true, 6).ToList(), new PolarVector(0.5, 0), 50, 80, 0);
            _centerPolygon.ShaderProgram = _shaderProgram;

            _menuFont        = SceneManager.GameFontLibrary.GetFirstOrDefault("menuworld");
            _menuFontDrawing = new QFontDrawing();
            _menuFontDrawing.ProjectionMatrix = SceneManager.ScreenCamera.WorldModelViewProjection;
            _menuRenderOptions = new QFontRenderOptions {
                DropShadowActive = true, Colour = Color.White
            };

            _versionFont = SceneManager.GameFontLibrary.GetFirstOrDefault("versiontext");

            var guiRenderer = new Gwen.Renderer.OpenTK();
            var skin        = new TexturedBase(guiRenderer, Path.Combine(SceneManager.Directories["Images"].FullName, "DefaultSkin.png"));

            skin.DefaultFont = new Gwen.Font(guiRenderer, SceneManager.FontPath, 30);
            _GUIComponents   = new GUIComponentContainer(guiRenderer, skin);

            Loaded = true;
        }
Пример #14
0
        private void Open(string path)
        {
            Engine platform;
            Game   game;

            if (!SelectPlatform(PlatformDetection.DetectPlaform(path), out platform, out game))
            {
                return;
            }

            GetAsyncProgress().QueueTask(progress => {
                progress.NewTask("Loading content from " + platform.Name, 3);
                PlatformData data = platform.Create(path, game, progress);
                progress.Progress();
                ImportMap map = new ImportMap(data.Game);
                map.AddSongs(data, progress);
                progress.Progress();
                data.Mutex.WaitOne();
                progress.NewTask(data.Songs.Count);
                foreach (FormatData song in data.Songs)
                {
                    map.Populate(song.Song);
                    progress.Progress();
                }
                data.Mutex.ReleaseMutex();
                progress.EndTask();
                progress.Progress();

                if (data.Game == Game.LegoRockBand)
                {
                    progress.NewTask("Loading Rock Band 1 content from Lego Rock Band");
                    Exports.ImportRB1Lipsync(data);
                    progress.Progress();
                    progress.EndTask();
                }

                SongUpdateMutex.WaitOne();
                Platforms.Add(data);
                SongUpdateMutex.ReleaseMutex();

                UpdateSongList();
                UpdatePlatformList();
                progress.EndTask();
            });
        }
Пример #15
0
        internal void StartSubnautica(string subnauticaPath)
        {
            string           subnauticaExe = Path.Combine(subnauticaPath, "Subnautica.exe");
            ProcessStartInfo startInfo     = new ProcessStartInfo();

            startInfo.WorkingDirectory = subnauticaPath;
            startInfo.FileName         = subnauticaExe;

            if (PlatformDetection.IsEpic(subnauticaPath))
            {
                startInfo.Arguments = "-EpicPortal";
            }
            else if (PlatformDetection.IsSteam(subnauticaPath))
            {
                startInfo.FileName = "steam://run/264710";
            }

            gameProcess = Process.Start(startInfo);
        }
Пример #16
0
        public void DumpRuntimeInformationToConsole()
        {
            if (s_dumpedRuntimeInfo || !PlatformDetection.IsInHelix)
            {
                return;
            }

            s_dumpedRuntimeInfo = true;

            // Not really a test, but useful to dump a variety of information to the test log to help
            // debug environmental issues, in particular in CI

            string dvs = PlatformDetection.GetDistroVersionString();
            string osd = RuntimeInformation.OSDescription.Trim();
            string osv = Environment.OSVersion.ToString();
            string osa = RuntimeInformation.OSArchitecture.ToString();
            string rid = RuntimeInformation.RuntimeIdentifier;

            Console.WriteLine($"### OS: Distro={dvs} Description={osd} Version={osv} Arch={osa} Rid={rid}");

            string lcr = PlatformDetection.LibcRelease;
            string lcv = PlatformDetection.LibcVersion;

            Console.WriteLine($"### LIBC: Release={lcr} Version={lcv}");

            Console.WriteLine($"### FRAMEWORK: Version={Environment.Version} Description={RuntimeInformation.FrameworkDescription.Trim()}");

            string binariesLocation       = Path.GetDirectoryName(typeof(object).Assembly.Location);
            string binariesLocationFormat = string.IsNullOrEmpty(binariesLocation) ? "Unknown" : new DriveInfo(binariesLocation).DriveFormat;

            Console.WriteLine($"### BINARIES: {binariesLocation} (drive format {binariesLocationFormat})");

            string tempPathLocation       = Path.GetTempPath();
            string tempPathLocationFormat = string.IsNullOrEmpty(binariesLocation) ? "Unknown" : new DriveInfo(tempPathLocation).DriveFormat;

            Console.WriteLine($"### TEMP PATH: {tempPathLocation} (drive format {tempPathLocationFormat})");

            Console.WriteLine($"### CURRENT DIRECTORY: {Environment.CurrentDirectory}");

            Console.WriteLine($"### CGROUPS VERSION: {Interop.cgroups.s_cgroupVersion}");
            string cgroupsLocation = Interop.cgroups.s_cgroupMemoryLimitPath;

            if (cgroupsLocation != null)
            {
                Console.WriteLine($"### CGROUPS MEMORY: {cgroupsLocation}");
            }

            Console.WriteLine($"### ENVIRONMENT VARIABLES");
            foreach (DictionaryEntry envvar in Environment.GetEnvironmentVariables())
            {
                Console.WriteLine($"###\t{envvar.Key}: {envvar.Value}");
            }

            using (Process p = Process.GetCurrentProcess())
            {
                var sb = new StringBuilder();
                sb.AppendLine("### PROCESS INFORMATION:");
                sb.AppendLine($"###\tArchitecture: {RuntimeInformation.ProcessArchitecture}");
                foreach (string prop in new string[]
                {
                    nameof(p.BasePriority),
                    nameof(p.HandleCount),
                    nameof(p.Id),
                    nameof(p.MachineName),
                    nameof(p.MainModule),
                    nameof(p.MainWindowHandle),
                    nameof(p.MainWindowTitle),
                    nameof(p.MaxWorkingSet),
                    nameof(p.MinWorkingSet),
                    nameof(p.NonpagedSystemMemorySize64),
                    nameof(p.PagedMemorySize64),
                    nameof(p.PagedSystemMemorySize64),
                    nameof(p.PeakPagedMemorySize64),
                    nameof(p.PeakVirtualMemorySize64),
                    nameof(p.PeakWorkingSet64),
                    nameof(p.PriorityBoostEnabled),
                    nameof(p.PriorityClass),
                    nameof(p.PrivateMemorySize64),
                    nameof(p.PrivilegedProcessorTime),
                    nameof(p.ProcessName),
                    nameof(p.ProcessorAffinity),
                    nameof(p.Responding),
                    nameof(p.SessionId),
                    nameof(p.StartTime),
                    nameof(p.TotalProcessorTime),
                    nameof(p.UserProcessorTime),
                    nameof(p.VirtualMemorySize64),
                    nameof(p.WorkingSet64),
                })
                {
                    sb.Append($"###\t{prop}: ");
                    try
                    {
                        sb.Append(p.GetType().GetProperty(prop).GetValue(p));
                    }
                    catch (Exception e)
                    {
                        sb.Append($"(Exception: {e.Message})");
                    }
                    sb.AppendLine();
                }
                Console.WriteLine(sb.ToString());
            }

            if (osd.Contains("Linux"))
            {
                // Dump several procfs files and /etc/os-release
                foreach (string path in new string[] {
                    "/proc/self/mountinfo",
                    "/proc/self/cgroup",
                    "/proc/self/limits",
                    "/etc/os-release",
                    "/etc/sysctl.conf",
                    "/proc/meminfo",
                    "/proc/sys/vm/oom_kill_allocating_task",
                    "/proc/sys/kernel/core_pattern",
                    "/proc/sys/kernel/core_uses_pid",
                    "/proc/sys/kernel/coredump_filter"
                })
                {
                    Console.WriteLine($"### CONTENTS OF \"{path}\":");
                    try
                    {
                        using (Process cat = new Process())
                        {
                            cat.StartInfo.FileName  = "cat";
                            cat.StartInfo.Arguments = path;
                            cat.StartInfo.RedirectStandardOutput = true;
                            cat.OutputDataReceived += (sender, e) =>
                            {
                                string trimmed = e.Data?.Trim();
                                if (!string.IsNullOrEmpty(trimmed) && trimmed[0] != '#') // skip comments in files
                                {
                                    Console.WriteLine(e.Data);
                                }
                            };
                            cat.Start();
                            cat.BeginOutputReadLine();
                            cat.WaitForExit();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"###\t(Exception: {e.Message})");
                    }
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Отображение уведомления
        /// </summary>
        /// <param name="aText">Текст для отображения</param>
        /// <param name="aSilent">Иконка</param>
        /// <param name="aStraightToTray">Silent режим</param>
        static void OnNotificationShow(string aText, System.Drawing.Icon aIcon, bool aSilent)
        {
            DebugHelper.WriteLogEntry("OnNotificationShow " + aText + aSilent);

            _notification.Caption        = Properties.Resources.Program_OnNtfnShow_Caption;
            _notification.Text           = aText;
            _notification.Icon           = aIcon;
            _notification.StraightToTray = aSilent;
            _notification.Silent         = true;
            _notification.DisplayOn      = !aSilent;
            _notification.Visible        = true;

            //Get info from the registry about the notification type and the options
            DebugHelper.WriteLogEntry("OnNotificationShow NotificationClass.Get");
            var nc = NotificationClass.Get(NotificationCLSID);

            //Application.DoEvents();

            DebugHelper.WriteLogEntry("OnNotificationShow Vibrate");
            if (!aSilent)
            {
                #region vibrate if need
                if ((nc.Options & NotificationOptions.Vibrate) > 0)
                {
                    try
                    {
                        VibrateLED.Vibrate();
                    }
                    catch (Exception ex)
                    {
                        DebugHelper.WriteLogEntry(ex, "Vibrate error");
                    }
                }
                #endregion

                DebugHelper.WriteLogEntry("OnNotificationShow Sound");

                #region play music if need
                try
                {
                    if ((nc.Options & NotificationOptions.Sound) > 0)
                    {
                        if (!String.IsNullOrEmpty(nc.WaveFile))
                        {
                            if (PlatformDetection.IsWM5())
                            {
                                WCE_PlaySound(nc.WaveFile, IntPtr.Zero, (int)(Flags.SND_FILENAME | Flags.SND_ASYNC));
                            }
                            else
                            {
                                string ext = null;
                                try
                                {
                                    ext = Path.GetExtension(nc.WaveFile);
                                }
                                catch (ArgumentException)
                                {
                                }

                                int esuccess = 0;
                                switch (ext)
                                {
                                //case ".wav":
                                //    esuccess = WCE_PlaySound(nc.WaveFile, IntPtr.Zero, (int)(Flags.SND_FILENAME | Flags.SND_ASYNC));
                                //    break;
                                case ".wav":
                                case ".mp3":
                                case ".wma":
                                case ".mid":
                                case ".midi":
                                    //Application.DoEvents();
                                    using (SoundPlayer player = new SoundPlayer(nc.WaveFile))
                                    {
                                        player.Play();
                                        esuccess = 1;
                                    }
                                    break;
                                }

                                if (esuccess == 0)
                                {
                                    //WCE_PlaySound("Default", IntPtr.Zero, (int)(Flags.SND_ALIAS_ID | Flags.SND_ASYNC));
                                    WCE_PlaySound("\\Windows\\asterisk.wav", IntPtr.Zero, (int)(Flags.SND_FILENAME | Flags.SND_ASYNC));
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    DebugHelper.WriteLogEntry(ex, "Play sound error");
                }

                #endregion
            }
            DebugHelper.WriteLogEntry("OnNotificationShow End");
        }
        [PlatformSpecific(~TestPlatforms.Browser)] // throws PNSE when binariesLocation is not an empty string.
        public void DumpRuntimeInformationToConsole()
        {
            // Not really a test, but useful to dump a variety of information to the test log to help
            // debug environmental issues, in particular in CI

            string dvs = PlatformDetection.GetDistroVersionString();
            string osd = RuntimeInformation.OSDescription.Trim();
            string osv = Environment.OSVersion.ToString();
            string osa = RuntimeInformation.OSArchitecture.ToString();
            string rid = RuntimeInformation.RuntimeIdentifier;

            Console.WriteLine($"### OS: Distro={dvs} Description={osd} Version={osv} Arch={osa} Rid={rid}");

            string lcr = PlatformDetection.LibcRelease;
            string lcv = PlatformDetection.LibcVersion;

            Console.WriteLine($"### LIBC: Release={lcr} Version={lcv}");

            Console.WriteLine($"### FRAMEWORK: Version={Environment.Version} Description={RuntimeInformation.FrameworkDescription.Trim()}");

            string binariesLocation       = Path.GetDirectoryName(typeof(object).Assembly.Location);
            string binariesLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(binariesLocation).DriveFormat;

            Console.WriteLine($"### BINARIES: {binariesLocation} (drive format {binariesLocationFormat})");

            string tempPathLocation       = Path.GetTempPath();
            string tempPathLocationFormat = PlatformDetection.IsInAppContainer ? "Unknown" : new DriveInfo(tempPathLocation).DriveFormat;

            Console.WriteLine($"### TEMP PATH: {tempPathLocation} (drive format {tempPathLocationFormat})");

            Console.WriteLine($"### CURRENT DIRECTORY: {Environment.CurrentDirectory}");

            Console.WriteLine($"### CGROUPS VERSION: {Interop.cgroups.s_cgroupVersion}");
            string cgroupsLocation = Interop.cgroups.s_cgroupMemoryLimitPath;

            if (cgroupsLocation != null)
            {
                Console.WriteLine($"### CGROUPS MEMORY: {cgroupsLocation}");
            }

            Console.WriteLine($"### ENVIRONMENT VARIABLES");
            foreach (DictionaryEntry envvar in Environment.GetEnvironmentVariables())
            {
                Console.WriteLine($"###\t{envvar.Key}: {envvar.Value}");
            }

            using (Process p = Process.GetCurrentProcess())
            {
                var sb = new StringBuilder();
                sb.AppendLine("### PROCESS INFORMATION:");
                sb.AppendFormat($"###\tArchitecture: {RuntimeInformation.ProcessArchitecture.ToString()}").AppendLine();
                foreach (string prop in new string[]
                {
                        #pragma warning disable 0618 // some of these Int32-returning properties are marked obsolete
                    nameof(p.BasePriority),
                    nameof(p.HandleCount),
                    nameof(p.Id),
                    nameof(p.MachineName),
                    nameof(p.MainModule),
                    nameof(p.MainWindowHandle),
                    nameof(p.MainWindowTitle),
                    nameof(p.MaxWorkingSet),
                    nameof(p.MinWorkingSet),
                    nameof(p.NonpagedSystemMemorySize),
                    nameof(p.NonpagedSystemMemorySize64),
                    nameof(p.PagedMemorySize),
                    nameof(p.PagedMemorySize64),
                    nameof(p.PagedSystemMemorySize),
                    nameof(p.PagedSystemMemorySize64),
                    nameof(p.PeakPagedMemorySize),
                    nameof(p.PeakPagedMemorySize64),
                    nameof(p.PeakVirtualMemorySize),
                    nameof(p.PeakVirtualMemorySize64),
                    nameof(p.PeakWorkingSet),
                    nameof(p.PeakWorkingSet64),
                    nameof(p.PriorityBoostEnabled),
                    nameof(p.PriorityClass),
                    nameof(p.PrivateMemorySize),
                    nameof(p.PrivateMemorySize64),
                    nameof(p.PrivilegedProcessorTime),
                    nameof(p.ProcessName),
                    nameof(p.ProcessorAffinity),
                    nameof(p.Responding),
                    nameof(p.SessionId),
                    nameof(p.StartTime),
                    nameof(p.TotalProcessorTime),
                    nameof(p.UserProcessorTime),
                    nameof(p.VirtualMemorySize),
                    nameof(p.VirtualMemorySize64),
                    nameof(p.WorkingSet),
                    nameof(p.WorkingSet64),
                        #pragma warning restore 0618
                })
                {
                    sb.Append($"###\t{prop}: ");
                    try
                    {
                        sb.Append(p.GetType().GetProperty(prop).GetValue(p));
                    }
                    catch (Exception e)
                    {
                        sb.Append($"(Exception: {e.Message})");
                    }
                    sb.AppendLine();
                }
                Console.WriteLine(sb.ToString());
            }

            if (osd.Contains("Linux"))
            {
                // Dump several procfs files and /etc/os-release
                foreach (string path in new string[] { "/proc/self/mountinfo", "/proc/self/cgroup", "/proc/self/limits", "/etc/os-release" })
                {
                    Console.WriteLine($"### CONTENTS OF \"{path}\":");
                    try
                    {
                        using (Process cat = Process.Start("cat", path))
                        {
                            cat.WaitForExit();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"###\t(Exception: {e.Message})");
                    }
                }
            }
        }
Пример #19
0
        public static void Main(string[] args)
        {
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, ce, ch, p) => true;

            // Load services
            var initialSettingsProvider = new PropertySettings();

            initialSettingsProvider.Load();

            // Default settings provider is the Windows application settings implementation
            ServiceLocator.Settings = initialSettingsProvider;

            // DEBUG SETTINGS - Force first run
            //ServiceLocator.Settings["Analytics"] = false;
            //ServiceLocator.Settings["FirstRun"] = true;

            string PiwikURL  = AESEncryption.Decrypt((string)ServiceLocator.Settings["Piwik"]);
            string SentryURL = AESEncryption.Decrypt((string)ServiceLocator.Settings["Sentry"]);

#if DEBUG
            string sentryEnvironment = "debug";
#else
            string sentryEnvironment = "release";
#endif
            Version version     = Assembly.GetExecutingAssembly().GetName().Version;
            string  gameVersion = $"{version.Major}.{version.Minor}.{version.Build}";
            var     userID      = (string)ServiceLocator.Settings["UserID"];
            // Generate or load user ID for Piwik
            Guid userGUID;
            if (!Guid.TryParse(userID, out userGUID))
            {
                userGUID = Guid.NewGuid();
            }

            // Save user GUID
            ServiceLocator.Settings["UserID"] = userGUID.ToString();

            Platform runningPlatform = PlatformDetection.RunningPlatform();
            string   platformVersion = PlatformDetection.GetVersionName();

            // Load Sentry service
            if ((bool)ServiceLocator.Settings["Analytics"] || (bool)ServiceLocator.Settings["FirstRun"])
            {
                ServiceLocator.ErrorReporting = new SentryErrorReporting(
                    SentryURL,
                    sentryEnvironment,
                    gameVersion,
                    userGUID.ToString(),
                    runningPlatform,
                    platformVersion);
            }

            int PiwikAppID = 3;

            // Load Piwik service
            if ((bool)ServiceLocator.Settings["Analytics"] || (bool)ServiceLocator.Settings["FirstRun"])
            {
                ServiceLocator.Analytics = new PiwikAnalytics(
                    PiwikAppID,
                    PiwikURL,
                    runningPlatform,
                    platformVersion,
                    DisplayDevice.Default.Width,
                    DisplayDevice.Default.Height,
                    gameVersion,
                    userGUID.ToString(),
                    "http://turntninja");
            }

            ServiceLocator.Directories = new DirectoryHandler();

            var directoryHandler = ServiceLocator.Directories;

            //set application path
            directoryHandler.AddPath("Application", AppDomain.CurrentDomain.BaseDirectory);
            //set base path
            if (Directory.Exists(directoryHandler.Locate("Application", "Content")))
            {
                directoryHandler.AddPath("Base", directoryHandler["Application"].FullName);
            }
            else if (Directory.Exists(directoryHandler.Locate("Application", @"../../src/TurntNinja/Content")))
            {
                directoryHandler.AddPath("Base", directoryHandler.Locate("Application", @"../../src/TurntNinja"));
            }
            else
            {
                throw new Exception("Couldn't find resource folder location");
            }

            directoryHandler.AddPath("AppData",
                                     Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), (string)ServiceLocator.Settings["AppDataFolderName"]));

            directoryHandler.AddPath("Resources", Path.Combine(directoryHandler["Base"].FullName, "Content"));
            directoryHandler.AddPath("Fonts", Path.Combine(directoryHandler["Resources"].FullName, @"Fonts"));
            directoryHandler.AddPath("Shaders", Path.Combine(directoryHandler["Resources"].FullName, @"Shaders"));
            directoryHandler.AddPath("Images", Path.Combine(directoryHandler["Resources"].FullName, @"Images"));
            directoryHandler.AddPath("Crash", Path.Combine(directoryHandler["AppData"].FullName, "CrashLogs"));
            directoryHandler.AddPath("BundledSongs", Path.Combine(directoryHandler["Resources"].FullName, @"Songs"));
            directoryHandler.AddPath("ProcessedSongs", Path.Combine(directoryHandler["AppData"].FullName, @"Processed Songs"));

            if (!Directory.Exists(directoryHandler["AppData"].FullName))
            {
                Directory.CreateDirectory(directoryHandler["AppData"].FullName);
            }

            if (!Debugger.IsAttached)
            {
                //initialise crash reporter
                _crashReporter = new CrashReporter(directoryHandler["Crash"].FullName);

                //attach exception handlers
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }

            // If we are not running on a windows platform, use the JsonSettings backend
            if (PlatformDetection.RunningPlatform() != Platform.Windows)
            {
                ServiceLocator.Settings = new JsonSettings(initialSettingsProvider, directoryHandler.Locate("AppData", "settings.json"));
                ServiceLocator.Settings.Load();
            }

            //init logging
            Splat.DependencyResolverMixins.RegisterConstant(Splat.Locator.CurrentMutable,
                                                            new SimpleLogger(directoryHandler["Application"].FullName, Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location) + ".log")
            {
                Level = Splat.LogLevel.Debug
            },
                                                            typeof(Splat.ILogger));

            int          rX           = (int)ServiceLocator.Settings["ResolutionX"];
            int          rY           = (int)ServiceLocator.Settings["ResolutionY"];
            int          FSAASamples  = (int)ServiceLocator.Settings["AntiAliasingSamples"];
            GraphicsMode graphicsMode = new GraphicsMode(32, 32, 8, FSAASamples, GraphicsMode.Default.AccumulatorFormat, 3);

            // Choose right OpenGL version for mac
            int major = 3;
            int minor = 0;
            if (PlatformDetection.RunningPlatform() == Platform.MacOSX)
            {
                major = 4;
            }

            if ((bool)ServiceLocator.Settings["Analytics"])
            {
                ServiceLocator.Analytics.TrackApplicationStartup();
            }

            using (GameController game = new GameController(ServiceLocator.Settings, rX, rY, graphicsMode, "Turnt Ninja",
                                                            major, minor, directoryHandler))
            {
                game.Title = "Turnt Ninja";
                // Only set icon if we're on Windows or Linux
                if (runningPlatform != Platform.MacOSX)
                {
                    game.Icon = new System.Drawing.Icon(directoryHandler.Locate("Images", "icon.ico"));
                }
                game.Run();
            }
        }
Пример #20
0
        public override void Load()
        {
            _fontBounds = new System.Drawing.SizeF(WindowWidth * 0.75f, -1f);
            _updateFont = SceneManager.GameFontLibrary.GetFirstOrDefault(GameFontType.Heading);
            _cancellationTokenSource = new CancellationTokenSource();
            _statusString            = "Checking for updates...";

            if (_isSquirrel)
            {
                _statusString = "Checking for updates...";
                Task.Run(() =>
                {
                    //Check if local package host exists first - if so then update from that
                    string packageHost = (Directory.Exists(LOCALPACKAGEHOST)) ? LOCALPACKAGEHOST : GITHUBPACKAGEHOST;
                    using (var upmgr = Directory.Exists(LOCALPACKAGEHOST) ? new UpdateManager(packageHost) : UpdateManager.GitHubUpdateManager(packageHost).Result)
                    {
                        UpdateInfo updateInfo = null;
                        try
                        {
                            updateInfo = upmgr.CheckForUpdate().Result;
                        }
                        catch (Exception ex)
                        {
                            _ex = ex;
                        }
                        var needToUpdate = (updateInfo.ReleasesToApply.Count > 0);
                        Dictionary <ReleaseEntry, string> releaseNotes = null;

                        //if we need to update
                        if (needToUpdate)
                        {
                            releaseNotes = FetchReleaseNotes(updateInfo.ReleasesToApply, packageHost);
                        }

                        lock (_lock)
                        {
                            _updateManager = upmgr;
                            _needToUpdate  = needToUpdate;
                            _updateInfo    = updateInfo;
                            _releaseNotes  = releaseNotes;

                            try
                            {
                                if (needToUpdate)
                                {
                                    //_statusString = "Update Available";
                                    var releaseNoteJoined = string.Join("\n\n", releaseNotes.Select(kvp => string.Format("{0}\n{1}", kvp.Key.Version.ToString(), kvp.Value)).Reverse());
                                    _statusString         = string.Format("New version {0} found\nPress Enter to update or Escape to cancel\n\n{1}",
                                                                          updateInfo.ReleasesToApply.Last().Version, releaseNoteJoined);
                                }
                                else
                                {
                                    _continue = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                _ex = ex;
                            }
                        }
                    }
                }, _cancellationTokenSource.Token);
            }
            else
            {
                Task.Run(() =>
                {
                    var informationalVersionAttribute = System.Reflection.Assembly.GetExecutingAssembly().CustomAttributes.FirstOrDefault(cad => cad.AttributeType == typeof(System.Reflection.AssemblyInformationalVersionAttribute));
                    string channelBase = "";
                    switch (PlatformDetection.RunningPlatform())
                    {
                    case Platform.Windows:
                        channelBase = "win";
                        break;

                    case Platform.Linux:
                        channelBase = "linux";
                        break;

                    case Platform.MacOSX:
                        channelBase = "mac";
                        break;
                    }
                    string tag         = ((string)informationalVersionAttribute.ConstructorArguments.First().Value).Split(' ')[0].Split(':')[1];
                    string channelName = tag.Contains(ALPHATAGSUFFIX) ? channelBase + ITCHALPHACHANNEL : channelBase;

                    UriBuilder ub = new UriBuilder(ITCHRELEASEAPI);
                    ub.Query      = $"target={ITCHTARGET}&channel_name={channelName}";

                    HttpClient hc     = new HttpClient();
                    var resp          = hc.GetAsync(ub.Uri).Result;
                    var content       = Newtonsoft.Json.Linq.JObject.Parse(resp.Content.ReadAsStringAsync().Result);
                    var versionString = content.Value <string>("latest").Split('-');

                    var ver                 = Version.Parse(versionString[0]);
                    var currentVer          = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                    var newVersionAvailable = ver > currentVer;

                    // Check tag if we don't need to update based purely on version string
                    if (!newVersionAvailable)
                    {
                        var ctp = tag.Split('-');
                        if (ctp.Length > 1 || (bool)ServiceLocator.Settings["GetAlphaReleases"])
                        {
                            if (versionString.Length > 1)
                            {
                                var currentTag      = ctp[1];
                                var serverTag       = versionString[1];
                                newVersionAvailable = serverTag.CompareTo(currentTag) == 1;
                            }
                            else
                            {
                                newVersionAvailable = true;
                            }
                        }
                    }

                    if (newVersionAvailable)
                    {
                        _statusString = $"Version {string.Join("-", versionString)} is available.\nYou can update through the Itch.io app, or download the latest release from {@"https://opcon.itch.io/turnt-ninja"}.";
                    }
                    else
                    {
                        _statusString = "You have the latest version!";
                    }
                }, _cancellationTokenSource.Token);
            }

            Loaded = true;
        }
Пример #21
0
        /// <summary>
        /// Setup OpenGL and load resources here.
        /// </summary>
        /// <param name="e">Not used.</param>
        protected override void OnLoad(EventArgs e)
        {
            //fontPath = Path.Combine(_directoryHandler["Fonts"].FullName, "./Chamgagne Limousines/Champagne & Limousines Italic.ttf");
            //fontPath = Path.Combine(_directoryHandler["Fonts"].FullName, "./Ostrich Sans/OstrichSans-Black.otf");
            var menuFontPath      = Path.Combine(_directoryHandler["Fonts"].FullName, "./Oswald-Bold.ttf");
            var versionFontPath   = _directoryHandler.Locate("Fonts", "./Oswald-Regular.ttf");
            var bodyFontPath      = _directoryHandler.Locate("Fonts", "./Open Sans/OpenSans-Light.ttf");
            var largeBodyFontPath = _directoryHandler.Locate("Fonts", "./Open Sans/OpenSans-Regular.ttf");
            //var selectedFontPath = _directoryHandler.Locate("Fonts", "./Open Sans/OpenSans-Bold.ttf");
            var selectedFontPath = Path.Combine(_directoryHandler["Fonts"].FullName, "./Oswald-Bold.ttf");

            Console.WriteLine("Initializing");

            Console.WriteLine("Creating game camera");
            var gameCamera = new Camera(prefWidth, prefHeight, Width, Height, Mouse);

            gameCamera.CameraBounds = gameCamera.OriginalBounds = new Polygon(new Vector2(-prefWidth * 10, -prefHeight * 10), (int)prefWidth * 20, (int)(prefHeight * 20));

            // Register OSX codecs if running on OSX
            if (PlatformDetection.RunningPlatform() == Platform.MacOSX)
            {
                Console.WriteLine("Registering OSX Audio codecs");
                CSCore.OSXCoreAudio.OSXAudio.RegisterCodecs();
            }

            Console.WriteLine("Creating font library");
            var fontLibrary = new FontLibrary();

            Console.WriteLine("Loading fonts");
            // Default font
            var gameFont = new QFont(bodyFontPath, 18, new QFontBuilderConfiguration()
            {
                SuperSampleLevels = 2
            });

            fontLibrary.AddFont(new GameFont(gameFont, GameFontType.Default, new Vector2(Width, Height)));

            // Menu font
            fontLibrary.AddFont(
                new GameFont(new QFont(menuFontPath, 50, new QFontBuilderConfiguration(true)),
                             GameFontType.Menu,
                             new Vector2(Width, Height)));

            // Menu World font
            fontLibrary.AddFont(
                new GameFont(new QFont(menuFontPath, 70, new QFontBuilderConfiguration(true)
            {
                SuperSampleLevels = 2, PageMaxTextureSize = 8192, Characters = CharacterSet.BasicSet
            }),
                             "menuworld",
                             new Vector2(Width, Height)));

            // Heading font
            fontLibrary.AddFont(
                new GameFont(new QFont(menuFontPath, 20, new QFontBuilderConfiguration(true)
            {
                SuperSampleLevels = 2
            }),
                             GameFontType.Heading,
                             new Vector2(Width, Height)));

            // Large body font
            fontLibrary.AddFont(
                new GameFont(new QFont(largeBodyFontPath, 25, new QFontBuilderConfiguration()
            {
                SuperSampleLevels = 1
            }),
                             "largebody",
                             new Vector2(Width, Height)));

            // Version text font
            fontLibrary.AddFont(
                new GameFont(new QFont(versionFontPath, 15, new QFontBuilderConfiguration()),
                             "versiontext",
                             new Vector2(Width, Height)));

            // Selected text font (song browser
            fontLibrary.AddFont(
                new GameFont(new QFont(selectedFontPath, 34, new QFontBuilderConfiguration()
            {
                SuperSampleLevels = 2, Characters = CharacterSet.General
            }),
                             "selected",
                             new Vector2(Width, Height)));

            Console.WriteLine("Creating scene manager");
            _gameSceneManager = new SceneManager(this, gameCamera, fontLibrary, bodyFontPath, _directoryHandler, _gameSettings, DebugMode);
            _gameSceneManager.AddScene(new MenuScene(), null);

            Console.WriteLine("Checking for first run scene");
            if ((bool)ServiceLocator.Settings["FirstRun"])
            {
                _gameSceneManager.AddScene(new FirstRunScene(), null);
            }

            Console.WriteLine("Setting up input system callbacks");
            Keyboard.KeyDown   += (o, args) => InputSystem.KeyDown(args);
            Keyboard.KeyUp     += (o, args) => InputSystem.KeyUp(args);
            Mouse.ButtonDown   += (o, args) => InputSystem.MouseDown(args);
            Mouse.ButtonUp     += (o, args) => InputSystem.MouseUp(args);
            Mouse.WheelChanged += (o, args) => InputSystem.MouseWheelChanged(args);
            Mouse.Move         += (o, args) => InputSystem.MouseMoved(args);

            Console.WriteLine("Setting clear color");
            GL.ClearColor(Color.Black);

            Console.WriteLine("Creating stopwatch");
            _watch = new Stopwatch();

            Console.WriteLine("Finished OnLoad");
        }