Inheritance: MonoBehaviour
Exemplo n.º 1
0
 private static void SetDebugBuild(Version version)
 {
     // debug builds, to keep track of minor/revisions, etc..
     // Adds also the revision
     VersionString = version.ToString();
     aboutText     = String.Format("{0} - {1}", TitleVersion, BuildDate.ToShortDateString());
 }
Exemplo n.º 2
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Version.Length != 0)
            {
                hash ^= Version.GetHashCode();
            }
            if (BuildDate.Length != 0)
            {
                hash ^= BuildDate.GetHashCode();
            }
            if (Commit.Length != 0)
            {
                hash ^= Commit.GetHashCode();
            }
            if (OsArch.Length != 0)
            {
                hash ^= OsArch.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemplo n.º 3
0
        private void UpdateAppStatuses()
        {
            while (Get() != null)
            {
                if (Visible)
                {
                    if (Core.UpdateAvailable)
                    {
                        BuildDate.Invoke((MethodInvoker) delegate { BuildDate.Text = Core.Version + " (Update available, click here!)"; });
                    }

                    foreach (var entry in m_AppRowDictionary)
                    {
                        App             app      = entry.Key;
                        DataGridViewRow row      = entry.Value.row;
                        AppRowTemplate  template = entry.Value.template;

                        // We wrap this in a try just because it's not exactly thread safe to the app's processes.
                        // If an exception is thrown here we can pretty safely assume the process ended one way or another - we'll just use what was cached.
                        try { app.RefreshStatuses(ref template); } catch (Exception) { }

                        row.Cells[1].Value = template.Title;
                        row.Cells[2].Value = template.Crashes;
                        row.Cells[3].Value = template.Uptime;
                        row.Cells[4].Value = template.CPU;
                        row.Cells[5].Value = template.Memory;
                    }
                }

                Thread.Sleep(750);
            }
        }
Exemplo n.º 4
0
        public double GetFxRate(DateTime settlementDate, Currency domesticCcy, Currency foreignCcy)
        { //domestic-per-foreign
            if (foreignCcy == domesticCcy)
            {
                return(1.0);
            }

            double spot;

            if (domesticCcy == FxMatrix.BaseCurrency)
            {
                spot = FxMatrix.GetSpotRate(foreignCcy);
            }
            else if (foreignCcy == FxMatrix.BaseCurrency)
            {
                spot = 1.0 / FxMatrix.GetSpotRate(domesticCcy);
            }
            else
            {
                var forToBase = GetFxRate(settlementDate, FxMatrix.BaseCurrency, foreignCcy);
                var domToBase = GetFxRate(settlementDate, FxMatrix.BaseCurrency, domesticCcy);
                return(forToBase / domToBase);
            }
            var fxPair   = FxMatrix.GetFxPair(domesticCcy, foreignCcy);
            var spotDate = BuildDate.AddPeriod(RollType.F, fxPair.PrimaryCalendar, fxPair.SpotLag);
            var dfDom    = GetDf(domesticCcy, spotDate, settlementDate);
            var dfFor    = GetDf(foreignCcy, spotDate, settlementDate);

            return(spot * dfDom / dfFor);
        }
Exemplo n.º 5
0
 private static void SetDebugBuild(Version version)
 {
     // debug builds, to keep track of minor/revisions, etc..
     // Adds also the revision
     VersionString = version.ToString();
     aboutText     = $"{TitleVersion} - {BuildDate.ToShortDateString()}";
 }
Exemplo n.º 6
0
        /// <summary>
        /// Gets a collection of assembly attributes exposed by the assembly.
        /// </summary>
        /// <returns>A System.Specialized.KeyValueCollection of assembly attributes.</returns>
        public NameValueCollection GetAttributes()
        {
            NameValueCollection assemblyAttributes = new NameValueCollection();

            //Add some values that are not in AssemblyInfo.
            assemblyAttributes.Add("Full Name", FullName);
            assemblyAttributes.Add("Name", Name);
            assemblyAttributes.Add("Version", Version.ToString());
            assemblyAttributes.Add("Image Runtime Version", ImageRuntimeVersion);
            assemblyAttributes.Add("Build Date", BuildDate.ToString());
            assemblyAttributes.Add("Location", Location);
            assemblyAttributes.Add("Code Base", CodeBase);
            assemblyAttributes.Add("GAC Loaded", GACLoaded.ToString());

            //Add all attributes available from AssemblyInfo.
            assemblyAttributes.Add("Title", Title);
            assemblyAttributes.Add("Description", Description);
            assemblyAttributes.Add("Company", Company);
            assemblyAttributes.Add("Product", Product);
            assemblyAttributes.Add("Copyright", Copyright);
            assemblyAttributes.Add("Trademark", Trademark);
            assemblyAttributes.Add("Configuration", Configuration);
            assemblyAttributes.Add("Delay Sign", DelaySign.ToString());
            assemblyAttributes.Add("Informational Version", InformationalVersion);
            assemblyAttributes.Add("Key File", KeyFile);
            assemblyAttributes.Add("Culture Name", CultureName);
            assemblyAttributes.Add("Satellite Contract Version", SatelliteContractVersion);
            assemblyAttributes.Add("Com Compatible Version", ComCompatibleVersion);
            assemblyAttributes.Add("Com Visible", ComVisible.ToString());
            assemblyAttributes.Add("Guid", Guid);
            assemblyAttributes.Add("Type Lib Version", TypeLibVersion);
            assemblyAttributes.Add("CLS Compliant", CLSCompliant.ToString());

            return(assemblyAttributes);
        }
Exemplo n.º 7
0
 public override void DumpBody(XmlWriter writer)
 {
     writer.WriteElementString("product-id", ProductId.ToString());
     writer.WriteElementString("edition", Edition.ToString());
     writer.WriteElementString("major-version", MajorVersion.ToString());
     writer.WriteElementString("minor-version", MinorVersion.ToString());
     writer.WriteElementString("build-number", BuildNumber.ToString());
     writer.WriteElementString("build-date", BuildDate.ToString());
 }
Exemplo n.º 8
0
        public IPriceCurve RebaseDate(DateTime newAnchorDate)
        {
            switch (_curveType)
            {
            case PriceCurveType.Linear:
                var oldSpotDate = BuildDate.SpotDate(SpotLag, SpotCalendar, SpotCalendar);
                var newSpotDate = newAnchorDate.SpotDate(SpotLag, SpotCalendar, SpotCalendar);
                var newPillars  = _pillarDates
                                  .Where(d => d >= newAnchorDate && d != oldSpotDate)
                                  .Concat(new[] { newSpotDate })
                                  .Distinct()
                                  .OrderBy(x => x)
                                  .ToArray();
                var newPrices = newPillars.Select(x => GetPriceForDate(x)).ToArray();
                return(new PriceCurve(newAnchorDate, newPillars, newPrices, _curveType, _currencyProvider, _pillarLabels)
                {
                    CollateralSpec = CollateralSpec, Currency = Currency, AssetId = AssetId, SpotCalendar = SpotCalendar, SpotLag = SpotLag
                });

            case PriceCurveType.NYMEX:
                var newPillarsNM = _pillarDates
                                   .Where(d => d >= newAnchorDate)
                                   .Distinct()
                                   .OrderBy(x => x)
                                   .ToArray();
                var newPricesNM = newPillarsNM.Select(x => GetPriceForDate(x)).ToArray();
                return(new PriceCurve(newAnchorDate, newPillarsNM, newPricesNM, _curveType, _currencyProvider, _pillarLabels)
                {
                    CollateralSpec = CollateralSpec, Currency = Currency, AssetId = AssetId, SpotCalendar = SpotCalendar, SpotLag = SpotLag
                });

            case PriceCurveType.ICE:
                var newPillarsIC = _pillarDates
                                   .Where(d => d > newAnchorDate)
                                   .Distinct()
                                   .OrderBy(x => x)
                                   .ToArray();
                var newPricesIC = newPillarsIC.Select(x => GetPriceForDate(x.AddDays(-1))).ToArray();
                return(new PriceCurve(newAnchorDate, newPillarsIC, newPricesIC, _curveType, _currencyProvider, _pillarLabels)
                {
                    CollateralSpec = CollateralSpec, Currency = Currency, AssetId = AssetId, SpotCalendar = SpotCalendar, SpotLag = SpotLag
                });

            case PriceCurveType.Constant:
                return(new ConstantPriceCurve(_prices.First(), BuildDate, _currencyProvider));

            default:
                throw new Exception("Unknown curve type");
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Constructor for WaveBox service.  Initializes the service and sets up the graceful shutdown
        /// </summary>
        public WaveBoxService()
        {
            logger.IfInfo("Initializing WaveBoxService");
            try
            {
                // Name the service
                this.ServiceName = "WaveBox";

                // Register shutdown handlers for Unix or Windows
                this.RegisterShutdownHandler();

                // Detect operating system
                OS = ServerUtility.DetectOS();

                // Now that platform is detected, inject platform-specific classes
                InjectPlatformSpecificClasses();

                // Store version
                var assembly = Assembly.GetExecutingAssembly().GetName();
                BuildVersion = String.Format("{0}.{1}.{2}.{3}", assembly.Version.Major, assembly.Version.Minor, assembly.Version.Build, assembly.Version.Revision);

                // Build date detection
                BuildDate = ServerUtility.GetBuildDate();

                logger.IfInfo("BuildDate timestamp: " + BuildDate.ToUnixTime());

                // Get start up time
                StartTime = DateTime.UtcNow;

                // Create WaveBox's temporary folder
                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                    logger.IfInfo("Created temp folder: " + TempFolder);
                }

                // Instantiate a WaveBox object
                wavebox = new WaveBoxMain();

                // Start it!
                this.OnStart();
            }
            // Handle any uncaught exceptions
            catch (Exception e)
            {
                ServerUtility.ReportCrash(e, false);
            }
        }
Exemplo n.º 10
0
        public double GetCompositeVolForStrikeAndDate(string assetId, DateTime expiry, double strike, Currency ccy)
        {
            var curve = GetPriceCurve(assetId);

            var fxId   = $"{curve.Currency.Ccy}/{ccy.Ccy}";
            var fxPair = FundingModel.FxMatrix.GetFxPair(fxId);

            var fxSpotDate = fxPair.SpotDate(expiry);
            var fxFwd      = FundingModel.GetFxRate(fxSpotDate, fxId);
            var fxVol      = FundingModel.GetVolSurface(fxId).GetVolForDeltaStrike(0.5, expiry, fxFwd);
            var tExpC      = BuildDate.CalculateYearFraction(expiry, DayCountBasis.Act365F);
            var correl     = CorrelationMatrix.GetCorrelation(fxId, assetId, tExpC);
            var sigma      = GetVolForStrikeAndDate(assetId, expiry, strike / fxFwd);

            sigma = System.Math.Sqrt(sigma * sigma + fxVol * fxVol + 2 * correl * fxVol * sigma);
            return(sigma);
        }
Exemplo n.º 11
0
        private void UpdateAppStatuses()
        {
            while (Get() != null)
            {
                if (Visible)
                {
                    if (Core.UpdateAvailable)
                    {
                        BuildDate.Invoke((MethodInvoker) delegate { BuildDate.Text = Core.Version + " (Update available, click here!)"; });
                    }

                    System.Management.ManagementObjectCollection wmiRes = null;

                    try
                    {
                        System.Management.ManagementObjectSearcher wmiSearcher =
                            new System.Management.ManagementObjectSearcher("root\\CIMV2",
                                                                           "SELECT * FROM Win32_PerfFormattedData_PerfProc_Process");
                        wmiRes = wmiSearcher.Get();
                    } catch (Exception e)
                    {
                        Debug.Error("Couldn't query WMI: " + e.Message);
                    }

                    foreach (var entry in m_AppRowDictionary)
                    {
                        App             app      = entry.Key;
                        DataGridViewRow row      = entry.Value.row;
                        AppRowTemplate  template = entry.Value.template;

                        // We wrap this in a try just because it's not exactly thread safe to the app's processes.
                        // If an exception is thrown here we can pretty safely assume the process ended one way or another - we'll just use what was cached.
                        try { app.RefreshStatuses(ref template, wmiRes); } catch (Exception) { }

                        row.Cells[1].Value = template.Title;
                        row.Cells[2].Value = template.Crashes;
                        row.Cells[3].Value = template.Uptime;
                        row.Cells[4].Value = template.CPU;
                        row.Cells[5].Value = template.Memory;
                    }
                }

                Thread.Sleep(750);
            }
        }
Exemplo n.º 12
0
 static void Main(string[] args)
 {
     try
     {
         Console.WriteLine("CPUCapabilities v{0:D}.{1:D2} [{2}]", CPU.LibraryVersion.Item1, CPU.LibraryVersion.Item2, BuildDate.ToString("yyyy-MM-dd"));
         Console.WriteLine();
         Console.WriteLine("Architecture: {0}", CPU.Architecture);
         Console.WriteLine("Count: {0}", CPU.Count);
         Console.WriteLine("Vendor: \"{0}\"", OrDefault(CPU.Vendor));
         Console.WriteLine("Information: {0}", CPU.Information);
         Console.WriteLine("Brand: \"{0}\"", OrDefault(CPU.Brand));
         Console.WriteLine("Capabilities: {0}", CPU.Capabilities);
         Console.WriteLine();
         Console.WriteLine("[Debug]");
         Console.WriteLine("IsX64Process: {0}", CPU.IsX64Process);
         Console.WriteLine();
     }
     catch (Exception e)
     {
         Console.Error.WriteLine();
         Console.Error.WriteLine("Error: Something went seriously wrong !!!");
         Console.Error.WriteLine();
         Console.Error.WriteLine(e.ToString());
     }
 }
Exemplo n.º 13
0
        public void Initalize()
        {
            try
            {
                var x          = Environment.OSVersion;
                var runtimedir = RuntimeEnvironment.GetRuntimeDirectory();
                logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")");
                logger.Info(
                    "OS version: " + Environment.OSVersion.ToString() +
                    (Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") +
                    (Environment.Is64BitProcess ? " (64bit process)" : ""));
                var variants = new Variants();
                var variant  = variants.GetVariant();
                logger.Info("Jackett variant: " + variant.ToString());

                try
                {
                    var issueFile = "/etc/issue";
                    if (File.Exists(issueFile))
                    {
                        using (var reader = new StreamReader(issueFile))
                        {
                            var firstLine = reader.ReadLine();
                            if (firstLine != null)
                            {
                                logger.Info($"File {issueFile}: {firstLine}");
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while reading the issue file");
                }

                try
                {
                    var          dockerMsg  = "No";
                    const string cgroupFile = "/proc/1/cgroup";
                    if (File.Exists(cgroupFile) && File.ReadAllText(cgroupFile).Contains("/docker/"))
                    {
                        // this file is created in the Docker image build
                        // https://github.com/linuxserver/docker-jackett/pull/105
                        const string dockerImageFile = "/etc/docker-image";
                        dockerMsg = File.Exists(dockerImageFile)
                            ? "Yes (image build: " + File.ReadAllText(dockerImageFile).Trim() + ")"
                            : "Yes (image build: unknown)";
                    }
                    logger.Info($"Running in Docker: {dockerMsg}");
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while reading the Docker cgroup file");
                }

                try
                {
                    ThreadPool.GetMaxThreads(out var workerThreads, out var completionPortThreads);
                    logger.Info(
                        "ThreadPool MaxThreads: " + workerThreads + " workerThreads, " + completionPortThreads +
                        " completionPortThreads");
                }
                catch (Exception e)
                {
                    logger.Error("Error while getting MaxThreads details: " + e);
                }

                logger.Info("App config/log directory: " + configService.GetAppDataFolder());

                logger.Info("Using Proxy: " + (string.IsNullOrEmpty(config.ProxyUrl) ? "No" : config.ProxyType.ToString()));

                var monotype = Type.GetType("Mono.Runtime");
                if (monotype != null && !DotNetCoreUtil.IsRunningOnDotNetCore)
                {
                    var displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                    var monoVersion = "unknown";
                    if (displayName != null)
                    {
                        monoVersion = displayName.Invoke(null, null).ToString();
                    }
                    logger.Info("Mono version: " + monoVersion);

                    var monoVersionO = new Version(monoVersion.Split(' ')[0]);

                    if (monoVersionO.Major < 5 || (monoVersionO.Major == 5 && monoVersionO.Minor < 8))
                    {
                        //Hard minimum of 5.8
                        //5.4 throws a SIGABRT, looks related to this which was fixed in 5.8 https://bugzilla.xamarin.com/show_bug.cgi?id=60625
                        logger.Error(
                            "Your Mono version is too old. Please update to the latest version from http://www.mono-project.com/download/");
                        Environment.Exit(2);
                    }

                    if (monoVersionO.Major < 5 || (monoVersionO.Major == 5 && monoVersionO.Minor < 8))
                    {
                        var notice = "A minimum Mono version of 5.8 is required. Please update to the latest version from http://www.mono-project.com/download/";
                        notices.Add(notice);
                        logger.Error(notice);
                    }

                    try
                    {
                        // Check for mono-devel
                        // Is there any better way which doesn't involve a hard cashes?
                        var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe");
                        if (!File.Exists(mono_devel_file))
                        {
                            var notice =
                                "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
                            notices.Add(notice);
                            logger.Error(notice);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for mono-devel");
                    }

                    try
                    {
                        // Check for ca-certificates-mono
                        var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe");
                        if (!File.Exists(mono_cert_file))
                        {
                            var notice =
                                "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
                            notices.Add(notice);
                            logger.Error(notice);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for ca-certificates-mono");
                    }

                    try
                    {
                        Encoding.GetEncoding("windows-1255");
                    }
                    catch (NotSupportedException e)
                    {
                        logger.Debug(e);
                        logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed.");
                        Environment.Exit(2);
                    }

                    if (monoVersionO.Major < 6)
                    {
                        //We don't check on Mono 6 since Mono.Security was removed
                        // check if the certificate store was initialized using Mono.Security.X509.X509StoreManager.TrustedRootCertificates.Count
                        try
                        {
                            var monoSecurity         = Assembly.Load("Mono.Security");
                            var monoX509StoreManager = monoSecurity.GetType("Mono.Security.X509.X509StoreManager");
                            if (monoX509StoreManager != null)
                            {
                                var TrustedRootCertificatesProperty =
                                    monoX509StoreManager.GetProperty("TrustedRootCertificates");
                                var TrustedRootCertificates = (ICollection)TrustedRootCertificatesProperty.GetValue(null);

                                logger.Info("TrustedRootCertificates count: " + TrustedRootCertificates.Count);

                                if (TrustedRootCertificates.Count == 0)
                                {
                                    var CACertificatesFiles = new string[]
                                    {
                                        "/etc/ssl/certs/ca-certificates.crt", // Debian based
                                        "/etc/pki/tls/certs/ca-bundle.c",     // RedHat based
                                        "/etc/ssl/ca-bundle.pem",             // SUSE
                                    };

                                    var notice             = "The mono certificate store is not initialized.<br/>\n";
                                    var logSpacer          = "                     ";
                                    var CACertificatesFile = CACertificatesFiles.Where(File.Exists).FirstOrDefault();
                                    var CommandRoot        = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin";
                                    var CommandUser        =
                                        "******";
                                    if (CACertificatesFile != null)
                                    {
                                        CommandRoot = "cert-sync " + CACertificatesFile;
                                        CommandUser = "******" + CACertificatesFile;
                                    }

                                    notice += logSpacer + "Please run the following command as root:<br/>\n";
                                    notice += logSpacer + "<pre>" + CommandRoot + "</pre><br/>\n";
                                    notice += logSpacer +
                                              "If you don't have root access or you're running MacOS, please run the following command as the jackett user (" +
                                              Environment.UserName + "):<br/>\n";
                                    notice += logSpacer + "<pre>" + CommandUser + "</pre>";
                                    notices.Add(notice);
                                    logger.Error(Regex.Replace(notice, "<.*?>", string.Empty));
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            logger.Error(e, "Error while chekcing the mono certificate store");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while getting environment details: " + e);
            }

            try
            {
                if (Environment.UserName == "root")
                {
                    var notice = "Jackett is running with root privileges. You should run Jackett as an unprivileged user.";
                    notices.Add(notice);
                    logger.Error(notice);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "Error while checking the username");
            }

            //Warn user that they are using an old version of Jackett
            try
            {
                var compiledData = BuildDate.GetBuildDateTime();

                if (compiledData < DateTime.Now.AddMonths(-3))
                {
                    var version = configService.GetVersion();
                    var notice  = $"Your version of Jackett v{version} is very old. Multiple indexers are likely to fail when using an old version. Update to the latest version of Jackett.";
                    notices.Add(notice);
                    logger.Error(notice);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "Error while checking build date of Jackett.Common");
            }

            //Alert user that they no longer need to use Mono
            try
            {
                var variants = new Variants();
                var variant  = variants.GetVariant();

                if (variant == Variants.JackettVariant.Mono)
                {
                    var process = new Process();
                    process.StartInfo.FileName               = "uname";
                    process.StartInfo.Arguments              = "-m";
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.Start();
                    var output = process.StandardOutput.ReadToEnd();
                    process.WaitForExit();
                    logger.Debug($"uname output was: {output}");

                    output = output.ToLower();
                    if (output.Contains("armv7") || output.Contains("armv8") || output.Contains("x86_64"))
                    {
                        isDotNetCoreCapable = true;
                    }
                }
            }
            catch (Exception e)
            {
                logger.Debug(e, "Unable to get architecture");
            }

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");

            // Load indexers
            indexerService.InitIndexers(configService.GetCardigannDefinitionsFolders());
            client.Init();

            updater.CleanupTempDir();
            updater.CheckUpdaterLock();
        }
    public string format = "g";        // see: https://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx

    void Start()
    {
        GetComponent <UnityEngine.UI.Text>().text = BuildDate.ToString(format);
    }
Exemplo n.º 15
0
 public override string ToString()
 {
     return($"{Id} - {Platform} - {Environment} - {BuildNumber} - {BuildDate.ToString()} - {SourceBranch}");
 }
Exemplo n.º 16
0
    private void WritePropertiesToFile()
    {
        var aiFile = Path.Combine(Environment.CurrentDirectory, OutputFile);

        if (!File.Exists(aiFile))
        {
            Console.WriteLine($"Could not find AssemblyInfo.cs file '{aiFile}'");
            return;
        }

        var lines = File.ReadAllLines(aiFile);

        var title       = "";
        var copyright   = Copyright.Replace("{Year}", BuildDate.Year.ToString());
        var fullVersion = "";

        for (var i = 0; i < lines.Length; i++)
        {
            var line = lines[i].Trim();
            if (line.StartsWith("[assembly: System.Reflection.AssemblyVersionAttribute("))
            {
                var version = line.Substring(line.IndexOf('"') + 1, line.LastIndexOf('"') - line.IndexOf('"') - 1);
                var vparts  = version.Split('.');
                fullVersion = $"{vparts[0]}.{vparts[1]}.{BuildDate.ToString("yyMMdd").Substring(1)}.{CommitCount}";
                //Console.WriteLine($"fullVersion == '{fullVersion}'");
            }
            if (line.StartsWith("[assembly: System.Reflection.AssemblyTitleAttribute("))
            {
                title = line.Substring(line.IndexOf('"') + 1, line.LastIndexOf('"') - line.IndexOf('"') - 1);
                //Console.WriteLine($"title == '{title}'");
            }
        }

        for (var i = 0; i < lines.Length; i++)
        {
            var line = lines[i].Trim();

            if (line.StartsWith("[assembly: System.Reflection.AssemblyProductAttribute("))
            {
                lines[i] = $"[assembly: System.Reflection.AssemblyProductAttribute(\"{title} v:{fullVersion} #{CommitHash}\")]";
            }
            else if (line.StartsWith("[assembly: System.Reflection.AssemblyCopyrightAttribute("))
            {
                lines[i] = $"[assembly: System.Reflection.AssemblyCopyrightAttribute(\"{copyright}\")]";
            }
            else if (line.StartsWith("[assembly: System.Reflection.AssemblyFileVersionAttribute("))
            {
                lines[i] = $"[assembly: System.Reflection.AssemblyFileVersionAttribute(\"{fullVersion}\")]";
            }
            else if (line.StartsWith("[assembly: System.Reflection.AssemblyInformationalVersionAttribute("))
            {
                lines[i] = $"[assembly: System.Reflection.AssemblyInformationalVersionAttribute(\"{fullVersion}\")]";
            }
            else if (line.StartsWith("[assembly: System.Reflection.AssemblyVersionAttribute("))
            {
                lines[i] = $"[assembly: System.Reflection.AssemblyVersionAttribute(\"{fullVersion}\")]";
            }
        }

        File.WriteAllLines(aiFile, lines, Encoding.UTF8);

        Console.WriteLine($"  GitVersionCore(): {title} version: {fullVersion} hash: {CommitHash}");
    }
Exemplo n.º 17
0
    // Update is called once per frame
    void Update()
    {
        if (swipeRecognizer.GetComponent <SwipeRecognizer>().congratsPanel.activeSelf)
        {
            PauseCountdown();
        }
        else
        {
            ContinueCountdown();
        }

        if (countDown && !paused)
        {
            oneSec += Time.deltaTime;
            if (oneSec >= 1f)
            {
                oneSec = 0f;
                timeLeft--;
                if (timeLeft >= 0)
                {
                    string countTxt = "Time left: " + timeLeft.ToString();
                    GetComponent <UnityEngine.UI.Text>().text  = countTxt;
                    GetComponent <UnityEngine.UI.Text>().color = Color.white;

                    if (timeLeft <= 5)
                    {
                        GetComponent <UnityEngine.UI.Text>().color = Color.red;
                        GetComponent <AudioSource>().volume        = 1;
                        GetComponent <AudioSource>().pitch         = .9f;
                        GetComponent <AudioSource>().Play();
                    }
                }
                else
                {
                    countDown = false;
                    int tempCount = swipeRecognizer.GetComponent <SwipeRecognizer>().neutrinoCount;
                    eventPanelManager.GetComponent <EventPanelManager>().panels.Clear();
                    //trigger a restart of the game...
                    //high score list?
                    timeLeft = gameTime;
                    string countTxt = "Time left: " + timeLeft.ToString();
                    GetComponent <UnityEngine.UI.Text>().text = countTxt;
                    int tempScore = swipeRecognizer.GetComponent <SwipeRecognizer>().neutrinoScore;

                    if (swipeGame != null)
                    {
                        if (summaryPanel != null)
                        {
                            if (tempCount == 1)
                            {
                                summaryPanel.transform.GetChild(4).gameObject.GetComponent <UnityEngine.UI.Text>().text = "Game Summary: You detected " + tempCount + " neutrino source for a score of: " + tempScore;
                            }
                            else
                            {
                                summaryPanel.transform.GetChild(4).gameObject.GetComponent <UnityEngine.UI.Text>().text = "Game Summary: You detected " + tempCount + " neutrino sources for a score of: " + tempScore;
                            }

                            int numTimesTouched = Camera.main.GetComponent <TouchScript.Gestures.MultiFlickGesture>().numTouches;

                            //write out log file here
                            StreamWriter w;

                            string d = BuildDate.ToString();// DateTime.Now.ToString();
                            d = d.Replace("/", "_");
                            d = d.Replace(" ", "_");
                            d = d.Replace(":", "_");

                            using (w = File.AppendText(d + ".log"))
                            {
                                string time = DateTime.Now.ToShortTimeString();
                                string date = DateTime.Now.ToShortDateString();

                                w.WriteLine(date + ", " + time + ", " + tempCount + ", " + tempScore + ", " + numTimesTouched);
                                w.Close();
                            }

                            StreamWriter w2;
                            try
                            {
                                w2 = new StreamWriter("S:\\research_data\\Polar\\" + d + ".log", true);
                                string time = DateTime.Now.ToShortTimeString();
                                string date = DateTime.Now.ToShortDateString();
                                Debug.Log("updated scores");
                                w2.WriteLine(date + ", " + time + ", " + tempCount + ", " + tempScore + ", " + numTimesTouched);
                                w2.Close();
                            } catch (IOException e)
                            {
                                //just don't write it
                                Debug.Log("Couldn't update scores log to cave shared");
                            }

                            Camera.main.GetComponent <TouchScript.Gestures.MultiFlickGesture> ().numTouches = 0;
                            summaryPanel.SetActive(true);
                        }

                        if (swipeGame != null)
                        {
                            swipeGame.GetComponent <SwipeGameMode>().StopGame();
                        }

                        StartCoroutine(DelayedResolve(summaryPanelLength, false));
                    }

                    if (score != null)
                    {
                        //reset score..
                        swipeRecognizer.GetComponent <SwipeRecognizer>().neutrinoScore = 0;
                        swipeRecognizer.GetComponent <SwipeRecognizer>().neutrinoCount = 0;
                        score.GetComponent <UnityEngine.UI.Text>().text = "Score: 0 Points";
                        GetComponent <UnityEngine.UI.Text>().color      = Color.white;
                    }
                }
            }
        }
    }
Exemplo n.º 18
0
 public override string ToString()
 {
     return($"{OperatingSystem} {Tag} {Version} {Architecture} {Size} {BuildDate.ToString("yyyy-MM-dd hh:mm")}");
 }
Exemplo n.º 19
0
        public void Initalize()
        {
            try
            {
                var x          = Environment.OSVersion;
                var runtimedir = RuntimeEnvironment.GetRuntimeDirectory();
                logger.Info("Environment version: " + Environment.Version.ToString() + " (" + runtimedir + ")");
                logger.Info("OS version: " + Environment.OSVersion.ToString() + (Environment.Is64BitOperatingSystem ? " (64bit OS)" : "") + (Environment.Is64BitProcess ? " (64bit process)" : ""));
                Variants variants = new Variants();
                Variants.JackettVariant variant = variants.GetVariant();
                logger.Info("Jackett variant: " + variant.ToString());

                try
                {
                    ThreadPool.GetMaxThreads(out int workerThreads, out int completionPortThreads);
                    logger.Info("ThreadPool MaxThreads: " + workerThreads + " workerThreads, " + completionPortThreads + " completionPortThreads");
                }
                catch (Exception e)
                {
                    logger.Error("Error while getting MaxThreads details: " + e);
                }

                logger.Info("App config/log directory: " + configService.GetAppDataFolder());

                try
                {
                    var issuefile = "/etc/issue";
                    if (File.Exists(issuefile))
                    {
                        using (StreamReader reader = new StreamReader(issuefile))
                        {
                            string firstLine = reader.ReadLine();
                            if (firstLine != null)
                            {
                                logger.Info("issue: " + firstLine);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, "Error while reading the issue file");
                }

                Type monotype = Type.GetType("Mono.Runtime");
                if (monotype != null && !DotNetCoreUtil.IsRunningOnDotNetCore)
                {
                    MethodInfo displayName = monotype.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                    var        monoVersion = "unknown";
                    if (displayName != null)
                    {
                        monoVersion = displayName.Invoke(null, null).ToString();
                    }
                    logger.Info("mono version: " + monoVersion);

                    var monoVersionO = new Version(monoVersion.Split(' ')[0]);

                    if (monoVersionO.Major < 5 || (monoVersionO.Major == 5 && monoVersionO.Minor < 8))
                    {
                        //Hard minimum of 5.8
                        //5.4 throws a SIGABRT, looks related to this which was fixed in 5.8 https://bugzilla.xamarin.com/show_bug.cgi?id=60625

                        logger.Error("Your mono version is too old. Please update to the latest version from http://www.mono-project.com/download/");
                        Environment.Exit(2);
                    }

                    if (monoVersionO.Major < 5 || (monoVersionO.Major == 5 && monoVersionO.Minor < 8))
                    {
                        string notice = "A minimum Mono version of 5.8 is required. Please update to the latest version from http://www.mono-project.com/download/";
                        _notices.Add(notice);
                        logger.Error(notice);
                    }

                    try
                    {
                        // Check for mono-devel
                        // Is there any better way which doesn't involve a hard cashes?
                        var mono_devel_file = Path.Combine(runtimedir, "mono-api-info.exe");
                        if (!File.Exists(mono_devel_file))
                        {
                            var notice = "It looks like the mono-devel package is not installed, please make sure it's installed to avoid crashes.";
                            _notices.Add(notice);
                            logger.Error(notice);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for mono-devel");
                    }

                    try
                    {
                        // Check for ca-certificates-mono
                        var mono_cert_file = Path.Combine(runtimedir, "cert-sync.exe");
                        if (!File.Exists(mono_cert_file))
                        {
                            var notice = "The ca-certificates-mono package is not installed, HTTPS trackers won't work. Please install it.";
                            _notices.Add(notice);
                            logger.Error(notice);
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while checking for ca-certificates-mono");
                    }

                    try
                    {
                        Encoding.GetEncoding("windows-1255");
                    }
                    catch (NotSupportedException e)
                    {
                        logger.Debug(e);
                        logger.Error(e.Message + " Most likely the mono-locale-extras package is not installed.");
                        Environment.Exit(2);
                    }

                    // check if the certificate store was initialized using Mono.Security.X509.X509StoreManager.TrustedRootCertificates.Count
                    try
                    {
                        var  monoSecurity         = Assembly.Load("Mono.Security");
                        Type monoX509StoreManager = monoSecurity.GetType("Mono.Security.X509.X509StoreManager");
                        if (monoX509StoreManager != null)
                        {
                            var TrustedRootCertificatesProperty = monoX509StoreManager.GetProperty("TrustedRootCertificates");
                            var TrustedRootCertificates         = (ICollection)TrustedRootCertificatesProperty.GetValue(null);

                            logger.Info("TrustedRootCertificates count: " + TrustedRootCertificates.Count);

                            if (TrustedRootCertificates.Count == 0)
                            {
                                var CACertificatesFiles = new string[] {
                                    "/etc/ssl/certs/ca-certificates.crt", // Debian based
                                    "/etc/pki/tls/certs/ca-bundle.c",     // RedHat based
                                    "/etc/ssl/ca-bundle.pem",             // SUSE
                                };

                                var notice             = "The mono certificate store is not initialized.<br/>\n";
                                var logSpacer          = "                     ";
                                var CACertificatesFile = CACertificatesFiles.Where(f => File.Exists(f)).FirstOrDefault();
                                var CommandRoot        = "curl -sS https://curl.haxx.se/ca/cacert.pem | cert-sync /dev/stdin";
                                var CommandUser        = "******";
                                if (CACertificatesFile != null)
                                {
                                    CommandRoot = "cert-sync " + CACertificatesFile;
                                    CommandUser = "******" + CACertificatesFile;
                                }
                                notice += logSpacer + "Please run the following command as root:<br/>\n";
                                notice += logSpacer + "<pre>" + CommandRoot + "</pre><br/>\n";
                                notice += logSpacer + "If you don't have root access or you're running MacOS, please run the following command as the jackett user (" + Environment.UserName + "):<br/>\n";
                                notice += logSpacer + "<pre>" + CommandUser + "</pre>";
                                _notices.Add(notice);
                                logger.Error(Regex.Replace(notice, "<.*?>", String.Empty));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, "Error while chekcing the mono certificate store");
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while getting environment details: " + e);
            }

            try
            {
                if (Environment.UserName == "root")
                {
                    var notice = "Jackett is running with root privileges. You should run Jackett as an unprivileged user.";
                    _notices.Add(notice);
                    logger.Error(notice);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "Error while checking the username");
            }

            //Warn user that they are using an old version of Jackett
            try
            {
                DateTime compiledData = BuildDate.GetBuildDateTime();

                if (compiledData < DateTime.Now.AddMonths(-3))
                {
                    string version = configService.GetVersion();
                    string notice  = $"Your version of Jackett v{version} is very old. Multiple indexers are likely to fail when using an old version. Update to the latest version of Jackett.";
                    _notices.Add(notice);
                    logger.Error(notice);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "Error while checking build date of Jackett.Common");
            }

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
            // Load indexers
            indexerService.InitIndexers(configService.GetCardigannDefinitionsFolders());
            client.Init();
            updater.CleanupTempDir();
        }
Exemplo n.º 20
0
        public Engine(HostType hostType, ICommandLine commandLine, string gameDirectory, EngineConfiguration engineConfiguration, ILogger logger, ForwardingTextWriter forwardingTextWriter)
        {
            _hostType = hostType;

            CommandLine         = commandLine ?? throw new ArgumentNullException(nameof(commandLine));
            GameDirectory       = gameDirectory ?? throw new ArgumentNullException(nameof(gameDirectory));
            EngineConfiguration = engineConfiguration ?? throw new ArgumentNullException(nameof(engineConfiguration));
            Log.Logger          = Logger = logger ?? throw new ArgumentNullException(nameof(logger));
            LogTextWriter       = forwardingTextWriter ?? throw new ArgumentNullException(nameof(forwardingTextWriter));

            FileSystem = new DiskFileSystem();

            SetupFileSystem(GameDirectory);

            CommandSystem = new SharpLife.CommandSystem.CommandSystem(Logger, CultureInfo.InvariantCulture);

            EngineContext = CommandSystem.CreateContext("EngineContext");

            var startupState = new EngineStartupState(Logger, GameDirectory,
                                                      new IModelFormatProvider[]
            {
                new SpriteModelFormatProvider(),
                new StudioModelFormatProvider(),
                //BSP loader comes last due to not having a way to positively recognize the format
                new BSPModelFormatProvider(Framework.BSPModelNamePrefix)
            });

            //Add the engine assembly so builtin data gets added
            startupState.EntitySystemMetaData.AddAssembly(typeof(Engine).Assembly);

            //create the game window if this is a client
            if (_hostType == HostType.Client)
            {
                Client = new EngineClient(this, startupState);
            }

            Server = new EngineServer(this, Logger, startupState);

            PluginManager = startupState.PluginManager.Build();

            //Automatically add in all plugin assemblies to the entity system
            foreach (var pluginAssembly in PluginManager.Assemblies)
            {
                startupState.EntitySystemMetaData.AddAssembly(pluginAssembly);
            }

            var renderer = (IRenderer)Client?.UserInterface.Renderer ?? new ServerRenderer();

            World = new WorldState(
                Logger,
                EventSystem,
                FileSystem,
                startupState.EntitySystemMetaData.Build(),
                renderer,
                startupState.ModelFormats);

            _engineTimeStopwatch.Start();

            EngineContext.AddStuffCmds(Logger, CommandLine);
            EngineContext.AddExec(Logger, FileSystem, ExecPathIDs);
            EngineContext.AddEcho(Logger);
            EngineContext.AddAlias(Logger);
            EngineContext.AddFind(Logger);
            EngineContext.AddHelp(Logger);

            _fpsMax = EngineContext.RegisterVariable(
                new VirtualVariableInfo <uint>("fps_max", DefaultFPS)
                .WithHelpInfo("Sets the maximum frames per second")
                .WithChangeHandler((ref VariableChangeEvent <uint> @event) =>
            {
                @event.Value = Math.Min(@event.Value, MaximumFPS);

                var desiredFPS = @event.Value;

                if (desiredFPS == 0)
                {
                    desiredFPS = MaximumFPS;
                }

                _desiredFrameLengthSeconds = 1.0 / desiredFPS;
            }));

            EngineContext.RegisterVariable("engine_builddate", () => BuildDate, "The engine's build date");

            EngineContext.RegisterCommand(new CommandInfo("map", StartNewMap).WithHelpInfo("Loads the specified map"));

            //Get the build date from the generated resource file
            var assembly = typeof(Engine).Assembly;

            using (var reader = new StreamReader(assembly.GetManifestResourceStream($"{assembly.GetName().Name}.Resources.BuildDate.txt")))
            {
                string buildTimestamp = reader.ReadToEnd();

                BuildDate = DateTimeOffset.Parse(buildTimestamp);

                Logger.Information($"Exe: {BuildDate.ToString("HH:mm:ss MMM dd yyyy")}");
            }

            //TODO: initialize subsystems
        }